From 6002a983c3d96faa9f2030425b195309a67e05a2 Mon Sep 17 00:00:00 2001 From: Wolfgang Berger Date: Fri, 12 Feb 2016 16:01:39 +0100 Subject: [PATCH 001/470] first version of session manager --- output/objcSessionManager/README.md | 74 ++ output/objcSessionManager/pom.xml | 102 +++ .../codegen/ObjcsessionmanagerGenerator.java | 515 ++++++++++++++ .../services/io.swagger.codegen.CodegenConfig | 1 + .../ApiSessionManager-body.mustache | 637 ++++++++++++++++++ .../ApiSessionManager-header.mustache | 72 ++ .../BasicAuthTokenProvider-body.mustache | 14 + .../BasicAuthTokenProvider-header.mustache | 14 + .../Configuration-protocol.mustache | 23 + .../DefaultConfiguration-body.mustache | 38 ++ .../DefaultConfiguration-header.mustache | 26 + .../JSONRequestSerializer-body.mustache | 35 + .../JSONRequestSerializer-header.mustache | 5 + .../JSONResponseSerializer-body.mustache | 39 ++ .../JSONResponseSerializer-header.mustache | 6 + .../JSONValueTransformer+ISO8601.h | 6 + .../JSONValueTransformer+ISO8601.m | 10 + .../objcSessionManager/Object-body.mustache | 4 + .../objcSessionManager/Object-header.mustache | 5 + .../QueryParamCollection-body.mustache | 16 + .../QueryParamCollection-header.mustache | 11 + .../objcSessionManager/README.mustache | 23 + .../objcSessionManager/api-body.mustache | 153 +++++ .../objcSessionManager/api-header.mustache | 42 ++ .../objcSessionManager/model-body.mustache | 55 ++ .../objcSessionManager/model-header.mustache | 29 + .../objcSessionManager/podspec.mustache | 36 + 27 files changed, 1991 insertions(+) create mode 100644 output/objcSessionManager/README.md create mode 100644 output/objcSessionManager/pom.xml create mode 100644 output/objcSessionManager/src/main/java/com/diamonddogs/codegen/ObjcsessionmanagerGenerator.java create mode 100644 output/objcSessionManager/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-header.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/BasicAuthTokenProvider-body.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/BasicAuthTokenProvider-header.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/Configuration-protocol.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/DefaultConfiguration-body.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/DefaultConfiguration-header.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/JSONRequestSerializer-body.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/JSONRequestSerializer-header.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/JSONResponseSerializer-body.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/JSONResponseSerializer-header.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.h create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.m create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/Object-body.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/Object-header.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/QueryParamCollection-body.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/QueryParamCollection-header.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/README.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/api-body.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/api-header.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/model-body.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/model-header.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/podspec.mustache diff --git a/output/objcSessionManager/README.md b/output/objcSessionManager/README.md new file mode 100644 index 00000000000..c6d23ed16d2 --- /dev/null +++ b/output/objcSessionManager/README.md @@ -0,0 +1,74 @@ +# Swagger Codegen for the objcSessionManager library + +## Overview +This is a boiler-plate project to generate your own client library with Swagger. It's goal is +to get you started with the basic plumbing so you can put in your own logic. It won't work without +your changes applied. + +## What's Swagger? +The goal of Swagger™ is to define a standard, language-agnostic interface to REST APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined via Swagger, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. Similar to what interfaces have done for lower-level programming, Swagger removes the guesswork in calling the service. + + +Check out [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) for additional information about the Swagger project, including additional libraries with support for other languages and more. + +## How do I use this? +At this point, you've likely generated a client setup. It will include something along these lines: + +``` +. +|- README.md // this file +|- pom.xml // build script +|-- src +|--- main +|---- java +|----- com.diamonddogs.codegen.ObjcsessionmanagerGenerator.java // generator file +|---- resources +|----- objcSessionManager // template files +|----- META-INF +|------ services +|------- io.swagger.codegen.CodegenConfig +``` + +You _will_ need to make changes in at least the following: + +`ObjcsessionmanagerGenerator.java` + +Templates in this folder: + +`src/main/resources/objcSessionManager` + +Once modified, you can run this: + +``` +mvn package +``` + +In your generator project. A single jar file will be produced in `target`. You can now use that with codegen: + +``` +java -cp /path/to/swagger-codegen-distribution:/path/to/your/jar io.swagger.codegen.Codegen -l objcSessionManager -o ./test +``` + +Now your templates are available to the client generator and you can write output values + +## But how do I modify this? +The `ObjcsessionmanagerGenerator.java` has comments in it--lots of comments. There is no good substitute +for reading the code more, though. See how the `ObjcsessionmanagerGenerator` implements `CodegenConfig`. +That class has the signature of all values that can be overridden. + +For the templates themselves, you have a number of values available to you for generation. +You can execute the `java` command from above while passing different debug flags to show +the object you have available during client generation: + +``` +# The following additional debug options are available for all codegen targets: +# -DdebugSwagger prints the OpenAPI Specification as interpreted by the codegen +# -DdebugModels prints models passed to the template engine +# -DdebugOperations prints operations passed to the template engine +# -DdebugSupportingFiles prints additional data passed to the template engine + +java -DdebugOperations -cp /path/to/swagger-codegen-distribution:/path/to/your/jar io.swagger.codegen.Codegen -l objcSessionManager -o ./test +``` + +Will, for example, output the debug info for operations. You can use this info +in the `api.mustache` file. \ No newline at end of file diff --git a/output/objcSessionManager/pom.xml b/output/objcSessionManager/pom.xml new file mode 100644 index 00000000000..2e62110f88e --- /dev/null +++ b/output/objcSessionManager/pom.xml @@ -0,0 +1,102 @@ + + 4.0.0 + io.swagger + objcSessionManager-swagger-codegen + jar + objcSessionManager-swagger-codegen + 1.0.0 + + 2.2.0 + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + + + 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-codegen + ${swagger-codegen-version} + provided + + + + 2.1.5 + 1.0.0 + 4.8.1 + + diff --git a/output/objcSessionManager/src/main/java/com/diamonddogs/codegen/ObjcsessionmanagerGenerator.java b/output/objcSessionManager/src/main/java/com/diamonddogs/codegen/ObjcsessionmanagerGenerator.java new file mode 100644 index 00000000000..2f1c54c4381 --- /dev/null +++ b/output/objcSessionManager/src/main/java/com/diamonddogs/codegen/ObjcsessionmanagerGenerator.java @@ -0,0 +1,515 @@ +package com.diamonddogs.codegen; + +import io.swagger.codegen.CliOption; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.CodegenProperty; +import io.swagger.codegen.CodegenType; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.SupportingFile; +import io.swagger.models.properties.*; + +import java.io.File; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; + +import org.apache.commons.lang.StringUtils; + +public class ObjcsessionmanagerGenerator extends DefaultCodegen implements CodegenConfig { + + public static final String CLASS_PREFIX = "classPrefix"; + public static final String POD_NAME = "podName"; + public static final String AUTHOR_NAME = "authorName"; + public static final String AUTHOR_EMAIL = "authorEmail"; + public static final String GIT_REPO_URL = "gitRepoURL"; + public static final String LICENSE = "license"; + + protected Set foundationClasses = new HashSet(); + protected String podName = "SwaggerClient"; + protected String podVersion = "1.0.0"; + protected String classPrefix = "SWG"; + protected String authorName = "Swagger"; + protected String authorEmail = "apiteam@swagger.io"; + protected String license = "MIT"; + protected String gitRepoURL = "https://github.com/swagger-api/swagger-codegen"; + protected String[] specialWords = {"new", "copy"}; + + + + public ObjcsessionmanagerGenerator() { + super(); + + outputFolder = "generated-code" + File.separator + "objc-SessionManager"; + + modelTemplateFiles.put("model-header.mustache", ".h"); + modelTemplateFiles.put("model-body.mustache", ".m"); + + apiTemplateFiles.put("api-header.mustache", ".h"); + apiTemplateFiles.put("api-body.mustache", ".m"); + + embeddedTemplateDir = templateDir = "objc-SessionManager"; + + defaultIncludes.clear(); + defaultIncludes.add("bool"); + defaultIncludes.add("BOOL"); + defaultIncludes.add("int"); + defaultIncludes.add("NSURL"); + defaultIncludes.add("NSString"); + defaultIncludes.add("NSObject"); + defaultIncludes.add("NSArray"); + defaultIncludes.add("NSNumber"); + defaultIncludes.add("NSDate"); + defaultIncludes.add("NSDictionary"); + defaultIncludes.add("NSMutableArray"); + defaultIncludes.add("NSMutableDictionary"); + + languageSpecificPrimitives.clear(); + languageSpecificPrimitives.add("NSNumber"); + languageSpecificPrimitives.add("NSString"); + languageSpecificPrimitives.add("NSObject"); + languageSpecificPrimitives.add("NSDate"); + languageSpecificPrimitives.add("NSURL"); + languageSpecificPrimitives.add("bool"); + languageSpecificPrimitives.add("BOOL"); + + typeMapping.clear(); + typeMapping.put("enum", "NSString"); + typeMapping.put("date", "NSDate"); + typeMapping.put("DateTime", "NSDate"); + typeMapping.put("boolean", "NSNumber"); + typeMapping.put("string", "NSString"); + typeMapping.put("integer", "NSNumber"); + typeMapping.put("int", "NSNumber"); + typeMapping.put("float", "NSNumber"); + typeMapping.put("long", "NSNumber"); + typeMapping.put("double", "NSNumber"); + typeMapping.put("array", "NSArray"); + typeMapping.put("map", "NSDictionary"); + typeMapping.put("number", "NSNumber"); + typeMapping.put("List", "NSArray"); + typeMapping.put("object", "NSObject"); + typeMapping.put("file", "NSURL"); + + + // ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm + reservedWords = new HashSet( + Arrays.asList( + // local variable names in API methods (endpoints) + "resourcePath", "pathParams", "queryParams", "headerParams", + "responseContentType", "requestContentType", "authSettings", + "formParams", "files", "bodyParam", + // objc reserved words + "auto", "else", "long", "switch", + "break", "enum", "register", "typedef", + "case", "extern", "return", "union", + "char", "float", "short", "unsigned", + "const", "for", "signed", "void", + "continue", "goto", "sizeof", "volatile", + "default", "if", "id", "static", "while", + "do", "int", "struct", "_Packed", + "double", "protocol", "interface", "implementation", + "NSObject", "NSInteger", "NSNumber", "CGFloat", + "property", "nonatomic", "retain", "strong", + "weak", "unsafe_unretained", "readwrite", "readonly", + "description" + )); + + importMapping = new HashMap(); + + foundationClasses = new HashSet( + Arrays.asList( + "NSNumber", + "NSObject", + "NSString", + "NSDate", + "NSURL", + "NSDictionary") + ); + + instantiationTypes.put("array", "NSMutableArray"); + instantiationTypes.put("map", "NSMutableDictionary"); + + cliOptions.clear(); + cliOptions.add(new CliOption(CLASS_PREFIX, "prefix for generated classes (convention: Abbreviation of pod name e.g. `HN` for `HackerNews`).`") + .defaultValue("SWG")); + cliOptions.add(new CliOption(POD_NAME, "cocoapods package name (convention: CameCase).") + .defaultValue("SwaggerClient")); + cliOptions.add(new CliOption(CodegenConstants.POD_VERSION, "cocoapods package version.") + .defaultValue("1.0.0")); + cliOptions.add(new CliOption(AUTHOR_NAME, "Name to use in the podspec file.").defaultValue("Swagger")); + cliOptions.add(new CliOption(AUTHOR_EMAIL, "Email to use in the podspec file.").defaultValue("apiteam@swagger.io")); + cliOptions.add(new CliOption(GIT_REPO_URL, "URL for the git repo where this podspec should point to.") + .defaultValue("https://github.com/swagger-api/swagger-codegen")); + cliOptions.add(new CliOption(LICENSE, "License to use in the podspec file.").defaultValue("MIT")); + } + + @Override + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + @Override + public String getName() { + return "objc-SessionManager"; + } + + @Override + public String getHelp() { + return "Generates an Objective-C client library."; + } + + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey(POD_NAME)) { + setPodName((String) additionalProperties.get(POD_NAME)); + } + + if (additionalProperties.containsKey(CodegenConstants.POD_VERSION)) { + setPodVersion((String) additionalProperties.get(CodegenConstants.POD_VERSION)); + } + + if (additionalProperties.containsKey(CLASS_PREFIX)) { + setClassPrefix((String) additionalProperties.get(CLASS_PREFIX)); + } + + if (additionalProperties.containsKey(AUTHOR_NAME)) { + setAuthorName((String) additionalProperties.get(AUTHOR_NAME)); + } + + if (additionalProperties.containsKey(AUTHOR_EMAIL)) { + setAuthorEmail((String) additionalProperties.get(AUTHOR_EMAIL)); + } + + if (additionalProperties.containsKey(GIT_REPO_URL)) { + setGitRepoURL((String) additionalProperties.get(GIT_REPO_URL)); + } + + if (additionalProperties.containsKey(LICENSE)) { + setLicense((String) additionalProperties.get(LICENSE)); + } + + additionalProperties.put(POD_NAME, podName); + additionalProperties.put(CodegenConstants.POD_VERSION, podVersion); + additionalProperties.put(CLASS_PREFIX, classPrefix); + additionalProperties.put(AUTHOR_NAME, authorName); + additionalProperties.put(AUTHOR_EMAIL, authorEmail); + additionalProperties.put(GIT_REPO_URL, gitRepoURL); + additionalProperties.put(LICENSE, license); + + String swaggerFolder = podName; + + modelPackage = swaggerFolder; + apiPackage = swaggerFolder; + + supportingFiles.add(new SupportingFile("Object-header.mustache", swaggerFolder, classPrefix + "Object.h")); + supportingFiles.add(new SupportingFile("Object-body.mustache", swaggerFolder, classPrefix + "Object.m")); + supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", swaggerFolder, classPrefix + "QueryParamCollection.h")); + supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", swaggerFolder, classPrefix + "QueryParamCollection.m")); + supportingFiles.add(new SupportingFile("ApiSessionManager-header.mustache", swaggerFolder, classPrefix + "ApiSessionManager.h")); + supportingFiles.add(new SupportingFile("ApiSessionManager-body.mustache", swaggerFolder, classPrefix + "ApiSessionManager.m")); + supportingFiles.add(new SupportingFile("JSONResponseSerializer-header.mustache", swaggerFolder, classPrefix + "JSONResponseSerializer.h")); + supportingFiles.add(new SupportingFile("JSONResponseSerializer-body.mustache", swaggerFolder, classPrefix + "JSONResponseSerializer.m")); + supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", swaggerFolder, classPrefix + "JSONRequestSerializer.m")); + supportingFiles.add(new SupportingFile("JSONRequestSerializer-header.mustache", swaggerFolder, classPrefix + "JSONRequestSerializer.h")); + supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.m", swaggerFolder, "JSONValueTransformer+ISO8601.m")); + supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.h", swaggerFolder, "JSONValueTransformer+ISO8601.h")); + supportingFiles.add(new SupportingFile("Configuration-protocol.mustache", swaggerFolder, classPrefix + "Configuration.h")); + supportingFiles.add(new SupportingFile("DefaultConfiguration-body.mustache", swaggerFolder, classPrefix + "DefaultConfiguration.m")); + supportingFiles.add(new SupportingFile("DefaultConfiguration-header.mustache", swaggerFolder, classPrefix + "DefaultConfiguration.h")); + supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-header.mustache", swaggerFolder, classPrefix + "BasicAuthTokenProvider.h")); + supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-body.mustache", swaggerFolder, classPrefix + "BasicAuthTokenProvider.m")); + supportingFiles.add(new SupportingFile("podspec.mustache", "", podName + ".podspec")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + } + + @Override + public String toInstantiationType(Property p) { + if (p instanceof MapProperty) { + return instantiationTypes.get("map"); + } else if (p instanceof ArrayProperty) { + return instantiationTypes.get("array"); + } else { + return null; + } + } + + @Override + public String getTypeDeclaration(String name) { + if (languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name)) { + return name; + } else { + return name + "*"; + } + } + + @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) && !foundationClasses.contains(type)) { + return toModelName(type); + } + } else { + type = swaggerType; + } + return toModelName(type); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + String innerType = getSwaggerType(inner); + + String innerTypeDeclaration = getTypeDeclaration(inner); + + if (innerTypeDeclaration.endsWith("*")) { + innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); + } + + // In this codition, type of property p is array of primitive, + // return container type with pointer, e.g. `NSArray* /* NSString */' + if (languageSpecificPrimitives.contains(innerType)) { + return getSwaggerType(p) + "*" + " /* " + innerTypeDeclaration + " */"; + } + // In this codition, type of property p is array of model, + // return container type combine inner type with pointer, e.g. `NSArray*' + else { + return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*"; + } + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + String innerTypeDeclaration = getTypeDeclaration(inner); + + if (innerTypeDeclaration.endsWith("*")) { + innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); + } + return getSwaggerType(p) + "* /* NSString, " + innerTypeDeclaration + " */"; + } else { + String swaggerType = getSwaggerType(p); + + // In this codition, type of p is objective-c primitive type, e.g. `NSSNumber', + // return type of p with pointer, e.g. `NSNumber*' + if (languageSpecificPrimitives.contains(swaggerType) && + foundationClasses.contains(swaggerType)) { + return swaggerType + "*"; + } + // In this codition, type of p is c primitive type, e.g. `bool', + // return type of p, e.g. `bool' + else if (languageSpecificPrimitives.contains(swaggerType)) { + return swaggerType; + } + // In this codition, type of p is objective-c object type, e.g. `SWGPet', + // return type of p with pointer, e.g. `SWGPet*' + else { + return swaggerType + "*"; + } + } + } + + @Override + public String toModelName(String type) { + type = type.replaceAll("[^0-9a-zA-Z_]", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + + // language build-in classes + if (typeMapping.keySet().contains(type) || + foundationClasses.contains(type) || + importMapping.values().contains(type) || + defaultIncludes.contains(type) || + languageSpecificPrimitives.contains(type)) { + return camelize(type); + } + // custom classes + else { + return classPrefix + camelize(type); + } + } + + @Override + public String toModelFilename(String name) { + // should be the same as the model name + return toModelName(name); + } + + @Override + protected void setNonArrayMapProperty(CodegenProperty property, String type) { + super.setNonArrayMapProperty(property, type); + if ("NSDictionary".equals(type)) { + property.setter = "initWithDictionary"; + } else { + property.setter = "initWithValues"; + } + } + + @Override + public String toModelImport(String name) { + return name; + } + + @Override + public String apiFileFolder() { + return outputFolder + File.separatorChar + apiPackage(); + } + + @Override + public String modelFileFolder() { + return outputFolder + File.separatorChar + modelPackage(); + } + + @Override + public String toApiName(String name) { + return classPrefix + camelize(name) + "Api"; + } + + @Override + public String toApiFilename(String name) { + return classPrefix + camelize(name) + "Api"; + } + + @Override + public String toVarName(String name) { + // sanitize name + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + + // if it's all upper case, do noting + if (name.matches("^[A-Z_]$")) { + return name; + } + + // if name starting with special word, escape with '_' + for(int i =0; i < specialWords.length; i++) { + if (name.matches("(?i:^" + specialWords[i] + ".*)")) + name = escapeSpecialWord(name); + } + + // camelize (lower first character) the variable name + // e.g. `pet_id` to `petId` + name = camelize(name, true); + + // for reserved word or word starting with number, prepend `_` + if (reservedWords.contains(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } + + + return name; + } + + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @SuppressWarnings("static-method") + public String escapeSpecialWord(String name) { + return "var_" + name; + } + + @Override + public String toOperationId(String operationId) { + // throw exception if method name is empty + if (StringUtils.isEmpty(operationId)) { + throw new RuntimeException("Empty method name (operationId) not allowed"); + } + + // method name cannot use reserved keyword, e.g. return + if (reservedWords.contains(operationId)) { + throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + } + + return camelize(sanitizeName(operationId), true); + } + + public void setClassPrefix(String classPrefix) { + this.classPrefix = classPrefix; + } + + public void setPodName(String podName) { + this.podName = podName; + } + + public void setPodVersion(String podVersion) { + this.podVersion = podVersion; + } + + public void setAuthorEmail(String authorEmail) { + this.authorEmail = authorEmail; + } + + public void setAuthorName(String authorName) { + this.authorName = authorName; + } + + public void setGitRepoURL(String gitRepoURL) { + this.gitRepoURL = gitRepoURL; + } + + 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; + } +} \ No newline at end of file diff --git a/output/objcSessionManager/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/output/objcSessionManager/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig new file mode 100644 index 00000000000..ee53c92c410 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig @@ -0,0 +1 @@ +com.diamonddogs.codegen.ObjcsessionmanagerGenerator \ No newline at end of file diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache new file mode 100644 index 00000000000..1064458ba4f --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache @@ -0,0 +1,637 @@ +#import + +#import "{{classPrefix}}ApiSessionManager.h" +#import "{{classPrefix}}JSONRequestSerializer.h" +#import "{{classPrefix}}JSONResponseSerializer.h" +#import "{{classPrefix}}QueryParamCollection.h" +#import "{{classPrefix}}Object.h" +#import "{{classPrefix}}DefaultConfiguration.h" + +#define {{classPrefix}}DebugLog(format, ...) [{{classPrefix}}ApiSessionManager debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__]; + + +NSString *const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}ResponseObject"; + + +@interface {{classPrefix}}ApiSessionManager () + +@property (nonatomic, strong, readwrite) id<{{classPrefix}}Configuration> configuration; + +@end + +@implementation {{classPrefix}}ApiSessionManager + +- (void)dealloc +{ + NSLog(@"%s: %p", __PRETTY_FUNCTION__, self); +} + +- (instancetype)init +{ + return [self initWithConfiguration:[{{classPrefix}}DefaultConfiguration sharedConfiguration]]; +} + +- (instancetype)initWithBaseURL:(NSURL *)url +{ + return [self initWithBaseURL:url + configuration:[{{classPrefix}}DefaultConfiguration sharedConfiguration]]; + +} + +- (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration +{ + return [self initWithBaseURL:[NSURL URLWithString:configuration.host] configuration:configuration]; +} + +- (instancetype)initWithBaseURL:(NSURL *)url + configuration:(id<{{classPrefix}}Configuration>)configuration +{ + self = [super initWithBaseURL:url]; + if (self) + { + _configuration = configuration; + } + NSLog(@"%s: %p", __PRETTY_FUNCTION__, self); + return self; +} + +- (NSURLSessionTask *)requestWithCompletionBlock:(NSString *)path + method:(NSString *)method + pathParams:(NSDictionary *)pathParams + queryParams:(NSDictionary *)queryParams + formParams:(NSDictionary *)formParams + files:(NSDictionary *)files + body:(id)body + headerParams:(NSDictionary *)headerParams + authSettings:(NSArray *)authSettings + requestContentType:(NSString *)requestContentType + responseContentType:(NSString *)responseContentType + responseType:(NSString *)responseType + completionBlock:(void (^)(id, NSError *))completionBlock +{ + // setting request serializer + if ([requestContentType isEqualToString:@"application/json"]) { + self.requestSerializer = [{{classPrefix}}JSONRequestSerializer serializer]; + } + else if ([requestContentType isEqualToString:@"application/x-www-form-urlencoded"]) { + self.requestSerializer = [AFHTTPRequestSerializer serializer]; + } + else if ([requestContentType isEqualToString:@"multipart/form-data"]) { + self.requestSerializer = [AFHTTPRequestSerializer serializer]; + } + else { + NSAssert(false, @"unsupport request type %@", requestContentType); + } + + // setting response serializer + if ([responseContentType isEqualToString:@"application/json"]) { + self.responseSerializer = [{{classPrefix}}JSONResponseSerializer serializer]; + } + else { + self.responseSerializer = [AFHTTPResponseSerializer serializer]; + } + + // sanitize parameters + pathParams = [self sanitizeForSerialization:pathParams]; + queryParams = [self sanitizeForSerialization:queryParams]; + headerParams = [self sanitizeForSerialization:headerParams]; + formParams = [self sanitizeForSerialization:formParams]; + body = [self sanitizeForSerialization:body]; + + // auth setting + [self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings]; + + NSMutableString *resourcePath = [NSMutableString stringWithString:path]; + [pathParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + [resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", key, @"}"]] + withString:[{{classPrefix}}ApiSessionManager escape:obj]]; + }]; + + NSMutableURLRequest * request = nil; + + NSString* pathWithQueryParams = [self pathWithQueryParamsToString:resourcePath queryParams:queryParams]; + if ([pathWithQueryParams hasPrefix:@"/"]) { + pathWithQueryParams = [pathWithQueryParams substringFromIndex:1]; + } + + NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString]; + if (files.count > 0) { + request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" + URLString:urlString + parameters:nil + constructingBodyWithBlock:^(id formData) { + [formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + NSString *objString = [self parameterToString:obj]; + NSData *data = [objString dataUsingEncoding:NSUTF8StringEncoding]; + [formData appendPartWithFormData:data name:key]; + }]; + [files enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + NSURL *filePath = (NSURL *)obj; + [formData appendPartWithFileURL:filePath name:key error:nil]; + }]; + } error:nil]; + } + else { + if (formParams) { + request = [self.requestSerializer requestWithMethod:method + URLString:urlString + parameters:formParams + error:nil]; + } + if (body) { + request = [self.requestSerializer requestWithMethod:method + URLString:urlString + parameters:body + error:nil]; + } + } + + // request cache + BOOL hasHeaderParams = false; + if (headerParams != nil && [headerParams count] > 0) { + hasHeaderParams = true; + } + //if (offlineState) { + if (self.configuration.offlineState) { + {{classPrefix}}DebugLog(@"%@ cache forced", resourcePath); + [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; + } + //else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { + else if(!hasHeaderParams && [method isEqualToString:@"GET"] && self.configuration.cacheEnabled) { + {{classPrefix}}DebugLog(@"%@ cache enabled", resourcePath); + [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; + } + else { + {{classPrefix}}DebugLog(@"%@ cache disabled", resourcePath); + [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; + } + + if (hasHeaderParams){ + for(NSString * key in [headerParams keyEnumerator]){ + [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; + } + } + [self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"]; + + + // Always disable cookies! + [request setHTTPShouldHandleCookies:NO]; + + NSURLSessionTask *task = nil; + + if ([responseType isEqualToString:@"NSURL*"]) { + task = [self downloadTaskWithCompletionBlock:request completionBlock:^(id data, NSError *error) { + completionBlock(data, error); + }]; + } + else { + task = [self taskWithCompletionBlock:request completionBlock:^(id data, NSError *error) { + completionBlock([self deserialize:data class:responseType], error); + }]; + } + + [task resume]; + + return task; +} + +#pragma mark - Task Methods + +- (NSURLSessionDataTask *) taskWithCompletionBlock: (NSURLRequest *)request + completionBlock: (void (^)(id, NSError *))completionBlock { + + NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { + if (error) { + NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; + if (responseObject) { + // Add in the (parsed) response body. + userInfo[{{classPrefix}}ResponseObjectErrorKey] = responseObject; + } + NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; + + completionBlock(nil, augmentedError); + } else { + completionBlock(responseObject, nil); + } + }]; + + return task; +} + +- (NSURLSessionDownloadTask *) downloadTaskWithCompletionBlock: (NSURLRequest *)request + completionBlock: (void (^)(id, NSError *))completionBlock { + + id<{{classPrefix}}Configuration> config = self.configuration; + + NSURLSessionDownloadTask *task = [self downloadTaskWithRequest:request progress:nil destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) { + NSString *directory = nil; + if (config.tempFolderPath) { + directory = config.tempFolderPath; + } + else { + directory = NSTemporaryDirectory(); + } + + NSDictionary *headers = nil; + if ([response isKindOfClass:[NSHTTPURLResponse class]]) + { + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; + headers = httpResponse.allHeaderFields; + } + + NSString *filename = nil; + if ([headers objectForKey:@"Content-Disposition"]) { + + NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?"; + NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern + options:NSRegularExpressionCaseInsensitive + error:nil]; + NSString *contentDispositionHeader = [headers objectForKey:@"Content-Disposition"]; + NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader + options:0 + range:NSMakeRange(0, [contentDispositionHeader length])]; + filename = [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]]; + } + else { + filename = [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]]; + } + + NSString *filepath = [directory stringByAppendingPathComponent:filename]; + NSURL *file = [NSURL fileURLWithPath:filepath]; + + return file; + } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) { + if (error) { + completionBlock(nil, error); + } else { + completionBlock(filePath, nil); + } + }]; + + return task; +} + +#pragma mark - Serialization + +- (void) updateHeaderParams:(NSDictionary *__autoreleasing *)headers + queryParams:(NSDictionary *__autoreleasing *)querys + WithAuthSettings:(NSArray *)authSettings { + + if (!authSettings || [authSettings count] == 0) { + return; + } + + NSMutableDictionary *headersWithAuth = [NSMutableDictionary dictionaryWithDictionary:*headers]; + NSMutableDictionary *querysWithAuth = [NSMutableDictionary dictionaryWithDictionary:*querys]; + + id<{{classPrefix}}Configuration> config = self.configuration; + for (NSString *auth in authSettings) { + //NSDictionary *authSetting = [[config authSettings] objectForKey:auth]; + NSDictionary *authSetting = config.authSettings[auth]; + + if (authSetting) { + if ([authSetting[@"in"] isEqualToString:@"header"]) { + [headersWithAuth setObject:authSetting[@"value"] forKey:authSetting[@"key"]]; + } + else if ([authSetting[@"in"] isEqualToString:@"query"]) { + [querysWithAuth setObject:authSetting[@"value"] forKey:authSetting[@"key"]]; + } + } + } + + *headers = [NSDictionary dictionaryWithDictionary:headersWithAuth]; + *querys = [NSDictionary dictionaryWithDictionary:querysWithAuth]; +} + +- (id) sanitizeForSerialization:(id) object { + if (object == nil) { + return nil; + } + else if ([object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSNumber class]] || [object isKindOfClass:[{{classPrefix}}QueryParamCollection class]]) { + return object; + } + else if ([object isKindOfClass:[NSDate class]]) { + return [object ISO8601String]; + } + else if ([object isKindOfClass:[NSArray class]]) { + NSArray *objectArray = object; + NSMutableArray *sanitizedObjs = [NSMutableArray arrayWithCapacity:[objectArray count]]; + [object enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + if (obj) { + [sanitizedObjs addObject:[self sanitizeForSerialization:obj]]; + } + }]; + return sanitizedObjs; + } + else if ([object isKindOfClass:[NSDictionary class]]) { + NSDictionary *objectDict = object; + NSMutableDictionary *sanitizedObjs = [NSMutableDictionary dictionaryWithCapacity:[objectDict count]]; + [object enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + if (obj) { + [sanitizedObjs setValue:[self sanitizeForSerialization:obj] forKey:key]; + } + }]; + return sanitizedObjs; + } + else if ([object isKindOfClass:[{{classPrefix}}Object class]]) { + return [object toDictionary]; + } + else { + NSException *e = [NSException + exceptionWithName:@"InvalidObjectArgumentException" + reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", object] + userInfo:nil]; + @throw e; + } +} + +- (id) deserialize:(id) data class:(NSString *) class { + NSRegularExpression *regexp = nil; + NSTextCheckingResult *match = nil; + NSMutableArray *resultArray = nil; + NSMutableDictionary *resultDict = nil; + NSString *innerType = nil; + + // return nil if data is nil or class is nil + if (!data || !class) { + return nil; + } + + // remove "*" from class, if ends with "*" + if ([class hasSuffix:@"*"]) { + class = [class substringToIndex:[class length] - 1]; + } + + // pure object + if ([class isEqualToString:@"NSObject"]) { + return data; + } + + // list of models + NSString *arrayOfModelsPat = @"NSArray<(.+)>"; + regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfModelsPat + options:NSRegularExpressionCaseInsensitive + error:nil]; + + match = [regexp firstMatchInString:class + options:0 + range:NSMakeRange(0, [class length])]; + + if (match) { + NSArray *dataArray = data; + innerType = [class substringWithRange:[match rangeAtIndex:1]]; + + resultArray = [NSMutableArray arrayWithCapacity:[dataArray count]]; + [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + [resultArray addObject:[self deserialize:obj class:innerType]]; + } + ]; + + return resultArray; + } + + // list of primitives + NSString *arrayOfPrimitivesPat = @"NSArray\\* /\\* (.+) \\*/"; + regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfPrimitivesPat + options:NSRegularExpressionCaseInsensitive + error:nil]; + match = [regexp firstMatchInString:class + options:0 + range:NSMakeRange(0, [class length])]; + + if (match) { + NSArray *dataArray = data; + innerType = [class substringWithRange:[match rangeAtIndex:1]]; + + resultArray = [NSMutableArray arrayWithCapacity:[dataArray count]]; + [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + [resultArray addObject:[self deserialize:obj class:innerType]]; + }]; + + return resultArray; + } + + // map + NSString *dictPat = @"NSDictionary\\* /\\* (.+?), (.+) \\*/"; + regexp = [NSRegularExpression regularExpressionWithPattern:dictPat + options:NSRegularExpressionCaseInsensitive + error:nil]; + match = [regexp firstMatchInString:class + options:0 + range:NSMakeRange(0, [class length])]; + + if (match) { + NSDictionary *dataDict = data; + NSString *valueType = [class substringWithRange:[match rangeAtIndex:2]]; + + resultDict = [NSMutableDictionary dictionaryWithCapacity:[dataDict count]]; + [data enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + [resultDict setValue:[self deserialize:obj class:valueType] forKey:key]; + }]; + + return resultDict; + } + + // primitives + NSArray *primitiveTypes = @[@"NSString", @"NSDate", @"NSNumber"]; + + if ([primitiveTypes containsObject:class]) { + if ([class isEqualToString:@"NSString"]) { + return [NSString stringWithString:data]; + } + else if ([class isEqualToString:@"NSDate"]) { + return [NSDate dateWithISO8601String:data]; + } + else if ([class isEqualToString:@"NSNumber"]) { + // NSNumber from NSNumber + if ([data isKindOfClass:[NSNumber class]]) { + return data; + } + else if ([data isKindOfClass:[NSString class]]) { + // NSNumber (NSCFBoolean) from NSString + if ([[data lowercaseString] isEqualToString:@"true"] || [[data lowercaseString] isEqualToString:@"false"]) { + return [NSNumber numberWithBool:[data boolValue]]; + // NSNumber from NSString + } else { + NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; + formatter.numberStyle = NSNumberFormatterDecimalStyle; + return [formatter numberFromString:data]; + } + } + } + } + + // model + Class ModelClass = NSClassFromString(class); + if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) { + return [[ModelClass alloc] initWithDictionary:data error:nil]; + } + + return nil; +} + +- (NSString*) pathWithQueryParamsToString:(NSString*) path + queryParams:(NSDictionary*) queryParams { + NSString * separator = nil; + int counter = 0; + + NSMutableString * requestUrl = [NSMutableString stringWithFormat:@"%@", path]; + if (queryParams != nil){ + for(NSString * key in [queryParams keyEnumerator]){ + if (counter == 0) separator = @"?"; + else separator = @"&"; + id queryParam = [queryParams valueForKey:key]; + if ([queryParam isKindOfClass:[NSString class]]){ + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, + [{{classPrefix}}ApiSessionManager escape:key], [{{classPrefix}}ApiSessionManager escape:[queryParams valueForKey:key]]]]; + } + 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"]) { + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, + [{{classPrefix}}ApiSessionManager escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@","]]]]; + + } + else if ([format isEqualToString:@"tsv"]) { + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, + [{{classPrefix}}ApiSessionManager escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@"\t"]]]]; + + } + else if ([format isEqualToString:@"pipes"]) { + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, + [{{classPrefix}}ApiSessionManager escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@"|"]]]]; + + } + else if ([format isEqualToString:@"multi"]) { + for(id obj in values) { + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, + [{{classPrefix}}ApiSessionManager escape:key], [NSString stringWithFormat:@"%@", obj]]]; + counter += 1; + } + + } + } + else { + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, + [{{classPrefix}}ApiSessionManager escape:key], [NSString stringWithFormat:@"%@", [queryParams valueForKey:key]]]]; + } + + counter += 1; + } + } + return requestUrl; +} + +- (NSString *) parameterToString:(id)param { + if ([param isKindOfClass:[NSString class]]) { + return param; + } + else if ([param isKindOfClass:[NSNumber class]]) { + return [param stringValue]; + } + else if ([param isKindOfClass:[NSDate class]]) { + return [param ISO8601String]; + } + else if ([param isKindOfClass:[NSArray class]]) { + NSMutableArray *mutableParam; + [param enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + [mutableParam addObject:[self parameterToString:obj]]; + }]; + return [mutableParam componentsJoinedByString:@","]; + } + else { + NSException *e = [NSException + exceptionWithName:@"InvalidObjectArgumentException" + reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", param] + userInfo:nil]; + @throw e; + } +} + +#pragma mark - Utility Methods + +/* + * Detect `Accept` from accepts + */ ++ (NSString *) selectHeaderAccept:(NSArray *)accepts { + if (accepts == nil || [accepts count] == 0) { + return @""; + } + + NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]]; + for (NSString *string in accepts) { + NSString * lowerAccept = [string lowercaseString]; + if ([lowerAccept containsString:@"application/json"]) { + return @"application/json"; + } + [lowerAccepts addObject:lowerAccept]; + } + + if (lowerAccepts.count == 1) { + return [lowerAccepts firstObject]; + } + + return [lowerAccepts componentsJoinedByString:@", "]; +} + +/* + * Detect `Content-Type` from contentTypes + */ ++ (NSString *) selectHeaderContentType:(NSArray *)contentTypes +{ + if (contentTypes == nil || [contentTypes count] == 0) { + return @"application/json"; + } + + NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]]; + [contentTypes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + [lowerContentTypes addObject:[obj lowercaseString]]; + }]; + + if ([lowerContentTypes containsObject:@"application/json"]) { + return @"application/json"; + } + else { + return lowerContentTypes[0]; + } +} + ++ (NSString*)escape:(id)unescaped { + if ([unescaped isKindOfClass:[NSString class]]){ + return (NSString *)CFBridgingRelease + (CFURLCreateStringByAddingPercentEscapes( + NULL, + (__bridge CFStringRef) unescaped, + NULL, + (CFStringRef)@"!*'();:@&=+$,/?%#[]", + kCFStringEncodingUTF8)); + } + else { + return [NSString stringWithFormat:@"%@", unescaped]; + } +} + +#pragma mark - Log Methods + ++ (void)debugLog:(NSString *)method + message:(NSString *)format, ... { + NSMutableString *message = [NSMutableString stringWithCapacity:1]; + + if (method) { + [message appendString:[NSString stringWithFormat:@"%@: ", method]]; + } + + va_list args; + va_start(args, format); + + [message appendString:[[NSString alloc] initWithFormat:format arguments:args]]; + + NSLog(@"%@", message); + + va_end(args); +} + +@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-header.mustache new file mode 100644 index 00000000000..46171940862 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-header.mustache @@ -0,0 +1,72 @@ +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + +#import +#import "{{classPrefix}}Configuration.h" + +/** + * A key for `NSError` user info dictionaries. + * + * The corresponding value is the parsed response body for an HTTP error. + */ +extern NSString *const {{classPrefix}}ResponseObjectErrorKey; + + +@interface {{classPrefix}}ApiSessionManager : AFHTTPSessionManager + +@property (nonatomic, strong, readonly) id<{{classPrefix}}Configuration> configuration; + +- (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration; + +/** + * Performs request + * + * @param path Request url. + * @param method Request method. + * @param pathParams Request path parameters. + * @param queryParams Request query parameters. + * @param body Request body. + * @param headerParams Request header parameters. + * @param authSettings Request authentication names. + * @param requestContentType Request content-type. + * @param responseContentType Response content-type. + * @param completionBlock The block will be executed when the request completed. + * + * @return The created session task. + */ +- (NSURLSessionTask *)requestWithCompletionBlock:(NSString*) path + method:(NSString*) method + pathParams:(NSDictionary *) pathParams + queryParams:(NSDictionary*) queryParams + formParams:(NSDictionary *) formParams + files:(NSDictionary *) files + body:(id) body + headerParams:(NSDictionary*) headerParams + authSettings: (NSArray *) authSettings + requestContentType:(NSString*) requestContentType + responseContentType:(NSString*) responseContentType + responseType:(NSString *) responseType + completionBlock:(void (^)(id, NSError *))completionBlock; + +/** + * Detects Accept header from accepts NSArray + * + * @param accepts NSArray of header + * + * @return The Accept header + */ ++(NSString *) selectHeaderAccept:(NSArray *)accepts; + +/** + * Detects Content-Type header from contentTypes NSArray + * + * @param contentTypes NSArray of header + * + * @return The Content-Type header + */ ++(NSString *) selectHeaderContentType:(NSArray *)contentTypes; + +@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/BasicAuthTokenProvider-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/BasicAuthTokenProvider-body.mustache new file mode 100644 index 00000000000..d1d9285ac0d --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/BasicAuthTokenProvider-body.mustache @@ -0,0 +1,14 @@ +#import "{{classPrefix}}BasicAuthTokenProvider.h" + +@implementation {{classPrefix}}BasicAuthTokenProvider + ++ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password +{ + NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password]; + NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; + basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; + + return basicAuthCredentials; +} + +@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/BasicAuthTokenProvider-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/BasicAuthTokenProvider-header.mustache new file mode 100644 index 00000000000..dfb287568a0 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/BasicAuthTokenProvider-header.mustache @@ -0,0 +1,14 @@ +/** The `{{classPrefix}}BasicAuthTokenProvider` class creates a basic auth token from username and password. + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + +#import + +@interface {{classPrefix}}BasicAuthTokenProvider : NSObject + ++ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password; + +@end \ No newline at end of file diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/Configuration-protocol.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/Configuration-protocol.mustache new file mode 100644 index 00000000000..7c585f598f9 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/Configuration-protocol.mustache @@ -0,0 +1,23 @@ +/** The `{{classPrefix}}Configuration` protocol defines the interface of a configuration object for the sdk. + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + +#import + +@protocol {{classPrefix}}Configuration + +@property (nonatomic, readonly) BOOL debug; +@property (nonatomic, readonly) BOOL cacheEnabled; +@property (nonatomic, readonly) BOOL offlineState; +@property (nonatomic, readonly) NSString *tempFolderPath; + +@property (nonatomic, readonly) NSDictionary *authSettings; + +@property (nonatomic, readonly) NSString *host; +@property (nonatomic, readonly) NSString *username; +@property (nonatomic, readonly) NSString *password; + +@end \ No newline at end of file diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/DefaultConfiguration-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/DefaultConfiguration-body.mustache new file mode 100644 index 00000000000..c4e93c613fa --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/DefaultConfiguration-body.mustache @@ -0,0 +1,38 @@ +#import "{{classPrefix}}DefaultConfiguration.h" + +@implementation {{classPrefix}}DefaultConfiguration + +#pragma mark - Singletion Methods + ++ (instancetype) sharedConfiguration { + static {{classPrefix}}DefaultConfiguration *shardConfig = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + shardConfig = [[self alloc] init]; + }); + return shardConfig; +} + +#pragma mark - Initialize Methods + +- (instancetype) init { + self = [super init]; + if (self) { + _host = @"{{basePath}}"; + _username = @""; + _password = @""; + _tempFolderPath = nil; + _debug = NO; + _cacheEnabled = YES; + _offlineState = NO; + } + return self; +} + +#pragma mark - + +- (NSDictionary *) authSettings { + return @{}; +} + +@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/DefaultConfiguration-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/DefaultConfiguration-header.mustache new file mode 100644 index 00000000000..a5da4a2fc68 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/DefaultConfiguration-header.mustache @@ -0,0 +1,26 @@ +/** The `{{classPrefix}}Configuration` class provides a default implementation of the configuration protocol for the sdk. + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + +#import +#import "{{classPrefix}}Configuration.h" + +@interface {{classPrefix}}DefaultConfiguration : NSObject <{{classPrefix}}Configuration> + ++ ({{classPrefix}}DefaultConfiguration *)sharedConfiguration; + +@property (nonatomic, assign) BOOL debug; + +@property (nonatomic, assign) BOOL cacheEnabled; +@property (nonatomic, assign) BOOL offlineState; + +@property (nonatomic, strong) NSString *host; +@property (nonatomic, strong) NSString *username; +@property (nonatomic, strong) NSString *password; + +@property (nonatomic, strong) NSString *tempFolderPath; + +@end \ No newline at end of file diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONRequestSerializer-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONRequestSerializer-body.mustache new file mode 100644 index 00000000000..78b1409b6b9 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONRequestSerializer-body.mustache @@ -0,0 +1,35 @@ +#import "{{classPrefix}}JSONRequestSerializer.h" + +@implementation {{classPrefix}}JSONRequestSerializer + +/// +/// When customize a request serializer, +/// the serializer must conform the protocol `AFURLRequestSerialization` +/// and implements the protocol method `requestBySerializingRequest:withParameters:error:` +/// +/// @param request The original request. +/// @param parameters The parameters to be encoded. +/// @param error The error that occurred while attempting to encode the request parameters. +/// +/// @return A serialized request. +/// +- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request + withParameters:(id)parameters + error:(NSError *__autoreleasing *)error +{ + // If the body data which will be serialized isn't NSArray or NSDictionary + // then put the data in the http request body directly. + if ([parameters isKindOfClass:[NSArray class]] || [parameters isKindOfClass:[NSDictionary class]]) { + return [super requestBySerializingRequest:request withParameters:parameters error:error]; + } else { + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + + if (parameters) { + [mutableRequest setHTTPBody:[parameters dataUsingEncoding:self.stringEncoding]]; + } + + return mutableRequest; + } +} + +@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONRequestSerializer-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONRequestSerializer-header.mustache new file mode 100644 index 00000000000..a0732b93706 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONRequestSerializer-header.mustache @@ -0,0 +1,5 @@ +#import +#import + +@interface {{classPrefix}}JSONRequestSerializer : AFJSONRequestSerializer +@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONResponseSerializer-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONResponseSerializer-body.mustache new file mode 100644 index 00000000000..3a19dd1ca4e --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONResponseSerializer-body.mustache @@ -0,0 +1,39 @@ +#import "{{classPrefix}}JSONResponseSerializer.h" + +static BOOL JSONParseError(NSError *error) { + if ([error.domain isEqualToString:NSCocoaErrorDomain] && error.code == 3840) { + return YES; + } + + return NO; +} + +@implementation {{classPrefix}}JSONResponseSerializer + +/// +/// When customize a response serializer, +/// the serializer must conform the protocol `AFURLResponseSerialization` +/// and implements the protocol method `responseObjectForResponse:error:` +/// +/// @param response The response to be processed. +/// @param data The response data to be decoded. +/// @param error The error that occurred while attempting to decode the respnse data. +/// +/// @return The object decoded from the specified response data. +/// +- (id) responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error { + NSDictionary *responseJson = [super responseObjectForResponse:response data:data error:error]; + + // if response data is not a valid json, return string of data. + if (JSONParseError(*error)) { + *error = nil; + NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; + return responseString; + } + + return responseJson; +} + +@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONResponseSerializer-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONResponseSerializer-header.mustache new file mode 100644 index 00000000000..7a5f152e271 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONResponseSerializer-header.mustache @@ -0,0 +1,6 @@ +#import +#import + +@interface {{classPrefix}}JSONResponseSerializer : AFJSONResponseSerializer + +@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.h b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.h new file mode 100644 index 00000000000..832f485f4f0 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.h @@ -0,0 +1,6 @@ +#import +#import +#import + +@interface JSONValueTransformer (ISO8601) +@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.m b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.m new file mode 100644 index 00000000000..cec8bdeea27 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.m @@ -0,0 +1,10 @@ +#import "JSONValueTransformer+ISO8601.h" + +@implementation JSONValueTransformer (ISO8601) + +- (NSDate *) NSDateFromNSString:(NSString *)string +{ + return [NSDate dateWithISO8601String:string]; +} + +@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/Object-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/Object-body.mustache new file mode 100644 index 00000000000..122484f1ad4 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/Object-body.mustache @@ -0,0 +1,4 @@ +#import "{{classPrefix}}Object.h" + +@implementation {{classPrefix}}Object +@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/Object-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/Object-header.mustache new file mode 100644 index 00000000000..d96e379908f --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/Object-header.mustache @@ -0,0 +1,5 @@ +#import +#import + +@interface {{classPrefix}}Object : JSONModel +@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/QueryParamCollection-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/QueryParamCollection-body.mustache new file mode 100644 index 00000000000..23d0c8eaa86 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/QueryParamCollection-body.mustache @@ -0,0 +1,16 @@ +#import "{{classPrefix}}QueryParamCollection.h" + +@implementation {{classPrefix}}QueryParamCollection + +@synthesize values = _values; +@synthesize format = _format; + +- (id) initWithValuesAndFormat: (NSArray*) values + format: (NSString*) format { + _values = values; + _format = format; + + return self; +} + +@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/QueryParamCollection-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/QueryParamCollection-header.mustache new file mode 100644 index 00000000000..0389cce98be --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/QueryParamCollection-header.mustache @@ -0,0 +1,11 @@ +#import + +@interface {{classPrefix}}QueryParamCollection : NSObject + +@property(nonatomic, readonly) NSArray* values; +@property(nonatomic, readonly) NSString* format; + +- (id) initWithValuesAndFormat: (NSArray*) values + format: (NSString*) format; + +@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/README.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/README.mustache new file mode 100644 index 00000000000..30a8927c41a --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/README.mustache @@ -0,0 +1,23 @@ +# {{podName}} + +## Requirements + +The API client library requires ARC (Automatic Reference Counting) to be enabled in your Xcode project. + +## Installation + +To install it, put the API client library in your project and then simply add the following line to your Podfile: + +```ruby +pod "{{podName}}", :path => "/path/to/lib" +``` + +## Recommendation + +It's recommended to create an instance of ApiClient per thread in a multithreaded environment to avoid any potential issue. + +## Author + +{{#apiInfo}}{{#apis}}{{^hasMore}}{{infoEmail}} +{{/hasMore}}{{/apis}}{{/apiInfo}} + diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/api-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/api-body.mustache new file mode 100644 index 00000000000..979f9d7811b --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/api-body.mustache @@ -0,0 +1,153 @@ +{{#operations}} +#import "{{classname}}.h" +#import "{{classPrefix}}QueryParamCollection.h" +{{#imports}}#import "{{import}}.h" +{{/imports}} +{{newline}} + +@interface {{classname}} () + +@property (nonatomic, strong, readwrite) {{classPrefix}}ApiSessionManager *sessionManager; +@property (nonatomic, strong, readwrite) NSMutableDictionary *defaultHeaders; + +@end + +@implementation {{classname}} + +#pragma mark - Initialize methods + +- (id) initWithSessionManager:({{classPrefix}}ApiSessionManager *)sessionManager { + self = [super init]; + if (self) { + _sessionManager = sessionManager; + _defaultHeaders = [NSMutableDictionary dictionary]; + } + + return self; +} + +#pragma mark - + +-(void) addHeader:(NSString*)value forKey:(NSString*)key { + [self.defaultHeaders setValue:value forKey:key]; +} + +#pragma mark - Api Methods + +{{#operation}} +/// +/// {{{summary}}} +/// {{{notes}}} +/// {{#allParams}} @param {{paramName}} {{{description}}} +/// +/// {{/allParams}} @returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} +/// +-(NSURLSessionTask*) {{nickname}}WithCompletionBlock{{^allParams}}: {{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}} + {{/allParams}} + {{#returnBaseType}}{{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{{returnType}}} output, NSError* error))completionBlock { {{/returnBaseType}} + {{^returnBaseType}}{{#hasParams}}completionHandler: {{/hasParams}}(void (^)(NSError* error))completionBlock { {{/returnBaseType}} + + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == nil) { + [NSException raise:@"Invalid parameter" format:@"Missing the required parameter `{{paramName}}` when calling `{{nickname}}`"]; + } + {{/required}}{{/allParams}} + + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"{{path}}"]; + + // remove format in URL if needed + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + {{#pathParams}}if ({{paramName}} != nil) { + pathParams[@"{{baseName}}"] = {{paramName}}; + } + {{/pathParams}} + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + {{#queryParams}}if ({{paramName}} != nil) { + {{#collectionFormat}} + queryParams[@"{{baseName}}"] = [[{{classPrefix}}QueryParamCollection alloc] initWithValuesAndFormat: {{baseName}} format: @"{{collectionFormat}}"]; + {{/collectionFormat}} + {{^collectionFormat}}queryParams[@"{{baseName}}"] = {{paramName}};{{/collectionFormat}} + } + {{/queryParams}} + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + + {{#headerParams}}if ({{paramName}} != nil) { + headerParams[@"{{baseName}}"] = {{paramName}}; + } + {{/headerParams}} + + // HTTP header `Accept` + headerParams[@"Accept"] = [{{classPrefix}}ApiSessionManager selectHeaderAccept:@[{{#produces}}@"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}}]]; + if ([headerParams[@"Accept"] length] == 0) { + [headerParams removeObjectForKey:@"Accept"]; + } + + // response content type + NSString *responseContentType; + if ([headerParams objectForKey:@"Accept"]) { + responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; + } + else { + responseContentType = @""; + } + + // request content type + NSString *requestContentType = [{{classPrefix}}ApiSessionManager selectHeaderContentType:@[{{#consumes}}@"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}]]; + + // Authentication setting + NSArray *authSettings = @[{{#authMethods}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; + + id bodyParam = nil; + NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary *files = [[NSMutableDictionary alloc] init]; + {{#bodyParam}} + bodyParam = {{paramName}}; + {{/bodyParam}}{{^bodyParam}} + {{#formParams}} + {{#notFile}} + if ({{paramName}}) { + formParams[@"{{baseName}}"] = {{paramName}}; + } + {{/notFile}}{{#isFile}} + files[@"{{paramName}}"] = {{paramName}}; + {{/isFile}} + {{/formParams}} + {{/bodyParam}} + + {{#requiredParamCount}} + {{#requiredParams}} + if ({{paramName}} == nil) { + // error + } + {{/requiredParams}} + {{/requiredParamCount}} + return [self.sessionManager requestWithCompletionBlock: resourcePath + method: @"{{httpMethod}}" + pathParams: pathParams + queryParams: queryParams + formParams: formParams + files: files + body: bodyParam + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + responseType: {{^returnType}}nil{{/returnType}}{{#returnType}}@"{{{ returnType }}}"{{/returnType}} + completionBlock: ^(id data, NSError *error) { + {{^returnType}}completionBlock(error);{{/returnType}} + {{#returnType}}completionBlock(({{{ returnType }}})data, error);{{/returnType}} + } + ]; +} + +{{/operation}} + +{{newline}} +{{/operations}} +@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/api-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/api-header.mustache new file mode 100644 index 00000000000..762b31970f2 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/api-header.mustache @@ -0,0 +1,42 @@ +#import +{{#imports}}#import "{{import}}.h" +{{/imports}} +#import "{{classPrefix}}ApiSessionManager.h" +{{newline}} + +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + +{{#operations}} +@interface {{classname}}: NSObject + +@property (nonatomic, strong, readonly) {{classPrefix}}ApiSessionManager *sessionManager; + +-(instancetype) initWithSessionManager:({{classPrefix}}ApiSessionManager *)sessionManager; +-(void) addHeader:(NSString*)value forKey:(NSString*)key; + +{{#operation}} +/// +/// +/// {{{summary}}} +/// {{#notes}}{{{notes}}}{{/notes}} +/// +/// {{#allParams}}@param {{paramName}} {{description}} +/// {{/allParams}} +/// +/// @return {{{returnType}}} +-(NSURLSessionTask*) {{nickname}}WithCompletionBlock {{^allParams}}:{{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}:({{{dataType}}}) {{paramName}} {{#hasMore}} +{{/hasMore}}{{/allParams}} + {{#returnBaseType}}{{#hasParams}} + completionHandler: {{/hasParams}}(void (^)({{{returnType}}} output, NSError* error))completionBlock;{{/returnBaseType}} + {{^returnBaseType}}{{#hasParams}} + completionHandler: {{/hasParams}}(void (^)(NSError* error))completionBlock;{{/returnBaseType}} + +{{newline}} +{{/operation}} + +{{/operations}} +@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/model-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/model-body.mustache new file mode 100644 index 00000000000..3d70cebfae2 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/model-body.mustache @@ -0,0 +1,55 @@ +{{#models}} +{{#model}} +#import "{{classname}}.h" + +@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`. + */ ++ (JSONKeyMapper *)keyMapper +{ + return [[JSONKeyMapper alloc] initWithDictionary:@{ {{#vars}}@"{{baseName}}": @"{{name}}"{{#hasMore}}, {{/hasMore}}{{/vars}} }]; +} + +/** + * Indicates whether the property with the given name is optional. + * If `propertyName` is optional, then return `YES`, otherwise return `NO`. + * This method is used by `JSONModel`. + */ ++ (BOOL)propertyIsOptional:(NSString *)propertyName +{ + NSArray *optionalProperties = @[{{#vars}}{{^required}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/required}}{{/vars}}]; + + if ([optionalProperties containsObject:propertyName]) { + return YES; + } + else { + return NO; + } +} + +/** + * Gets the string presentation of the object. + * This method will be called when logging model object using `NSLog`. + */ +- (NSString *)description { + return [[self toDictionary] description]; +} + +{{/model}} +@end +{{/models}} diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/model-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/model-header.mustache new file mode 100644 index 00000000000..f9a33042491 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/model-header.mustache @@ -0,0 +1,29 @@ +#import +#import "{{classPrefix}}Object.h" + +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + +{{#imports}}#import "{{import}}.h" +{{/imports}} +{{newline}} +{{#models}} +{{#model}} + +@protocol {{classname}} +@end + +@interface {{classname}} : {{#parent}}{{{parent}}}{{/parent}}{{^parent}}{{classPrefix}}Object{{/parent}} + +{{#vars}} +{{#description}}/* {{{description}}} {{^required}}[optional]{{/required}} + */{{/description}} +@property(nonatomic) {{{ datatype }}} {{name}}; +{{/vars}} + +@end +{{/model}} +{{/models}} diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/podspec.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/podspec.mustache new file mode 100644 index 00000000000..338ded84e89 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/podspec.mustache @@ -0,0 +1,36 @@ +# +# Be sure to run `pod lib lint {{podName}}.podspec' to ensure this is a +# valid spec and remove all comments before submitting the spec. +# +# Any lines starting with a # are optional, but encouraged +# +# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html +# + +Pod::Spec.new do |s| + s.name = "{{podName}}" + s.version = "{{podVersion}}" +{{#apiInfo}}{{#apis}}{{^hasMore}} + s.summary = "{{appName}}" + s.description = <<-DESC + {{appDescription}} + DESC +{{/hasMore}}{{/apis}}{{/apiInfo}} + s.platform = :ios, '7.0' + s.requires_arc = true + + s.framework = 'SystemConfiguration' + + s.homepage = "{{gitRepoURL}}" + s.license = "{{license}}" + s.source = { :git => "{{gitRepoURL}}.git", :tag => "#{s.version}" } + s.author = { "{{authorName}}" => "{{authorEmail}}" } + + s.source_files = '{{podName}}/**/*' + s.public_header_files = '{{podName}}/**/*.h' + + s.dependency 'AFNetworking', '~> 2.3' + s.dependency 'JSONModel', '~> 1.1' + s.dependency 'ISO8601', '~> 0.3' +end + From 0c7bb8b2cab33cb66fa3b6d6d2e6adb29de5e86e Mon Sep 17 00:00:00 2001 From: Wolfgang Berger Date: Mon, 15 Feb 2016 10:43:16 +0100 Subject: [PATCH 002/470] updates templates according to https://github.com/NYTimes/objective-c-style-guide --- output/objcSessionManager/README.md | 12 ++-- output/objcSessionManager/pom.xml | 4 +- .../ObjcSessionManagerGenerator.java} | 10 ++-- .../services/io.swagger.codegen.CodegenConfig | 2 +- .../ApiSessionManager-body.mustache | 56 +++++++++---------- .../ApiSessionManager-header.mustache | 26 ++++----- .../BasicAuthTokenProvider-body.mustache | 4 +- .../DefaultConfiguration-body.mustache | 5 +- .../JSONRequestSerializer-body.mustache | 7 ++- .../JSONResponseSerializer-body.mustache | 6 +- .../JSONValueTransformer+ISO8601.m | 3 +- .../QueryParamCollection-body.mustache | 22 +++++--- .../QueryParamCollection-header.mustache | 8 +-- .../objcSessionManager/api-body.mustache | 6 +- .../objcSessionManager/api-header.mustache | 10 ++-- 15 files changed, 93 insertions(+), 88 deletions(-) rename output/objcSessionManager/src/main/java/{com/diamonddogs/codegen/ObjcsessionmanagerGenerator.java => io/swagger/codegen/languages/ObjcSessionManagerGenerator.java} (98%) diff --git a/output/objcSessionManager/README.md b/output/objcSessionManager/README.md index c6d23ed16d2..2bd0d9b256e 100644 --- a/output/objcSessionManager/README.md +++ b/output/objcSessionManager/README.md @@ -1,4 +1,4 @@ -# Swagger Codegen for the objcSessionManager library +# Swagger Codegen for the ObjcSessionManager library ## Overview This is a boiler-plate project to generate your own client library with Swagger. It's goal is @@ -21,9 +21,9 @@ At this point, you've likely generated a client setup. It will include somethin |-- src |--- main |---- java -|----- com.diamonddogs.codegen.ObjcsessionmanagerGenerator.java // generator file +|----- io.swagger.codegen.languages.ObjcsessionmanagerGenerator.java // generator file |---- resources -|----- objcSessionManager // template files +|----- ObjcSessionManager // template files |----- META-INF |------ services |------- io.swagger.codegen.CodegenConfig @@ -35,7 +35,7 @@ You _will_ need to make changes in at least the following: Templates in this folder: -`src/main/resources/objcSessionManager` +`src/main/resources/ObjcSessionManager` Once modified, you can run this: @@ -46,7 +46,7 @@ mvn package In your generator project. A single jar file will be produced in `target`. You can now use that with codegen: ``` -java -cp /path/to/swagger-codegen-distribution:/path/to/your/jar io.swagger.codegen.Codegen -l objcSessionManager -o ./test +java -cp /path/to/swagger-codegen-distribution:/path/to/your/jar io.swagger.codegen.Codegen -l ObjcSessionManager -o ./test ``` Now your templates are available to the client generator and you can write output values @@ -67,7 +67,7 @@ the object you have available during client generation: # -DdebugOperations prints operations passed to the template engine # -DdebugSupportingFiles prints additional data passed to the template engine -java -DdebugOperations -cp /path/to/swagger-codegen-distribution:/path/to/your/jar io.swagger.codegen.Codegen -l objcSessionManager -o ./test +java -DdebugOperations -cp /path/to/swagger-codegen-distribution:/path/to/your/jar io.swagger.codegen.Codegen -l ObjcSessionManager -o ./test ``` Will, for example, output the debug info for operations. You can use this info diff --git a/output/objcSessionManager/pom.xml b/output/objcSessionManager/pom.xml index 2e62110f88e..6ec6fe8a8fb 100644 --- a/output/objcSessionManager/pom.xml +++ b/output/objcSessionManager/pom.xml @@ -2,9 +2,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 io.swagger - objcSessionManager-swagger-codegen + ObjcSessionManager-swagger-codegen jar - objcSessionManager-swagger-codegen + ObjcSessionManager-swagger-codegen 1.0.0 2.2.0 diff --git a/output/objcSessionManager/src/main/java/com/diamonddogs/codegen/ObjcsessionmanagerGenerator.java b/output/objcSessionManager/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerGenerator.java similarity index 98% rename from output/objcSessionManager/src/main/java/com/diamonddogs/codegen/ObjcsessionmanagerGenerator.java rename to output/objcSessionManager/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerGenerator.java index 2f1c54c4381..385f4c23b4c 100644 --- a/output/objcSessionManager/src/main/java/com/diamonddogs/codegen/ObjcsessionmanagerGenerator.java +++ b/output/objcSessionManager/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerGenerator.java @@ -1,4 +1,4 @@ -package com.diamonddogs.codegen; +package io.swagger.codegen.languages; import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConfig; @@ -17,7 +17,7 @@ import org.apache.commons.lang.StringUtils; -public class ObjcsessionmanagerGenerator extends DefaultCodegen implements CodegenConfig { +public class ObjcSessionManagerGenerator extends DefaultCodegen implements CodegenConfig { public static final String CLASS_PREFIX = "classPrefix"; public static final String POD_NAME = "podName"; @@ -38,10 +38,10 @@ public class ObjcsessionmanagerGenerator extends DefaultCodegen implements Codeg - public ObjcsessionmanagerGenerator() { + public ObjcSessionManagerGenerator() { super(); - outputFolder = "generated-code" + File.separator + "objc-SessionManager"; + outputFolder = "generated-code" + File.separator + "ObjcSessionManager"; modelTemplateFiles.put("model-header.mustache", ".h"); modelTemplateFiles.put("model-body.mustache", ".m"); @@ -49,7 +49,7 @@ public ObjcsessionmanagerGenerator() { apiTemplateFiles.put("api-header.mustache", ".h"); apiTemplateFiles.put("api-body.mustache", ".m"); - embeddedTemplateDir = templateDir = "objc-SessionManager"; + embeddedTemplateDir = templateDir = "ObjcSessionManager"; defaultIncludes.clear(); defaultIncludes.add("bool"); diff --git a/output/objcSessionManager/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/output/objcSessionManager/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig index ee53c92c410..c52d64bdbbf 100644 --- a/output/objcSessionManager/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig +++ b/output/objcSessionManager/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig @@ -1 +1 @@ -com.diamonddogs.codegen.ObjcsessionmanagerGenerator \ No newline at end of file +io.swagger.codegen.languages.ObjcSessionManagerGenerator \ No newline at end of file diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache index 1064458ba4f..57e39d9eaa1 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache @@ -10,7 +10,7 @@ #define {{classPrefix}}DebugLog(format, ...) [{{classPrefix}}ApiSessionManager debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__]; -NSString *const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}ResponseObject"; +NSString * const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}ResponseObject"; @interface {{classPrefix}}ApiSessionManager () @@ -21,37 +21,31 @@ NSString *const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}Respons @implementation {{classPrefix}}ApiSessionManager -- (void)dealloc -{ - NSLog(@"%s: %p", __PRETTY_FUNCTION__, self); -} +- (instancetype)init { -- (instancetype)init -{ return [self initWithConfiguration:[{{classPrefix}}DefaultConfiguration sharedConfiguration]]; } -- (instancetype)initWithBaseURL:(NSURL *)url -{ +- (instancetype)initWithBaseURL:(NSURL *)url { + return [self initWithBaseURL:url configuration:[{{classPrefix}}DefaultConfiguration sharedConfiguration]]; } -- (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration -{ +- (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration { + return [self initWithBaseURL:[NSURL URLWithString:configuration.host] configuration:configuration]; } - (instancetype)initWithBaseURL:(NSURL *)url - configuration:(id<{{classPrefix}}Configuration>)configuration -{ + configuration:(id<{{classPrefix}}Configuration>)configuration { + self = [super initWithBaseURL:url]; - if (self) - { + if (self) { _configuration = configuration; } - NSLog(@"%s: %p", __PRETTY_FUNCTION__, self); + return self; } @@ -67,8 +61,8 @@ NSString *const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}Respons requestContentType:(NSString *)requestContentType responseContentType:(NSString *)responseContentType responseType:(NSString *)responseType - completionBlock:(void (^)(id, NSError *))completionBlock -{ + completionBlock:(void (^)(id, NSError *))completionBlock { + // setting request serializer if ([requestContentType isEqualToString:@"application/json"]) { self.requestSerializer = [{{classPrefix}}JSONRequestSerializer serializer]; @@ -151,12 +145,11 @@ NSString *const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}Respons if (headerParams != nil && [headerParams count] > 0) { hasHeaderParams = true; } - //if (offlineState) { + if (self.configuration.offlineState) { {{classPrefix}}DebugLog(@"%@ cache forced", resourcePath); [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; } - //else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { else if(!hasHeaderParams && [method isEqualToString:@"GET"] && self.configuration.cacheEnabled) { {{classPrefix}}DebugLog(@"%@ cache enabled", resourcePath); [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; @@ -166,8 +159,8 @@ NSString *const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}Respons [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; } - if (hasHeaderParams){ - for(NSString * key in [headerParams keyEnumerator]){ + if (hasHeaderParams) { + for(NSString * key in [headerParams keyEnumerator]) { [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; } } @@ -303,7 +296,8 @@ NSString *const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}Respons *querys = [NSDictionary dictionaryWithDictionary:querysWithAuth]; } -- (id) sanitizeForSerialization:(id) object { +- (id)sanitizeForSerialization:(id)object { + if (object == nil) { return nil; } @@ -345,7 +339,8 @@ NSString *const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}Respons } } -- (id) deserialize:(id) data class:(NSString *) class { +- (id)deserialize:(id)data class:(NSString *)class { + NSRegularExpression *regexp = nil; NSTextCheckingResult *match = nil; NSMutableArray *resultArray = nil; @@ -470,8 +465,9 @@ NSString *const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}Respons return nil; } -- (NSString*) pathWithQueryParamsToString:(NSString*) path - queryParams:(NSDictionary*) queryParams { +- (NSString *)pathWithQueryParamsToString:(NSString *)path + queryParams:(NSDictionary *)queryParams { + NSString * separator = nil; int counter = 0; @@ -525,7 +521,8 @@ NSString *const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}Respons return requestUrl; } -- (NSString *) parameterToString:(id)param { +- (NSString *)parameterToString:(id)param { + if ([param isKindOfClass:[NSString class]]) { return param; } @@ -556,7 +553,7 @@ NSString *const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}Respons /* * Detect `Accept` from accepts */ -+ (NSString *) selectHeaderAccept:(NSArray *)accepts { ++ (NSString *)selectHeaderAccept:(NSArray *)accepts { if (accepts == nil || [accepts count] == 0) { return @""; } @@ -580,8 +577,7 @@ NSString *const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}Respons /* * Detect `Content-Type` from contentTypes */ -+ (NSString *) selectHeaderContentType:(NSArray *)contentTypes -{ ++ (NSString *)selectHeaderContentType:(NSArray *)contentTypes { if (contentTypes == nil || [contentTypes count] == 0) { return @"application/json"; } diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-header.mustache index 46171940862..1af58428f9a 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-header.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-header.mustache @@ -37,18 +37,18 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; * * @return The created session task. */ -- (NSURLSessionTask *)requestWithCompletionBlock:(NSString*) path +- (NSURLSessionTask *)requestWithCompletionBlock:(NSString*)path method:(NSString*) method - pathParams:(NSDictionary *) pathParams - queryParams:(NSDictionary*) queryParams - formParams:(NSDictionary *) formParams - files:(NSDictionary *) files - body:(id) body - headerParams:(NSDictionary*) headerParams - authSettings: (NSArray *) authSettings - requestContentType:(NSString*) requestContentType - responseContentType:(NSString*) responseContentType - responseType:(NSString *) responseType + pathParams:(NSDictionary *)pathParams + queryParams:(NSDictionary*)queryParams + formParams:(NSDictionary *)formParams + files:(NSDictionary *)files + body:(id)body + headerParams:(NSDictionary *)headerParams + authSettings: (NSArray *)authSettings + requestContentType:(NSString *)requestContentType + responseContentType:(NSString *)responseContentType + responseType:(NSString *)responseType completionBlock:(void (^)(id, NSError *))completionBlock; /** @@ -58,7 +58,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; * * @return The Accept header */ -+(NSString *) selectHeaderAccept:(NSArray *)accepts; ++ (NSString *)selectHeaderAccept:(NSArray *)accepts; /** * Detects Content-Type header from contentTypes NSArray @@ -67,6 +67,6 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; * * @return The Content-Type header */ -+(NSString *) selectHeaderContentType:(NSArray *)contentTypes; ++ (NSString *)selectHeaderContentType:(NSArray *)contentTypes; @end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/BasicAuthTokenProvider-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/BasicAuthTokenProvider-body.mustache index d1d9285ac0d..e2ba00badb7 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/BasicAuthTokenProvider-body.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/BasicAuthTokenProvider-body.mustache @@ -2,8 +2,8 @@ @implementation {{classPrefix}}BasicAuthTokenProvider -+ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password -{ ++ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password { + NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password]; NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/DefaultConfiguration-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/DefaultConfiguration-body.mustache index c4e93c613fa..62696b6e56f 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/DefaultConfiguration-body.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/DefaultConfiguration-body.mustache @@ -4,7 +4,8 @@ #pragma mark - Singletion Methods -+ (instancetype) sharedConfiguration { ++ (instancetype)sharedConfiguration { + static {{classPrefix}}DefaultConfiguration *shardConfig = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ @@ -15,7 +16,7 @@ #pragma mark - Initialize Methods -- (instancetype) init { +- (instancetype)init { self = [super init]; if (self) { _host = @"{{basePath}}"; diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONRequestSerializer-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONRequestSerializer-body.mustache index 78b1409b6b9..3896c49cfb7 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONRequestSerializer-body.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONRequestSerializer-body.mustache @@ -15,13 +15,14 @@ /// - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request withParameters:(id)parameters - error:(NSError *__autoreleasing *)error -{ + error:(NSError *__autoreleasing *)error { + // If the body data which will be serialized isn't NSArray or NSDictionary // then put the data in the http request body directly. if ([parameters isKindOfClass:[NSArray class]] || [parameters isKindOfClass:[NSDictionary class]]) { return [super requestBySerializingRequest:request withParameters:parameters error:error]; - } else { + } + else { NSMutableURLRequest *mutableRequest = [request mutableCopy]; if (parameters) { diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONResponseSerializer-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONResponseSerializer-body.mustache index 3a19dd1ca4e..c36c171018c 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONResponseSerializer-body.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONResponseSerializer-body.mustache @@ -21,9 +21,9 @@ static BOOL JSONParseError(NSError *error) { /// /// @return The object decoded from the specified response data. /// -- (id) responseObjectForResponse:(NSURLResponse *)response - data:(NSData *)data - error:(NSError *__autoreleasing *)error { +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error { NSDictionary *responseJson = [super responseObjectForResponse:response data:data error:error]; // if response data is not a valid json, return string of data. diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.m b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.m index cec8bdeea27..4659594802a 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.m +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.m @@ -2,8 +2,7 @@ @implementation JSONValueTransformer (ISO8601) -- (NSDate *) NSDateFromNSString:(NSString *)string -{ +- (NSDate *)NSDateFromNSString:(NSString *)string { return [NSDate dateWithISO8601String:string]; } diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/QueryParamCollection-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/QueryParamCollection-body.mustache index 23d0c8eaa86..f2d31cf4560 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/QueryParamCollection-body.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/QueryParamCollection-body.mustache @@ -1,15 +1,23 @@ #import "{{classPrefix}}QueryParamCollection.h" -@implementation {{classPrefix}}QueryParamCollection +@interface {{classPrefix}}QueryParamCollection () + +@property (nonatomic, strong) NSArray * values; +@property (nonatomic, strong) NSString * format; -@synthesize values = _values; -@synthesize format = _format; +@end + +@implementation {{classPrefix}}QueryParamCollection -- (id) initWithValuesAndFormat: (NSArray*) values - format: (NSString*) format { - _values = values; - _format = format; +- (id)initWithValuesAndFormat:(NSArray *)values + format:(NSString *)format { + self = [super init]; + if (self) { + _values = values; + _format = format; + } + return self; } diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/QueryParamCollection-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/QueryParamCollection-header.mustache index 0389cce98be..7dc3cbc6e1c 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/QueryParamCollection-header.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/QueryParamCollection-header.mustache @@ -2,10 +2,10 @@ @interface {{classPrefix}}QueryParamCollection : NSObject -@property(nonatomic, readonly) NSArray* values; -@property(nonatomic, readonly) NSString* format; +@property (nonatomic, readonly) NSArray * values; +@property (nonatomic, readonly) NSString * format; -- (id) initWithValuesAndFormat: (NSArray*) values - format: (NSString*) format; +- (id)initWithValuesAndFormat:(NSArray *)values + format:(NSString *)format; @end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/api-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/api-body.mustache index 979f9d7811b..369046fe484 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/api-body.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/api-body.mustache @@ -16,7 +16,7 @@ #pragma mark - Initialize methods -- (id) initWithSessionManager:({{classPrefix}}ApiSessionManager *)sessionManager { +- (id)initWithSessionManager:({{classPrefix}}ApiSessionManager *)sessionManager { self = [super init]; if (self) { _sessionManager = sessionManager; @@ -28,7 +28,7 @@ #pragma mark - --(void) addHeader:(NSString*)value forKey:(NSString*)key { +- (void)addHeader:(NSString *)value forKey:(NSString *)key { [self.defaultHeaders setValue:value forKey:key]; } @@ -42,7 +42,7 @@ /// /// {{/allParams}} @returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} /// --(NSURLSessionTask*) {{nickname}}WithCompletionBlock{{^allParams}}: {{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}} +- (NSURLSessionTask *){{nickname}}WithCompletionBlock{{^allParams}}: {{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}} {{/allParams}} {{#returnBaseType}}{{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{{returnType}}} output, NSError* error))completionBlock { {{/returnBaseType}} {{^returnBaseType}}{{#hasParams}}completionHandler: {{/hasParams}}(void (^)(NSError* error))completionBlock { {{/returnBaseType}} diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/api-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/api-header.mustache index 762b31970f2..d20008561d4 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/api-header.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/api-header.mustache @@ -15,8 +15,8 @@ @property (nonatomic, strong, readonly) {{classPrefix}}ApiSessionManager *sessionManager; --(instancetype) initWithSessionManager:({{classPrefix}}ApiSessionManager *)sessionManager; --(void) addHeader:(NSString*)value forKey:(NSString*)key; +- (instancetype)initWithSessionManager:({{classPrefix}}ApiSessionManager *)sessionManager; +- (void)addHeader:(NSString *)value forKey:(NSString *)key; {{#operation}} /// @@ -28,12 +28,12 @@ /// {{/allParams}} /// /// @return {{{returnType}}} --(NSURLSessionTask*) {{nickname}}WithCompletionBlock {{^allParams}}:{{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}:({{{dataType}}}) {{paramName}} {{#hasMore}} +- (NSURLSessionTask *){{nickname}}WithCompletionBlock {{^allParams}}:{{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}:({{{dataType}}}){{paramName}} {{#hasMore}} {{/hasMore}}{{/allParams}} {{#returnBaseType}}{{#hasParams}} - completionHandler: {{/hasParams}}(void (^)({{{returnType}}} output, NSError* error))completionBlock;{{/returnBaseType}} + completionHandler:{{/hasParams}}(void (^)({{{returnType}}} output, NSError *error))completionBlock;{{/returnBaseType}} {{^returnBaseType}}{{#hasParams}} - completionHandler: {{/hasParams}}(void (^)(NSError* error))completionBlock;{{/returnBaseType}} + completionHandler: {{/hasParams}}(void (^)(NSError * error))completionBlock;{{/returnBaseType}} {{newline}} {{/operation}} From e258fb97ca00c734c4a2cee314cfbb1053a5c01d Mon Sep 17 00:00:00 2001 From: Wolfgang Berger Date: Mon, 6 Jun 2016 16:17:39 +0200 Subject: [PATCH 003/470] updates for ISO8601 0.5.1 --- .../objcSessionManager/ApiSessionManager-body.mustache | 2 +- .../resources/objcSessionManager/JSONValueTransformer+ISO8601.h | 1 - .../resources/objcSessionManager/JSONValueTransformer+ISO8601.m | 1 + 3 files changed, 2 insertions(+), 2 deletions(-) diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache index 57e39d9eaa1..f319f65d03e 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache @@ -1,4 +1,4 @@ -#import +#import #import "{{classPrefix}}ApiSessionManager.h" #import "{{classPrefix}}JSONRequestSerializer.h" diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.h b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.h index 832f485f4f0..6f66d0e1c13 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.h +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.h @@ -1,5 +1,4 @@ #import -#import #import @interface JSONValueTransformer (ISO8601) diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.m b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.m index 4659594802a..aaa7a808f32 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.m +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.m @@ -1,3 +1,4 @@ +#import #import "JSONValueTransformer+ISO8601.h" @implementation JSONValueTransformer (ISO8601) From cd6a80591054bbe33117a3d647b4a3c6343faca6 Mon Sep 17 00:00:00 2001 From: Wolfgang Berger Date: Wed, 8 Jun 2016 13:31:04 +0200 Subject: [PATCH 004/470] updates templates with JSONModel workaround --- .../main/resources/objc/Object-body.mustache | 31 +++++++++++++++++++ .../objcSessionManager/Object-body.mustache | 29 +++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/modules/swagger-codegen/src/main/resources/objc/Object-body.mustache b/modules/swagger-codegen/src/main/resources/objc/Object-body.mustache index 122484f1ad4..a56acfbcbde 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Object-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Object-body.mustache @@ -1,4 +1,35 @@ #import "{{classPrefix}}Object.h" @implementation {{classPrefix}}Object + +@implementation {{classPrefix}}Object + +// workaround for JSONModel multithreading issues +// https://github.com/icanzilb/JSONModel/issues/441 +- (instancetype)initWithDictionary:(NSDictionary *)dict error:(NSError **)err +{ + static NSMutableSet *classNames; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + classNames = [NSMutableSet new]; + }); + + BOOL initSync; + @synchronized([self class]) + { + NSString *className = NSStringFromClass([self class]); + initSync = ![classNames containsObject:className]; + if(initSync) + { + [classNames addObject:className]; + self = [super initWithDictionary:dict error:err]; + } + } + if(!initSync) + { + self = [super initWithDictionary:dict error:err]; + } + return self; +} + @end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/Object-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/Object-body.mustache index 122484f1ad4..458249a49a2 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/Object-body.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/Object-body.mustache @@ -1,4 +1,33 @@ #import "{{classPrefix}}Object.h" @implementation {{classPrefix}}Object + +// workaround for JSONModel multithreading issues +// https://github.com/icanzilb/JSONModel/issues/441 +- (instancetype)initWithDictionary:(NSDictionary *)dict error:(NSError **)err +{ + static NSMutableSet *classNames; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + classNames = [NSMutableSet new]; + }); + + BOOL initSync; + @synchronized([self class]) + { + NSString *className = NSStringFromClass([self class]); + initSync = ![classNames containsObject:className]; + if(initSync) + { + [classNames addObject:className]; + self = [super initWithDictionary:dict error:err]; + } + } + if(!initSync) + { + self = [super initWithDictionary:dict error:err]; + } + return self; +} + @end From 6c350a7d2d097d6c98558e60149d8763b8823868 Mon Sep 17 00:00:00 2001 From: Maneesh Sahu-SSI Date: Wed, 15 Jun 2016 13:43:36 -0700 Subject: [PATCH 005/470] Added long to primitive data types supported in Python codegen --- .../src/main/resources/python/api_client.mustache | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index 2a4732f5afd..81f670dee1f 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -180,7 +180,7 @@ class ApiClient(object): Builds a JSON POST object. If obj is None, return None. - If obj is str, int, float, bool, return directly. + If obj is str, int, long, float, bool, return directly. If obj is datetime.datetime, datetime.date convert to string in iso8601 format. If obj is list, sanitize each element in the list. @@ -190,7 +190,7 @@ class ApiClient(object): :param obj: The data to serialize. :return: The serialized form of data. """ - types = (str, int, float, bool, tuple) + types = (str, int, long, float, bool, tuple) if sys.version_info < (3, 0): types = types + (unicode,) if isinstance(obj, type(None)): @@ -266,14 +266,14 @@ class ApiClient(object): # convert str to class # for native types - if klass in ['int', 'float', 'str', 'bool', + if klass in ['int', 'long', 'float', 'str', 'bool', "date", 'datetime', "object"]: klass = eval(klass) # for model types else: klass = eval('models.' + klass) - if klass in [int, float, str, bool]: + if klass in [int, long, float, str, bool]: return self.__deserialize_primitive(data, klass) elif klass == object: return self.__deserialize_object(data) @@ -501,7 +501,7 @@ class ApiClient(object): :param data: str. :param klass: class literal. - :return: int, float, str, bool. + :return: int, long, float, str, bool. """ try: value = klass(data) From e40ad8ce3c6a9240b2380870eb4441e7d9d30d23 Mon Sep 17 00:00:00 2001 From: ant3 Date: Mon, 20 Jun 2016 23:10:01 +0100 Subject: [PATCH 006/470] Added sample build for Java8 Jersey2 client --- bin/all-petstore.sh | 1 + bin/java-petstore-all.sh | 1 + bin/java8-petstore-jersey2.json | 5 + bin/java8-petstore-jersey2.sh | 34 + .../petstore/java/jersey2-java8/.gitignore | 21 + .../jersey2-java8/.swagger-codegen-ignore | 23 + .../petstore/java/jersey2-java8/.travis.yml | 29 + .../petstore/java/jersey2-java8/LICENSE | 201 +++++ .../petstore/java/jersey2-java8/README.md | 177 +++++ .../petstore/java/jersey2-java8/build.gradle | 113 +++ .../petstore/java/jersey2-java8/build.sbt | 24 + .../docs/AdditionalPropertiesClass.md | 11 + .../java/jersey2-java8/docs/Animal.md | 11 + .../java/jersey2-java8/docs/AnimalFarm.md | 9 + .../java/jersey2-java8/docs/ArrayTest.md | 12 + .../petstore/java/jersey2-java8/docs/Cat.md | 12 + .../java/jersey2-java8/docs/Category.md | 11 + .../petstore/java/jersey2-java8/docs/Dog.md | 12 + .../java/jersey2-java8/docs/EnumClass.md | 14 + .../java/jersey2-java8/docs/EnumTest.md | 36 + .../java/jersey2-java8/docs/FakeApi.md | 75 ++ .../java/jersey2-java8/docs/FormatTest.md | 22 + ...dPropertiesAndAdditionalPropertiesClass.md | 12 + .../jersey2-java8/docs/Model200Response.md | 10 + .../jersey2-java8/docs/ModelApiResponse.md | 12 + .../java/jersey2-java8/docs/ModelReturn.md | 10 + .../petstore/java/jersey2-java8/docs/Name.md | 13 + .../petstore/java/jersey2-java8/docs/Order.md | 24 + .../petstore/java/jersey2-java8/docs/Pet.md | 24 + .../java/jersey2-java8/docs/PetApi.md | 448 +++++++++++ .../java/jersey2-java8/docs/ReadOnlyFirst.md | 11 + .../jersey2-java8/docs/SpecialModelName.md | 10 + .../java/jersey2-java8/docs/StoreApi.md | 197 +++++ .../petstore/java/jersey2-java8/docs/Tag.md | 11 + .../petstore/java/jersey2-java8/docs/User.md | 17 + .../java/jersey2-java8/docs/UserApi.md | 370 ++++++++++ .../petstore/java/jersey2-java8/git_push.sh | 52 ++ .../java/jersey2-java8/gradle.properties | 2 + .../petstore/java/jersey2-java8/gradlew | 160 ++++ .../petstore/java/jersey2-java8/gradlew.bat | 90 +++ .../petstore/java/jersey2-java8/pom.xml | 177 +++++ .../java/jersey2-java8/settings.gradle | 1 + .../src/main/AndroidManifest.xml | 3 + .../java/io/swagger/client/ApiClient.java | 698 ++++++++++++++++++ .../java/io/swagger/client/ApiException.java | 103 +++ .../java/io/swagger/client/Configuration.java | 51 ++ .../src/main/java/io/swagger/client/JSON.java | 36 + .../src/main/java/io/swagger/client/Pair.java | 64 ++ .../java/io/swagger/client/StringUtil.java | 67 ++ .../java/io/swagger/client/api/FakeApi.java | 129 ++++ .../java/io/swagger/client/api/PetApi.java | 384 ++++++++++ .../java/io/swagger/client/api/StoreApi.java | 196 +++++ .../java/io/swagger/client/api/UserApi.java | 370 ++++++++++ .../io/swagger/client/auth/ApiKeyAuth.java | 87 +++ .../swagger/client/auth/Authentication.java | 41 + .../io/swagger/client/auth/HttpBasicAuth.java | 70 ++ .../java/io/swagger/client/auth/OAuth.java | 51 ++ .../io/swagger/client/auth/OAuthFlow.java | 30 + .../model/AdditionalPropertiesClass.java | 97 +++ .../java/io/swagger/client/model/Animal.java | 94 +++ .../io/swagger/client/model/AnimalFarm.java | 54 ++ .../io/swagger/client/model/ArrayTest.java | 116 +++ .../java/io/swagger/client/model/Cat.java | 116 +++ .../io/swagger/client/model/Category.java | 94 +++ .../java/io/swagger/client/model/Dog.java | 116 +++ .../io/swagger/client/model/EnumClass.java | 28 + .../io/swagger/client/model/EnumTest.java | 178 +++++ .../io/swagger/client/model/FormatTest.java | 327 ++++++++ ...ropertiesAndAdditionalPropertiesClass.java | 119 +++ .../client/model/Model200Response.java | 75 ++ .../client/model/ModelApiResponse.java | 114 +++ .../io/swagger/client/model/ModelReturn.java | 75 ++ .../java/io/swagger/client/model/Name.java | 115 +++ .../java/io/swagger/client/model/Order.java | 199 +++++ .../java/io/swagger/client/model/Pet.java | 202 +++++ .../swagger/client/model/ReadOnlyFirst.java | 84 +++ .../client/model/SpecialModelName.java | 74 ++ .../java/io/swagger/client/model/Tag.java | 94 +++ .../java/io/swagger/client/model/User.java | 215 ++++++ .../io/swagger/client/api/FakeApiTest.java | 74 ++ .../io/swagger/client/api/PetApiTest.java | 180 +++++ .../io/swagger/client/api/StoreApiTest.java | 108 +++ .../io/swagger/client/api/UserApiTest.java | 174 +++++ 83 files changed, 8007 insertions(+) create mode 100644 bin/java8-petstore-jersey2.json create mode 100644 bin/java8-petstore-jersey2.sh create mode 100644 samples/client/petstore/java/jersey2-java8/.gitignore create mode 100644 samples/client/petstore/java/jersey2-java8/.swagger-codegen-ignore create mode 100644 samples/client/petstore/java/jersey2-java8/.travis.yml create mode 100644 samples/client/petstore/java/jersey2-java8/LICENSE create mode 100644 samples/client/petstore/java/jersey2-java8/README.md create mode 100644 samples/client/petstore/java/jersey2-java8/build.gradle create mode 100644 samples/client/petstore/java/jersey2-java8/build.sbt create mode 100644 samples/client/petstore/java/jersey2-java8/docs/AdditionalPropertiesClass.md create mode 100644 samples/client/petstore/java/jersey2-java8/docs/Animal.md create mode 100644 samples/client/petstore/java/jersey2-java8/docs/AnimalFarm.md create mode 100644 samples/client/petstore/java/jersey2-java8/docs/ArrayTest.md create mode 100644 samples/client/petstore/java/jersey2-java8/docs/Cat.md create mode 100644 samples/client/petstore/java/jersey2-java8/docs/Category.md create mode 100644 samples/client/petstore/java/jersey2-java8/docs/Dog.md create mode 100644 samples/client/petstore/java/jersey2-java8/docs/EnumClass.md create mode 100644 samples/client/petstore/java/jersey2-java8/docs/EnumTest.md create mode 100644 samples/client/petstore/java/jersey2-java8/docs/FakeApi.md create mode 100644 samples/client/petstore/java/jersey2-java8/docs/FormatTest.md create mode 100644 samples/client/petstore/java/jersey2-java8/docs/MixedPropertiesAndAdditionalPropertiesClass.md create mode 100644 samples/client/petstore/java/jersey2-java8/docs/Model200Response.md create mode 100644 samples/client/petstore/java/jersey2-java8/docs/ModelApiResponse.md create mode 100644 samples/client/petstore/java/jersey2-java8/docs/ModelReturn.md create mode 100644 samples/client/petstore/java/jersey2-java8/docs/Name.md create mode 100644 samples/client/petstore/java/jersey2-java8/docs/Order.md create mode 100644 samples/client/petstore/java/jersey2-java8/docs/Pet.md create mode 100644 samples/client/petstore/java/jersey2-java8/docs/PetApi.md create mode 100644 samples/client/petstore/java/jersey2-java8/docs/ReadOnlyFirst.md create mode 100644 samples/client/petstore/java/jersey2-java8/docs/SpecialModelName.md create mode 100644 samples/client/petstore/java/jersey2-java8/docs/StoreApi.md create mode 100644 samples/client/petstore/java/jersey2-java8/docs/Tag.md create mode 100644 samples/client/petstore/java/jersey2-java8/docs/User.md create mode 100644 samples/client/petstore/java/jersey2-java8/docs/UserApi.md create mode 100644 samples/client/petstore/java/jersey2-java8/git_push.sh create mode 100644 samples/client/petstore/java/jersey2-java8/gradle.properties create mode 100644 samples/client/petstore/java/jersey2-java8/gradlew create mode 100644 samples/client/petstore/java/jersey2-java8/gradlew.bat create mode 100644 samples/client/petstore/java/jersey2-java8/pom.xml create mode 100644 samples/client/petstore/java/jersey2-java8/settings.gradle create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/AndroidManifest.xml create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiClient.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiException.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/Configuration.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/JSON.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/Pair.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/StringUtil.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/FakeApi.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/PetApi.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/StoreApi.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/UserApi.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/ApiKeyAuth.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/Authentication.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/HttpBasicAuth.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/OAuth.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/OAuthFlow.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Animal.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AnimalFarm.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayTest.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Cat.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Category.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Dog.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumClass.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumTest.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/FormatTest.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Model200Response.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelApiResponse.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelReturn.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Name.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Order.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Pet.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ReadOnlyFirst.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/SpecialModelName.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Tag.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/User.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/FakeApiTest.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/PetApiTest.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/StoreApiTest.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/UserApiTest.java diff --git a/bin/all-petstore.sh b/bin/all-petstore.sh index 849af6b5d4a..5ca48a53ae0 100755 --- a/bin/all-petstore.sh +++ b/bin/all-petstore.sh @@ -30,6 +30,7 @@ cd $APP_DIR ./bin/java-petstore-okhttp-gson.sh ./bin/java-petstore-retrofit.sh ./bin/java-petstore-retrofit2.sh +./bin/java8-petstore-jersey2.sh ./bin/jaxrs-petstore-server.sh ./bin/nodejs-petstore-server.sh ./bin/objc-petstore.sh diff --git a/bin/java-petstore-all.sh b/bin/java-petstore-all.sh index 143ebc819c5..b108cc06a4d 100755 --- a/bin/java-petstore-all.sh +++ b/bin/java-petstore-all.sh @@ -8,3 +8,4 @@ ./bin/java-petstore-retrofit.sh ./bin/java-petstore-retrofit2.sh ./bin/java-petstore-retrofit2rx.sh +./bin/java8-petstore-jersey2.sh diff --git a/bin/java8-petstore-jersey2.json b/bin/java8-petstore-jersey2.json new file mode 100644 index 00000000000..113828ca9d5 --- /dev/null +++ b/bin/java8-petstore-jersey2.json @@ -0,0 +1,5 @@ +{ + "library": "jersey2", + "artifactId": "swagger-petstore-jersey2", + "dateLibrary": "java8" +} \ No newline at end of file diff --git a/bin/java8-petstore-jersey2.sh b/bin/java8-petstore-jersey2.sh new file mode 100644 index 00000000000..33dca82a2ba --- /dev/null +++ b/bin/java8-petstore-jersey2.sh @@ -0,0 +1,34 @@ +#!/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-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java8-petstore-jersey2.json -o samples/client/petstore/java/jersey2-java8 -DhideGenerationTimestamp=true" + +echo "Removing files and folders under samples/client/petstore/java/jersey2-java8/src/main" +rm -rf samples/client/petstore/java/jersey2-java8/src/main +find samples/client/petstore/java/jersey2-java8 -maxdepth 1 -type f ! -name "README.md" -exec rm {} + +java $JAVA_OPTS -jar $executable $ags diff --git a/samples/client/petstore/java/jersey2-java8/.gitignore b/samples/client/petstore/java/jersey2-java8/.gitignore new file mode 100644 index 00000000000..a530464afa1 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/.gitignore @@ -0,0 +1,21 @@ +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# exclude jar for gradle wrapper +!gradle/wrapper/*.jar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# build files +**/target +target +.gradle +build diff --git a/samples/client/petstore/java/jersey2-java8/.swagger-codegen-ignore b/samples/client/petstore/java/jersey2-java8/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/java/jersey2-java8/.travis.yml b/samples/client/petstore/java/jersey2-java8/.travis.yml new file mode 100644 index 00000000000..33e79472abd --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/.travis.yml @@ -0,0 +1,29 @@ +# +# Generated by: https://github.com/swagger-api/swagger-codegen.git +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +language: java +jdk: + - oraclejdk8 + - oraclejdk7 +before_install: + # ensure gradlew has proper permission + - chmod a+x ./gradlew +script: + # test using maven + - mvn test + # uncomment below to test using gradle + # - gradle test + # uncomment below to test using sbt + # - sbt test diff --git a/samples/client/petstore/java/jersey2-java8/LICENSE b/samples/client/petstore/java/jersey2-java8/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore/java/jersey2-java8/README.md b/samples/client/petstore/java/jersey2-java8/README.md new file mode 100644 index 00000000000..579d98c8224 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/README.md @@ -0,0 +1,177 @@ +# swagger-petstore-jersey2 + +## Requirements + +Building the API client library requires [Maven](https://maven.apache.org/) to be installed. + +## Installation + +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. + +### Maven users + +Add this dependency to your project's POM: + +```xml + + io.swagger + swagger-petstore-jersey2 + 1.0.0 + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy +compile "io.swagger:swagger-petstore-jersey2:1.0.0" +``` + +### Others + +At first generate the JAR by executing: + + mvn package + +Then manually install the following JARs: + +* target/swagger-petstore-jersey2-1.0.0.jar +* target/lib/*.jar + +## Getting Started + +Please follow the [installation](#installation) instruction and execute the following Java code: + +```java + +import io.swagger.client.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; +import io.swagger.client.api.FakeApi; + +import java.io.File; +import java.util.*; + +public class FakeApiExample { + + public static void main(String[] args) { + + FakeApi apiInstance = new FakeApi(); + BigDecimal number = new BigDecimal(); // BigDecimal | None + Double _double = 3.4D; // Double | None + String string = "string_example"; // String | None + byte[] _byte = B; // byte[] | None + Integer integer = 56; // Integer | None + Integer int32 = 56; // Integer | None + Long int64 = 789L; // Long | None + Float _float = 3.4F; // Float | None + byte[] binary = B; // byte[] | None + LocalDate date = new LocalDate(); // LocalDate | None + OffsetDateTime dateTime = new OffsetDateTime(); // OffsetDateTime | None + String password = "password_example"; // String | None + try { + apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEndpointParameters"); + e.printStackTrace(); + } + } +} + +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*FakeApi* | [**testEndpointParameters**](docs/FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**deletePet**](docs/PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByStatus**](docs/PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**findPetsByTags**](docs/PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**getPetById**](docs/PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**updatePet**](docs/PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +*PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**uploadFile**](docs/PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**getInventory**](docs/StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**getOrderById**](docs/StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**placeOrder**](docs/StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**createUser**](docs/UserApi.md#createUser) | **POST** /user | Create user +*UserApi* | [**createUsersWithArrayInput**](docs/UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**createUsersWithListInput**](docs/UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**deleteUser**](docs/UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**getUserByName**](docs/UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +*UserApi* | [**loginUser**](docs/UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +*UserApi* | [**logoutUser**](docs/UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**updateUser**](docs/UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + +## Documentation for Models + + - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) + - [Animal](docs/Animal.md) + - [AnimalFarm](docs/AnimalFarm.md) + - [ArrayTest](docs/ArrayTest.md) + - [Cat](docs/Cat.md) + - [Category](docs/Category.md) + - [Dog](docs/Dog.md) + - [EnumClass](docs/EnumClass.md) + - [EnumTest](docs/EnumTest.md) + - [FormatTest](docs/FormatTest.md) + - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) + - [Model200Response](docs/Model200Response.md) + - [ModelApiResponse](docs/ModelApiResponse.md) + - [ModelReturn](docs/ModelReturn.md) + - [Name](docs/Name.md) + - [Order](docs/Order.md) + - [Pet](docs/Pet.md) + - [ReadOnlyFirst](docs/ReadOnlyFirst.md) + - [SpecialModelName](docs/SpecialModelName.md) + - [Tag](docs/Tag.md) + - [User](docs/User.md) + + +## Documentation for Authorization + +Authentication schemes defined for the API: +### petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorizatoin URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - write:pets: modify pets in your account + - read:pets: read your pets + +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + + +## 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/jersey2-java8/build.gradle b/samples/client/petstore/java/jersey2-java8/build.gradle new file mode 100644 index 00000000000..1fa7d76afcc --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/build.gradle @@ -0,0 +1,113 @@ +apply plugin: 'idea' +apply plugin: 'eclipse' + +group = 'io.swagger' +version = '1.0.0' + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.5.+' + classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3' + } +} + +repositories { + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 23 + buildToolsVersion '23.0.2' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 23 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + // 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_8 + targetCompatibility = JavaVersion.VERSION_1_8 + + install { + repositories.mavenInstaller { + pom.artifactId = 'swagger-petstore-jersey2' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + swagger_annotations_version = "1.5.8" + jackson_version = "2.7.0" + jersey_version = "2.22.2" + junit_version = "4.12" +} + +dependencies { + compile "io.swagger:swagger-annotations:$swagger_annotations_version" + compile "org.glassfish.jersey.core:jersey-client:$jersey_version" + compile "org.glassfish.jersey.media:jersey-media-multipart:$jersey_version" + compile "org.glassfish.jersey.media:jersey-media-json-jackson:2.22.1" + 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-jsr310:$jackson_version" + compile "com.brsanthu:migbase64:2.2" + testCompile "junit:junit:$junit_version" +} diff --git a/samples/client/petstore/java/jersey2-java8/build.sbt b/samples/client/petstore/java/jersey2-java8/build.sbt new file mode 100644 index 00000000000..961083958a2 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/build.sbt @@ -0,0 +1,24 @@ +lazy val root = (project in file(".")). + settings( + organization := "io.swagger", + name := "swagger-petstore-jersey2", + version := "1.0.0", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "io.swagger" % "swagger-annotations" % "1.5.8", + "org.glassfish.jersey.core" % "jersey-client" % "2.22.2", + "org.glassfish.jersey.media" % "jersey-media-multipart" % "2.22.2", + "org.glassfish.jersey.media" % "jersey-media-json-jackson" % "2.22.1", + "com.fasterxml.jackson.core" % "jackson-core" % "2.7.0", + "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.0", + "com.fasterxml.jackson.core" % "jackson-databind" % "2.7.0", + "com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % "2.7.0", + "com.brsanthu" % "migbase64" % "2.2", + "junit" % "junit" % "4.12" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/samples/client/petstore/java/jersey2-java8/docs/AdditionalPropertiesClass.md b/samples/client/petstore/java/jersey2-java8/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..0437c4dd8cc --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/AdditionalPropertiesClass.md @@ -0,0 +1,11 @@ + +# AdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapProperty** | **Map<String, String>** | | [optional] +**mapOfMapProperty** | [**Map<String, Map<String, String>>**](Map.md) | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/Animal.md b/samples/client/petstore/java/jersey2-java8/docs/Animal.md new file mode 100644 index 00000000000..b3f325c3524 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/Animal.md @@ -0,0 +1,11 @@ + +# Animal + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/AnimalFarm.md b/samples/client/petstore/java/jersey2-java8/docs/AnimalFarm.md new file mode 100644 index 00000000000..c7c7f1ddcce --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/AnimalFarm.md @@ -0,0 +1,9 @@ + +# AnimalFarm + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/ArrayTest.md b/samples/client/petstore/java/jersey2-java8/docs/ArrayTest.md new file mode 100644 index 00000000000..9feee16427f --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/ArrayTest.md @@ -0,0 +1,12 @@ + +# ArrayTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayOfString** | **List<String>** | | [optional] +**arrayArrayOfInteger** | [**List<List<Long>>**](List.md) | | [optional] +**arrayArrayOfModel** | [**List<List<ReadOnlyFirst>>**](List.md) | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/Cat.md b/samples/client/petstore/java/jersey2-java8/docs/Cat.md new file mode 100644 index 00000000000..be6e56fa8ce --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/Cat.md @@ -0,0 +1,12 @@ + +# Cat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | [optional] +**declawed** | **Boolean** | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/Category.md b/samples/client/petstore/java/jersey2-java8/docs/Category.md new file mode 100644 index 00000000000..e2df0803278 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/Category.md @@ -0,0 +1,11 @@ + +# Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**name** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/Dog.md b/samples/client/petstore/java/jersey2-java8/docs/Dog.md new file mode 100644 index 00000000000..71a7dbe809e --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/Dog.md @@ -0,0 +1,12 @@ + +# Dog + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | [optional] +**breed** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/EnumClass.md b/samples/client/petstore/java/jersey2-java8/docs/EnumClass.md new file mode 100644 index 00000000000..c746edc3cb1 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/EnumClass.md @@ -0,0 +1,14 @@ + +# EnumClass + +## Enum + + +* `_ABC` (value: `"_abc"`) + +* `_EFG` (value: `"-efg"`) + +* `_XYZ_` (value: `"(xyz)"`) + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/EnumTest.md b/samples/client/petstore/java/jersey2-java8/docs/EnumTest.md new file mode 100644 index 00000000000..deb1951c552 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/EnumTest.md @@ -0,0 +1,36 @@ + +# EnumTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enumString** | [**EnumStringEnum**](#EnumStringEnum) | | [optional] +**enumInteger** | [**EnumIntegerEnum**](#EnumIntegerEnum) | | [optional] +**enumNumber** | [**EnumNumberEnum**](#EnumNumberEnum) | | [optional] + + + +## Enum: EnumStringEnum +Name | Value +---- | ----- +UPPER | "UPPER" +LOWER | "lower" + + + +## Enum: EnumIntegerEnum +Name | Value +---- | ----- +NUMBER_1 | 1 +NUMBER_MINUS_1 | -1 + + + +## Enum: EnumNumberEnum +Name | Value +---- | ----- +NUMBER_1_DOT_1 | 1.1 +NUMBER_MINUS_1_DOT_2 | -1.2 + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/FakeApi.md b/samples/client/petstore/java/jersey2-java8/docs/FakeApi.md new file mode 100644 index 00000000000..0e2b14922de --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/FakeApi.md @@ -0,0 +1,75 @@ +# FakeApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + + + +# **testEndpointParameters** +> testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +BigDecimal number = new BigDecimal(); // BigDecimal | None +Double _double = 3.4D; // Double | None +String string = "string_example"; // String | None +byte[] _byte = B; // byte[] | None +Integer integer = 56; // Integer | None +Integer int32 = 56; // Integer | None +Long int64 = 789L; // Long | None +Float _float = 3.4F; // Float | None +byte[] binary = B; // byte[] | None +LocalDate date = new LocalDate(); // LocalDate | None +OffsetDateTime dateTime = new OffsetDateTime(); // OffsetDateTime | None +String password = "password_example"; // String | None +try { + apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEndpointParameters"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **number** | **BigDecimal**| None | + **_double** | **Double**| None | + **string** | **String**| None | + **_byte** | **byte[]**| None | + **integer** | **Integer**| None | [optional] + **int32** | **Integer**| None | [optional] + **int64** | **Long**| None | [optional] + **_float** | **Float**| None | [optional] + **binary** | **byte[]**| None | [optional] + **date** | **LocalDate**| None | [optional] + **dateTime** | **OffsetDateTime**| None | [optional] + **password** | **String**| None | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/xml; charset=utf-8, application/json; charset=utf-8 + - **Accept**: application/xml; charset=utf-8, application/json; charset=utf-8 + diff --git a/samples/client/petstore/java/jersey2-java8/docs/FormatTest.md b/samples/client/petstore/java/jersey2-java8/docs/FormatTest.md new file mode 100644 index 00000000000..ba089e5a561 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/FormatTest.md @@ -0,0 +1,22 @@ + +# FormatTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**integer** | **Integer** | | [optional] +**int32** | **Integer** | | [optional] +**int64** | **Long** | | [optional] +**number** | [**BigDecimal**](BigDecimal.md) | | +**_float** | **Float** | | [optional] +**_double** | **Double** | | [optional] +**string** | **String** | | [optional] +**_byte** | **byte[]** | | +**binary** | **byte[]** | | [optional] +**date** | [**LocalDate**](LocalDate.md) | | +**dateTime** | [**OffsetDateTime**](OffsetDateTime.md) | | [optional] +**uuid** | **String** | | [optional] +**password** | **String** | | + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/java/jersey2-java8/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..c0bc277c74c --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,12 @@ + +# MixedPropertiesAndAdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | **String** | | [optional] +**dateTime** | [**OffsetDateTime**](OffsetDateTime.md) | | [optional] +**map** | [**Map<String, Animal>**](Animal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/Model200Response.md b/samples/client/petstore/java/jersey2-java8/docs/Model200Response.md new file mode 100644 index 00000000000..0819b88c4f4 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/Model200Response.md @@ -0,0 +1,10 @@ + +# Model200Response + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Integer** | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/ModelApiResponse.md b/samples/client/petstore/java/jersey2-java8/docs/ModelApiResponse.md new file mode 100644 index 00000000000..3eec8686cc9 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/ModelApiResponse.md @@ -0,0 +1,12 @@ + +# ModelApiResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **Integer** | | [optional] +**type** | **String** | | [optional] +**message** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/ModelReturn.md b/samples/client/petstore/java/jersey2-java8/docs/ModelReturn.md new file mode 100644 index 00000000000..a679b04953e --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/ModelReturn.md @@ -0,0 +1,10 @@ + +# ModelReturn + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_return** | **Integer** | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/Name.md b/samples/client/petstore/java/jersey2-java8/docs/Name.md new file mode 100644 index 00000000000..ce2fb4dee50 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/Name.md @@ -0,0 +1,13 @@ + +# Name + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Integer** | | +**snakeCase** | **Integer** | | [optional] +**property** | **String** | | [optional] +**_123Number** | **Integer** | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/Order.md b/samples/client/petstore/java/jersey2-java8/docs/Order.md new file mode 100644 index 00000000000..268c617d1ff --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/Order.md @@ -0,0 +1,24 @@ + +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**petId** | **Long** | | [optional] +**quantity** | **Integer** | | [optional] +**shipDate** | [**OffsetDateTime**](OffsetDateTime.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] +**complete** | **Boolean** | | [optional] + + + +## Enum: StatusEnum +Name | Value +---- | ----- +PLACED | "placed" +APPROVED | "approved" +DELIVERED | "delivered" + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/Pet.md b/samples/client/petstore/java/jersey2-java8/docs/Pet.md new file mode 100644 index 00000000000..5b63109ef92 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/Pet.md @@ -0,0 +1,24 @@ + +# Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**name** | **String** | | +**photoUrls** | **List<String>** | | +**tags** | [**List<Tag>**](Tag.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] + + + +## Enum: StatusEnum +Name | Value +---- | ----- +AVAILABLE | "available" +PENDING | "pending" +SOLD | "sold" + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/PetApi.md b/samples/client/petstore/java/jersey2-java8/docs/PetApi.md new file mode 100644 index 00000000000..e0314e20e51 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/PetApi.md @@ -0,0 +1,448 @@ +# PetApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image + + + +# **addPet** +> addPet(body) + +Add a new pet to the store + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Pet body = new Pet(); // Pet | Pet object that needs to be added to the store +try { + apiInstance.addPet(body); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#addPet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/xml, application/json + + +# **deletePet** +> deletePet(petId, apiKey) + +Deletes a pet + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | Pet id to delete +String apiKey = "apiKey_example"; // String | +try { + apiInstance.deletePet(petId, apiKey); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#deletePet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| Pet id to delete | + **apiKey** | **String**| | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **findPetsByStatus** +> List<Pet> findPetsByStatus(status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +List status = Arrays.asList("status_example"); // List | Status values that need to be considered for filter +try { + List result = apiInstance.findPetsByStatus(status); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByStatus"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **findPetsByTags** +> List<Pet> findPetsByTags(tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +List tags = Arrays.asList("tags_example"); // List | Tags to filter by +try { + List result = apiInstance.findPetsByTags(tags); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByTags"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**List<String>**](String.md)| Tags to filter by | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **getPetById** +> Pet getPetById(petId) + +Find pet by ID + +Returns a single pet + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure API key authorization: api_key +ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); +api_key.setApiKey("YOUR API KEY"); +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//api_key.setApiKeyPrefix("Token"); + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | ID of pet to return +try { + Pet result = apiInstance.getPetById(petId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#getPetById"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **updatePet** +> updatePet(body) + +Update an existing pet + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Pet body = new Pet(); // Pet | Pet object that needs to be added to the store +try { + apiInstance.updatePet(body); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/xml, application/json + + +# **updatePetWithForm** +> updatePetWithForm(petId, name, status) + +Updates a pet in the store with form data + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | ID of pet that needs to be updated +String name = "name_example"; // String | Updated name of the pet +String status = "status_example"; // String | Updated status of the pet +try { + apiInstance.updatePetWithForm(petId, name, status); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePetWithForm"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet that needs to be updated | + **name** | **String**| Updated name of the pet | [optional] + **status** | **String**| Updated status of the pet | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: application/xml, application/json + + +# **uploadFile** +> ModelApiResponse uploadFile(petId, additionalMetadata, file) + +uploads an image + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | ID of pet to update +String additionalMetadata = "additionalMetadata_example"; // String | Additional data to pass to server +File file = new File("/path/to/file.txt"); // File | file to upload +try { + ModelApiResponse result = apiInstance.uploadFile(petId, additionalMetadata, file); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#uploadFile"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to update | + **additionalMetadata** | **String**| Additional data to pass to server | [optional] + **file** | **File**| file to upload | [optional] + +### Return type + +[**ModelApiResponse**](ModelApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + diff --git a/samples/client/petstore/java/jersey2-java8/docs/ReadOnlyFirst.md b/samples/client/petstore/java/jersey2-java8/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..426b7cde95a --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/ReadOnlyFirst.md @@ -0,0 +1,11 @@ + +# ReadOnlyFirst + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] +**baz** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/SpecialModelName.md b/samples/client/petstore/java/jersey2-java8/docs/SpecialModelName.md new file mode 100644 index 00000000000..c2c6117c552 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/SpecialModelName.md @@ -0,0 +1,10 @@ + +# SpecialModelName + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**specialPropertyName** | **Long** | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/StoreApi.md b/samples/client/petstore/java/jersey2-java8/docs/StoreApi.md new file mode 100644 index 00000000000..0b30791725a --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/StoreApi.md @@ -0,0 +1,197 @@ +# StoreApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet + + + +# **deleteOrder** +> deleteOrder(orderId) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +String orderId = "orderId_example"; // String | ID of the order that needs to be deleted +try { + apiInstance.deleteOrder(orderId); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#deleteOrder"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **String**| ID of the order that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **getInventory** +> Map<String, Integer> getInventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.StoreApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure API key authorization: api_key +ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); +api_key.setApiKey("YOUR API KEY"); +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//api_key.setApiKeyPrefix("Token"); + +StoreApi apiInstance = new StoreApi(); +try { + Map result = apiInstance.getInventory(); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getInventory"); + e.printStackTrace(); +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**Map<String, Integer>**](Map.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +# **getOrderById** +> Order getOrderById(orderId) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +Long orderId = 789L; // Long | ID of pet that needs to be fetched +try { + Order result = apiInstance.getOrderById(orderId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getOrderById"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **Long**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **placeOrder** +> Order placeOrder(body) + +Place an order for a pet + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +Order body = new Order(); // Order | order placed for purchasing the pet +try { + Order result = apiInstance.placeOrder(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#placeOrder"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + diff --git a/samples/client/petstore/java/jersey2-java8/docs/Tag.md b/samples/client/petstore/java/jersey2-java8/docs/Tag.md new file mode 100644 index 00000000000..de6814b55d5 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/Tag.md @@ -0,0 +1,11 @@ + +# Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**name** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/User.md b/samples/client/petstore/java/jersey2-java8/docs/User.md new file mode 100644 index 00000000000..8b6753dd284 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/User.md @@ -0,0 +1,17 @@ + +# User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**username** | **String** | | [optional] +**firstName** | **String** | | [optional] +**lastName** | **String** | | [optional] +**email** | **String** | | [optional] +**password** | **String** | | [optional] +**phone** | **String** | | [optional] +**userStatus** | **Integer** | User Status | [optional] + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/UserApi.md b/samples/client/petstore/java/jersey2-java8/docs/UserApi.md new file mode 100644 index 00000000000..8cdc15992ee --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/UserApi.md @@ -0,0 +1,370 @@ +# UserApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createUser**](UserApi.md#createUser) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + + +# **createUser** +> createUser(body) + +Create user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +User body = new User(); // User | Created user object +try { + apiInstance.createUser(body); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md)| Created user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **createUsersWithArrayInput** +> createUsersWithArrayInput(body) + +Creates list of users with given input array + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +List body = Arrays.asList(new User()); // List | List of user object +try { + apiInstance.createUsersWithArrayInput(body); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithArrayInput"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List<User>**](User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **createUsersWithListInput** +> createUsersWithListInput(body) + +Creates list of users with given input array + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +List body = Arrays.asList(new User()); // List | List of user object +try { + apiInstance.createUsersWithListInput(body); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithListInput"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List<User>**](User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **deleteUser** +> deleteUser(username) + +Delete user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The name that needs to be deleted +try { + apiInstance.deleteUser(username); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#deleteUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **getUserByName** +> User getUserByName(username) + +Get user by user name + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The name that needs to be fetched. Use user1 for testing. +try { + User result = apiInstance.getUserByName(username); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#getUserByName"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **loginUser** +> String loginUser(username, password) + +Logs user into the system + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The user name for login +String password = "password_example"; // String | The password for login in clear text +try { + String result = apiInstance.loginUser(username, password); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#loginUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The user name for login | + **password** | **String**| The password for login in clear text | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **logoutUser** +> logoutUser() + +Logs out current logged in user session + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +try { + apiInstance.logoutUser(); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#logoutUser"); + e.printStackTrace(); +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **updateUser** +> updateUser(username, body) + +Updated user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | name that need to be deleted +User body = new User(); // User | Updated user object +try { + apiInstance.updateUser(username, body); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#updateUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| name that need to be deleted | + **body** | [**User**](User.md)| Updated user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + diff --git a/samples/client/petstore/java/jersey2-java8/git_push.sh b/samples/client/petstore/java/jersey2-java8/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/client/petstore/java/jersey2-java8/gradle.properties b/samples/client/petstore/java/jersey2-java8/gradle.properties new file mode 100644 index 00000000000..05644f0754a --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/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/jersey2-java8/gradlew b/samples/client/petstore/java/jersey2-java8/gradlew new file mode 100644 index 00000000000..9d82f789151 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/samples/client/petstore/java/jersey2-java8/gradlew.bat b/samples/client/petstore/java/jersey2-java8/gradlew.bat new file mode 100644 index 00000000000..5f192121eb4 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/java/jersey2-java8/pom.xml b/samples/client/petstore/java/jersey2-java8/pom.xml new file mode 100644 index 00000000000..d56bda6b181 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/pom.xml @@ -0,0 +1,177 @@ + + 4.0.0 + io.swagger + swagger-petstore-jersey2 + jar + swagger-petstore-jersey2 + 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.8 + 1.8 + + + + + + + io.swagger + swagger-annotations + ${swagger-core-version} + + + + + org.glassfish.jersey.core + jersey-client + ${jersey-version} + + + org.glassfish.jersey.media + jersey-media-multipart + ${jersey-version} + + + org.glassfish.jersey.media + jersey-media-json-jackson + 2.22.1 + + + + + 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-jsr310 + ${jackson-version} + + + + + com.brsanthu + migbase64 + 2.2 + + + + + junit + junit + ${junit-version} + test + + + + 1.5.8 + 2.22.2 + 2.7.0 + 1.0.0 + 4.12 + + diff --git a/samples/client/petstore/java/jersey2-java8/settings.gradle b/samples/client/petstore/java/jersey2-java8/settings.gradle new file mode 100644 index 00000000000..498d426abee --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "swagger-petstore-jersey2" \ No newline at end of file diff --git a/samples/client/petstore/java/jersey2-java8/src/main/AndroidManifest.xml b/samples/client/petstore/java/jersey2-java8/src/main/AndroidManifest.xml new file mode 100644 index 00000000000..465dcb520c4 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiClient.java new file mode 100644 index 00000000000..06f6d4d899a --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiClient.java @@ -0,0 +1,698 @@ +package io.swagger.client; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +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; + +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.client.ClientProperties; +import org.glassfish.jersey.filter.LoggingFilter; +import org.glassfish.jersey.jackson.JacksonFeature; +import org.glassfish.jersey.media.multipart.FormDataBodyPart; +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.MultiPart; +import org.glassfish.jersey.media.multipart.MultiPartFeature; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.Map.Entry; +import java.util.HashMap; +import java.util.List; +import java.util.ArrayList; +import java.util.Date; +import java.util.TimeZone; + +import java.net.URLEncoder; + +import java.io.File; +import java.io.UnsupportedEncodingException; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import io.swagger.client.auth.Authentication; +import io.swagger.client.auth.HttpBasicAuth; +import io.swagger.client.auth.ApiKeyAuth; +import io.swagger.client.auth.OAuth; + + +public class ApiClient { + private Map defaultHeaderMap = new HashMap(); + private String basePath = "http://petstore.swagger.io/v2"; + private boolean debugging = false; + private int connectionTimeout = 0; + + private Client httpClient; + private JSON json; + private String tempFolderPath = null; + + private Map authentications; + + private int statusCode; + private Map> responseHeaders; + + private DateFormat dateFormat; + + public ApiClient() { + json = new JSON(); + httpClient = buildHttpClient(debugging); + + // Use RFC3339 format for date and datetime. + // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + + // Use UTC as the default time zone. + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + + this.json.setDateFormat((DateFormat) dateFormat.clone()); + + // Set default User-Agent. + setUserAgent("Swagger-Codegen/1.0.0/java"); + + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap(); + authentications.put("petstore_auth", new OAuth()); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + /** + * Gets the JSON instance to do JSON serialization and deserialization. + */ + public JSON getJSON() { + return json; + } + + public Client getHttpClient() { + return httpClient; + } + + public ApiClient setHttpClient(Client httpClient) { + this.httpClient = httpClient; + return this; + } + + public String getBasePath() { + return basePath; + } + + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + /** + * Gets the status code of the previous request + */ + public int getStatusCode() { + return statusCode; + } + + /** + * Gets the response headers of the previous request + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + + /** + * Get authentications (key: authentication name, value: authentication). + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set access token for the first OAuth2 authentication. + */ + public void setAccessToken(String accessToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); + return; + } + } + throw new RuntimeException("No OAuth2 authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + */ + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + /** + * Check that whether debugging is enabled for this API client. + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + */ + public ApiClient setDebugging(boolean debugging) { + this.debugging = debugging; + // Rebuild HTTP Client according to the new "debugging" value. + this.httpClient = buildHttpClient(debugging); + return this; + } + + /** + * The path of temporary folder used to store downloaded files from endpoints + * with file response. The default value is null, i.e. using + * the system's default tempopary folder. + * + * @see https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createTempFile(java.lang.String,%20java.lang.String,%20java.io.File) + */ + public String getTempFolderPath() { + return tempFolderPath; + } + + public ApiClient setTempFolderPath(String tempFolderPath) { + this.tempFolderPath = tempFolderPath; + return this; + } + + /** + * Connect timeout (in milliseconds). + */ + public int getConnectTimeout() { + return connectionTimeout; + } + + /** + * Set the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link Integer#MAX_VALUE}. + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + this.connectionTimeout = connectionTimeout; + httpClient.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout); + return this; + } + + /** + * Get the date format used to parse/format date parameters. + */ + public DateFormat getDateFormat() { + return dateFormat; + } + + /** + * Set the date format used to parse/format date parameters. + */ + 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()); + return this; + } + + /** + * Parse the given string into Date object. + */ + public Date parseDate(String str) { + try { + return dateFormat.parse(str); + } catch (java.text.ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Format the given Date object into string. + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } + + /** + * 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 to {@code Pair} objects. + */ + public List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + + // create the params based on the collection format + if (collectionFormat.equals("multi")) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); + } + + return params; + } + + String delimiter = ","; + + if (collectionFormat.equals("csv")) { + delimiter = ","; + } else if (collectionFormat.equals("ssv")) { + delimiter = " "; + } else if (collectionFormat.equals("tsv")) { + delimiter = "\t"; + } else if (collectionFormat.equals("pipes")) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + + return params; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + */ + public boolean isJsonMime(String mime) { + return mime != null && mime.matches("(?i)application\\/json(;.*)?"); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } + return contentTypes[0]; + } + + /** + * Escape the given string to be used as URL query value. + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Serialize the given Java object into string entity according the given + * Content-Type (only JSON is supported for now). + */ + 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 { + // 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, GenericType returnType) throws ApiException { + // Handle file downloading. + if (returnType.equals(File.class)) { + @SuppressWarnings("unchecked") + T file = (T) downloadFileFromResponse(response); + return file; + } + + String contentType = null; + List contentTypes = response.getHeaders().get("Content-Type"); + if (contentTypes != null && !contentTypes.isEmpty()) + contentType = String.valueOf(contentTypes.get(0)); + if (contentType == null) + throw new ApiException(500, "missing Content-Type in response"); + + return response.readEntity(returnType); + } + + /** + * Download file from the given response. + * @throws ApiException If fail to read file content from response and write to disk + */ + public File downloadFileFromResponse(Response response) throws ApiException { + try { + File file = prepareDownloadFile(response); + Files.copy(response.readEntity(InputStream.class), file.toPath()); + return file; + } catch (IOException e) { + throw new ApiException(e); + } + } + + public File prepareDownloadFile(Response response) throws IOException { + String filename = null; + String contentDisposition = (String) response.getHeaders().getFirst("Content-Disposition"); + if (contentDisposition != null && !"".equals(contentDisposition)) { + // Get filename from the Content-Disposition header. + Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); + Matcher matcher = pattern.matcher(contentDisposition); + if (matcher.find()) + filename = matcher.group(1); + } + + String prefix = null; + String suffix = null; + if (filename == null) { + prefix = "download-"; + suffix = ""; + } else { + int pos = filename.lastIndexOf("."); + if (pos == -1) { + prefix = filename + "-"; + } else { + prefix = filename.substring(0, pos) + "-"; + suffix = filename.substring(pos); + } + // File.createTempFile requires the prefix to be at least three characters long + if (prefix.length() < 3) + prefix = "download-"; + } + + if (tempFolderPath == null) + return File.createTempFile(prefix, suffix); + else + return File.createTempFile(prefix, suffix, new File(tempFolderPath)); + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @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 + * @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 + * @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, GenericType returnType) throws ApiException { + updateParamsForAuth(authNames, queryParams, headerParams); + + // Not using `.target(this.basePath).path(path)` below, + // to support (constant) query string in `path`, e.g. "/posts?draft=1" + WebTarget target = httpClient.target(this.basePath + path); + + if (queryParams != null) { + for (Pair queryParam : queryParams) { + if (queryParam.getValue() != null) { + target = target.queryParam(queryParam.getName(), queryParam.getValue()); + } + } + } + + Invocation.Builder invocationBuilder = target.request().accept(accept); + + for (String key : headerParams.keySet()) { + String value = headerParams.get(key); + if (value != null) { + invocationBuilder = invocationBuilder.header(key, value); + } + } + + for (String key : defaultHeaderMap.keySet()) { + if (!headerParams.containsKey(key)) { + String value = defaultHeaderMap.get(key); + if (value != null) { + invocationBuilder = invocationBuilder.header(key, value); + } + } + } + + Entity entity = serialize(body, formParams, contentType); + + Response response = null; + + if ("GET".equals(method)) { + response = invocationBuilder.get(); + } else if ("POST".equals(method)) { + response = invocationBuilder.post(entity); + } else if ("PUT".equals(method)) { + response = invocationBuilder.put(entity); + } else if ("DELETE".equals(method)) { + response = invocationBuilder.delete(); + } else { + throw new ApiException(500, "unknown method type " + method); + } + + statusCode = response.getStatusInfo().getStatusCode(); + responseHeaders = buildResponseHeaders(response); + + if (response.getStatus() == Status.NO_CONTENT.getStatusCode()) { + return null; + } else if (response.getStatusInfo().getFamily().equals(Status.Family.SUCCESSFUL)) { + if (returnType == null) + return null; + else + return deserialize(response, returnType); + } else { + String message = "error"; + String respBody = null; + if (response.hasEntity()) { + try { + respBody = String.valueOf(response.readEntity(String.class)); + message = respBody; + } catch (RuntimeException e) { + // e.printStackTrace(); + } + } + throw new ApiException( + response.getStatus(), + message, + buildResponseHeaders(response), + respBody); + } + } + + /** + * Build the Client used to make HTTP requests. + */ + private Client buildHttpClient(boolean debugging) { + final ClientConfig clientConfig = new ClientConfig(); + clientConfig.register(MultiPartFeature.class); + clientConfig.register(json); + clientConfig.register(JacksonFeature.class); + if (debugging) { + clientConfig.register(LoggingFilter.class); + } + return ClientBuilder.newClient(clientConfig); + } + + private Map> buildResponseHeaders(Response response) { + Map> responseHeaders = new HashMap>(); + for (Entry> entry: response.getHeaders().entrySet()) { + List values = entry.getValue(); + List headers = new ArrayList(); + for (Object o : values) { + headers.add(String.valueOf(o)); + } + responseHeaders.put(entry.getKey(), headers); + } + return responseHeaders; + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + */ + private void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); + auth.applyToParams(queryParams, headerParams); + } + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiException.java new file mode 100644 index 00000000000..600bb507f09 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiException.java @@ -0,0 +1,103 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import java.util.Map; +import java.util.List; + + +public class ApiException extends Exception { + private int code = 0; + private Map> responseHeaders = null; + private String responseBody = null; + + public ApiException() {} + + public ApiException(Throwable throwable) { + super(throwable); + } + + public ApiException(String message) { + super(message); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } + + public ApiException(int code, Map> responseHeaders, String responseBody) { + this((String) null, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(int code, String message) { + super(message); + this.code = code; + } + + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this(code, message); + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + /** + * Get the HTTP status code. + * + * @return HTTP status code + */ + public int getCode() { + return code; + } + + /** + * Get the HTTP response headers. + * + * @return A map of list of string + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + + /** + * Get the HTTP response body. + * + * @return Response body in the form of string + */ + public String getResponseBody() { + return responseBody; + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/Configuration.java new file mode 100644 index 00000000000..cbdadd6262d --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/Configuration.java @@ -0,0 +1,51 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + + +public class Configuration { + private static ApiClient defaultApiClient = new ApiClient(); + + /** + * Get the default API client, which would be used when creating API + * instances without providing an API client. + * + * @return Default API client + */ + public static ApiClient getDefaultApiClient() { + return defaultApiClient; + } + + /** + * Set the default API client, which would be used when creating API + * instances without providing an API client. + * + * @param apiClient API client + */ + public static void setDefaultApiClient(ApiClient apiClient) { + defaultApiClient = apiClient; + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/JSON.java new file mode 100644 index 00000000000..d4b7137c64a --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/JSON.java @@ -0,0 +1,36 @@ +package io.swagger.client; + +import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.datatype.jsr310.*; + +import java.text.DateFormat; + +import javax.ws.rs.ext.ContextResolver; + + +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 JSR310Module()); + } + + /** + * 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/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/Pair.java new file mode 100644 index 00000000000..4b44c415812 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/Pair.java @@ -0,0 +1,64 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + + +public class Pair { + private String name = ""; + private String value = ""; + + public Pair (String name, String value) { + setName(name); + setValue(value); + } + + private void setName(String name) { + if (!isValidString(name)) return; + + this.name = name; + } + + private void setValue(String value) { + if (!isValidString(value)) return; + + this.value = value; + } + + public String getName() { + return this.name; + } + + public String getValue() { + return this.value; + } + + private boolean isValidString(String arg) { + if (arg == null) return false; + if (arg.trim().isEmpty()) return false; + + return true; + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/StringUtil.java new file mode 100644 index 00000000000..03c6c81e434 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/StringUtil.java @@ -0,0 +1,67 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + + +public class 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(); + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/FakeApi.java new file mode 100644 index 00000000000..7738d3ac259 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/FakeApi.java @@ -0,0 +1,129 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.ApiClient; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; + +import javax.ws.rs.core.GenericType; + +import java.time.OffsetDateTime; +import java.time.LocalDate; +import java.math.BigDecimal; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +public class FakeApi { + private ApiClient apiClient; + + public FakeApi() { + this(Configuration.getDefaultApiClient()); + } + + public FakeApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param string None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @throws ApiException if fails to make API call + */ + public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'number' is set + if (number == null) { + throw new ApiException(400, "Missing the required parameter 'number' when calling testEndpointParameters"); + } + + // verify the required parameter '_double' is set + if (_double == null) { + throw new ApiException(400, "Missing the required parameter '_double' when calling testEndpointParameters"); + } + + // verify the required parameter 'string' is set + if (string == null) { + throw new ApiException(400, "Missing the required parameter 'string' when calling testEndpointParameters"); + } + + // verify the required parameter '_byte' is set + if (_byte == null) { + throw new ApiException(400, "Missing the required parameter '_byte' when calling testEndpointParameters"); + } + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + if (integer != null) + localVarFormParams.put("integer", integer); +if (int32 != null) + localVarFormParams.put("int32", int32); +if (int64 != null) + localVarFormParams.put("int64", int64); +if (number != null) + localVarFormParams.put("number", number); +if (_float != null) + localVarFormParams.put("float", _float); +if (_double != null) + localVarFormParams.put("double", _double); +if (string != null) + localVarFormParams.put("string", string); +if (_byte != null) + localVarFormParams.put("byte", _byte); +if (binary != null) + localVarFormParams.put("binary", binary); +if (date != null) + localVarFormParams.put("date", date); +if (dateTime != null) + localVarFormParams.put("dateTime", dateTime); +if (password != null) + localVarFormParams.put("password", password); + + final String[] localVarAccepts = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/PetApi.java new file mode 100644 index 00000000000..ad66598406d --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/PetApi.java @@ -0,0 +1,384 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.ApiClient; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; + +import javax.ws.rs.core.GenericType; + +import io.swagger.client.model.Pet; +import io.swagger.client.model.ModelApiResponse; +import java.io.File; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +public class PetApi { + private ApiClient apiClient; + + public PetApi() { + this(Configuration.getDefaultApiClient()); + } + + public PetApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException if fails to make API call + */ + public void addPet(Pet body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling addPet"); + } + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @throws ApiException if fails to make API call + */ + public void deletePet(Long petId, String apiKey) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling deletePet"); + } + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + if (apiKey != null) + localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + + apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return List + * @throws ApiException if fails to make API call + */ + public List findPetsByStatus(List status) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'status' is set + if (status == null) { + throw new ApiException(400, "Missing the required parameter 'status' when calling findPetsByStatus"); + } + + // create path and map variables + String localVarPath = "/pet/findByStatus".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "status", status)); + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + GenericType> localVarReturnType = new GenericType>() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return List + * @throws ApiException if fails to make API call + */ + public List findPetsByTags(List tags) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'tags' is set + if (tags == null) { + throw new ApiException(400, "Missing the required parameter 'tags' when calling findPetsByTags"); + } + + // create path and map variables + String localVarPath = "/pet/findByTags".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "tags", tags)); + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + GenericType> localVarReturnType = new GenericType>() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return Pet + * @throws ApiException if fails to make API call + */ + public Pet getPetById(Long petId) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling getPetById"); + } + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "api_key" }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException if fails to make API call + */ + public void updatePet(Pet body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling updatePet"); + } + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + + apiClient.invokeAPI(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @throws ApiException if fails to make API call + */ + public void updatePetWithForm(Long petId, String name, String status) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling updatePetWithForm"); + } + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + if (name != null) + localVarFormParams.put("name", name); +if (status != null) + localVarFormParams.put("status", status); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/x-www-form-urlencoded" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ModelApiResponse + * @throws ApiException if fails to make API call + */ + public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling uploadFile"); + } + + // create path and map variables + String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + if (additionalMetadata != null) + localVarFormParams.put("additionalMetadata", additionalMetadata); +if (file != null) + localVarFormParams.put("file", file); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/StoreApi.java new file mode 100644 index 00000000000..c0c9a166ad7 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/StoreApi.java @@ -0,0 +1,196 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.ApiClient; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; + +import javax.ws.rs.core.GenericType; + +import io.swagger.client.model.Order; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +public class StoreApi { + private ApiClient apiClient; + + public StoreApi() { + this(Configuration.getDefaultApiClient()); + } + + public StoreApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @throws ApiException if fails to make API call + */ + public void deleteOrder(String orderId) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder"); + } + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return Map + * @throws ApiException if fails to make API call + */ + public Map getInventory() throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/store/inventory".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "api_key" }; + + GenericType> localVarReturnType = new GenericType>() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @return Order + * @throws ApiException if fails to make API call + */ + public Order getOrderById(Long orderId) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById"); + } + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet (required) + * @return Order + * @throws ApiException if fails to make API call + */ + public Order placeOrder(Order body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling placeOrder"); + } + + // create path and map variables + String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/UserApi.java new file mode 100644 index 00000000000..7602f4e2ba9 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/UserApi.java @@ -0,0 +1,370 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.ApiClient; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; + +import javax.ws.rs.core.GenericType; + +import io.swagger.client.model.User; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +public class UserApi { + private ApiClient apiClient; + + public UserApi() { + this(Configuration.getDefaultApiClient()); + } + + public UserApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object (required) + * @throws ApiException if fails to make API call + */ + public void createUser(User body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling createUser"); + } + + // create path and map variables + String localVarPath = "/user".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException if fails to make API call + */ + public void createUsersWithArrayInput(List body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling createUsersWithArrayInput"); + } + + // create path and map variables + String localVarPath = "/user/createWithArray".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException if fails to make API call + */ + public void createUsersWithListInput(List body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling createUsersWithListInput"); + } + + // create path and map variables + String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @throws ApiException if fails to make API call + */ + public void deleteUser(String username) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling deleteUser"); + } + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return User + * @throws ApiException if fails to make API call + */ + public User getUserByName(String username) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling getUserByName"); + } + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return String + * @throws ApiException if fails to make API call + */ + public String loginUser(String username, String password) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling loginUser"); + } + + // verify the required parameter 'password' is set + if (password == null) { + throw new ApiException(400, "Missing the required parameter 'password' when calling loginUser"); + } + + // create path and map variables + String localVarPath = "/user/login".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("", "username", username)); + localVarQueryParams.addAll(apiClient.parameterToPairs("", "password", password)); + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Logs out current logged in user session + * + * @throws ApiException if fails to make API call + */ + public void logoutUser() throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/user/logout".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @throws ApiException if fails to make API call + */ + public void updateUser(String username, User body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser"); + } + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling updateUser"); + } + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/ApiKeyAuth.java new file mode 100644 index 00000000000..6ba15566b60 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -0,0 +1,87 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + + +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + if (apiKey == null) { + return; + } + String value; + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if (location == "query") { + queryParams.add(new Pair(paramName, value)); + } else if (location == "header") { + headerParams.put(paramName, value); + } + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/Authentication.java new file mode 100644 index 00000000000..a063a6998b5 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/Authentication.java @@ -0,0 +1,41 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + +public interface Authentication { + /** + * Apply authentication settings to header and query params. + * + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + */ + void applyToParams(List queryParams, Map headerParams); +} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/HttpBasicAuth.java new file mode 100644 index 00000000000..5895370e4d4 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -0,0 +1,70 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import com.migcomponents.migbase64.Base64; + +import java.util.Map; +import java.util.List; + +import java.io.UnsupportedEncodingException; + + +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + if (username == null && password == null) { + return; + } + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + try { + headerParams.put("Authorization", "Basic " + Base64.encodeToString(str.getBytes("UTF-8"), false)); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/OAuth.java new file mode 100644 index 00000000000..8802ebc92c8 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/OAuth.java @@ -0,0 +1,51 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + + +public class OAuth implements Authentication { + private String accessToken; + + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + if (accessToken != null) { + headerParams.put("Authorization", "Bearer " + accessToken); + } + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/OAuthFlow.java new file mode 100644 index 00000000000..ec1f942b0f2 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -0,0 +1,30 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.auth; + +public enum OAuthFlow { + accessCode, implicit, password, application +} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..ccaba7709c4 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -0,0 +1,97 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +/** + * AdditionalPropertiesClass + */ + +public class AdditionalPropertiesClass { + + private Map mapProperty = new HashMap(); + private Map> mapOfMapProperty = new HashMap>(); + + + /** + **/ + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("map_property") + public Map getMapProperty() { + return mapProperty; + } + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + + /** + **/ + public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("map_of_map_property") + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; + return Objects.equals(this.mapProperty, additionalPropertiesClass.mapProperty) && + Objects.equals(this.mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); + } + + @Override + public int hashCode() { + return Objects.hash(mapProperty, mapOfMapProperty); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Animal.java new file mode 100644 index 00000000000..25c7d3e421c --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Animal.java @@ -0,0 +1,94 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +/** + * Animal + */ + +public class Animal { + + private String className = null; + private String color = "red"; + + + /** + **/ + public Animal className(String className) { + this.className = className; + return this; + } + + @ApiModelProperty(example = "null", required = true, value = "") + @JsonProperty("className") + public String getClassName() { + return className; + } + public void setClassName(String className) { + this.className = className; + } + + + /** + **/ + public Animal color(String color) { + this.color = color; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("color") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Animal animal = (Animal) o; + return Objects.equals(this.className, animal.className) && + Objects.equals(this.color, animal.color); + } + + @Override + public int hashCode() { + return Objects.hash(className, color); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Animal {\n"); + + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AnimalFarm.java new file mode 100644 index 00000000000..647e3a893e1 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -0,0 +1,54 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import io.swagger.client.model.Animal; +import java.util.ArrayList; +import java.util.List; + + +/** + * AnimalFarm + */ + +public class AnimalFarm extends ArrayList { + + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + return true; + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayTest.java new file mode 100644 index 00000000000..6c1eb23d8d0 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayTest.java @@ -0,0 +1,116 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.ArrayList; +import java.util.List; + + +/** + * ArrayTest + */ + +public class ArrayTest { + + private List arrayOfString = new ArrayList(); + private List> arrayArrayOfInteger = new ArrayList>(); + private List> arrayArrayOfModel = new ArrayList>(); + + + /** + **/ + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("array_of_string") + public List getArrayOfString() { + return arrayOfString; + } + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + + /** + **/ + public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("array_array_of_integer") + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + + /** + **/ + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("array_array_of_model") + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayTest arrayTest = (ArrayTest) o; + return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && + Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); + } + + @Override + public int hashCode() { + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Cat.java new file mode 100644 index 00000000000..5ef9e23bd96 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Cat.java @@ -0,0 +1,116 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Animal; + + +/** + * Cat + */ + +public class Cat extends Animal { + + private String className = null; + private String color = "red"; + private Boolean declawed = null; + + + /** + **/ + public Cat className(String className) { + this.className = className; + return this; + } + + @ApiModelProperty(example = "null", required = true, value = "") + @JsonProperty("className") + public String getClassName() { + return className; + } + public void setClassName(String className) { + this.className = className; + } + + + /** + **/ + public Cat color(String color) { + this.color = color; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("color") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + + + /** + **/ + public Cat declawed(Boolean declawed) { + this.declawed = declawed; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("declawed") + public Boolean getDeclawed() { + return declawed; + } + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Cat cat = (Cat) o; + return Objects.equals(this.className, cat.className) && + Objects.equals(this.color, cat.color) && + Objects.equals(this.declawed, cat.declawed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(className, color, declawed, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Cat {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Category.java new file mode 100644 index 00000000000..c6cb703a89e --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Category.java @@ -0,0 +1,94 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +/** + * Category + */ + +public class Category { + + private Long id = null; + private String name = null; + + + /** + **/ + public Category id(Long id) { + this.id = id; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + public Category name(String name) { + this.name = name; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Dog.java new file mode 100644 index 00000000000..4b3cc947cc5 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Dog.java @@ -0,0 +1,116 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Animal; + + +/** + * Dog + */ + +public class Dog extends Animal { + + private String className = null; + private String color = "red"; + private String breed = null; + + + /** + **/ + public Dog className(String className) { + this.className = className; + return this; + } + + @ApiModelProperty(example = "null", required = true, value = "") + @JsonProperty("className") + public String getClassName() { + return className; + } + public void setClassName(String className) { + this.className = className; + } + + + /** + **/ + public Dog color(String color) { + this.color = color; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("color") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + + + /** + **/ + public Dog breed(String breed) { + this.breed = breed; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("breed") + public String getBreed() { + return breed; + } + public void setBreed(String breed) { + this.breed = breed; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Dog dog = (Dog) o; + return Objects.equals(this.className, dog.className) && + Objects.equals(this.color, dog.color) && + Objects.equals(this.breed, dog.breed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(className, color, breed, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Dog {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumClass.java new file mode 100644 index 00000000000..42434e297ff --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumClass.java @@ -0,0 +1,28 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonValue; + + +/** + * Gets or Sets EnumClass + */ +public enum EnumClass { + _ABC("_abc"), + _EFG("-efg"), + _XYZ_("(xyz)"); + + private String value; + + EnumClass(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } +} + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumTest.java new file mode 100644 index 00000000000..1c8657fd3ec --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumTest.java @@ -0,0 +1,178 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +/** + * EnumTest + */ + +public class EnumTest { + + + /** + * Gets or Sets enumString + */ + public enum EnumStringEnum { + UPPER("UPPER"), + LOWER("lower"); + + private String value; + + EnumStringEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + } + + private EnumStringEnum enumString = null; + + /** + * Gets or Sets enumInteger + */ + public enum EnumIntegerEnum { + NUMBER_1(1), + NUMBER_MINUS_1(-1); + + private Integer value; + + EnumIntegerEnum(Integer value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + } + + private EnumIntegerEnum enumInteger = null; + + /** + * Gets or Sets enumNumber + */ + public enum EnumNumberEnum { + NUMBER_1_DOT_1(1.1), + NUMBER_MINUS_1_DOT_2(-1.2); + + private Double value; + + EnumNumberEnum(Double value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + } + + private EnumNumberEnum enumNumber = null; + + + /** + **/ + public EnumTest enumString(EnumStringEnum enumString) { + this.enumString = enumString; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("enum_string") + public EnumStringEnum getEnumString() { + return enumString; + } + public void setEnumString(EnumStringEnum enumString) { + this.enumString = enumString; + } + + + /** + **/ + public EnumTest enumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("enum_integer") + public EnumIntegerEnum getEnumInteger() { + return enumInteger; + } + public void setEnumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + } + + + /** + **/ + public EnumTest enumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("enum_number") + public EnumNumberEnum getEnumNumber() { + return enumNumber; + } + public void setEnumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumTest enumTest = (EnumTest) o; + return Objects.equals(this.enumString, enumTest.enumString) && + Objects.equals(this.enumInteger, enumTest.enumInteger) && + Objects.equals(this.enumNumber, enumTest.enumNumber); + } + + @Override + public int hashCode() { + return Objects.hash(enumString, enumInteger, enumNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/FormatTest.java new file mode 100644 index 00000000000..fce146a9b6a --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/FormatTest.java @@ -0,0 +1,327 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.OffsetDateTime; + + +/** + * FormatTest + */ + +public class FormatTest { + + private Integer integer = null; + private Integer int32 = null; + private Long int64 = null; + private BigDecimal number = null; + private Float _float = null; + private Double _double = null; + private String string = null; + private byte[] _byte = null; + private byte[] binary = null; + private LocalDate date = null; + private OffsetDateTime dateTime = null; + private String uuid = null; + private String password = null; + + + /** + * minimum: 10.0 + * maximum: 100.0 + **/ + public FormatTest integer(Integer integer) { + this.integer = integer; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("integer") + public Integer getInteger() { + return integer; + } + public void setInteger(Integer integer) { + this.integer = integer; + } + + + /** + * minimum: 20.0 + * maximum: 200.0 + **/ + public FormatTest int32(Integer int32) { + this.int32 = int32; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("int32") + public Integer getInt32() { + return int32; + } + public void setInt32(Integer int32) { + this.int32 = int32; + } + + + /** + **/ + public FormatTest int64(Long int64) { + this.int64 = int64; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("int64") + public Long getInt64() { + return int64; + } + public void setInt64(Long int64) { + this.int64 = int64; + } + + + /** + * minimum: 32.1 + * maximum: 543.2 + **/ + public FormatTest number(BigDecimal number) { + this.number = number; + return this; + } + + @ApiModelProperty(example = "null", required = true, value = "") + @JsonProperty("number") + public BigDecimal getNumber() { + return number; + } + public void setNumber(BigDecimal number) { + this.number = number; + } + + + /** + * minimum: 54.3 + * maximum: 987.6 + **/ + public FormatTest _float(Float _float) { + this._float = _float; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("float") + public Float getFloat() { + return _float; + } + public void setFloat(Float _float) { + this._float = _float; + } + + + /** + * minimum: 67.8 + * maximum: 123.4 + **/ + public FormatTest _double(Double _double) { + this._double = _double; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("double") + public Double getDouble() { + return _double; + } + public void setDouble(Double _double) { + this._double = _double; + } + + + /** + **/ + public FormatTest string(String string) { + this.string = string; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("string") + public String getString() { + return string; + } + public void setString(String string) { + this.string = string; + } + + + /** + **/ + public FormatTest _byte(byte[] _byte) { + this._byte = _byte; + return this; + } + + @ApiModelProperty(example = "null", required = true, value = "") + @JsonProperty("byte") + public byte[] getByte() { + return _byte; + } + public void setByte(byte[] _byte) { + this._byte = _byte; + } + + + /** + **/ + public FormatTest binary(byte[] binary) { + this.binary = binary; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("binary") + public byte[] getBinary() { + return binary; + } + public void setBinary(byte[] binary) { + this.binary = binary; + } + + + /** + **/ + public FormatTest date(LocalDate date) { + this.date = date; + return this; + } + + @ApiModelProperty(example = "null", required = true, value = "") + @JsonProperty("date") + public LocalDate getDate() { + return date; + } + public void setDate(LocalDate date) { + this.date = date; + } + + + /** + **/ + public FormatTest dateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("dateTime") + public OffsetDateTime getDateTime() { + return dateTime; + } + public void setDateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + } + + + /** + **/ + public FormatTest uuid(String uuid) { + this.uuid = uuid; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("uuid") + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + + + /** + **/ + public FormatTest password(String password) { + this.password = password; + return this; + } + + @ApiModelProperty(example = "null", required = true, value = "") + @JsonProperty("password") + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + FormatTest formatTest = (FormatTest) o; + return Objects.equals(this.integer, formatTest.integer) && + Objects.equals(this.int32, formatTest.int32) && + Objects.equals(this.int64, formatTest.int64) && + Objects.equals(this.number, formatTest.number) && + Objects.equals(this._float, formatTest._float) && + Objects.equals(this._double, formatTest._double) && + Objects.equals(this.string, formatTest.string) && + Objects.equals(this._byte, formatTest._byte) && + Objects.equals(this.binary, formatTest.binary) && + Objects.equals(this.date, formatTest.date) && + Objects.equals(this.dateTime, formatTest.dateTime) && + Objects.equals(this.uuid, formatTest.uuid) && + Objects.equals(this.password, formatTest.password); + } + + @Override + public int hashCode() { + return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, uuid, password); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FormatTest {\n"); + + sb.append(" integer: ").append(toIndentedString(integer)).append("\n"); + sb.append(" int32: ").append(toIndentedString(int32)).append("\n"); + sb.append(" int64: ").append(toIndentedString(int64)).append("\n"); + sb.append(" number: ").append(toIndentedString(number)).append("\n"); + sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); + sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); + sb.append(" string: ").append(toIndentedString(string)).append("\n"); + sb.append(" _byte: ").append(toIndentedString(_byte)).append("\n"); + sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); + sb.append(" date: ").append(toIndentedString(date)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..5227df8a692 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,119 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Animal; +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +/** + * MixedPropertiesAndAdditionalPropertiesClass + */ + +public class MixedPropertiesAndAdditionalPropertiesClass { + + private String uuid = null; + private OffsetDateTime dateTime = null; + private Map map = new HashMap(); + + + /** + **/ + public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { + this.uuid = uuid; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("uuid") + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + + + /** + **/ + public MixedPropertiesAndAdditionalPropertiesClass dateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("dateTime") + public OffsetDateTime getDateTime() { + return dateTime; + } + public void setDateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + } + + + /** + **/ + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + this.map = map; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("map") + public Map getMap() { + return map; + } + public void setMap(Map map) { + this.map = map; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; + return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(this.dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(this.map, mixedPropertiesAndAdditionalPropertiesClass.map); + } + + @Override + public int hashCode() { + return Objects.hash(uuid, dateTime, map); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Model200Response.java new file mode 100644 index 00000000000..b2809525c7f --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Model200Response.java @@ -0,0 +1,75 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +/** + * Model for testing model name starting with number + */ +@ApiModel(description = "Model for testing model name starting with number") + +public class Model200Response { + + private Integer name = null; + + + /** + **/ + public Model200Response name(Integer name) { + this.name = name; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("name") + public Integer getName() { + return name; + } + public void setName(Integer name) { + this.name = name; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Model200Response _200Response = (Model200Response) o; + return Objects.equals(this.name, _200Response.name); + } + + @Override + public int hashCode() { + return Objects.hash(name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelApiResponse.java new file mode 100644 index 00000000000..32fb86dd323 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -0,0 +1,114 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +/** + * ModelApiResponse + */ + +public class ModelApiResponse { + + private Integer code = null; + private String type = null; + private String message = null; + + + /** + **/ + public ModelApiResponse code(Integer code) { + this.code = code; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("code") + public Integer getCode() { + return code; + } + public void setCode(Integer code) { + this.code = code; + } + + + /** + **/ + public ModelApiResponse type(String type) { + this.type = type; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("type") + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + + + /** + **/ + public ModelApiResponse message(String message) { + this.message = message; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("message") + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelReturn.java new file mode 100644 index 00000000000..a076d16f964 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelReturn.java @@ -0,0 +1,75 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +/** + * Model for testing reserved words + */ +@ApiModel(description = "Model for testing reserved words") + +public class ModelReturn { + + private Integer _return = null; + + + /** + **/ + public ModelReturn _return(Integer _return) { + this._return = _return; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("return") + public Integer getReturn() { + return _return; + } + public void setReturn(Integer _return) { + this._return = _return; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelReturn _return = (ModelReturn) o; + return Objects.equals(this._return, _return._return); + } + + @Override + public int hashCode() { + return Objects.hash(_return); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelReturn {\n"); + + sb.append(" _return: ").append(toIndentedString(_return)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Name.java new file mode 100644 index 00000000000..1ba2cc5e4a3 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Name.java @@ -0,0 +1,115 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +/** + * Model for testing model name same as property name + */ +@ApiModel(description = "Model for testing model name same as property name") + +public class Name { + + private Integer name = null; + private Integer snakeCase = null; + private String property = null; + private Integer _123Number = null; + + + /** + **/ + public Name name(Integer name) { + this.name = name; + return this; + } + + @ApiModelProperty(example = "null", required = true, value = "") + @JsonProperty("name") + public Integer getName() { + return name; + } + public void setName(Integer name) { + this.name = name; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("snake_case") + public Integer getSnakeCase() { + return snakeCase; + } + + + /** + **/ + public Name property(String property) { + this.property = property; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("property") + public String getProperty() { + return property; + } + public void setProperty(String property) { + this.property = property; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("123Number") + public Integer get123Number() { + return _123Number; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Name name = (Name) o; + return Objects.equals(this.name, name.name) && + Objects.equals(this.snakeCase, name.snakeCase) && + Objects.equals(this.property, name.property) && + Objects.equals(this._123Number, name._123Number); + } + + @Override + public int hashCode() { + return Objects.hash(name, snakeCase, property, _123Number); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Name {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); + sb.append(" property: ").append(toIndentedString(property)).append("\n"); + sb.append(" _123Number: ").append(toIndentedString(_123Number)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Order.java new file mode 100644 index 00000000000..132e0494f17 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Order.java @@ -0,0 +1,199 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.time.OffsetDateTime; + + +/** + * Order + */ + +public class Order { + + private Long id = null; + private Long petId = null; + private Integer quantity = null; + private OffsetDateTime shipDate = null; + + /** + * Order Status + */ + public enum StatusEnum { + PLACED("placed"), + APPROVED("approved"), + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + } + + private StatusEnum status = null; + private Boolean complete = false; + + + /** + **/ + public Order id(Long id) { + this.id = id; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + public Order petId(Long petId) { + this.petId = petId; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("petId") + public Long getPetId() { + return petId; + } + public void setPetId(Long petId) { + this.petId = petId; + } + + + /** + **/ + public Order quantity(Integer quantity) { + this.quantity = quantity; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("quantity") + public Integer getQuantity() { + return quantity; + } + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + + /** + **/ + public Order shipDate(OffsetDateTime shipDate) { + this.shipDate = shipDate; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("shipDate") + public OffsetDateTime getShipDate() { + return shipDate; + } + public void setShipDate(OffsetDateTime shipDate) { + this.shipDate = shipDate; + } + + + /** + * Order Status + **/ + public Order status(StatusEnum status) { + this.status = status; + return this; + } + + @ApiModelProperty(example = "null", value = "Order Status") + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + /** + **/ + public Order complete(Boolean complete) { + this.complete = complete; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("complete") + public Boolean getComplete() { + return complete; + } + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Pet.java new file mode 100644 index 00000000000..da8b76ad024 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Pet.java @@ -0,0 +1,202 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Category; +import io.swagger.client.model.Tag; +import java.util.ArrayList; +import java.util.List; + + +/** + * Pet + */ + +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(); + + /** + * pet status in the store + */ + public enum StatusEnum { + AVAILABLE("available"), + PENDING("pending"), + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + } + + private StatusEnum status = null; + + + /** + **/ + public Pet id(Long id) { + this.id = id; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + public Pet category(Category category) { + this.category = category; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("category") + public Category getCategory() { + return category; + } + public void setCategory(Category category) { + this.category = category; + } + + + /** + **/ + public Pet name(String name) { + this.name = name; + return this; + } + + @ApiModelProperty(example = "doggie", required = true, value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + /** + **/ + public Pet photoUrls(List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + @ApiModelProperty(example = "null", required = true, value = "") + @JsonProperty("photoUrls") + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + + /** + **/ + public Pet tags(List tags) { + this.tags = tags; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("tags") + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + + + /** + * pet status in the store + **/ + public Pet status(StatusEnum status) { + this.status = status; + return this; + } + + @ApiModelProperty(example = "null", 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(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..fdc3587df0e --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -0,0 +1,84 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +/** + * ReadOnlyFirst + */ + +public class ReadOnlyFirst { + + private String bar = null; + private String baz = null; + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("bar") + public String getBar() { + return bar; + } + + + /** + **/ + public ReadOnlyFirst baz(String baz) { + this.baz = baz; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("baz") + public String getBaz() { + return baz; + } + public void setBaz(String baz) { + this.baz = baz; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; + return Objects.equals(this.bar, readOnlyFirst.bar) && + Objects.equals(this.baz, readOnlyFirst.baz); + } + + @Override + public int hashCode() { + return Objects.hash(bar, baz); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/SpecialModelName.java new file mode 100644 index 00000000000..24e57756cb2 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -0,0 +1,74 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +/** + * SpecialModelName + */ + +public class SpecialModelName { + + private Long specialPropertyName = null; + + + /** + **/ + public SpecialModelName specialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("$special[property.name]") + public Long getSpecialPropertyName() { + return specialPropertyName; + } + public void setSpecialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SpecialModelName specialModelName = (SpecialModelName) o; + return Objects.equals(this.specialPropertyName, specialModelName.specialPropertyName); + } + + @Override + public int hashCode() { + return Objects.hash(specialPropertyName); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SpecialModelName {\n"); + + sb.append(" specialPropertyName: ").append(toIndentedString(specialPropertyName)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Tag.java new file mode 100644 index 00000000000..9d3bdd8cb9e --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Tag.java @@ -0,0 +1,94 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +/** + * Tag + */ + +public class Tag { + + private Long id = null; + private String name = null; + + + /** + **/ + public Tag id(Long id) { + this.id = id; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + public Tag name(String name) { + this.name = name; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/User.java new file mode 100644 index 00000000000..f23553660de --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/User.java @@ -0,0 +1,215 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +/** + * User + */ + +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; + + + /** + **/ + public User id(Long id) { + this.id = id; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + public User username(String username) { + this.username = username; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("username") + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + + + /** + **/ + public User firstName(String firstName) { + this.firstName = firstName; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("firstName") + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + + /** + **/ + public User lastName(String lastName) { + this.lastName = lastName; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("lastName") + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } + + + /** + **/ + public User email(String email) { + this.email = email; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("email") + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + + + /** + **/ + public User password(String password) { + this.password = password; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("password") + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + + + /** + **/ + public User phone(String phone) { + this.phone = phone; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("phone") + public String getPhone() { + return phone; + } + public void setPhone(String phone) { + this.phone = phone; + } + + + /** + * User Status + **/ + public User userStatus(Integer userStatus) { + this.userStatus = userStatus; + return this; + } + + @ApiModelProperty(example = "null", value = "User Status") + @JsonProperty("userStatus") + public Integer getUserStatus() { + return userStatus; + } + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/FakeApiTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/FakeApiTest.java new file mode 100644 index 00000000000..1ea1e270634 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/FakeApiTest.java @@ -0,0 +1,74 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import java.time.OffsetDateTime; +import java.time.LocalDate; +import java.math.BigDecimal; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for FakeApi + */ +public class FakeApiTest { + + private final FakeApi api = new FakeApi(); + + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testEndpointParametersTest() throws ApiException { + BigDecimal number = null; + Double _double = null; + String string = null; + byte[] _byte = null; + Integer integer = null; + Integer int32 = null; + Long int64 = null; + Float _float = null; + byte[] binary = null; + LocalDate date = null; + OffsetDateTime dateTime = null; + String password = null; + // api.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/PetApiTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/PetApiTest.java new file mode 100644 index 00000000000..5ca2d9be1d8 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/PetApiTest.java @@ -0,0 +1,180 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.model.Pet; +import io.swagger.client.model.ModelApiResponse; +import java.io.File; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for PetApi + */ +public class PetApiTest { + + private final PetApi api = new PetApi(); + + + /** + * Add a new pet to the store + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void addPetTest() throws ApiException { + Pet body = null; + // api.addPet(body); + + // TODO: test validations + } + + /** + * Deletes a pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deletePetTest() throws ApiException { + Long petId = null; + String apiKey = null; + // api.deletePet(petId, apiKey); + + // TODO: test validations + } + + /** + * Finds Pets by status + * + * Multiple status values can be provided with comma separated strings + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void findPetsByStatusTest() throws ApiException { + List status = null; + // List response = api.findPetsByStatus(status); + + // TODO: test validations + } + + /** + * Finds Pets by tags + * + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void findPetsByTagsTest() throws ApiException { + List tags = null; + // List response = api.findPetsByTags(tags); + + // TODO: test validations + } + + /** + * Find pet by ID + * + * Returns a single pet + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getPetByIdTest() throws ApiException { + Long petId = null; + // Pet response = api.getPetById(petId); + + // TODO: test validations + } + + /** + * Update an existing pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updatePetTest() throws ApiException { + Pet body = null; + // api.updatePet(body); + + // TODO: test validations + } + + /** + * Updates a pet in the store with form data + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updatePetWithFormTest() throws ApiException { + Long petId = null; + String name = null; + String status = null; + // api.updatePetWithForm(petId, name, status); + + // TODO: test validations + } + + /** + * uploads an image + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void uploadFileTest() throws ApiException { + Long petId = null; + String additionalMetadata = null; + File file = null; + // ModelApiResponse response = api.uploadFile(petId, additionalMetadata, file); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/StoreApiTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/StoreApiTest.java new file mode 100644 index 00000000000..513cc877d45 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/StoreApiTest.java @@ -0,0 +1,108 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.model.Order; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for StoreApi + */ +public class StoreApiTest { + + private final StoreApi api = new StoreApi(); + + + /** + * Delete purchase order by ID + * + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deleteOrderTest() throws ApiException { + String orderId = null; + // api.deleteOrder(orderId); + + // TODO: test validations + } + + /** + * Returns pet inventories by status + * + * Returns a map of status codes to quantities + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getInventoryTest() throws ApiException { + // Map response = api.getInventory(); + + // TODO: test validations + } + + /** + * Find purchase order by ID + * + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getOrderByIdTest() throws ApiException { + Long orderId = null; + // Order response = api.getOrderById(orderId); + + // TODO: test validations + } + + /** + * Place an order for a pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void placeOrderTest() throws ApiException { + Order body = null; + // Order response = api.placeOrder(body); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/UserApiTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/UserApiTest.java new file mode 100644 index 00000000000..e94858e8c27 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/UserApiTest.java @@ -0,0 +1,174 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.model.User; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for UserApi + */ +public class UserApiTest { + + private final UserApi api = new UserApi(); + + + /** + * Create user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUserTest() throws ApiException { + User body = null; + // api.createUser(body); + + // TODO: test validations + } + + /** + * Creates list of users with given input array + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUsersWithArrayInputTest() throws ApiException { + List body = null; + // api.createUsersWithArrayInput(body); + + // TODO: test validations + } + + /** + * Creates list of users with given input array + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUsersWithListInputTest() throws ApiException { + List body = null; + // api.createUsersWithListInput(body); + + // TODO: test validations + } + + /** + * Delete user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deleteUserTest() throws ApiException { + String username = null; + // api.deleteUser(username); + + // TODO: test validations + } + + /** + * Get user by user name + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getUserByNameTest() throws ApiException { + String username = null; + // User response = api.getUserByName(username); + + // TODO: test validations + } + + /** + * Logs user into the system + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void loginUserTest() throws ApiException { + String username = null; + String password = null; + // String response = api.loginUser(username, password); + + // TODO: test validations + } + + /** + * Logs out current logged in user session + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void logoutUserTest() throws ApiException { + // api.logoutUser(); + + // TODO: test validations + } + + /** + * Updated user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updateUserTest() throws ApiException { + String username = null; + User body = null; + // api.updateUser(username, body); + + // TODO: test validations + } + +} From 4ef10aa5ae09e7b8043a83b0dd96696e0ec539db Mon Sep 17 00:00:00 2001 From: ant3 Date: Tue, 21 Jun 2016 00:14:10 +0100 Subject: [PATCH 007/470] Upgraded dependency versions Also switched from using JSR310Module (Deprecated) to JavaTimeModule. --- .../main/resources/Java/ApiClient.mustache | 2 +- .../main/resources/Java/build.gradle.mustache | 25 ++++++++++++++++--- .../Java/libraries/jersey2/JSON.mustache | 2 +- .../libraries/jersey2/build.gradle.mustache | 8 +++--- .../Java/libraries/jersey2/build.sbt.mustache | 14 +++++------ .../Java/libraries/jersey2/pom.mustache | 12 ++++----- .../src/main/resources/Java/pom.mustache | 6 ++--- 7 files changed, 43 insertions(+), 26 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index 5f5376f2861..a64f33174da 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -71,7 +71,7 @@ public class ApiClient { objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); {{#java8}} - objectMapper.registerModule(new JSR310Module()); + objectMapper.registerModule(new JavaTimeModule()); {{/java8}} {{^java8}} objectMapper.registerModule(new JodaModule()); diff --git a/modules/swagger-codegen/src/main/resources/Java/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/build.gradle.mustache index 9920a371e5d..c969c9f7b08 100644 --- a/modules/swagger-codegen/src/main/resources/Java/build.gradle.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/build.gradle.mustache @@ -32,8 +32,14 @@ if(hasProperty('target') && target == 'android') { targetSdkVersion 23 } compileOptions { + {{#java8}} + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + {{/java8}} + {{^java8}} sourceCompatibility JavaVersion.VERSION_1_7 targetCompatibility JavaVersion.VERSION_1_7 + {{/java8}} } // Rename the aar correctly @@ -77,9 +83,15 @@ if(hasProperty('target') && target == 'android') { apply plugin: 'java' apply plugin: 'maven' - + + {{#java8}} + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + {{/java8}} + {{^java8}} sourceCompatibility = JavaVersion.VERSION_1_7 targetCompatibility = JavaVersion.VERSION_1_7 + {{/java8}} install { repositories.mavenInstaller { @@ -95,9 +107,9 @@ if(hasProperty('target') && target == 'android') { ext { swagger_annotations_version = "1.5.8" - jackson_version = "2.7.0" + jackson_version = "2.7.5" jersey_version = "1.19.1" - jodatime_version = "2.9.3" + jodatime_version = "2.9.4" junit_version = "4.12" } @@ -109,8 +121,13 @@ dependencies { compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version" compile "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:$jackson_version" - compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:2.1.5" + {{#java8}} + compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version" + {{/java8}} + {{^java8}} + compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version" compile "joda-time:joda-time:$jodatime_version" + {{/java8}} compile "com.brsanthu:migbase64:2.2" testCompile "junit:junit:$junit_version" } 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 index 7d9a9732862..243e444cf01 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/JSON.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/JSON.mustache @@ -25,7 +25,7 @@ public class JSON implements ContextResolver { mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); {{#java8}} - mapper.registerModule(new JSR310Module()); + mapper.registerModule(new JavaTimeModule()); {{/java8}} {{^java8}} mapper.registerModule(new JodaModule()); diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.gradle.mustache index b17cd34e420..285b35a32a4 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.gradle.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.gradle.mustache @@ -106,10 +106,10 @@ if(hasProperty('target') && target == 'android') { ext { swagger_annotations_version = "1.5.8" - jackson_version = "2.7.0" + jackson_version = "2.7.5" jersey_version = "2.22.2" {{^java8}} - jodatime_version = "2.9.3" + jodatime_version = "2.9.4" {{/java8}} junit_version = "4.12" } @@ -118,7 +118,7 @@ dependencies { compile "io.swagger:swagger-annotations:$swagger_annotations_version" compile "org.glassfish.jersey.core:jersey-client:$jersey_version" compile "org.glassfish.jersey.media:jersey-media-multipart:$jersey_version" - compile "org.glassfish.jersey.media:jersey-media-json-jackson:2.22.1" + compile "org.glassfish.jersey.media:jersey-media-json-jackson:$jersey_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" @@ -126,7 +126,7 @@ dependencies { compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version" {{/java8}} {{^java8}} - compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:2.1.5" + compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version" compile "joda-time:joda-time:$jodatime_version" {{/java8}} compile "com.brsanthu:migbase64:2.2" diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.sbt.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.sbt.mustache index 46ff84d1e72..c43d6a0375c 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.sbt.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.sbt.mustache @@ -12,16 +12,16 @@ lazy val root = (project in file(".")). "io.swagger" % "swagger-annotations" % "1.5.8", "org.glassfish.jersey.core" % "jersey-client" % "2.22.2", "org.glassfish.jersey.media" % "jersey-media-multipart" % "2.22.2", - "org.glassfish.jersey.media" % "jersey-media-json-jackson" % "2.22.1", - "com.fasterxml.jackson.core" % "jackson-core" % "2.7.0", - "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.0", - "com.fasterxml.jackson.core" % "jackson-databind" % "2.7.0", + "org.glassfish.jersey.media" % "jersey-media-json-jackson" % "2.22.2", + "com.fasterxml.jackson.core" % "jackson-core" % "2.7.5", + "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.5", + "com.fasterxml.jackson.core" % "jackson-databind" % "2.7.5", {{#java8}} - "com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % "2.7.0", + "com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % "2.7.5", {{/java8}} {{^java8}} - "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.1.5", - "joda-time" % "joda-time" % "2.9.3", + "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.7.5", + "joda-time" % "joda-time" % "2.9.4", {{/java8}} "com.brsanthu" % "migbase64" % "2.2", "junit" % "junit" % "4.12" % "test", 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 d6b51a2f884..ee55337e4b9 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 @@ -52,7 +52,7 @@ org.apache.maven.plugins maven-jar-plugin - 2.2 + 2.6 @@ -98,7 +98,7 @@ org.apache.maven.plugins maven-compiler-plugin - 2.3.2 + 2.5.1 {{#java8}} 1.8 @@ -133,7 +133,7 @@ org.glassfish.jersey.media jersey-media-json-jackson - 2.22.1 + ${jersey-version} @@ -163,7 +163,7 @@ com.fasterxml.jackson.datatype jackson-datatype-joda - 2.1.5 + ${jackson-version} joda-time @@ -190,9 +190,9 @@ 1.5.8 2.22.2 - 2.7.0 + 2.7.5 {{^java8}} - 2.9.3 + 2.9.4 {{/java8}} 1.0.0 4.12 diff --git a/modules/swagger-codegen/src/main/resources/Java/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/pom.mustache index 3a8c440eaee..95712934525 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pom.mustache @@ -160,7 +160,7 @@ com.fasterxml.jackson.datatype jackson-datatype-joda - 2.1.5 + ${jackson-version} joda-time @@ -188,9 +188,9 @@ UTF-8 1.5.8 1.19.1 - 2.7.0 + 2.7.5 {{^java8}} - 2.9.3 + 2.9.4 {{/java8}} 1.0.0 4.12 From b107b4693ddb42daf3b81e1dc2316854e35403ba Mon Sep 17 00:00:00 2001 From: ant3 Date: Tue, 21 Jun 2016 00:15:34 +0100 Subject: [PATCH 008/470] Rebuilt jersey2-java8 sample --- .../petstore/java/jersey2-java8/build.gradle | 4 ++-- .../petstore/java/jersey2-java8/build.sbt | 10 +++++----- .../gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 53639 bytes .../gradle/wrapper/gradle-wrapper.properties | 6 ++++++ .../client/petstore/java/jersey2-java8/pom.xml | 8 ++++---- .../src/main/java/io/swagger/client/JSON.java | 2 +- 6 files changed, 18 insertions(+), 12 deletions(-) create mode 100644 samples/client/petstore/java/jersey2-java8/gradle/wrapper/gradle-wrapper.jar create mode 100644 samples/client/petstore/java/jersey2-java8/gradle/wrapper/gradle-wrapper.properties diff --git a/samples/client/petstore/java/jersey2-java8/build.gradle b/samples/client/petstore/java/jersey2-java8/build.gradle index 1fa7d76afcc..ece2fa55d57 100644 --- a/samples/client/petstore/java/jersey2-java8/build.gradle +++ b/samples/client/petstore/java/jersey2-java8/build.gradle @@ -94,7 +94,7 @@ if(hasProperty('target') && target == 'android') { ext { swagger_annotations_version = "1.5.8" - jackson_version = "2.7.0" + jackson_version = "2.7.5" jersey_version = "2.22.2" junit_version = "4.12" } @@ -103,7 +103,7 @@ dependencies { compile "io.swagger:swagger-annotations:$swagger_annotations_version" compile "org.glassfish.jersey.core:jersey-client:$jersey_version" compile "org.glassfish.jersey.media:jersey-media-multipart:$jersey_version" - compile "org.glassfish.jersey.media:jersey-media-json-jackson:2.22.1" + compile "org.glassfish.jersey.media:jersey-media-json-jackson:$jersey_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" diff --git a/samples/client/petstore/java/jersey2-java8/build.sbt b/samples/client/petstore/java/jersey2-java8/build.sbt index 961083958a2..b187fb67ae2 100644 --- a/samples/client/petstore/java/jersey2-java8/build.sbt +++ b/samples/client/petstore/java/jersey2-java8/build.sbt @@ -12,11 +12,11 @@ lazy val root = (project in file(".")). "io.swagger" % "swagger-annotations" % "1.5.8", "org.glassfish.jersey.core" % "jersey-client" % "2.22.2", "org.glassfish.jersey.media" % "jersey-media-multipart" % "2.22.2", - "org.glassfish.jersey.media" % "jersey-media-json-jackson" % "2.22.1", - "com.fasterxml.jackson.core" % "jackson-core" % "2.7.0", - "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.0", - "com.fasterxml.jackson.core" % "jackson-databind" % "2.7.0", - "com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % "2.7.0", + "org.glassfish.jersey.media" % "jersey-media-json-jackson" % "2.22.2", + "com.fasterxml.jackson.core" % "jackson-core" % "2.7.5", + "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.5", + "com.fasterxml.jackson.core" % "jackson-databind" % "2.7.5", + "com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % "2.7.5", "com.brsanthu" % "migbase64" % "2.2", "junit" % "junit" % "4.12" % "test", "com.novocode" % "junit-interface" % "0.10" % "test" diff --git a/samples/client/petstore/java/jersey2-java8/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/java/jersey2-java8/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..2c6137b87896c8f70315ae454e00a969ef5f6019 GIT binary patch literal 53639 zcmafaW0a=B^559DjdyI@wr$%scWm3Xy<^+Pj_sKpY&N+!|K#4>Bz;ajPk*RBjZ;RV75EK*;qpZCo(BB5~-#>pF^k0$_Qx&3rs}{XFZ)$uJU-ZpbB>L3?|knJ{J+ge{%=bI`#Yn9v&Fxx>fd=_|H)(FY-DO{ z_Wxu>{a02GXCp^PGw1(fh-I*;dGTM?mA^##pNEJ#c-Y%I7@3kW(VN&Bxw!bn$iWOU zB8BZ)vT4(}GX%q~h3EYwbR?$d6|xnvg_e@4>dl5l+%FtPbGqa`;Uk##t$#g&CK4GO zz%my0ZR1Fv@~b2_>T0cBP)ECz-Uc^nW9e+`W4!=mSJPopgoe3A(NMzBd0mR?$&3XA zRL1}bJ2Q%R#bWHrC`j_)tPKMEyHuGSpdJMhT(Ob(e9H+#=Skp%#jzj=BVvc(-RSWB z{_T`UcEeWD{z`!3-y;_N|Ljr4%f;2qPSM%n?_s%GnYsM!d3p)CxmudpyIPqTxjH!i z;}A+!>>N;pko++K5n~I7m4>yco2%Zc$59RohB(l%KcJc9s^nw^?2JGy>O4#x5+CZH zqU~7kA>WE)ngvsdfKhLUX0Lc3r+In0Uyn}LZhm?n){&LHNJws546du%pia=j zyH8CD{^Qx%kFe@kX*$B!DxLa(Y?BO32sm8%#_ynjU-m>PJbabL`~0Ai zeJm<6okftSJUd2!X(>}i#KAh-NR2!Kg%c2JD=G|T%@Q0JQzqKB)Qc4E-{ZF=#PGZg zior4-caRB-Jj;l}Xb_!)TjB`jC}})6z~3AsRE&t~CO&)g{dqM0iK;lvav8?kE1< zmCrHxDZe?&rEK7M4tG-i!`Zk-*IzSk0M0&Ul8+J>*UD(A^;bAFDcz>d&lzAlw}b## zjfu@)rAou-86EN%8_Nv;%bNUmy*<6sbgB9)ZCihdSh_VT2iGFv+T8p&Z&wO02nKtdx?eZh^=*<>SZHSn(Pv)bgn{ zb15>YnVnJ^PO025c~^uK&W1C1XTs1az44L~-9Z-fU3{VvA?T& zdpi&S`mZ|$tMuN{{i|O}fAx#*KkroHe;6z^7c*x`2Rk!a2L~HB$A4@(Rz*hvM+og( zJW+4;S-A$#+Gec-rn8}at+q5gRrNy^iU?Z4Gz_|qzS~sG_EV#m%-VW!jQ>f3jc-Vq zW;~>OqI1Th&*fx#`c^=|A4GGoDp+ZH!n0_fDo-ks3d&GlT=(qzr(?Qw`PHvo3PoU6YJE zu{35)=P`LRm@+=ziAI)7jktM6KHx*v&WHVBYp<~UtR3c?Wv_{a0(k&NF!o#+@|Y6Y z>{||-i0v8N2ntXRrVx~#Z1JMA3C2ki}OkJ4W`WjZIuLByNUEL2HqqKrbi{9a8` zk-w0I$a<6;W6&X<&EbIqul`;nvc+D~{g5al{0oOSp~ zhg;6nG1Bh-XyOBM63jb_z`7apSsta``K{!Q{}mZ!m4rTmWi^<*BN2dh#PLZ)oXIJY zl#I3@$+8Fvi)m<}lK_}7q~VN%BvT^{q~ayRA7mwHO;*r0ePSK*OFv_{`3m+96HKgt z=nD-=Pv90Ae1p)+SPLT&g(Fdqbcc(Vnk5SFyc|Tq08qS;FJ1K4rBmtns%Su=GZchE zR(^9W-y!{QfeVPBeHpaBA{TZpQ*(d$H-*GI)Y}>X2Lk&27aFkqXE7D?G_iGav2r&P zx3V=8GBGi8agj5!H?lDMr`1nYmvKZj!~0{GMPb!tM=VIJXbTk9q8JRoSPD*CH@4I+ zfG-6{Z=Yb->)MIUmXq-#;=lNCyF1G*W+tW6gdD||kQfW$J_@=Y9KmMD!(t#9-fPcJ z>%&KQC-`%E`{y^i!1u=rJP_hhGErM$GYE3Y@ZzzA2a-PC>yaoDziZT#l+y)tfyR}U z5Epq`ACY|VUVISHESM5$BpWC0FpDRK&qi?G-q%Rd8UwIq&`d(Mqa<@(fH!OfNIgFICEG?j_Gj7FS()kY^P(I!zbl`%HB z7Rx=q2vZFjy^XypORT$^NJv_`Vm7-gkJWYsN5xg>snt5%oG?w1K#l_UH<>4@d0G@3 z)r?|yba6;ksyc+5+8YZ?)NZ+ER!4fIzK>>cs^(;ib7M}asT&)+J=J@U^~ffJ>65V# zt_lyUp52t`vT&gcQ%a6Ca)p8u6v}3iJzf?zsx#e9t)-1OtqD$Mky&Lpz6_v?p0|y4 zI{Nq9z89OxQbsqX)UYj z(BGu`28f8C^e9R2jf0Turq;v+fPCWD*z8!8-Q-_s`ILgwo@mtnjpC_D$J zCz7-()9@8rQ{4qy<5;*%bvX3k$grUQ{Bt;B#w))A+7ih631uN?!_~?i^g+zO^lGK$>O1T1$6VdF~%FKR6~Px%M`ibJG*~uQ>o^r9qLo*`@^ry@KX^$LH0>NGPL%MG8|;8 z@_)h2uvB1M!qjGtZgy~7-O=GUa`&;xEFvC zwIt?+O;Fjwgn3aE%`_XfZEw5ayP+JS8x?I|V3ARbQ5@{JAl1E*5a{Ytc(UkoDKtD# zu)K4XIYno7h3)0~5&93}pMJMDr*mcYM|#(FXS@Pj)(2!cl$)R-GwwrpOW!zZ2|wN) zE|B38xr4_NBv|%_Lpnm$We<_~S{F1x42tph3PAS`0saF^PisF6EDtce+9y6jdITmu zqI-CLeTn2%I3t3z_=e=YGzUX6i5SEujY`j|=aqv#(Q=iWPkKhau@g|%#xVC2$6<{2 zAoimy5vLq6rvBo3rv&^VqtaKt_@Vx^gWN{f4^@i6H??!ra^_KC-ShWC(GBNt3o~T^ zudX<0v!;s$rIflR?~Tu4-D=%~E=glv+1|pg*ea30re-2K@8EqQ{8#WY4X-br_!qpq zL;PRCi^e~EClLpGb1MrsXCqfD2m615mt;EyR3W6XKU=4(A^gFCMMWgn#5o1~EYOH* zOlolGlD;B!j%lRFaoc)q_bOH-O!r}g1Bhlhy*dRoTf-bI%`A`kU)Q=HA9HgCKqq&A z2$_rtL-uIA7`PiJfw380j@M4Fff-?(Xe(aR`4>BZyDN2$2E7QQ1}95@X819fnA(}= za=5VF-%;l}aHSRHCfs(#Qf%dPue~fGpy7qPs*eLX2Aa0+@mPxnS4Wm8@kP7KEL)8s z@tNmawLHST-FS4h%20%lVvd zkXpxWa43E`zX{6-{2c+L9C`l(ZRG8`kO9g7t&hx?>j~5_C;y5u*Bvl79)Bq?@T7bN z=G2?QDa0J3VwCfZG0BjOFP>xz4jtv3LS>jz#1x~b9u1*n9>Y6?u8W?I^~;N{GC<1y} zc&Wz{L`kJUSt=oA=5ZHtNj3PSB%w5^=0(U7GC^zUgcdkujo>ruzyBurtTjKuNf1-+ zzn~oZFXCbR&xq&W{ar~T`@fNef5M$u^-C92HMBo=*``D8Q^ktX z(qT{_R=*EI?-R9nNUFNR#{(Qb;27bM14bjI`c#4RiinHbnS445Jy^%krK%kpE zFw%RVQd6kqsNbiBtH*#jiPu3(%}P7Vhs0G9&Dwb4E-hXO!|whZ!O$J-PU@j#;GrzN zwP9o=l~Nv}4OPvv5rVNoFN>Oj0TC%P>ykicmFOx*dyCs@7XBH|w1k2hb`|3|i^GEL zyg7PRl9eV ztQ1z)v~NwH$ebcMSKc-4D=?G^3sKVG47ZWldhR@SHCr}SwWuj5t!W$&HAA*Wo_9tM zw5vs`2clw`z@~R-#W8d4B8!rFtO}+-$-{6f_`O-^-EhGraqg%$D618&<9KG``D|Rb zQJ&TSE3cfgf8i}I^DLu+-z{{;QM>K3I9~3R9!0~=Y`A1=6`CF#XVH@MWO?3@xa6ev zdw08_9L=>3%)iXA(_CE@ipRQ{Tb+@mxoN^3ktgmt^mJ(u#=_Plt?5qMZOA3&I1&NU zOG+0XTsIkbhGsp(ApF2MphRG^)>vqagn!-%pRnppa%`-l@DLS0KUm8*e9jGT0F%0J z*-6E@Z*YyeZ{eP7DGmxQedo}^+w zM~>&E$5&SW6MxP##J56Eo@0P34XG})MLCuhMyDFf**?tziO?_Ad&Jhd z`jok^B{3ff*7cydrxYjdxX`14`S+34kW^$fxDmNn2%fsQ6+Zou0%U{3Y>L}UIbQbw z*E#{Von}~UEAL?vvihW)4?Kr-R?_?JSN?B?QzhUWj==1VNEieTMuTJ#-nl*c@qP+` zGk@aE0oAD5!9_fO=tDQAt9g0rKTr{Z0t~S#oy5?F3&aWm+igqKi| zK9W3KRS|1so|~dx%90o9+FVuN7)O@by^mL=IX_m^M87i&kT1^#9TCpI@diZ_p$uW3 zbA+-ER9vJ{ii?QIZF=cfZT3#vJEKC|BQhNd zGmxBDLEMnuc*AET~k8g-P-K+S~_(+GE9q6jyIMka(dr}(H% z$*z;JDnyI@6BQ7KGcrv03Hn(abJ_-vqS>5~m*;ZJmH$W`@csQ8ejiC8S#sYTB;AoF zXsd!kDTG#3FOo-iJJpd$C~@8}GQJ$b1A85MXp?1#dHWQu@j~i4L*LG40J}+V=&-(g zh~Hzk(l1$_y}PX}Ypluyiib0%vwSqPaJdy9EZ;?+;lFF8%Kb7cwPD17C}@N z2OF;}QCM4;CDx~d;XnunQAx5mQbL#);}H57I+uB9^v|cmZwuXGkoH-cAJ%nIjSO$E z{BpYdC9poyO5pvdL+ZPWFuK}c8WGEq-#I3myONq^BL%uG`RIoSBTEK9sAeU4UBh7f zzM$s|&NtAGN&>`lp5Ruc%qO^oL;VGnzo9A8{fQn@YoORA>qw;^n2pydq>;Ji9(sPH zLGsEeTIH?_6C3uyWoW(gkmM(RhFkiDuQPXmL7Oes(+4)YIHt+B@i`*%0KcgL&A#ua zAjb8l_tO^Ag!ai3f54t?@{aoW%&Hdst}dglRzQlS=M{O!=?l z*xY2vJ?+#!70RO8<&N^R4p+f=z z*&_e}QT%6-R5Wt66moGfvorp$yE|3=-2_(y`FnL0-7A?h%4NMZ#F#Rcb^}971t5ib zw<20w|C?HVv%|)Q)Pef8tGjwQ+!+<{>IVjr@&SRVO*PyC?Efnsq;Eq{r;U2)1+tgp z)@pZ}gJmzf{m=K@7YA_8X#XK+)F465h%z38{V-K8k%&_GF+g^s&9o6^B-&|MDFI)H zj1ofQL>W(MJLOu3xkkJZV@$}GEG~XBz~WvRjxhT0$jKKZKjuKi$rmR-al}Hb3xDL) z^xGG2?5+vUAo4I;$(JgeVQe9+e)vvJ={pO~05f|J={%dsSLVcF>@F9p4|nYK&hMua zWjNvRod}l~WmGo|LX2j#w$r$y?v^H?Gu(_?(WR_%D@1I@$yMTKqD=Ca2) zWBQmx#A$gMrHe^A8kxAgB}c2R5)14G6%HfpDf$(Di|p8ntcN;Hnk)DR1;toC9zo77 zcWb?&&3h65(bLAte%hstI9o%hZ*{y=8t$^!y2E~tz^XUY2N2NChy;EIBmf(Kl zfU~&jf*}p(r;#MP4x5dI>i`vjo`w?`9^5(vfFjmWp`Ch!2Ig}rkpS|T%g@2h-%V~R zg!*o7OZSU-%)M8D>F^|z+2F|!u1mOt?5^zG%;{^CrV^J?diz9AmF!UsO?Pl79DKvD zo-2==yjbcF5oJY!oF?g)BKmC8-v|iL6VT|Gj!Gk5yaXfhs&GeR)OkZ}=q{exBPv)& zV!QTQBMNs>QQ))>(rZOn0PK+-`|7vKvrjky3-Kmuf8uJ`x6&wsA5S(tMf=m;79Hzv za%lZ(OhM&ZUCHtM~FRd#Uk3Iy%oXe^)!Jci39D(a$51WER+%gIZYP)!}nDtDw_FgPL3e>1ilFN=M(j~V` zjOtRhOB8bX8}*FD0oy}+s@r4XQT;OFH__cEn-G#aYHpJDI4&Zo4y2>uJdbPYe zOMGMvbA6#(p00i1{t~^;RaHmgZtE@we39mFaO0r|CJ0zUk$|1Pp60Q&$A;dm>MfP# zkfdw?=^9;jsLEXsccMOi<+0-z|NZb(#wwkcO)nVxJxkF3g(OvW4`m36ytfPx5e-ujFXf($)cVOn|qt9LL zNr!InmcuVkxEg8=_;E)+`>n2Y0eAIDrklnE=T9Pyct>^4h$VDDy>}JiA=W9JE79<6 zv%hpzeJC)TGX|(gP!MGWRhJV}!fa1mcvY%jC^(tbG3QIcQnTy&8UpPPvIekWM!R?R zKQanRv+YZn%s4bqv1LBgQ1PWcEa;-MVeCk`$^FLYR~v%9b-@&M%giqnFHV;5P5_et z@R`%W>@G<6GYa=JZ)JsNMN?47)5Y3@RY`EVOPzxj;z6bn#jZv|D?Fn#$b}F!a}D9{ ztB_roYj%34c-@~ehWM_z;B{G5;udhY`rBH0|+u#!&KLdnw z;!A%tG{%Ua;}OW$BG`B#^8#K$1wX2K$m`OwL-6;hmh{aiuyTz;U|EKES= z9UsxUpT^ZZyWk0;GO;Fe=hC`kPSL&1GWS7kGX0>+votm@V-lg&OR>0*!Iay>_|5OT zF0w~t01mupvy4&HYKnrG?sOsip%=<>nK}Bxth~}g)?=Ax94l_=mC{M@`bqiKtV5vf zIP!>8I;zHdxsaVt9K?{lXCc$%kKfIwh&WM__JhsA?o$!dzxP znoRU4ZdzeN3-W{6h~QQSos{-!W@sIMaM z4o?97?W5*cL~5%q+T@>q%L{Yvw(a2l&68hI0Ra*H=ZjU!-o@3(*7hIKo?I7$gfB(Vlr!62-_R-+T;I0eiE^><*1_t|scfB{r9+a%UxP~CBr zl1!X^l01w8o(|2da~Mca)>Mn}&rF!PhsP_RIU~7)B~VwKIruwlUIlOI5-yd4ci^m{ zBT(H*GvKNt=l7a~GUco)C*2t~7>2t?;V{gJm=WNtIhm4x%KY>Rm(EC^w3uA{0^_>p zM;Na<+I<&KwZOUKM-b0y6;HRov=GeEi&CqEG9^F_GR*0RSM3ukm2c2s{)0<%{+g78 zOyKO%^P(-(U09FO!75Pg@xA{p+1$*cD!3=CgW4NO*p}&H8&K`(HL&$TH2N-bf%?JL zVEWs;@_UDD7IoM&P^(k-U?Gs*sk=bLm+f1p$ggYKeR_7W>Zz|Dl{{o*iYiB1LHq`? ztT)b^6Pgk!Kn~ozynV`O(hsUI52|g{0{cwdQ+=&@$|!y8{pvUC_a5zCemee6?E{;P zVE9;@3w92Nu9m_|x24gtm23{ST8Bp;;iJlhaiH2DVcnYqot`tv>!xiUJXFEIMMP(ZV!_onqyQtB_&x}j9 z?LXw;&z%kyYjyP8CQ6X);-QW^?P1w}&HgM}irG~pOJ()IwwaDp!i2$|_{Ggvw$-%K zp=8N>0Fv-n%W6{A8g-tu7{73N#KzURZl;sb^L*d%leKXp2Ai(ZvO96T#6*!73GqCU z&U-NB*0p@?f;m~1MUN}mfdpBS5Q-dbhZ$$OWW=?t8bT+R5^vMUy$q$xY}ABi60bb_ z9;fj~2T2Ogtg8EDNr4j96{@+9bRP#Li7YDK1Jh8|Mo%NON|bYXi~D(W8oiC2SSE#p z=yQ0EP*}Z)$K$v?MJp8s=xroI@gSp&y!De;aik!U7?>3!sup&HY{6!eElc+?ZW*|3 zjJ;Nx>Kn@)3WP`{R821FpY6p1)yeJPi6yfq=EffesCZjO$#c;p!sc8{$>M-i#@fCt zw?GQV4MTSvDH(NlD2S*g-YnxCDp*%|z9^+|HQ(#XI0Pa8-Io=pz8C&Lp?23Y5JopL z!z_O3s+AY&`HT%KO}EB73{oTar{hg)6J7*KI;_Gy%V%-oO3t+vcyZ?;&%L z3t4A%Ltf=2+f8qITmoRfolL;I__Q8Z&K9*+_f#Sue$2C;xTS@%Z*z-lOAF-+gj1C$ zKEpt`_qg;q^41dggeNsJv#n=5i+6Wyf?4P_a=>s9n(ET_K|*zvh633Mv3Xm3OE!n` zFk^y65tStyk4aamG*+=5V^UePR2e0Fbt7g$({L1SjOel~1^9SmP2zGJ)RZX(>6u4^ zQ78wF_qtS~6b+t&mKM=w&Dt=k(oWMA^e&V#&Y5dFDc>oUn+OU0guB~h3};G1;X=v+ zs_8IR_~Y}&zD^=|P;U_xMA{Ekj+lHN@_n-4)_cHNj0gY4(Lx1*NJ^z9vO>+2_lm4N zo5^}vL2G%7EiPINrH-qX77{y2c*#;|bSa~fRN2)v=)>U@;YF}9H0XR@(+=C+kT5_1 zy?ZhA&_&mTY7O~ad|LX+%+F{GTgE0K8OKaC2@NlC1{j4Co8;2vcUbGpA}+hBiDGCS zl~yxngtG}PI$M*JZYOi{Ta<*0f{3dzV0R}yIV7V>M$aX=TNPo|kS;!!LP3-kbKWj` zR;R%bSf%+AA#LMkG$-o88&k4bF-uIO1_OrXb%uFp((Pkvl@nVyI&^-r5p}XQh`9wL zKWA0SMJ9X|rBICxLwhS6gCTVUGjH&)@nofEcSJ-t4LTj&#NETb#Z;1xu(_?NV@3WH z;c(@t$2zlY@$o5Gy1&pvja&AM`YXr3aFK|wc+u?%JGHLRM$J2vKN~}5@!jdKBlA>;10A(*-o2>n_hIQ7&>E>TKcQoWhx7um zx+JKx)mAsP3Kg{Prb(Z7b};vw&>Tl_WN)E^Ew#Ro{-Otsclp%Ud%bb`8?%r>kLpjh z@2<($JO9+%V+To>{K?m76vT>8qAxhypYw;Yl^JH@v9^QeU01$3lyvRt^C#(Kr#1&2 ziOa@LG9p6O=jO6YCVm-d1OB+_c858dtHm>!h6DUQ zj?dKJvwa2OUJ@qv4!>l1I?bS$Rj zdUU&mofGqgLqZ2jGREYM>;ubg@~XE>T~B)9tM*t-GmFJLO%^tMWh-iWD9tiYqN>eZ zuCTF%GahsUr#3r3I5D*SaA75=3lfE!SpchB~1Xk>a7Ik!R%vTAqhO z#H?Q}PPN8~@>ZQ^rAm^I=*z>a(M4Hxj+BKrRjJcRr42J@DkVoLhUeVWjEI~+)UCRs zja$08$Ff@s9!r47##j1A5^B6br{<%L5uW&8t%_te(t@c|4Fane;UzM{jKhXfC zQa|k^)d*t}!<)K)(nnDxQh+Q?e@YftzoGIIG?V?~$cDY_;kPF>N}C9u7YcZzjzc7t zx3Xi|M5m@PioC>dCO$ia&r=5ZLdGE8PXlgab`D}>z`dy(+;Q%tz^^s*@5D)gll+QL z6@O3@K6&zrhitg~{t*EQ>-YN zy&k{89XF*^mdeRJp{#;EAFi_U<7}|>dl^*QFg**9wzlA#N9!`Qnc68+XRbO-Za=t zy@wz`mi0MmgE?4b>L$q&!%B!6MC7JjyG#Qvwj{d8)bdF`hA`LWSv+lBIs(3~hKSQ^0Se!@QOt;z5`!;Wjy1l8w=(|6%GPeK)b)2&Ula zoJ#7UYiJf>EDwi%YFd4u5wo;2_gb`)QdsyTm-zIX954I&vLMw&_@qLHd?I~=2X}%1 zcd?XuDYM)(2^~9!3z)1@hrW`%-TcpKB1^;IEbz=d0hv4+jtH;wX~%=2q7YW^C67Fk zyxhyP=Au*oC7n_O>l)aQgISa=B$Be8x3eCv5vzC%fSCn|h2H#0`+P1D*PPuPJ!7Hs z{6WlvyS?!zF-KfiP31)E&xYs<)C03BT)N6YQYR*Be?;bPp>h?%RAeQ7@N?;|sEoQ% z4FbO`m}Ae_S79!jErpzDJ)d`-!A8BZ+ASx>I%lITl;$st<;keU6oXJgVi?CJUCotEY>)blbj&;Qh zN*IKSe7UpxWPOCl1!d0I*VjT?k6n3opl8el=lonT&1Xt8T{(7rpV(?%jE~nEAx_mK z2x=-+Sl-h<%IAsBz1ciQ_jr9+nX57O=bO_%VtCzheWyA}*Sw!kN-S9_+tM}G?KEqqx1H036ELVw3Ja0!*Kr-Qo>)t*?aj2$x;CajQ@t`vbVbNp1Oczu@ zIKB+{5l$S;n(ny4#$RSd#g$@+V+qpAU&pBORg2o@QMHYLxS;zGOPnTA`lURgS{%VA zujqnT8gx7vw18%wg2)A>Kn|F{yCToqC2%)srDX&HV#^`^CyAG4XBxu7QNb(Ngc)kN zPoAhkoqR;4KUlU%%|t2D8CYQ2tS2|N#4ya9zsd~cIR=9X1m~a zq1vs3Y@UjgzTk#$YOubL*)YvaAO`Tw+x8GwYPEqbiAH~JNB?Q@9k{nAuAbv)M=kKn zMgOOeEKdf8OTO|`sVCnx_UqR>pFDlXMXG*KdhoM9NRiwYgkFg7%1%0B2UWn_9{BBW zi(Ynp7L|1~Djhg=G&K=N`~Bgoz}Bu0TR6WsI&MC@&)~>7%@S4zHRZxEpO(sp7d)R- zTm)))1Z^NHOYIU?+b2HZL0u1k>{4VGqQJAQ(V6y6+O+>ftKzA`v~wyV{?_@hx>Wy# zE(L|zidSHTux00of7+wJ4YHnk%)G~x)Cq^7ADk{S-wSpBiR2u~n=gpqG~f=6Uc7^N zxd$7)6Cro%?=xyF>PL6z&$ik^I_QIRx<=gRAS8P$G0YnY@PvBt$7&%M`ao@XGWvuE zi5mkN_5kYHJCgC;f_Ho&!s%CF7`#|B`tbUp4>88a8m$kE_O+i@pmEOT*_r0PhCjRvYxN*d5+w5 z<+S)w+1pvfxU6u{0}0sknRj8t^$uf?FCLg<%7SQ-gR~Y6u|f!Abx5U{*KyZ8o(S{G znhQx#Zs_b8jEk`5jd9CUYo>05&e69Ys&-x_*|!PoX$msbdBEGgPSpIl93~>ndH;t5 z?g>S+H^$HtoWcj4>WYo*Gu;Y#8LcoaP!HO?SFS&F9TkZnX`WBhh2jea0Vy%vVx~36 z-!7X*!Tw{Zdsl3qOsK&lf!nnI(lud){Cp$j$@cKrIh@#?+cEyC*m$8tnZIbhG~Zb8 z95)0Fa=3ddJQjW)9W+G{80kq`gZT`XNM=8eTkr^fzdU%d5p>J}v#h&h$)O+oYYaiC z7~hr4Q0PtTg(Xne6E%E@0lhv-CW^o0@EI3>0ZbxAwd2Q zkaU2c{THdFUnut_q0l+0DpJ5KMWNTa^i@v%r`~}fxdmmVFzq6{%vbv?MJ+Q86h6qf zKiGz6Vrb>!7)}8~9}bEy^#HSP)Z^_vqKg2tAfO^GWSN3hV4YzUz)N3m`%I&UEux{a z>>tz9rJBg(&!@S9o5=M@E&|@v2N+w+??UBa3)CDVmgO9(CkCr+a1(#edYE( z7=AAYEV$R1hHyNrAbMnG^0>@S_nLgY&p9vv_XH7|y*X)!GnkY0Fc_(e)0~)Y5B0?S zO)wZqg+nr7PiYMe}!Rb@(l zV=3>ZI(0z_siWqdi(P_*0k&+_l5k``E8WC(s`@v6N3tCfOjJkZ3E2+js++(KEL|!7 z6JZg>9o=$0`A#$_E(Rn7Q78lD1>F}$MhL@|()$cYY`aSA3FK&;&tk3-Fn$m?|G11= z8+AqH86^TNcY64-<)aD>Edj$nbSh>V#yTIi)@m1b2n%j-NCQ51$9C^L6pt|!FCI>S z>LoMC0n<0)p?dWQRLwQC%6wI02x4wAos$QHQ-;4>dBqO9*-d+<429tbfq7d4!Bz~A zw@R_I;~C=vgM@4fK?a|@=Zkm=3H1<#sg`7IM7zB#6JKC*lUC)sA&P)nfwMko15q^^TlLnl5fY75&oPQ4IH{}dT3fc% z!h+Ty;cx9$M$}mW~k$k(($-MeP_DwDJ zXi|*ZdNa$(kiU?}x0*G^XK!i{P4vJzF|aR+T{)yA8LBH!cMjJGpt~YNM$%jK0HK@r z-Au8gN>$8)y;2q-NU&vH`htwS%|ypsMWjg@&jytzR(I|Tx_0(w74iE~aGx%A^s*&- zk#_zHpF8|67{l$Xc;OU^XI`QB5XTUxen~bSmAL6J;tvJSkCU0gM3d#(oWW$IfQXE{ zn3IEWgD|FFf_r2i$iY`bA~B0m zA9y069nq|>2M~U#o)a3V_J?v!I5Y|FZVrj|IbzwDCPTFEP<}#;MDK$4+z+?k5&t!TFS*)Iw)D3Ij}!|C2=Jft4F4=K74tMRar>_~W~mxphIne& zf8?4b?Aez>?UUN5sA$RU7H7n!cG5_tRB*;uY!|bNRwr&)wbrjfH#P{MU;qH>B0Lf_ zQL)-~p>v4Hz#@zh+}jWS`$15LyVn_6_U0`+_<*bI*WTCO+c&>4pO0TIhypN%y(kYy zbpG4O13DpqpSk|q=%UyN5QY2pTAgF@?ck2}gbs*@_?{L>=p77^(s)ltdP1s4hTvR# zbVEL-oMb~j$4?)op8XBJM1hEtuOdwkMwxzOf!Oc63_}v2ZyCOX3D-l+QxJ?adyrSiIJ$W&@WV>oH&K3-1w<073L3DpnPP)xVQVzJG{i)57QSd0e;Nk z4Nk0qcUDTVj@R-&%Z>&u6)a5x3E!|b;-$@ezGJ?J9L zJ#_Lt*u#&vpp2IxBL7fA$a~aJ*1&wKioHc#eC(TR9Q<>9ymdbA?RFnaPsa)iPg7Z; zid$y8`qji`WmJ5nDcKSVb}G$9yOPDUv?h1UiI_S=v%J8%S<83{;qMd0({c8>lc=7V zv$okC+*w{557!ohpAUMyBHhKLAwzs&D11ENhrvr_OtsnS!U{B+CmDH-C=+po+uSqt z+WVVXl8fKe5iCZoP;>}4OVen6_|uw8*ff-r;)O2W+6p7BPT7sT<|Qv=6lgV#3`Ch${(-Wy#6NA$YanDSFV_3aa=PAn%l@^l(XxVdh!TyFFE&->QRkk@GKyy( zC3N%PhyJf^y9iSI;o|)q9U-;Akk>;M>C8E6=3T!vc?1( zyKE(2vV5X_-HDSB2>a6LR9MvCfda}}+bZ>X z+S(fTl)S})HZM`YM`uzRw>!i~X71Kb^FnwAlOM;!g_+l~ri;+f44XrdZb4Lj% zLnTNWm+yi8c7CSidV%@Y+C$j{{Yom*(15277jE z9jJKoT4E%31A+HcljnWqvFsatET*zaYtpHAWtF|1s_}q8!<94D>pAzlt1KT6*zLQF z+QCva$ffV8NM}D4kPEFY+viR{G!wCcp_=a#|l?MwO^f4^EqV7OCWWFn3rmjW=&X+g|Pp(!m2b#9mg zf|*G(z#%g%U^ET)RCAU^ki|7_Do17Ada$cv$~( zHG#hw*H+aJSX`fwUs+fCgF0bc3Yz3eQqR@qIogSt10 znM-VrdE@vOy!0O4tT{+7Ds-+4yp}DT-60aRoqOe@?ZqeW1xR{Vf(S+~+JYGJ&R1-*anVaMt_zSKsob;XbReSb02#(OZ z#D3Aev@!944qL=76Ns-<0PJ;dXn&sw6vB9Wte1{(ah0OPDEDY9J!WVsm`axr_=>uc zQRIf|m;>km2Ivs`a<#Kq@8qn&IeDumS6!2y$8=YgK;QNDcTU}8B zepl6erp@*v{>?ixmx1RS_1rkQC<(hHfN%u_tsNcRo^O<2n71wFlb-^F2vLUoIfB|Hjxm#aY&*+um7eR@%00 zR;6vT(zb2ewr$(CwbHgKRf#X(?%wBgzk8qWw=d@1x>$40h?wIUG2;Jxys__b)vnPF z{VWvLyXGjG4LRo}MH@AP-GOti6rPu^F04vaIukReB|8<7&5cebX<)Zk(VysCOLBuL zW9pEvRa--4vwT?k6P??+#lGMUYE;EsaU~=i_|j!1qCVS_UjMVhKT%CuovR;6*~rP0)s5eX zxVhGZv+qtpZ{_FDf9p{m`ravh=h>mPMVR7J-U@%MaAOU2eY@`s-M3Oi>oRtT?Y&9o({nn~qU4FaEq|l^qnkXer)Cf0IZw;GaBt)}EIen=1lqeg zAHD~nbloktsjFh&*2iYVZ=l1yo%{RK#rgTg8a2WRS8>kl03$CS(p3}E-18`!UpyOg zcH=`UYwn0b@K1`E&aQ%*riO|F-hq;S;kE7UwYd~Ox(u)>VyaE7DA6h_V3_kW2vAR} zBZi_RC*l3!t;JPD;<*z1FiZt;=KK-xuZ`j>?c5oxC^E2R=d`f68!-X=Xw2ONC@;@V zu|Svg4StiAD$#wGarWU~exyzzchb#8=V6F<6*nAca@x}!zXN}k1t78xaOX1yloahl zC4{Ifib;g}#xqD)@Jej<+wsP+JlAn)&WO=qSu>9eKRnm6IOjwOiU=bzd;3R{^cl5* zc9kR~Gd9x`Q$_G^uwc4T9JQhvz3~XG+XpwCgz98Z>Pez=J{DD)((r(!ICFKrmR-;} zL^`7lPsSmZT?p&QpVY&Ps~!n($zaAM8X@%z!}!>;B|CbIl!Y={$prE7WS)cgB{?+| zFnW-KRB-9zM5!L+t{e~B$5lu-N8Yvbu<+|l;OcJH_P;}LdB~2?zAK67?L8YvX})BM zW1=g!&!aNylEkx#95zN~R=D=_+g^bvi(`m0Cxv2EiSJ>&ruObdT4&wfCLa2Vm*a{H z8w@~1h9cs&FqyLbv7}{R)aH=Bo80E3&u_CAxNMrTy_$&cgxR10Gj9c7F~{hm#j+lj z#){r0Qz?MaCV}f2TyRvb=Eh|GNa8M(rqpMPVxnYugYHqe!G`M@x(;>F%H46LGM_cU z{*0k6-F!7r3;j{KOaDxrV16WUIiFAfcx?^t*}ca4B8!-d?R|$UxwV8tyHdKL zhx;7%0Zn#qtx;S)REtEP-meAlV8*1qGFbRJ*eeX&+hsiLF*g9%r0Zl`L^Kn`4I)ul z32#3pg6Mu$LEI@hssUb?T$di_z zHgaB3zw;*0Lnzo$a~T_cFT&y%rdb*kR`|6opI#Pbq~F%t%*KnyUNu|G?-I#~C=i#L zEfu}ckXK+#bWo11e+-E$oobK=nX!q;YZhp}LSm6&Qe-w0XCN{-KL}l?AOUNppM-)A zyTRT@xvO=k&Zj|3XKebEPKZrJDrta?GFKYrlpnSt zA8VzCoU+3vT$%E;kH)pzIV7ZD6MIRB#w`0dViS6g^&rI_mEQjP!m=f>u=Hd04PU^cb>f|JhZ19Vl zkx66rj+G-*9z{b6?PBfYnZ4m6(y*&kN`VB?SiqFiJ#@hegDUqAh4f!+AXW*NgLQGs z>XrzVFqg&m>FT^*5DAgmMCMuFkN4y*!rK^eevG!HFvs7nC672ACBBu5h(+#G@{0J- zPLsJ{ohQEr2N|PmEHw9 znQ`qe-xyv93I;Ym=WnoVU8dau&S^(*Wp=}PSGw;&DtaKz-);y)zjD|@-RT`*6nowj z7B%)h3>Lro-}5THC@BLymuL&3~kh8M}ZrZGtYKAmrT^cym$^O!$eeK$q5X2JF1w5a}4Z6yJ<=8&J?(m6U?;+ z{+*B;P@yGffMz;OSfm7NDhkGR5|7&~FNvel8Yj{F!DWnHG>%?ReZ$1w5I$Bt_u|4v z-ow>!SF!pCGrD&K8=-<;Gp@oB<@9C&%>vPHrp4sQEJj2FdedjC=0FqD>EG?NCf=KQKVd^stDZP7KNCAP-uEO*!?vgwvdp&Dm3h5Cldn!cIOL@u>1!HSfK+~kn-9Ekr|MWNApAJCJ5&5#izmjm z$CI|Boo@;O?Z(Bo9ejP>bbH|jRKn7W3y0L1!O6v$RUtt;%5R#**`+39c$JuO`SMU+ zbzu$7Eu`JQ+ri_ap{w(R_juHcw0X8~e$48TzBX%Yd+HkSSYt2){)+rYm48G^^G#W* zFiC0%tJs0q3%fX_Mt8A=!ODeM?}KLDt@ot6_%aAdLgJ7jCqh_1O`#DT`IGhP2LIMhF* z=l?}r%Tl#)!CpcItYE2!^N8bo`z9X(%0NK9Dgg^cA|rsz?aR+dD6=;#tvNhT5W}1; zFG@_F2cO&7Pdp1;lJ8?TYlI(VI8nbx_FIGRX^Z(d zyWyJi58uPgr>8w$ugIGhX1kr*po@^F>fntO1j&ocjyK za8Z*GGvQt+q~@R@Y=LdQt&v=8-&4WOU^_-YOuT9Fx-H7c;7%(nzWD(B%>dgQ^ zU6~0sR24(ANJ?U>HZ#m8%EmD1X{uL{igUzdbi+JN=G9t`kZMGk!iLCQQiVMhOP&(*~gU(d+&V4$(z=>4zqh(GX+9C&;~g2 z9K2$`gyTRJpG_)fYq=9sG^1I{*I=s%0NX^}8!mJVc?y$OYM^n!x(2jw$$;}n&dh%D;St+FA;eW=+28j#G^YLi@Gdk*H#r-#6u?7sF7#_pv?WS^K7feY1F^;!;$rgU%J zS$lZ(hmo$F>zg$V^`25cS|=QKO1Qj((VZ;&RB*9tS;OXa7 zy(n<$4O;q>q5{{H>n}1-PoFt;=5Ap+$K8LoiaJV7w8Gb%y5icLxGD~6=6hgYQv`ZI z2Opn57nS-1{bJUr(syi^;dv+XcX8?rQRLbhfk1py8M(gkz{TH#=lTd;K=dr!mwk2s z#XnC){9$x)tjD0cUQ90|hE2BkJ9+_tIVobRGD6OQ-uKJ#4fQy!4P;tSC6Az)q?c>E zXt(59YUKD?U}Ssn(3hs&fD$i3I*L_Et-%lx%HDe%#|)*q+ZM-v%Ds3u1LPpPKe-q} zc!9Rt)FvptekA2s+NXxF7I;sH1CNPpN@RT+-*|6h*ZWL{jgu9vth{q)u=E<7D(F06 zN~UUfzhsK)`=W%Z-vr#IIVwmdb(q7k+FX-lciYO%NE!xl25SV53Hwdql-3>8y5X1U zWa3_Qfp2Z;jVX+N+1?`(dx-EJL)%oQsI0G3S=ad&v{dzNal~flHvq(0HjY!v;oE>n z4gQSa2FdJI52Weu$+lED4VYSW;D`5Zn`C#@7Hxa1Ls*#TLBjje(%NYFF+4uOc~dK! zlnyxE4NWVz0c8yx`=sP2t)fHW(PPKZPp{SCwT-on2sEM9tyGO4AW7|R;Iw5|n1KpV zR^S>`h}rxcNv2u+7H6rCvMLMV3p*H#WcN}}t0@Us{w}{20i<-v> zyos+Ev_>@CA**@JrZ6Jzm=pWd6ys`c!7-@jf<~3;!|A_`221MFp-IPg28ABf6kj-Y#eaRcQ!t!|0SRtkQK^pz;YiTC@@lJ4MDpI(++=}nTC zRb4Ak&K16t*d-P(s5zPs+vbqk1u>e5Y&a!;cO(x;E4A4}_Cgp_VoIFwhA z-o^7)=BRYu)zLT8>-5os4@Ss8R&I^?#p?bY1H-c;$NNdXK%RNCJHh)2LhC?B9yL2y z(P-1t9f~NV0_bQ{4zF|-e^9LG9qqevchug76wtFn95+@{PtD)XESnR2u}QuG0jYoh z0df4#&dz_FStgOPG0?LVGW&{znCUzHU%*b1f~F+)7aefg7_j76Vb|2WuG#1oYH_~4 zrzy#g1WMQ#gof`)Ar((3)4m3mARX~3(Ij=>-BC zR@&7dF70|)q>tI$wIr?&;>+!pE`i6CkomA1zEb&JOkmg9!>#z-nB{%!&T@S-2@Q)9 z)ekri>9QUuaHM{bWu&pZ+3|z@e2YjVG^?8F$0qad4oO9UI|R~2)ujGKZiX)9P2;pk z-kPg%FQ23x*$PhgM_1uIBbuz3YC z#9Rz(hzqTU{b28?PeO)PZWzB~VXM5)*}eUt_|uff_A8M4v&@iY{kshk{7dHX1vgHs zC%vd9vD^c;%!7NNz=JX9Q{?$~G@6h!`N>72MR*!Q{xE7IV*?trmw>3qWCP*?>qb01 zqe|3!Y0nv7sp|Md9c z4J5EJA%TD-;emh%|L2kLpA^g>)i56v6HIU8h7M+KSWYw~HHz3`ILj*{==jD(l33>r zmOdINZ8^Jo?ll^~q@{^5l#*3f`ETncJmo?iRLz*=W=o3MJ!K^xjVcw*H}p63#p4XX z1)|C%{Y&)IpRIk5oMVsUi6oyKAFy8MH$@|Zpjr^lxlMX3O{0AZTjc{gso{KRuo30V zUJxq2K=_CwV*Qx_D!hJCBTuQ}5oMNrWUBNVaa8zyMg5lrXgv8Zw@rm5NAcFplYa>P zmUNB>EB|r?#Z!Gq^`(HZl__UJ*K5 z=>`{UTlt0;Y+LmP1Wb19IWK(SIWDrqh=+K81c`t@BCS|2#@K0u5eEwQ7CG92=Axx4 zQ?CPaVE5!XY`2r!Ce@m(tRtB=&+c>a09WzP-Ys!~i;V0hEq}PU8n1a;bVbJ17rYW1 zjz|KkLZoO7-S6oQp_ocIzS43P@CJJxQ$k;$!fS3*V)m|VtBIEgCtU@W`AG9VMU_d znB-Zs3I)I(Wg=xj)Wcx03h}U3i5{D@*udPLg?Jx7dp&KEIwJiW=eh}Ps#FxbsS?F}7z<;<5RP6-UAD+_An$s3y-JAC zh{JlAX3e^CDJl1gJDbH`e=hD88ER_6+Mw8CwK&^|$BnzA|AvDV`#xF^z9b6iWb)0@ z+gir=oSUaVcJi%1k+9!pd`(3|h~4}!NM7NHPNV6rI(W4~Ie5 zl@(Xg2`OSq|HJRUg3qgr-c!}9@W?pEJXKtxP7f(aE2Es33gRSu#~XiCIpV-J;JLM{(@qK2wEvsi@6-9(cyXX!6YS0n7;TK0Ldf*JGmlvrF0 zGQ+Z509rmWa)O}r`z2W3!6u{^ZQrY`KR#VlTRmllG2v$R!7%B~IU@XnNi!E1qM$J8 z%{XFU4vy_*M0tKjDY3E*7N!d%&vnx5qr#=!IKWZfoRo8j=7ji1{xW?g^)A|7 zaaA5Rg6rwCF?y33Kz-90z!ze`@5N916S)(fHPa>{F`UEF8N5PTNjbo)PF5W_YLB*# z?o`qxQTIzokhSdBa1QGmn9b;O#g}y_4d*j*j`cx^bk(=%QwiFxlAhFSNhO0$g|ue> zDh=p|hUow5Knbclx8V;+^H6N_GHwOi!S>Qxv&}FeG-?F7bbOWud`NCE6Tv-~ud&PS6 z;F*l>WT4zvv39&RTmCZQLE67$bwxRykz(UkGzx}(C23?iLR}S-43{WT80c$J*Q`XT zVy-3mu&#j}wp^p0G%NAiIVP2_PN{*!R%t7*IJBVvWVD#wxNRyF9aXsIAl)YpxfQr$d%Rt20U@UE}@w?|8^FMT%k36 zcGi_Mw+vMvA@#}0SfIiy0KEKwQ|`iR++|PF2;LtiH7ea($I{z z32QPp-FlEQ**K_A@OC943z`Qy7wC~&v z*a`z;(`5(e#M|qb4bkN6sWR_|(7W~8<)GnX)cJAt``gu8gqP(AheO-SjJMYlQsGs0 z!;RBZwy>bfw)!(Abmna(pwAh^-;&+#$vChUEXs5QOQi8TZfgQHK$tspm+rc%ee0gy zjTq5y20IJ`i{ogd8l?~8Sbt^R_6Fx*!n6~Jl#rIt@w@qu2eHeyEKhrzqLtEPdFrzy z9*I^6dIZ z)8Gdw1V^@xGue9trS?=(#e5(O#tCJv9fRvP=`a{mnOTboq<-W$-ES7)!Xhi*#}R#6 zS&7hR(QeUetr=$Pt6uV%N&}tC;(iKI>U!y$j6RW&%@8W|29wXe@~{QlQ0OjzS;_>q z(B!=A71r|@CmR7eWdu9n0;OJ zP@VOOo#T+N$s{`3m`3Li+HA4owg&>YqCwsA5|E$b;J&v#6RbT$D!x$Yaflo92wU?A zvgD8g(aY`g7}Y2^2i31ocm&k9Km`NQipEsjU>MuRzD35*Jk7^Q(O;M32!gt1cEB@- zBOHd@@Qo{fQ^7o{FiNdS)_vTiP8toqZ`iNi^1-4(hp+s751}Tf34b z_UYQ1q0~*jIp9pRIpI8ue}$|~uu0#p>-y8t{yEwB(8yAjMXrJ{`{rp7*-wlh8&bso zHV`LnAF7Bw+w}Wm9ii3U@lEvcc-i$0&h+eUmlQuREzg!ao)ZjwThhqIKA})}akyX7 zcbuIw9K}9aUZ;hvAxk~rqpk?bYMWr-@b-pMTR8))ggQa$kBv=IinobKCR0?S&g*+Al2J`VR7he{}0Pu zae7LYa!OoTOk8?ma)M@Ta%NxQacV~KMw&)}fkmF7wvmagnTbWo))`Kofr)`-pNe99 zMnam7vRRs5LTXHWNqTzhfQo90dTdg<=@9teXaX2tyziuRI?UOxKZ5fmd%yNGf%Kis zEDdSxjSP&;Y#smYU$Dk>Sr0J42D)@hAo|7QaAGz(Qp*{d%{I-#UsBYP2*yY8d0&$4 zI^(l62Q-y4>!>S{ zn;iO%>={D42;(0h@P{>EZnIzpFV|^F%-OJADQz(1GpUqqg#t!*i zcK}eD_qV$RmK}-y_}f$Xy7B+hY~f4s{iCD7zq%C|SepGu`+>h6TI}dUGS3%oOYsZ0 z#rWTU&aeMhM%=(r(8kK@3rr|wW^MFE;dK5&^Z!>`JV{CWi^Gq?3jz~C-5hFFwLJ@e zSm3z9mnI+vIcF+RjyOL!VuZP3rJDjPSm4vYolnm)H;BIz!?dLyE0^5(pm)5*>2clW zaI^*Z;p6iGZW~Gr0(Eh+%8Jkz{S9{}=}Ewi6W0wF3|BbVb?CR2x>4xST?woP;Mz8L zDfs+0L9ga3jcM)zCC=`-ah9#oulxt9bZq9zH*fJK$bhT=%(2bPMY~}cPfTyE{_4p+ zc}3pPX`B04z+T>XwRQ4$(`U~037JrmN`)3F8vu_OcBE}M&B;1Vd%|I|1tni?f_b&$ z5wpdJ6F*oif)r=IzB$ytT72GuZi$y>H0p_#amQcJLZ^4KZySOUrRyXy3A2(i=$zB9 znZnGFLC34k?N@s@`)u8aZN({9Hfe}|^@Xk(TmCqNBR*Bter>opM!SGiDU8ShK6FNp zvod~z>Tj!GOXB^#R>6}_D@j67f5cNc#P;yMV}`S*A_OmXk_BIq3I$C}3M~aPU)agY zWC+0JA-)}O@e4XTtjzen&g=J0GIVNjG`_gS6ErXj3cGxeDN*4xEk0PNzfzO@6gb&N zB$S-WV-@efQWs%UX$AVjFN5M@8U>+?Mcqg?@=Z-R`~n~;mQGVJT_vBL|3^fHxZ?#T zE(Sd`8%2WHG)TcNaCHmv_Id%D+K}H3s&c`bxKs(_ScZzyCTpvU zHv~yhtKF9G{s+GC*7>_D@F+qEq@YmXiKTV(j#X7^?WpvIg!Yxi6uBAhh7<91{8vFL zfT?Y~vwmE;(WOL!V5Ag&#@U$mP~T=*#_ ze#QynX>tO#4IJqSj^UB>8ubSEn>Nk!Z?jZE01CJCYuY`1S3 zf%2eyXaWoAQUw)KYO;wi<&+R3_7E%h(7F?xq!8l>!^3Jqj_tNPrG= z+y2S-0j;(AilOo;>SCQu#;Cn?y4Eu za`??!yHz)qFH1Z(3KMqgn+B$&t+5s0zY|}<1kB^Q8FEAumh;^;Yr~amTx1K2%2JUk z@7uIE&0DVch|1R=ro5rjr)w!iU{_09PqfhnGqhAN^$^oz#wVNdTRQ!8^nF};4);Jz#=dTBTMMW7icnZ$dK1E0UEgP4&DNk9MFoKOhtAkVUR`d_vc!x zc|1mY&%{PBxepp^JPHmFDBQ8t@DD-3!C)-ZhGJt)?{)^0MvC%RzI;4}>XoOUF;6~j z{S20Ra%PaiGvM$pFbH;N6)b1J(N;{+Gp^^Qk34JAuPKH}Ap}fen!WlC5vrQ0$pnyq z5poi8VG>>PnGw2^-CY3XdG3<;|0xU}#WBPqn{mO=z0RwL=MXn3=;oA(1C@V^6F;ogwB4EBUpltu=)(MC@To2kSPbL zDdGz|C<@`&!MmQ*e>H>2Qkwa~K%;yZw;SnM<=qwNHu-Dh$r(}-d}T}u!=UOAkzvEOiZ6>{)t$$# zlAmjO$1)&1Zh^zdh8uhmZ>OBA1T4%s9Jex_y4|ifY_=XoX6UzpP;MuC5su(6%;)NI z4d#4aW<*)L6o7w?MY2+jRx6-3S4i zC(~)A`|)5(s?)pBvTfYjwvr@Z-Dx-F7uq}z#WJB6&}0TIi6sGXFWOxD!As%cUg)_A zI)sRCf-5kPBU|rVm0A{!s=W2){AJwvShr6Tsvbg|NrXi!7zoMde_n>-+XFX0fiQy~ zjRp|;6~pR()0a>ETtC7mZD|i$Emj!r-gq!yhAFdV1uR*M<4O?t83N1JRT~8Cy8Vha z+STlcw&CoCJt$k^#ar+~DBmvtC5tr{(>|W6wHq*NSE!^#8*rs>!oYj%fl9~Nu*d4t zdk!|mGJehKW8xJE5ZOcHRfp4plI+l1Pct;rK={=P`YH8&1hNW*YE)4yF2@wa7JFaL zLHJH6ZWc1j|nQ55Znh#>tV`!~N7lY_05Cq%|8I-yN}yf@EzDG zBL z(b0sjh+ui^*s(rg)=l8fU<%cPfba<7y?>}j3R83$2KHzWbVF*`!x^V8JY`D0itC?ZSTYH|w3lUD#$5G$@!v(Lphex2O1;%>w;Qh$t7YF3EjFuySPC$>~%EspW}@Ctn1Bghd5*HVJ=tZK~8oMiZ@9IxfFLSk~>p9cT9gOSPLyP!^bOah`U-6{}C_ zmyhS7S_-tYDm|9C6(Wu2Qe=*g5@{**z@#Ekz3Y{o7fw!^4z$yi z&=a^zmtOpsRO0lFr&c=khr)cL2v9LFKXRDdE}tWlOgpR%}oWHCeJ4;(9U_HeJYl! zwz$p|t6?#eCju@0{IF0gbk>So3C{Ror~JTpuOW!G@^?lBVrf zf?%rDK2E3x=xGC)J_lEk{(ESh-Uw*#k-n4l42f3oC3BJX0-2NMZo?P)-6y1v+?|+< zfFHX8(bw;H@;6K!?=!B#eZrkowcdn7)roPT=WM@MK?>T-cUa$oQdYp&3YRdWu~rhA z@rZKmqj8Ftz-*@`&iH|) zC(H;QiqYx4{Mz@rm`qs~*Ue~4EHM^J7i{QnL~t)O)tnwIQC;23p}TBoc=9rcuS!cQ zQgl)_F@t9{c)ESLtAcg1AbCXqVS%i1ZZRiy$*?Bu=r2ad13e|ZeWV=3pSL>YAk>X& zQZAY4kJD`CYrK-nNti&;uJ*e{cRILOFk@z?B@fNO(exjUhf!b=yuC`@(RS#ko1HA+ zOwsym7?F)}ufcD5&IV+qr+i7Mo3)6M2oI)*3?@-%ah^0rL#0PIn}XmOTP9Xsg5C;t zqkFe6yT##_ZG5KuhVQY)89LfWOeXpXVNWX2PmiRqq<$C!<^WlyO~Q=pk${$DsWY-7 zZ->4<+c@KPgKzKosGPF+&Q*>L>WaN6_FC~SP~3gH7bvg6>QgPzp`&QTpf3W>HjxDxj!y zZb`O;&XZzI2YJ4!^Mq5~Vz7lLv`StN|TSP@jdF}@9;ql?u*#Q+_E}~hak(3B%AQNq)t7PKgAWTYp>EJz^VIj67KcZ3^vvZ7{b;; zcOOArcAw2$T+$UwIib|pt3i#NAuP#3?Z@Oaz?Mt(H&u7HZu!03kV7`t5IRcf7hwck zf{Ujp*YsH;dvcW0q|=o$;z#Cg52;n5t1phY44To!sQ99h`iVzXd+v(L%?A$Ks|Ne; z7fby7IVUXqN8gzsnL-s?uIv>=Qh!qAxoe{fRaI&EcSGCTdggq-Qq?DU%SBOummO5cRa9NW}V>A0IH#pxch)!$2p8=^-XYjsB%$S$U5nI zlJEMBb!BZ_O4@87cEYUBH7}Y_MF$+(~gdf-!7)D-D)+O{*18TC{HGZFF+`%IPcmK{O{YxR> zSfJHSeQCChuPUAWe_x~gy*f!!wvt_tL-Dp=nUm+juu;4L6N1IIG4dsVMat#T^p7p1n*Tx2a!YaivBTqLsSJAF=kJej?@QWf)Y-8Ks>WkC456{B#hW-ML zI+f23(}F=MeSdbWQ>R98TOzv#Haw}ua+17H=P5|~#BDmoEPkzl#lBTvCoyj`XU|IS zHn?dXbq>rqUW8^kQN01zL~6!Vxn4!$Pu|F&#XbiF{{>T z)&khW&2Y?d8^jC|phWKQ4!CM9b66+l*HTdPm+)M|e5yT)I32Q~2ENVJ*ZH;JF^Y907{XNHLoQ+85J~!w@3h_5d04o=~|1 zCBAvjnXMn`S#qMkPZE}9#RX`%al{`J=oFKk(aJYT&Ss`4iBrXa_pQ=3lS1IUFA|Rr zgnh;c8nkGH)|*yyoUZ?tE1XKwkF$n6`sdkf^7)(wZ52xtm86N>o&&jG_@#ue(B`xPM|8oGz94>*kl17-|d^y0`D=&hScq6gGQ%Z6|LU zG@<~h-R{xW)y7k1x7XFw!TWW~HPC^bCO_;xG#A4he?=xkLjS=~U!uR+q>vqJxCN~J z+I}|P5RTv*qRT{k2N^Kz8OX*mz$hYR!aYq-f5bN4R4=omUVP19L|)EZq?O0#B9 z<3G&oAZ`UeIqZWlujz8UNNSK#{=_c`*(&TwlIr3ZpC0sfS5Jy?;t+&wb1g4Q91rRNiEt1|L zisgH;)V()S&(TSB|1yAxZLH%BY`nnhUw_6sz~zdKCCc!ZV*Ws6`U4u|CBpv4pYIX1 z5*)5C*N#D}gj<@pdZxtw!`5aFVQ^Jj?1W z+EsBx6>WV`%wnP@Fp{XlqFkbHf%LfCgIi_|w?uPPjHAgOF+lDnAb+WEB+i_53PFmu zj!=umx@ez9mVxC&jA_RtKRfQG>Cz`A77S2SpOt7%Rt*}fG|yO+2t7CMuK$^}D#i}k zZmO9yUwK6%!LbRsULVnxUxfxso5KFES=!WCm>y&YSR@0CS|iON0v59pkQ7dVA{j*+ zmcRtD@lxXuFq@#$DKKSal#ApSJLw58m_NIJ?z;eD3Z8u*-#}EaK zyG~L>-7laE`Y}{g#FPs9YA-wT4>X>xRNtTHp8_rhvWA|eJH(!o-G~C&tvHB9$UEJI{ngD>QjBz=wl~x-j1MB z4)L_#jZSvaQkbmVbN)4{#^r&ZmfhhV%?tet3`xJ;#jI}DsS94qc&s)#2kXv5pkt;K zaY6emqzF1JWMxI(7h}mk*MQ5C8WLAol60!DPj|u0jMrLTkU7G?ud**S@bYx-vp$+r zMVXWc4H}2=yF+YML9!k~LT(|<#By?F2bS~weMi9dD@DA&k#0e&MM1YT!qoQDeNLwB zA;{KvwSzP?-K(>@_b@4vTkIX7xwj}ckrusCw!k=#;Krt6;}3q4d*)?c{>I|C2I^4p zR(o48TqHbw?4Z`c`>?P{`cT;FpJoFW1wJ3IVO#5Q`wsB>o>zsRDDATmct`aaYQbTL zJVlHeok9_?w83#Z*J(_BMs-;N;mNeq{;f3S zSy{i5hNY5s`c#)~KhQZ{0_hNmrMD2b7CLC2+x#EmLcNa8V1Q=jz@e~VV)Yq!Z|$nv$TEG3j6K4opW+mH z3~z?*H$qobb652kQ}ZHFHUVj$%JAwS-Ie=Vh&Iivx3hjMCZ1k)4dRjdhxRb17P;Gz zZCsB4J=l1S8`O|(g!8c$aOMaYeUoCJj&n#kbDxe(^GQ)E)$Rq+i-wbPKeaQvL!`Y- zcL=QOLcWBdDq_`HLow9P5BG2EMY$v;w9cR$C{ zMv)5zrmYv!uzHFAxDI>aftAp&ad>GYoPt!d;A*$s)^6E5l5ct#&O7A0p^8J1ceXa) znIq{NgKbbOSC`6E_af2bCoI(gD@(krDr^mDVw>cRz3zJ^&9kbuf6)J@Cd#zbnko5m zdyD^j^!9J7`oH!u{~wlOl7jYM(OcdI^#*5Y>BjUumq_g&tx<#_pkzQL3{!g?50d=#eCov*uIw$N*glXJe1F{FuUF_wCElS)Z2X= z8&w0?WkCX%HfL)#n-m1tiLy!jDMqH$LikJF=#lu@k5%&vN zOEmQQ^n*t^76E;JhHPzQqbY0+m8GQ9;~dJLLZ@*sqVX0ui5yz%8Hyn87vqUisY_0- zDtUu5haWdOvDBOX9Y;=s;7ul^_xLxfU(?k(HStRfk0Ab!pY(scal?Nz{Qu?etFHNA ztD=60Y>dte)hUle1IUyYIFgMxgGpvx%Odv4q;WPV?Zj<0pph+zWMfSd=SIUcB_#7^ zgNlm4(v!WIBm4?kpvZnCvp?TXW7~Azs3LT8Gh<0Ew=&W*e+4X_xQ{(e+UCESTaWwz zd1ly>%|#A|W%fgeL_3gAwxjeb?Wi3rAR3U#9Rie*)dfz7YxUK;ex+a4F>@qyQAL0^ zZncndzG56R$F&?R4SOX>&%UDdBid6 zIn=GRfcto+s-%gMB)Wx7!_Z+SS)f3IG!&s%P2eNfHI6~E*=>e`^RpvJQY?T95IOKL zeX-_BCdRE#f06_QAoDyMH;#IIBnT#PWSOtks+PCo`04X-brsea32I~@X(Bwl*Q`$c z{Al@04k=Mmd0}}ts=u%dCO;qn-;qh>Hr7bB6!NOVxy@Yi#GK2vusj7iU9757HTqN~ zNMoKeZY}o)nA*{CqTTPKnWi*JgZFZj&EjD$V;O9zqHV#tB#r5Ur$V3To8iP-bO*Gl_d%qc2$SoU`Hu-6*hWbuWzAn(83_jZ%>P{PY3XVV!q$~ALE^GC( zdIGgR(HnV8Rn*P^7b8#AzONo*U_W}{Ne!=#*qNJIRZzapu_fOkvki(|8NDg>&D=OZ zL3G)1WS*8CFh`-sb*#8*hIN7WDjw6<$D&T|B>JPi`K!*5DF(O*^A+r*Jfnt))c8|M zQKtgEytAqpy@~XZGnVYMJmZSG0U~uvP?i*?DhgDOSYtx6s%6u*vL$SW87`&xJ9cmDLrPHI@G7Pb*cizPGf|!5th41a2ijel>Xfk3i?7Bd*{|)@>|ZBi zH6gO9a2Yd&_ZeKmNQC^e&S$cl!3D2oBCX)C;Ve{0qc|4+*fwK!x{=QYtb#3QD1|Yi z%r?t<$-Mjbli1fF(C?V&w#;Gq3-**PgsGPPsXN(0fb?pIDc{s6b<9{t%6D*47A9ZHlc4rEGU<}u;tiom3^lA-&)1i=j z|I#)cctK)AH-b2*a3Wm%Gt*;#GWjNF6q0q^Evid`6G2yhMg_4TaMUK&x*D*5+KtlF#!)86A7pn~&yvD-Rh%`@(o!Wc#9t=t;(9_y*(MWS;4cPU&cJcE+h} z6fZHrjH@7{6~n40#qgL(yA-oVrt;Kcu=fV1WQ0QY`_I8lVds$PYR7KDvhsTbkC8q6 zct`{-n;z2!($SBZ?;(ZMu1sY(VY)KJ@%p)!LEBL+M{ck-$kHEx=3N+%$#msc!LKD> z?(7`Owu6Iuf-Nb|5wFxCm}U)Du@JO|nHV?%8lk(y3x-=F_d}u8>#AU~iWtSD6|VuV&YM=#_v-HDjZ4mS|L2%K2K}Mhz zVb)f#Q>%4Du>|ea6cbNYrpi<6A!rSmbeh7+xGZ{-TPG);DG9qg=>9!44ScDdh49-_ z;|KUp*RQ-So$jyV%Ss5FnJa^|LYAl%8niBhd%(W!x$Rpq@pcp6(XF^fHFRF2KQP>$ zo@`Qi&QlkFxp%0@2)7RlN4+NzCWo{?_x}5$E?kh!!UM3Vg9R+=xPLWty|S}5Gt_qg z+-v~8k*0?Bf0^Q+IZS56Ny~Q$pap&c2NUt&f7P9P+zEz*>bOO!5J8(uhIJ#%lgMNl z3;y^@Yht z_Dko1D=J@nc@`zIXz6dWsr`Kdt!m8`gGlx59A(t5ZjDVmrsjl#0wT@It~$j=uGRM! z@XJK@Q})NA_sQpEZkNduP-h{cP|l+Qqwr{g--LeHY2&||4dJFD34ZCj7@+4ZH4}La zjfr1gHXr8j#ppOa+gkiuHYf$a+VGA${f!~LtdO!~|X+>{b zY8=`^(0d9`z1f!nNzD`;4&65cNlg)@h5m5oOj&gG%mslXlc+jou#n#`d_l6}hwB+CG5k*Sr36Yrz zP2B)Pq#G?*Iwb)FJiXU@lTvTrdR&WRpV8sUz(Sx3C%f;BHSLY@I$!TqSg!%IetroG zD$gu&K<>-imH@Bh&}f!zwO-`w8Dt>MMZ>8V@{X1g?!2BS0S;GtXTW(%@{L=6uC*fB znj>TvA9Cj80~Hn`A5GSVpyqA$*6rlEa`u=Z!{-DRtCo0{jnK|3KxpDEi3&^DwWNg4 z%|~wf=EtEq^ku$fbX{@*EYr&TP@j@?OyLdVKVk*&H23K=xzmgV8p0Y|jK+@cNaPE1 zovLSR73MssgV04G7S-h7L}ID!!8|-X7U6-7?t~caWg)yk6*s=m)9us~kZ7pC6I1+@ zd&wXWPx{8Z>47wN=yJJ;BgQ&`z)H7hxm}Jq_9GiAq)9R- z7(@1=H+oqdJ(YFEq(LiJW=s}h(Yx~}5%_cQ&3xV0VUT%{sXE!% zVMqItDE@pLL%E2I2<48s8InBVbnt|shpL|$wrvbdWe!LJMr$c+e86OWy77OJ6k_2&3KMqL9=QFd2QUVwwR8X*sgj}5OpiFWK zkiv)DX__mAlH9kRszqfgqLLvBrDbP&mL;Amd=_UXSF4&!?$+*0ZswW?9oH!-BQgjS z*IQf1yzUikvx`UPXLZi2UvHaGMOee-cPA0C5fni_Q zcj2Hhbit;RZ5t^!?2;o_*D4W$VcsfIc+m?Z?b!Uv2;-s&XYSCUiczc2-b0I0g-hNj z@xi1}g6j<*=Dr7UMa-%w&YN`cBbWT>BQ~p;QyS!^#eQ>q9dy!?Nrh+?bfo*_kEe;nyR%9=3OTAD90?RT8#Bk}X#Pkr(TqBF2&!V=` z^iWLr%Yk96POnG@bEb?cv#Uk)5}bP0=~;%g>Sm{t#hoNp#yeFj7UxuD?en)EXw2%= zTS`>YY)#O023TqIXj@8o2KAM29NQM4QH=;sYP$pcqtRoxg?ZK@CWy{=P7(uI7%TOp; zP-^!0wmMVv-f2E>6tEj7ZTG#-KaZMuUUgl1|nl&p%3Dc8tZ4 zW{0iAY38oin5YwiQlKRrH8RP-h95fX$>v!l2*6R~)3vTQ7V(gjstAxGVc>U<8Jwb) zPTqZIfoIV>X`vA2EuAW0Ghj||3;hwn0w`nHnL~5Xr-xuSDNmuyhoZWBBa|hf3)-7$ z6nhe93c?Vv(WT4=mKowy$9Fu8Y)h5yEW6z&zzB7;Yf(a|ei#jb>!ayFWo?MkgWxQK z47{-ws_k4#8xv#$x229MEUK#x*X1k=2QLLnaWhYREFj!ta9&)3I+w+wuB-hQ0SFLZ zlvuP9c*O0k+Bm_8bPyfY2o>Ts&0yRSIg4c@Rv71IVHGS{L3?%!54(HvY;tru5FCHC z9_ER%i7@?-Tq&gCLBVg_3g3?9Gu6P$T^70*)YqUQTN$IHtc4g5UG7WN_J&c!4-lZ& z0a=#~p%2D>Wvx?z(9bP0Z<&FgpEnI^CYsg{+)}t}Teb>kj&)7NNmPz4Zv@MJA2cA4 zE{uQ3IbdMxWrxK|%90Rdmx)yBJ3FI$YLuF4DF~35POQtBilKK{44PuvYIHjt?~mW& zzNwc$LazTnX6dO-hE|>Wu0KO)5xDdvCq>WTfkeI85j!LDvSNHy0&TTnCpr_Y@_=eYt;}dhqY5=4^QRl&pzt9Bed!EmviR=h>B6ynC7MGc`x^9c*)$$|imA)E z9KmcfaDlPY6j0i|;UW8=8oO5$aRyZaYTM*qBd?3;u=u(KdjqYJ_fLd`tRoym(-gX) zqoT2Ua$jR%Ibg0>jte$VWiyOhLaYcnGe^pQ(V0O%I}YnENL$+J%d>ulP(v~JZtnH_wYk$}A_OsQn5BbzOkG2(!baa2N({4d%BrLdzn_qpUhmGmod2kf3s)xrh|=VU=smdZ ze#hs3hAI5A(;4e45x>FbZjXU=hACbM{;p^HFvP31DFz6_lHCVuZC63Xv9`wzN@Y6rcuoPF<~3V<@&m2~m3D5&4GW7GA+XXs{sPo!wDK z85d-&4Og)(j6Q8x3f?Ooxm7VJf?Nw>3_s3fV9y_1xSDfCy31yBhkr2LI_&)xUpcLxXfuNl6z9z^w)MF}E8U)#3YWS4&8 z{-CVR?>0{F?ccm>oP#mMTY-&w90y~vwccFmV3Wd60@~aufc|xzwLI_AA^-goYhcMf z>+D@$bjnFLRX|X?6oMyaW_}(z!Ys&@5~HmlWUY|}!wJnBP8YPsWvf1%(iPjQZ2#s7 zd=-ANqy%pCwL5&H8Tzs{Ux(<1et1ny> z?C%$W*FgAI%!nl0a{QuH&7L*cr$DOVP-67{8fQkKPfPD$L+Lv zSnj#tSMG<%-tcmKzH8dSPFO)VC^+Dw0|si;bY^#=`Ilum3dEF5!JrA9J z^7-aQuXu7vwaQBlnT>)~G|scmodeOzMFBpiJ_`6WePZh+=vMX276uFz4Vd%}>sndc z95j(>Uq_*mC-r*$6iUb)5mCYRy8>n-Y?K==}9iFFRN zB_u(i5p)JpS@Is*ArpnM&nOOwsI6t6IAmTNaVm+)*gWI?2fN{+=&1n$oGYcUGS!0y znn-1azfTgI zyHQk7RQGW=l@WF&jO?B1KXJa9;4BdKcfcpq35}=O+x=GE;TGw}Ub3M+AbPW8_LG;zZ%{IenPEAQ0yCE`_ z5medk+}GQkcA+x*kGZgwAC&01r6-zspCxwld`4~iEZGot%8<4p%sS7d>FR_YB` z1Ifjyuvj`fc|U|FGJ>_SBP*e_IMD*V%9fftjgs&{b6*4#VT3Vun6n`CvL$#d*2ygL z)7eoDSMZ1NGifW#;&EW?%%%0BG5R6&cx8T(iz?c$ah{_eCRo%Dp%dN0c9w$xeo))f z!{R2?4ug`a98BH;1&H}cNC!iP7dTNKFKcpxcOl6#wP-SCOy% z!JYwOsHXEGr4S3cKrNjJ=%MF4T z@!bVaWe=0&6`nIQ;)FZc{l;u(ho}|4c%t0S8wEmM$g~?uCNTxxtk^R4o;IIHXg4Nb zZhIyY?230y#03^WP!{XWxKemhpfBjbwIDOpx8d|`8Pt~dI`s(SzLBSax8yVhRmu9{ zw$*00x8`h$)GaBWP=7&dA{3Isa5b890UcZ}9{lKpxjTOUjiBd@0mQR5q$sBg0u@Iy zwll8RkI|Pv!)|-}!4Q;*3w)M>CtQ|YfuY*dE7B89}m%)-8C#3~yUl6@M z@$xCS^_0V!62E%u6hMI}Baijc^H8CqqH=??%n$8DrN(@_lxx_H?j+3I+s>0uS4W-> zq0;-tBt+ZUCJDUZPCC#K`72}xS)J822;Tq5LaYD!CkRo6su~3oN zg&ag$fC3ZxSR5uvsAWN7eFh2^)f87O^;9TTDscs|OpfUC5ghp1K49VjDrt>4fKO=L zLxxhlumLD^ZNtMYZExK9PV1gvZsMjXa&<%d^2M4I|F-IW|5xsB0rGy*D60s$dYsg6 zMdyH$$qnp@ADG-=TiGN!GTMc$NnfrNngX>@GClAFT;EKG&5U1Bb*)IV83-ppR>OmP z;mE%>wS^m>hiH7_YYVSpTmR5U_95QXcNL(22X&|AmEtABFNSh^r+yF3YBOQc4!O80 zW_5fFeqSWTBALo%V#({BIC-%Lq^vp1z-V;gLfX5Rua>+TgW*Re+49!T|9sLVQu&ivPtDwn<# zB=%%^7~>Vd1WyRru7m;?SybRpuTdTkp!CqN?qy2_^y(`WSe9uYa9qE|o zcGg`Ff;qg;-$@F&9QY~YAiHAU+kZCb9ucTo{Gb6k#xmH@V2*O=2$V9hv3N!FG!${7 zTp-rnDN>xcgi;~=_Mxb*sFFSwD6?;CdR1Cbi8F3{DehvaW-t1+1l`nx@J2Uuss#I} z7YEQopO?lmS-vrY<18fFZQj;RUYHV1%R8M@0Tkd>SU5a}8CH-r{t1(N7NT#$sq)^w zmVCLx`_@z>k8uq?b|oJ{kgpSC_o3O$%4V2RH#rTN1lnS2uTuJCihJod=< zbK*bD&;BL?vnWrN{SD(*)sBR6Em-F63?LK}2oSl&aN^HYHdZan2q(BF z)D7uS5-tMDl2IECM|7gx%2> zc};Ho`i;kR%Dy)GUpF~6W1Ki*Wd%6#FMi5xBe)PX;SaussO4z3-v?U!u2?q%8AwgJaANO0!?)r6)*$^idCj}7^=gi;C5G{41QB@Q*c8MR zn@7|~dhs0<3%J0Tf=dI8%-XKKYj#sRI^D}q0b6V;M(o(HwO9@8wBzAG+cAYdGz_#F+444xshfBlAac=NZ;*fOTY9TtZ05z^pR5AEUigsEZVK|3P%EN69l9T#rt ztMj^w%zcjN9ADJ>WP_UYuZX&jZR@ji&u>=*IXGQau?w2zE-No+$nTgu_GgZsa&$M# zZYvI)dh>Bd=#L)dh+N*aEL{^5`qD^U_KpbEKUE%6$K7WS@R1G!nIcLmnv5J+Ack3a z2%04+f%{()h=i%kj`tsqCkKKoh%KE`ZGs_5p$zYHg~mcPi@d*l{hE-c6mFY*IgBX* zL6~^BD26Gh26+p)EPJ2IL;Sue$6HLwX#VB^s1h4Q+Hww|5(zlpA&M+;`=Svm=S+;v zJkHERRBWx#%q|GpK%F+Rc$V1Q(oO+`kKp_?Haa3}B9gaq1r)nI#4!25hPe^VDlLJ6 z5!=XtON&dC5`5o5js^}ccFq*%Q{E2ZcqcfHG;3~hzIV1Smr2JnUrzA}qvJS0pHByD zCj6^D|3`QKV-Mkn7l`7C+;{KiDa87OI_;q(s#HJaMS4T(P0Ely98^+ZR5*wy_!G56 z3+J?z-u?HtV2|%ah$ea4I0FGlLpsR$NLzoiQt?zYqY;)WuKzk zX&zj^7gwX#;?y|AsCmpgmqu;LL}sQV%xExYp;~&@;1uwbc*ZH@^yP4QVY8iniz)@m z`NT(X?G-$aA(h8Yb5{k|ODM1t4fD*k+EhMk&aPsfdgTiZ`crm;aE@iffH$0xl)xzk zP;cf1mo~EIT*L1pFr>c)6bMypnY#=C1chd$F z%xSI__^fdrclZD!Ywh;nrQKS)Gv4n`Ga?-lrHjRFhZVaU8$}1Fr&DC&0+5EHg+pD* z&pKO@6Taone5>3KFT+$B7Il<7`8grSj`|R;58(C6d48Z%;pV6 zj;G<~o22D(mZ@K0+17Z31aLV+Ib~<-!z5SSzQzTB0}{rh&2duz%ly zaG}^#dJ9k$#eoF^;`w!0|1(z1zu5!@L z@tL*vL%QefR>d1{NE>i|3C`dpl0@?KUi{TkiN6mGNRUDey67%i8-Y4@?C?4BK3S) zfr7HErec}l`_~GWBpfXk`;cTxqhQ@?lDsP1%O4g~b66sRNmD#`1VWS0+t5BO78E2& zICkZ`iPxc*m11BQxRt7dE1Ik0(P7<}s}!ezaiQ@+*Mlw==xGFmqi$4i>jy2&9mUsA z*j>?_P%uwoz{pMh_#KrelvNTR1Opo6mb0SRdK0M!Onk`Fp z=ys4!Z0vaFCTK~5b`EdIQS#2A*Qxqp3-@B7aA|=0WBE1wz(P~(nkuXl$tH%v&|#9R zeLm0olbua(?JgZv2G?R6yz3gVQMwP#Y?)mq-k6@gOK|{k8!R#T#dqf~3JgcyYV_!1 zp9v$!CMgIg^wGUhsG`m7QN0#1VZJ^W5m6TdZ-x>ULth(W{8-URkIild7h~&lW-x6# zkamVW=Fm$^>gUSsTS%jcc8$w;GJ85Mm6ERkFl=0h8YO#a*X7vZdhL(NZ^$yXf-l)ch{DbY`+M4q6{fN>WVq;uQz|Q)ZP2YT2wh+vZ+$wOqNyK`2r(RlH>uebaK2avbVcg z{@;W^5h;qUc)ExRI?u}9`&={vL4h#9%kfVg8oSDKpXrtx)=Dkv95RS`c6_Ya%CPQC zTS5MSS`B|Ys|SBOr^kwpi#7i^XAT5X7Z2tT*1m^K5{>uKVM+tlmjz}bI(8LGIh*ms zsMRF~)Z zhf64Z9SiFjJH1?Ww#3?_{~Ehqr&!d1@{PteLg{| z77qv)uM`QvK+3m{7!R~TPcnJ&7Vd@$JSpSW?&Q|)()t24_zF+GMe1DJe9u=JL((pz z4@A;xoiw;3?LGCEciG5$Z{N|`rA>OUUZZTmgJoTfSjMXtou~^{@2Gdt3#}aVPkp&$ z;<#mYqWv~IR4PWq6R@TK>G(xHnxscc2G>Kz zna3IzOUIMP6YyJPT55w=uM}j6{e%$j8MAVCg2K`y>GEQHGW+Q1C~P&o&OS8KcHC@N z=WVu!LBgQ8k675M3KmokUnj4A2`EwxIHITBFM{dT(;41?F>3Zo@~au76RvQJs*KoS z&L@-VLeWtdWPLNQgrr$_l(4LdjNv_DW?{dFzQj%)S2oXPWW_8#V2>5y%Hx-?Of->d(WT$~az&0U;asF!k=o??sn0dY zP~Sai?n7|WSX9ty2<<9(n`Ys=AX@RNRjzxYcMjsFZ?*klo(9`Xy0pz%+dO3^(+0== zbA1P2Ogj6>A;Xc#xtnp7B~iZ?OK=h>aDmEqi5QqA&V7UYaQwbvoMw%fid2k?v=$&W zU9LC1N7!8#Q-WfmkA|V1){F$W1nSN@5^O7TnxTnpys|30Y$U>gDEnU0u7`$EzCUgxKF=SKK zc(M!e{m6AkXWHEu3NF(2SA@7<23J^(Jg^;%h5KGp(c)gN$N7PNs6sUOs-M(%hY-0? z|B;LE-P5z_yS}s1J{j;76a!AP{;PNwe>?_)&boGne>lMWCEi7uGGMK$fW+GXaJzP@ zLeKG9htxxEMuTA+D1<>_B7;wzX8q{haH4_P(6W0v8!dhg{dEgbRwR;)&j-;kT{BT* zGF5alYiw*J#lFCK_w@1W)i+2V*HX%u9(Z`}>My23@3YcyD46nzA%%NuA6 z$lONl=$>A5cNf{XGkwN zKJmz+b(iE7?Za|mYx@aj!F+AgUP^!_!U^+IR_LR7^Wd6_?3V!V5M8Vknv-+Y*0=VB z3RDkWb~q(Xg>VWlaH=;l$s&6kowW8sh+In-9=`2&@$jt{s5oin8d<4-abf1&S1-yY z4Xll-Q5$CpVd1vYSL)4;BBv`+o2Uw73krO-6KUK|T~D`hx1+))!2)*!D_zF}$3nUF z@+Bco^6H5c!eU*o;#dsv6N7QlCIKiGMYk#s&zjCk;|@N&6P?8zHiT>2<9Z~6OW+dy z1;en?LH?maVakQZ=w<717oPTVD5{odQy#~CajBt5Rs?}0C1?oiNK3OWSt#y7$R%ayCbDQ7oAH<-&`Wp2>)fn@T+)hdW? zvE+)d2_$+7ALBDazH-i|WSMsT%KI8p;uxa*y6SzABt(4(r{>`#y^}+@uNBzb65Cdz zz%0=Yndh4^T4e5FymIOP2e;OLU$IhxNx)$Py!MR08zX)l`2XVJ z^~^~xQbAU_TL8%u;DbF~QB3)XgcU}tLY7)W0SyEOdbQ!8*+P<|dL`kJ9q|#!JE2iF z2P|F)Gcm)p=B!P3ckkv1x081a-vK`zC7nzWwj4fZ4YttY{*0j83 z`PT;>OuT#X3hZf2Y|#0OO*KdOdF<`w8GXTMqD!jidZDjP_B-7vFClC@%wCpeyiVBR z-jHXmyT>GNns9^GS}Ruz7(N+Gs|YythV2@4+Vsb`i=eGpP)ZXpdFz-;FN8{;cCt`v zc+QT8%U1bDX*pG@Uj@NNt;c*Ds=wF$3*_JHS9k(r_YmL_=>d2n_*Y@vV3A``LM;>6=Nn|z zre+N07A%UrbNF+fy2fh#6N|1jjqmfH-t*^9**oh)QB;1kEqHS}+ypo@-}EWd{rd6h z%$flx&-P89`bb8uk&YOaJsvhT3Wg!wx(1MRS$J~<4L!=WM+XbG8e#Rw9dqM9!@ z+#_6QHns5>W898fQL8nHugDl&2EBr0Q&x_YDt@cktT5=HQP5iCd`p4gHB$_A!2NZi zfd&6%=r+PKcF zcD>}A2!}ZrljP{g7lSURAIQNm87b5}hmrWXJFAsVr&+soJYUbIW<3f`8Rn&64AN|n zSdEEN^c|s2!F}}qI+8?SVwkqY15P7FqL;E!ycf$J%{gv!1HO@T*!_;91hNgu4&Yv_ zLVv=T^B%)U-s|Imj%(pjRp^!<7P~u*P@4{oI(<@|8!tD9aMICh#2eS4$eGG3v%|!D z3A9hb5HtqpqehMMa#N!Ts_sj&kZ`-;{^vSa$2KvUzQTu(^Rn+6Ub!urJ5;1XyfGF+ zPk&ug5Jz{R?Xt?FQ>0Rd;JiS)`RxM2aDHoU{Tt$KM~`fJ4=u@MHp~=H1h{{0>(l^Z z)`#oM8@Fg94%5>@ozPzIKn4u?Z9^Kdq zb>z6+;*Il{_Z$%8;%)VaMOgBcyqA`}UcP78_o$yfdftM9!cK-_c98twa zHqXs$;lCQr75r$Jq!!*D1TBMN$&{KKiwJy76aO*8aAD0)##01^2jiQZ=S6PyL9z`dPCX(PcIvRFR%Q%oq&J*9@-?yiy6KV#!b`ri50d zRQ+HHJA+XuO_7QOd(_ieE+CfY<*sY!`#?Q6B zy5398or>DtM&>Pt;fqQzX%#y7TO~D@!Q8N`jsznSaHVV@QII_GY`mUV{igy`NP(A}J%X}?5&&wsZWPQiBz zc?)>svRp9m2Q!__B)myK^VmyYTJ!dL1hE0?7sFX%XPzI+HQT~=qMN2?g-TJ)yv&^o zP-?RkV&wTaPG0K7dqAKQ@lbwGb9HunYmN}@dk%i*Y6CgtG26<8lS=_zY90qI7DfB}ire6El{#mc z;nEwoLQ&~Dc`v!lIOL$!8Cqc^q1h(sj5ncZeba?%Dy69??%`Jp?ZZZ>TN*R4Ep}sI zw{?js2HG>`K26%gY%2}$aMg~J`MfG&2;w$5vc%2GLM?tmm92FD7>Lt&#@luqnUb7n zMTH2f?x*aH%6_dW3+wKB{N5x-bY8Q7_w;nlC+dFhl!&BN&Ff1*S?}lyRicHzJ65=f zO#y?AA+n$PMh7kEH#NpfC>Lnwc{{Z)Vlk`VfVXgIAuJw^YU76nsxsw4)XG69SOl3M zXsToc7Sjz)_Km2o@OS4l8Pk|X#8Bcodlqp{eX(rt5%t!Csf6D|iO(IUR*jxn8u2KO zQ2ElC42(){N+?>x3X&7oo+mgooiaS zIvzb95Qu_Akw-&VCsEKR{6ZwE1sQ^Dq&q8pmb6%CggTRbctH9@U2Nq8LLNW}pd=Wl z)2ye3h=#^9CL^`Tj0Z|w$>T;#V)NRoh|No=l@&1z-e+UkRuibQ&9wG2&Ky}hRs@pk z&{u^6Votln-4}O_cY$AM;?jnlE9nfz_he1h*m+5^E44Gg@Gffy)%TbyGEpeMe`{2) z5*7nD8Bstj#>{{T1EU_vd5^`35WIP5gh(GPDeFoGC)=FJWY{fZomyNDEx}y7*y@Q+ zE!*X`kfss8HWb@hx{mGnzB$zNE*{{roGJ) z74vfpFx-*xmyL|>aP{5|H_RRB2nK&RUyU)Q5Nyxk0h)N4isUHfG~i4EXs`76b>R{p zaTE$B^0yjYa0Dz4T!#L-BNMU4i_Hbr=KTo*#^mn;q#H-@)7~#Sw!WzJVyR2QRWHPVe)!r_j!+mZ)-gCwne;e2sekE2s#u zBB@|AlL)>RmIfI%!jyQ9yJ=36Y=kjt3Ss$!7>SBfYIXZ3iz10mkjP@voHl-|)^tIh z#IY2OH0SyP1y$O`Gex+}Lv)?dR?e$O)x$1IK~cET zQ>(H{FhP9X=x~9~8;=t1n2V;CyWI65+}B__iGq-W+!Er~oYCPvy%Po`*xl&OqhjBD zAY4Ky{Ib^XLF8{~54CQ6@9!S7KA#DyA;cCC4>(OU)A_lDLI*%?VKI zVF7!a^&(NWCGBf}7T177CBQTaEqJ;4=I>8sWt6@0_tP^XfDa+y^Fs#!aMb<(TLYk) zx#~9>06Tw+{0|I*1`1Fvhk^oP1X%b0y#E*V9xyumxR8KO1iyck6;%?Xmy{C&9Mu1N zvW7l2DgnShC<8udfX|;-p6~a!#s5ntD<~%^CaS3PLRRdr2;|R*0khqY3km3(U>e}N zwVm0c5a{ypIj35H*oP5cau-UI%12Jj*Mk^K9u z))ybJ{`#KRAIyIO{HY7|XQcJ#IqF>voJ9l7^EQBze{cRjuUcPVz+e9f@cF6^u)cF~ z6?Akk0mQyF)&CjT`8ng>v6_7`fMyBsA^DRIaIf`s2IS#4jFNwr;g6Th=XhX6ZYx@V zyea@v)Bg=m7ho&?4W782u7QQ2G9diCgteuijJ377qs{N3@iw)WdI2E!fL{82L-^0D z))&xce+LbS`D@{54>(sQW@=$5sIPBmZ!fEBrEC1B(!%q+kHG7QeUG4h2e9Y;J?{hn zQPbb#UG)!X4uGk{$kf;o5I!3aO8)nGSMbC)-2qeyHX!eee`XwTul2o0`YrVH_LKmK zMOgf|jOV*DHmd+K4g{#3?<2;aSFJBS#&6MOtd0L`EsWV6g`ordOsoK9{(da#&#TtA z6CeWen_Bpr?A`B+&$(K^f(v-Wjsc?p(Vu{Td#x`v;OB2J0fzz|bS*4?kG9e&6WRl) z%y)o+>F@1i2j~~SK@+mJcK9y4VI!++Y6Y;l{uJAI-UTFP8_1>rZA1zv>UYV6Kd)L} zU(Vk`|L6juE{6J!{}(;|Icfk-UP(0oRS1Ae^Cu+WUhA7G{9DvN9*Q5>-!uLDig>QM z`zLg*ZvsF><~J4bqgwyl@bg^b@F$)FU_k#3-rt)3zbPI*uZ`#Wc|TdaRDa9z&m+!r z*_@wnvv2-y^87IX|8@fXYyQ4(ZatU1`3Y$J_P>kZJV*JS>iZ-4{rWB&^T+jl9<$W_ zTPeSXuz8;Nxrof4$!mSne@*(7j@&*7g7gZzZ2H25WNe}Vn+a>?{-Z~R_w z&m}m1qM{o93)FuQ46!nEyV!!gHSIhx~u?BuD(h^XuU8ua5jb=X`!t`zNPZ^#A7k{c!c% zr}ii2dCvdF{Edh0^GrW?VEjq2llLzO{yIwiz68(R$9@tF6#hc+=PdDW48PAy^4#6y zCy{UIFGRm|*MEB4o^PT5L=LX_1^L&`^au3sH`JdO;`!F)Pb#&ybLsOPyPvR& zHU9+rW5D=_{k!J{cy8DK$wbij3)A!WhriU_|0vLNTk}tv^QK>D{sQ}>K!4o+VeETu zbo_}g(fTj&|GNqDd3`;%qx>XV1sDeYcrynq2!C%?c_j@FcnkclF2e+b1PDE++xh+1 F{{tUq7iIte literal 0 HcmV?d00001 diff --git a/samples/client/petstore/java/jersey2-java8/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/java/jersey2-java8/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..b7a36473955 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue May 17 23:08:05 CST 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-bin.zip diff --git a/samples/client/petstore/java/jersey2-java8/pom.xml b/samples/client/petstore/java/jersey2-java8/pom.xml index d56bda6b181..d3327ef4b98 100644 --- a/samples/client/petstore/java/jersey2-java8/pom.xml +++ b/samples/client/petstore/java/jersey2-java8/pom.xml @@ -52,7 +52,7 @@ org.apache.maven.plugins maven-jar-plugin - 2.2 + 2.6 @@ -98,7 +98,7 @@ org.apache.maven.plugins maven-compiler-plugin - 2.3.2 + 2.5.1 1.8 1.8 @@ -127,7 +127,7 @@ org.glassfish.jersey.media jersey-media-json-jackson - 2.22.1 + ${jersey-version} @@ -170,7 +170,7 @@ 1.5.8 2.22.2 - 2.7.0 + 2.7.5 1.0.0 4.12 diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/JSON.java index d4b7137c64a..d0feb432d99 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/JSON.java @@ -19,7 +19,7 @@ public JSON() { 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 JSR310Module()); + mapper.registerModule(new JavaTimeModule()); } /** From b7e4be77c68a58e2f82213be7abf5845e08ac64f Mon Sep 17 00:00:00 2001 From: ant3 Date: Tue, 21 Jun 2016 00:16:17 +0100 Subject: [PATCH 009/470] Rebuilt jersey1 client sample --- .../client/petstore/java/default/.gitignore | 6 ++++ .../java/default/.swagger-codegen-ignore | 2 +- .../client/petstore/java/default/.travis.yml | 29 +++++++++++++++++++ .../client/petstore/java/default/build.gradle | 8 ++--- samples/client/petstore/java/default/pom.xml | 6 ++-- .../java/io/swagger/client/ApiClient.java | 2 +- .../java/io/swagger/client/api/FakeApi.java | 2 +- .../java/io/swagger/client/api/PetApi.java | 2 +- 8 files changed, 46 insertions(+), 11 deletions(-) create mode 100644 samples/client/petstore/java/default/.travis.yml diff --git a/samples/client/petstore/java/default/.gitignore b/samples/client/petstore/java/default/.gitignore index 7cf39af816c..a530464afa1 100644 --- a/samples/client/petstore/java/default/.gitignore +++ b/samples/client/petstore/java/default/.gitignore @@ -13,3 +13,9 @@ # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* + +# build files +**/target +target +.gradle +build diff --git a/samples/client/petstore/java/default/.swagger-codegen-ignore b/samples/client/petstore/java/default/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/java/default/.swagger-codegen-ignore +++ b/samples/client/petstore/java/default/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/samples/client/petstore/java/default/.travis.yml b/samples/client/petstore/java/default/.travis.yml new file mode 100644 index 00000000000..33e79472abd --- /dev/null +++ b/samples/client/petstore/java/default/.travis.yml @@ -0,0 +1,29 @@ +# +# Generated by: https://github.com/swagger-api/swagger-codegen.git +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +language: java +jdk: + - oraclejdk8 + - oraclejdk7 +before_install: + # ensure gradlew has proper permission + - chmod a+x ./gradlew +script: + # test using maven + - mvn test + # uncomment below to test using gradle + # - gradle test + # uncomment below to test using sbt + # - sbt test diff --git a/samples/client/petstore/java/default/build.gradle b/samples/client/petstore/java/default/build.gradle index 33ceee9bb95..1e4969e26fd 100644 --- a/samples/client/petstore/java/default/build.gradle +++ b/samples/client/petstore/java/default/build.gradle @@ -77,7 +77,7 @@ if(hasProperty('target') && target == 'android') { apply plugin: 'java' apply plugin: 'maven' - + sourceCompatibility = JavaVersion.VERSION_1_7 targetCompatibility = JavaVersion.VERSION_1_7 @@ -95,9 +95,9 @@ if(hasProperty('target') && target == 'android') { ext { swagger_annotations_version = "1.5.8" - jackson_version = "2.7.0" + jackson_version = "2.7.5" jersey_version = "1.19.1" - jodatime_version = "2.9.3" + jodatime_version = "2.9.4" junit_version = "4.12" } @@ -109,7 +109,7 @@ dependencies { compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version" compile "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:$jackson_version" - compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:2.1.5" + compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version" 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/default/pom.xml b/samples/client/petstore/java/default/pom.xml index 0b24e120100..c4cb68e99f4 100644 --- a/samples/client/petstore/java/default/pom.xml +++ b/samples/client/petstore/java/default/pom.xml @@ -146,7 +146,7 @@ com.fasterxml.jackson.datatype jackson-datatype-joda - 2.1.5 + ${jackson-version} joda-time @@ -173,8 +173,8 @@ UTF-8 1.5.8 1.19.1 - 2.7.0 - 2.9.3 + 2.7.5 + 2.9.4 1.0.0 4.12 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 0d7898329d0..ba846404249 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 @@ -75,8 +75,8 @@ public ApiClient() { // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap(); - authentications.put("api_key", new ApiKeyAuth("header", "api_key")); authentications.put("petstore_auth", new OAuth()); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/FakeApi.java index 18ec9428c16..dc9faf57ea6 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/FakeApi.java @@ -9,8 +9,8 @@ import io.swagger.client.Pair; import org.joda.time.LocalDate; -import org.joda.time.DateTime; import java.math.BigDecimal; +import org.joda.time.DateTime; import java.util.ArrayList; 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 0816f9a2961..50a6ecff737 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 @@ -9,8 +9,8 @@ import io.swagger.client.Pair; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.ModelApiResponse; +import java.io.File; import java.util.ArrayList; From 274c3150a719a26a52a8b0e3970f780f6f00fbe5 Mon Sep 17 00:00:00 2001 From: ant3 Date: Tue, 21 Jun 2016 00:16:39 +0100 Subject: [PATCH 010/470] Rebuilt jersey2 client sample. --- .../client/petstore/java/jersey2/.gitignore | 6 ++++ .../java/jersey2/.swagger-codegen-ignore | 2 +- .../client/petstore/java/jersey2/.travis.yml | 29 ++++++++++++++++ .../client/petstore/java/jersey2/build.gradle | 9 +++-- .../client/petstore/java/jersey2/build.sbt | 12 +++---- .../client/petstore/java/jersey2/hello.txt | 1 + samples/client/petstore/java/jersey2/pom.xml | 33 ++++--------------- .../java/io/swagger/client/ApiClient.java | 2 +- .../java/io/swagger/client/api/FakeApi.java | 2 +- .../java/io/swagger/client/api/PetApi.java | 2 +- 10 files changed, 56 insertions(+), 42 deletions(-) create mode 100644 samples/client/petstore/java/jersey2/.travis.yml create mode 100644 samples/client/petstore/java/jersey2/hello.txt diff --git a/samples/client/petstore/java/jersey2/.gitignore b/samples/client/petstore/java/jersey2/.gitignore index 7cf39af816c..a530464afa1 100644 --- a/samples/client/petstore/java/jersey2/.gitignore +++ b/samples/client/petstore/java/jersey2/.gitignore @@ -13,3 +13,9 @@ # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* + +# build files +**/target +target +.gradle +build diff --git a/samples/client/petstore/java/jersey2/.swagger-codegen-ignore b/samples/client/petstore/java/jersey2/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/java/jersey2/.swagger-codegen-ignore +++ b/samples/client/petstore/java/jersey2/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/samples/client/petstore/java/jersey2/.travis.yml b/samples/client/petstore/java/jersey2/.travis.yml new file mode 100644 index 00000000000..33e79472abd --- /dev/null +++ b/samples/client/petstore/java/jersey2/.travis.yml @@ -0,0 +1,29 @@ +# +# Generated by: https://github.com/swagger-api/swagger-codegen.git +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +language: java +jdk: + - oraclejdk8 + - oraclejdk7 +before_install: + # ensure gradlew has proper permission + - chmod a+x ./gradlew +script: + # test using maven + - mvn test + # uncomment below to test using gradle + # - gradle test + # uncomment below to test using sbt + # - sbt test diff --git a/samples/client/petstore/java/jersey2/build.gradle b/samples/client/petstore/java/jersey2/build.gradle index 6574f746d05..067c81e1645 100644 --- a/samples/client/petstore/java/jersey2/build.gradle +++ b/samples/client/petstore/java/jersey2/build.gradle @@ -77,7 +77,6 @@ if(hasProperty('target') && target == 'android') { apply plugin: 'java' apply plugin: 'maven' - sourceCompatibility = JavaVersion.VERSION_1_7 targetCompatibility = JavaVersion.VERSION_1_7 @@ -95,9 +94,9 @@ if(hasProperty('target') && target == 'android') { ext { swagger_annotations_version = "1.5.8" - jackson_version = "2.7.0" + jackson_version = "2.7.5" jersey_version = "2.22.2" - jodatime_version = "2.9.3" + jodatime_version = "2.9.4" junit_version = "4.12" } @@ -105,11 +104,11 @@ dependencies { compile "io.swagger:swagger-annotations:$swagger_annotations_version" compile "org.glassfish.jersey.core:jersey-client:$jersey_version" compile "org.glassfish.jersey.media:jersey-media-multipart:$jersey_version" - compile "org.glassfish.jersey.media:jersey-media-json-jackson:2.22.1" + compile "org.glassfish.jersey.media:jersey-media-json-jackson:$jersey_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 "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version" 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/jersey2/build.sbt b/samples/client/petstore/java/jersey2/build.sbt index 08a215edacf..555b44f16db 100644 --- a/samples/client/petstore/java/jersey2/build.sbt +++ b/samples/client/petstore/java/jersey2/build.sbt @@ -12,12 +12,12 @@ lazy val root = (project in file(".")). "io.swagger" % "swagger-annotations" % "1.5.8", "org.glassfish.jersey.core" % "jersey-client" % "2.22.2", "org.glassfish.jersey.media" % "jersey-media-multipart" % "2.22.2", - "org.glassfish.jersey.media" % "jersey-media-json-jackson" % "2.22.1", - "com.fasterxml.jackson.core" % "jackson-core" % "2.7.0", - "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.0", - "com.fasterxml.jackson.core" % "jackson-databind" % "2.7.0", - "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.1.5", - "joda-time" % "joda-time" % "2.9.3", + "org.glassfish.jersey.media" % "jersey-media-json-jackson" % "2.22.2", + "com.fasterxml.jackson.core" % "jackson-core" % "2.7.5", + "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.5", + "com.fasterxml.jackson.core" % "jackson-databind" % "2.7.5", + "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.7.5", + "joda-time" % "joda-time" % "2.9.4", "com.brsanthu" % "migbase64" % "2.2", "junit" % "junit" % "4.12" % "test", "com.novocode" % "junit-interface" % "0.10" % "test" diff --git a/samples/client/petstore/java/jersey2/hello.txt b/samples/client/petstore/java/jersey2/hello.txt new file mode 100644 index 00000000000..6769dd60bdf --- /dev/null +++ b/samples/client/petstore/java/jersey2/hello.txt @@ -0,0 +1 @@ +Hello world! \ No newline at end of file diff --git a/samples/client/petstore/java/jersey2/pom.xml b/samples/client/petstore/java/jersey2/pom.xml index c07ae01939a..0026cda2c47 100644 --- a/samples/client/petstore/java/jersey2/pom.xml +++ b/samples/client/petstore/java/jersey2/pom.xml @@ -52,7 +52,7 @@ org.apache.maven.plugins maven-jar-plugin - 2.2 + 2.6 @@ -98,33 +98,12 @@ org.apache.maven.plugins maven-compiler-plugin - 2.3.2 + 2.5.1 1.7 1.7 - - - org.codehaus.mojo - exec-maven-plugin - 1.2.1 - - - gradle-test - integration-test - - exec - - - gradle - - check - - - - - @@ -148,7 +127,7 @@ org.glassfish.jersey.media jersey-media-json-jackson - 2.22.1 + ${jersey-version} @@ -170,7 +149,7 @@ com.fasterxml.jackson.datatype jackson-datatype-joda - 2.1.5 + ${jackson-version} joda-time @@ -196,8 +175,8 @@ 1.5.8 2.22.2 - 2.7.0 - 2.9.3 + 2.7.5 + 2.9.4 1.0.0 4.12 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 047a47252f8..06f6d4d899a 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 @@ -84,8 +84,8 @@ public ApiClient() { // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap(); - authentications.put("api_key", new ApiKeyAuth("header", "api_key")); authentications.put("petstore_auth", new OAuth()); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java index b8b499c4dee..ce4830a1f77 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java @@ -8,8 +8,8 @@ import javax.ws.rs.core.GenericType; import org.joda.time.LocalDate; -import org.joda.time.DateTime; import java.math.BigDecimal; +import org.joda.time.DateTime; import java.util.ArrayList; import java.util.HashMap; 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 ab85c4ac394..ad66598406d 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java @@ -8,8 +8,8 @@ import javax.ws.rs.core.GenericType; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.ModelApiResponse; +import java.io.File; import java.util.ArrayList; import java.util.HashMap; From 693c73171e244bab158a5956c356a7cf5187fa88 Mon Sep 17 00:00:00 2001 From: Jason Gavris Date: Wed, 29 Jun 2016 15:42:58 -0400 Subject: [PATCH 011/470] [Swift] Use ISO-8601 date format - Also fix up Enum parameter generation for formParams by extracting _param partial --- .../main/resources/swift/Extensions.mustache | 7 +- .../src/main/resources/swift/_param.mustache | 1 + .../src/main/resources/swift/api.mustache | 4 +- .../swagger/codegen/swift/SwiftModelTest.java | 66 +++++++++++ .../Classes/Swaggers/APIs/PetAPI.swift | 106 +++++++++--------- .../Classes/Swaggers/APIs/StoreAPI.swift | 64 +++++------ .../Classes/Swaggers/APIs/UserAPI.swift | 36 +++--- .../Classes/Swaggers/Extensions.swift | 7 +- .../SwaggerClientTests/Pods/Manifest.lock | 2 +- .../Pods-SwaggerClient-resources.sh | 4 +- .../Pods-SwaggerClientTests-resources.sh | 4 +- .../SwaggerClient.xcodeproj/project.pbxproj | 36 +++--- .../SwaggerClientTests/StoreAPITests.swift | 39 ++++--- .../Classes/Swaggers/Extensions.swift | 7 +- .../SwaggerClientTests/StoreAPITests.swift | 38 +++++-- 15 files changed, 259 insertions(+), 162 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/swift/_param.mustache create mode 100644 modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftModelTest.java diff --git a/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache b/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache index 54a1f127ef7..fce415ddcbf 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache @@ -61,9 +61,10 @@ extension Dictionary: JSONEncodable { private let dateFormatter: NSDateFormatter = { - let dateFormatter = NSDateFormatter() - dateFormatter.dateFormat = "yyyy-MM-dd" - return dateFormatter + let fmt = NSDateFormatter() + fmt.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + fmt.locale = NSLocale(localeIdentifier: "en_US_POSIX") + return fmt }() extension NSDate: JSONEncodable { diff --git a/modules/swagger-codegen/src/main/resources/swift/_param.mustache b/modules/swagger-codegen/src/main/resources/swift/_param.mustache new file mode 100644 index 00000000000..6d2de20a655 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift/_param.mustache @@ -0,0 +1 @@ +"{{baseName}}": {{paramName}}{{#isInteger}}{{^required}}?{{/required}}.encodeToJSON(){{/isInteger}}{{#isLong}}{{^required}}?{{/required}}.encodeToJSON(){{/isLong}}{{#isEnum}}{{^isContainer}}{{^required}}?{{/required}}.rawValue{{/isContainer}}{{/isEnum}}{{#isDate}}{{^required}}?{{/required}}.encodeToJSON(){{/isDate}}{{#isDateTime}}{{^required}}?{{/required}}.encodeToJSON(){{/isDateTime}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/swift/api.mustache b/modules/swagger-codegen/src/main/resources/swift/api.mustache index 8a9dc9077e7..8698c5da4e7 100644 --- a/modules/swagger-codegen/src/main/resources/swift/api.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/api.mustache @@ -89,9 +89,9 @@ public class {{classname}}: APIBase { {{#bodyParam}} let parameters = {{paramName}}{{^required}}?{{/required}}.encodeToJSON() as? [String:AnyObject]{{/bodyParam}}{{^bodyParam}} let nillableParameters: [String:AnyObject?] = {{^queryParams}}{{^formParams}}[:]{{/formParams}}{{#formParams}}{{^secondaryParam}}[{{/secondaryParam}} - "{{baseName}}": {{paramName}}{{#isInteger}}{{^required}}?{{/required}}.encodeToJSON(){{/isInteger}}{{#isLong}}{{^required}}?{{/required}}.encodeToJSON(){{/isLong}}{{#hasMore}},{{/hasMore}}{{^hasMore}} + {{> _param}}{{#hasMore}},{{/hasMore}}{{^hasMore}} ]{{/hasMore}}{{/formParams}}{{/queryParams}}{{#queryParams}}{{^secondaryParam}}[{{/secondaryParam}} - "{{baseName}}": {{paramName}}{{#isInteger}}{{^required}}?{{/required}}.encodeToJSON(){{/isInteger}}{{#isLong}}{{^required}}?{{/required}}.encodeToJSON(){{/isLong}}{{#isEnum}}{{^isContainer}}{{^required}}?{{/required}}.rawValue{{/isContainer}}{{/isEnum}}{{#hasMore}},{{/hasMore}}{{^hasMore}} + {{> _param}}{{#hasMore}},{{/hasMore}}{{^hasMore}} ]{{/hasMore}}{{/queryParams}} let parameters = APIHelper.rejectNil(nillableParameters){{/bodyParam}} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftModelTest.java new file mode 100644 index 00000000000..eb2c18a40db --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftModelTest.java @@ -0,0 +1,66 @@ +package io.swagger.codegen.swift; + +import io.swagger.codegen.*; +import io.swagger.codegen.languages.SwiftCodegen; +import io.swagger.models.*; +import io.swagger.models.properties.*; + +import org.testng.Assert; +import org.testng.annotations.Test; + +@SuppressWarnings("static-method") +public class SwiftModelTest { + + @Test(description = "convert a simple java model") + public void simpleModelTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("id", new LongProperty()) + .property("name", new StringProperty()) + .property("createdAt", new DateTimeProperty()) + .required("id") + .required("name") + .discriminator("test"); + final DefaultCodegen codegen = new SwiftCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 3); + Assert.assertEquals(cm.discriminator,"test"); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "id"); + Assert.assertEquals(property1.datatype, "Int64"); + Assert.assertEquals(property1.name, "id"); + Assert.assertNull(property1.defaultValue); + Assert.assertEquals(property1.baseType, "Int64"); + Assert.assertTrue(property1.hasMore); + Assert.assertTrue(property1.required); + Assert.assertTrue(property1.isPrimitiveType); + Assert.assertTrue(property1.isNotContainer); + + final CodegenProperty property2 = cm.vars.get(1); + Assert.assertEquals(property2.baseName, "name"); + Assert.assertEquals(property2.datatype, "String"); + Assert.assertEquals(property2.name, "name"); + Assert.assertNull(property2.defaultValue); + Assert.assertEquals(property2.baseType, "String"); + Assert.assertTrue(property2.hasMore); + Assert.assertTrue(property2.required); + Assert.assertTrue(property2.isPrimitiveType); + Assert.assertTrue(property2.isNotContainer); + + final CodegenProperty property3 = cm.vars.get(2); + Assert.assertEquals(property3.baseName, "createdAt"); + Assert.assertEquals(property3.datatype, "NSDate"); + Assert.assertEquals(property3.name, "createdAt"); + Assert.assertNull(property3.defaultValue); + Assert.assertEquals(property3.baseType, "NSDate"); + Assert.assertNull(property3.hasMore); + Assert.assertNull(property3.required); + Assert.assertTrue(property3.isNotContainer); + } + +} diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index cdbd4323e70..6e4ddc4227b 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -108,13 +108,13 @@ public class PetAPI: APIBase { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example={ + - examples: [{contentType=application/json, example={ "name" : "Puma", "type" : "Dog", "color" : "Black", "gender" : "Female", "breed" : "Mixed" -}, contentType=application/json}] +}}] - parameter status: (query) Status values that need to be considered for filter (optional, default to available) @@ -157,20 +157,20 @@ public class PetAPI: APIBase { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], + - examples: [{contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}, {contentType=application/xml, example= 123456 doggie @@ -179,21 +179,21 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] - - examples: [{example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}] + - examples: [{contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}, {contentType=application/xml, example= 123456 doggie @@ -202,7 +202,7 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] +}] - parameter tags: (query) Tags to filter by (optional) @@ -242,26 +242,26 @@ public class PetAPI: APIBase { Find pet by ID - GET /pet/{petId} - Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - - API Key: - - type: apiKey api_key - - name: api_key - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example={ - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], + - API Key: + - type: apiKey api_key + - name: api_key + - examples: [{contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -}, contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 doggie @@ -270,21 +270,21 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] - - examples: [{example={ - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}] + - examples: [{contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -}, contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 doggie @@ -293,7 +293,7 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] +}] - parameter petId: (path) ID of pet that needs to be fetched diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 1c575eb79f8..c51d8d37357 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -67,12 +67,12 @@ public class StoreAPI: APIBase { - API Key: - type: apiKey api_key - name: api_key - - examples: [{example={ + - examples: [{contentType=application/json, example={ "key" : 123 -}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}] - - examples: [{example={ +}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}] + - examples: [{contentType=application/json, example={ "key" : 123 -}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}] +}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}] - returns: RequestBuilder<[String:Int32]> */ @@ -108,36 +108,36 @@ public class StoreAPI: APIBase { Find purchase order by ID - GET /store/order/{orderId} - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - - examples: [{example={ - "id" : 123456789, + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] - - examples: [{example={ - "id" : 123456789, +}] + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] +}] - parameter orderId: (path) ID of pet that needs to be fetched @@ -176,36 +176,36 @@ public class StoreAPI: APIBase { Place an order for a pet - POST /store/order - - - examples: [{example={ - "id" : 123456789, + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] - - examples: [{example={ - "id" : 123456789, +}] + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] +}] - parameter body: (body) order placed for purchasing the pet (optional) diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index a7497487f85..d6df7754683 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -167,16 +167,16 @@ public class UserAPI: APIBase { Get user by user name - GET /user/{username} - - - examples: [{example={ - "id" : 123456789, + - examples: [{contentType=application/json, example={ + "firstName" : "aeiou", "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, "phone" : "aeiou", - "username" : "aeiou", + "id" : 123456789, "email" : "aeiou", - "userStatus" : 123, - "firstName" : "aeiou", - "password" : "aeiou" -}, contentType=application/json}, {example= + "username" : "aeiou" +}}, {contentType=application/xml, example= 123456 string string @@ -185,17 +185,17 @@ public class UserAPI: APIBase { string string 0 -, contentType=application/xml}] - - examples: [{example={ - "id" : 123456789, +}] + - examples: [{contentType=application/json, example={ + "firstName" : "aeiou", "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, "phone" : "aeiou", - "username" : "aeiou", + "id" : 123456789, "email" : "aeiou", - "userStatus" : 123, - "firstName" : "aeiou", - "password" : "aeiou" -}, contentType=application/json}, {example= + "username" : "aeiou" +}}, {contentType=application/xml, example= 123456 string string @@ -204,7 +204,7 @@ public class UserAPI: APIBase { string string 0 -, contentType=application/xml}] +}] - parameter username: (path) The name that needs to be fetched. Use user1 for testing. @@ -244,8 +244,8 @@ public class UserAPI: APIBase { Logs user into the system - GET /user/login - - - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}] - - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}] + - examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] + - examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] - parameter username: (query) The user name for login (optional) - parameter password: (query) The password for login in clear text (optional) diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Extensions.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Extensions.swift index fed87969388..786e3218c80 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Extensions.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Extensions.swift @@ -60,9 +60,10 @@ extension Dictionary: JSONEncodable { private let dateFormatter: NSDateFormatter = { - let dateFormatter = NSDateFormatter() - dateFormatter.dateFormat = "yyyy-MM-dd" - return dateFormatter + let fmt = NSDateFormatter() + fmt.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + fmt.locale = NSLocale(localeIdentifier: "en_US_POSIX") + return fmt }() extension NSDate: JSONEncodable { diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Manifest.lock b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Manifest.lock index b369a60a1bb..ce1490e954e 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Manifest.lock +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Manifest.lock @@ -16,4 +16,4 @@ SPEC CHECKSUMS: PODFILE CHECKSUM: 84472aca2a88b7f7ed9fcd63e9f5fdb5ad4aab94 -COCOAPODS: 1.0.0 +COCOAPODS: 1.0.1 diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh index e768f92993e..0a1561528cb 100755 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh @@ -48,8 +48,8 @@ EOM ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ;; *.xib) - echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT}" - ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ;; *.framework) echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh index e768f92993e..0a1561528cb 100755 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh @@ -48,8 +48,8 @@ EOM ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ;; *.xib) - echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT}" - ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ;; *.framework) echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index 3d557a9280f..0eec9dcf8c6 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -143,12 +143,12 @@ isa = PBXNativeTarget; buildConfigurationList = 6D4EFBAE1C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClient" */; buildPhases = ( - 1F03F780DC2D9727E5E64BA9 /* 📦 Check Pods Manifest.lock */, + 1F03F780DC2D9727E5E64BA9 /* [CP] Check Pods Manifest.lock */, 6D4EFB8D1C692C6300B96B06 /* Sources */, 6D4EFB8E1C692C6300B96B06 /* Frameworks */, 6D4EFB8F1C692C6300B96B06 /* Resources */, - 4485A75250058E2D5BBDF63F /* 📦 Embed Pods Frameworks */, - 808CE4A0CE801CAC5ABF5B08 /* 📦 Copy Pods Resources */, + 4485A75250058E2D5BBDF63F /* [CP] Embed Pods Frameworks */, + 808CE4A0CE801CAC5ABF5B08 /* [CP] Copy Pods Resources */, ); buildRules = ( ); @@ -163,12 +163,12 @@ isa = PBXNativeTarget; buildConfigurationList = 6D4EFBB11C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */; buildPhases = ( - 79FE27B09B2DD354C831BD49 /* 📦 Check Pods Manifest.lock */, + 79FE27B09B2DD354C831BD49 /* [CP] Check Pods Manifest.lock */, 6D4EFBA11C692C6300B96B06 /* Sources */, 6D4EFBA21C692C6300B96B06 /* Frameworks */, 6D4EFBA31C692C6300B96B06 /* Resources */, - 796EAD48F1BCCDAA291CD963 /* 📦 Embed Pods Frameworks */, - 1652CB1A246A4689869E442D /* 📦 Copy Pods Resources */, + 796EAD48F1BCCDAA291CD963 /* [CP] Embed Pods Frameworks */, + 1652CB1A246A4689869E442D /* [CP] Copy Pods Resources */, ); buildRules = ( ); @@ -239,14 +239,14 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ - 1652CB1A246A4689869E442D /* 📦 Copy Pods Resources */ = { + 1652CB1A246A4689869E442D /* [CP] Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Copy Pods Resources"; + name = "[CP] Copy Pods Resources"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -254,14 +254,14 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh\"\n"; showEnvVarsInLog = 0; }; - 1F03F780DC2D9727E5E64BA9 /* 📦 Check Pods Manifest.lock */ = { + 1F03F780DC2D9727E5E64BA9 /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Check Pods Manifest.lock"; + name = "[CP] Check Pods Manifest.lock"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -269,14 +269,14 @@ shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; showEnvVarsInLog = 0; }; - 4485A75250058E2D5BBDF63F /* 📦 Embed Pods Frameworks */ = { + 4485A75250058E2D5BBDF63F /* [CP] Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Embed Pods Frameworks"; + name = "[CP] Embed Pods Frameworks"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -284,14 +284,14 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; - 796EAD48F1BCCDAA291CD963 /* 📦 Embed Pods Frameworks */ = { + 796EAD48F1BCCDAA291CD963 /* [CP] Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Embed Pods Frameworks"; + name = "[CP] Embed Pods Frameworks"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -299,14 +299,14 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; - 79FE27B09B2DD354C831BD49 /* 📦 Check Pods Manifest.lock */ = { + 79FE27B09B2DD354C831BD49 /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Check Pods Manifest.lock"; + name = "[CP] Check Pods Manifest.lock"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -314,14 +314,14 @@ shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; showEnvVarsInLog = 0; }; - 808CE4A0CE801CAC5ABF5B08 /* 📦 Copy Pods Resources */ = { + 808CE4A0CE801CAC5ABF5B08 /* [CP] Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Copy Pods Resources"; + name = "[CP] Copy Pods Resources"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift index 68232d063d1..679285394d0 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift @@ -11,34 +11,27 @@ import XCTest @testable import SwaggerClient class StoreAPITests: XCTestCase { + + let isoDateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" let testTimeout = 10.0 - override func setUp() { - super.setUp() - // Put setup code here. This method is called before the invocation of each test method in the class. - } - - override func tearDown() { - // Put teardown code here. This method is called after the invocation of each test method in the class. - super.tearDown() - } - func test1PlaceOrder() { let expectation = self.expectationWithDescription("testPlaceOrder") + let shipDate = NSDate() let newOrder = Order() newOrder.id = 1000 newOrder.petId = 1000 newOrder.complete = false newOrder.quantity = 10 - newOrder.shipDate = NSDate() + newOrder.shipDate = shipDate // use explicit naming to reference the enum so that we test we don't regress on enum naming newOrder.status = Order.Status.Placed StoreAPI.placeOrder(body: newOrder) { (order, error) in guard error == nil else { - XCTFail("error placing order") + XCTFail("error placing order: \(error.debugDescription)") return } @@ -46,6 +39,8 @@ class StoreAPITests: XCTestCase { XCTAssert(order.id == 1000, "invalid id") XCTAssert(order.quantity == 10, "invalid quantity") XCTAssert(order.status == .Placed, "invalid status") + XCTAssert(order.shipDate!.isEqual(shipDate, format: self.isoDateFormat), + "Date should be idempotent") expectation.fulfill() } @@ -59,7 +54,7 @@ class StoreAPITests: XCTestCase { StoreAPI.getOrderById(orderId: "1000") { (order, error) in guard error == nil else { - XCTFail("error retrieving order") + XCTFail("error retrieving order: \(error.debugDescription)") return } @@ -96,3 +91,21 @@ class StoreAPITests: XCTestCase { } } + +private extension NSDate { + + /** + Returns true if the dates are equal given the format string. + + - parameter date: The date to compare to. + - parameter format: The format string to use to compare. + + - returns: true if the dates are equal, given the format string. + */ + func isEqual(date: NSDate, format: String) -> Bool { + let fmt = NSDateFormatter() + fmt.dateFormat = format + return fmt.stringFromDate(self).isEqual(fmt.stringFromDate(date)) + } + +} diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Extensions.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Extensions.swift index 62d374eed05..2a032d561b1 100644 --- a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Extensions.swift +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Extensions.swift @@ -61,9 +61,10 @@ extension Dictionary: JSONEncodable { private let dateFormatter: NSDateFormatter = { - let dateFormatter = NSDateFormatter() - dateFormatter.dateFormat = "yyyy-MM-dd" - return dateFormatter + let fmt = NSDateFormatter() + fmt.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + fmt.locale = NSLocale(localeIdentifier: "en_US_POSIX") + return fmt }() extension NSDate: JSONEncodable { diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift index b52fe4a0fa8..210868dfb12 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift @@ -12,26 +12,19 @@ import XCTest @testable import SwaggerClient class StoreAPITests: XCTestCase { - - let testTimeout = 10.0 - override func setUp() { - super.setUp() - // Put setup code here. This method is called before the invocation of each test method in the class. - } - - override func tearDown() { - // Put teardown code here. This method is called after the invocation of each test method in the class. - super.tearDown() - } + let isoDateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + + let testTimeout = 10.0 func test1PlaceOrder() { let order = Order() + let shipDate = NSDate() order.id = 1000 order.petId = 1000 order.complete = false order.quantity = 10 - order.shipDate = NSDate() + order.shipDate = shipDate // use explicit naming to reference the enum so that we test we don't regress on enum naming order.status = Order.Status.Placed let expectation = self.expectationWithDescription("testPlaceOrder") @@ -39,6 +32,9 @@ class StoreAPITests: XCTestCase { XCTAssert(order.id == 1000, "invalid id") XCTAssert(order.quantity == 10, "invalid quantity") XCTAssert(order.status == .Placed, "invalid status") + XCTAssert(order.shipDate!.isEqual(shipDate, format: self.isoDateFormat), + "Date should be idempotent") + expectation.fulfill() }.always { // Noop for now @@ -86,3 +82,21 @@ class StoreAPITests: XCTestCase { } } + +private extension NSDate { + + /** + Returns true if the dates are equal given the format string. + + - parameter date: The date to compare to. + - parameter format: The format string to use to compare. + + - returns: true if the dates are equal, given the format string. + */ + func isEqual(date: NSDate, format: String) -> Bool { + let fmt = NSDateFormatter() + fmt.dateFormat = format + return fmt.stringFromDate(self).isEqual(fmt.stringFromDate(date)) + } + +} From 0117cbb29a313298d7aff3389766ef60a7e91f5f Mon Sep 17 00:00:00 2001 From: zhenjun115 Date: Sat, 2 Jul 2016 12:14:31 +0800 Subject: [PATCH 012/470] update the dependencies for Java Feign API clients to the latest versions; --- .../main/resources/Java/libraries/feign/build.gradle.mustache | 2 +- .../src/main/resources/Java/libraries/feign/build.sbt.mustache | 2 +- .../src/main/resources/Java/libraries/feign/pom.mustache | 2 +- samples/client/petstore/java/feign/gradlew | 0 samples/client/petstore/java/feign/pom.xml | 2 +- 5 files changed, 4 insertions(+), 4 deletions(-) mode change 100755 => 100644 samples/client/petstore/java/feign/gradlew 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 index e1df11443b7..6cf93578816 100644 --- 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 @@ -96,7 +96,7 @@ if(hasProperty('target') && target == 'android') { ext { swagger_annotations_version = "1.5.8" jackson_version = "2.7.5" - feign_version = "8.16.0" + feign_version = "8.17.0" junit_version = "4.12" oltu_version = "1.0.1" } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.sbt.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.sbt.mustache index f26bd27f1e8..04ae4ce11aa 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.sbt.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.sbt.mustache @@ -11,7 +11,7 @@ lazy val root = (project in file(".")). libraryDependencies ++= Seq( "io.swagger" % "swagger-annotations" % "1.5.8" % "compile", "com.netflix.feign" % "feign-core" % "8.16.0" % "compile", - "com.netflix.feign" % "feign-jackson" % "8.16.0" % "compile", + "com.netflix.feign" % "feign-jackson" % "8.17.0" % "compile", "com.netflix.feign" % "feign-slf4j" % "8.16.0" % "compile", "com.fasterxml.jackson.core" % "jackson-core" % "2.7.5" % "compile", "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.5" % "compile", diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache index 36cde285499..3eb45f850bc 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache @@ -161,7 +161,7 @@ ${java.version} ${java.version} 1.5.8 - 8.16.0 + 8.17.0 2.7.5 4.12 1.0.0 diff --git a/samples/client/petstore/java/feign/gradlew b/samples/client/petstore/java/feign/gradlew old mode 100755 new mode 100644 diff --git a/samples/client/petstore/java/feign/pom.xml b/samples/client/petstore/java/feign/pom.xml index 84cc6f1ddc5..6c988402422 100644 --- a/samples/client/petstore/java/feign/pom.xml +++ b/samples/client/petstore/java/feign/pom.xml @@ -161,7 +161,7 @@ ${java.version} ${java.version} 1.5.8 - 8.16.0 + 8.17.0 2.7.5 4.12 1.0.0 From 4401e1bf8efb391d2d8247f7a5d3d5232ccdbff0 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sat, 2 Jul 2016 14:32:41 +0800 Subject: [PATCH 013/470] build test --- appveyor.yml | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 appveyor.yml diff --git a/appveyor.yml b/appveyor.yml new file mode 100644 index 00000000000..7b5fe1cfbd9 --- /dev/null +++ b/appveyor.yml @@ -0,0 +1,23 @@ +# for CI with appveyor.yml +version: '{build}' +os: Windows Server 2012 +install: + - ps: | + Add-Type -AssemblyName System.IO.Compression.FileSystem + if (!(Test-Path -Path "C:\maven" )) { + (new-object System.Net.WebClient).DownloadFile( + 'http://www.us.apache.org/dist/maven/maven-3/3.2.5/binaries/apache-maven-3.2.5-bin.zip', + 'C:\maven-bin.zip' + ) + [System.IO.Compression.ZipFile]::ExtractToDirectory("C:\maven-bin.zip", "C:\maven") + } + - cmd: SET PATH=C:\maven\apache-maven-3.2.5\bin;%JAVA_HOME%\bin;%PATH% + - cmd: SET MAVEN_OPTS=-XX:MaxPermSize=2g -Xmx4g + - cmd: SET JAVA_OPTS=-XX:MaxPermSize=2g -Xmx4g +build_script: + - mvn clean package --batch-mode -DskipTest +test_script: + - mvn clean install --batch-mode +cache: + - C:\maven\ + - C:\Users\appveyor\.m2 From f8362a56b3fb052fa6ab9059b1a9cb4ae7875cc6 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sat, 2 Jul 2016 15:01:45 +0800 Subject: [PATCH 014/470] failure test --- pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/pom.xml b/pom.xml index c502c48914d..a38a35a9036 100644 --- a/pom.xml +++ b/pom.xml @@ -1,3 +1,4 @@ +failure From e013747535dbf88f8cccb01cf54fdba0f21783d6 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sat, 2 Jul 2016 15:10:38 +0800 Subject: [PATCH 015/470] add comments --- appveyor.yml | 1 + pom.xml | 3 +-- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index 7b5fe1cfbd9..f55637ac920 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,4 +1,5 @@ # for CI with appveyor.yml +# Ref: http://www.yegor256.com/2015/01/10/windows-appveyor-maven.html version: '{build}' os: Windows Server 2012 install: diff --git a/pom.xml b/pom.xml index a38a35a9036..4153879b61b 100644 --- a/pom.xml +++ b/pom.xml @@ -1,4 +1,3 @@ -failure @@ -30,7 +29,7 @@ failure github - https://github.com/swagger-api/swagger-core/issues + https://github.com/swagger-api/swagger-codegen/issues From 4a71a4c2904f3cfef488cd470a16f03fc56c9285 Mon Sep 17 00:00:00 2001 From: zhenjun115 Date: Sat, 2 Jul 2016 16:16:50 +0800 Subject: [PATCH 016/470] add more tips about npe; --- .../src/main/java/io/swagger/codegen/DefaultGenerator.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index b0cb8d1006c..b0a2fd34292 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -284,7 +284,7 @@ private Model getParent(Model model) { allProcessedModels.put(name, models); } catch (Exception e) { - throw new RuntimeException("Could not process model '" + name + "'", e); + throw new RuntimeException("Could not process model '" + name + "'" + ".Please make sure that your schema is correct!", e); } } From ac328ccc59e2d4efed14ff3bde543962ad853c65 Mon Sep 17 00:00:00 2001 From: jfiala Date: Sat, 2 Jul 2016 18:01:45 +0200 Subject: [PATCH 017/470] add pom-file to cxf including cxf-client #2017 --- .../languages/JavaCXFServerCodegen.java | 12 ++ .../main/resources/JavaJaxRS/cxf/pom.mustache | 139 ++++++++++++++++++ 2 files changed, 151 insertions(+) create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java index c9d558d51ab..9cfeba12726 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java @@ -8,6 +8,7 @@ import io.swagger.codegen.CodegenModel; import io.swagger.codegen.CodegenOperation; import io.swagger.codegen.CodegenProperty; +import io.swagger.codegen.SupportingFile; import io.swagger.models.Operation; public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen @@ -37,6 +38,17 @@ public JavaCXFServerCodegen() } + @Override + public void processOpts() + { + super.processOpts(); + + supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen + writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); + + + } + @Override public String getName() { diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache new file mode 100644 index 00000000000..ca0d370b98a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache @@ -0,0 +1,139 @@ + + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + + src/main/java + + + org.apache.maven.plugins + maven-war-plugin + 2.1.1 + + + maven-failsafe-plugin + 2.6 + + + + integration-test + verify + + + + + + org.eclipse.jetty + jetty-maven-plugin + ${jetty-version} + + + / + + target/${project.artifactId}-${project.version} + 8079 + stopit + + {{serverPort}} + 60000 + + + + + start-jetty + pre-integration-test + + start + + + 0 + true + + + + stop-jetty + post-integration-test + + stop + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.9.1 + + + add-source + generate-sources + + add-source + + + + src/gen/java + + + + + + + + + + io.swagger + swagger-jersey2-jaxrs + compile + ${swagger-core-version} + + + ch.qos.logback + logback-classic + ${logback-version} + compile + + + ch.qos.logback + logback-core + ${logback-version} + compile + + + junit + junit + ${junit-version} + test + + + org.apache.cxf + cxf-rt-rs-client + 3.1.6 + test + + + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + true + + + + + {{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}} + ${java.version} + ${java.version} + 1.5.9 + 9.2.9.v20150224 + 2.22.2 + 4.12 + 1.1.7 + 2.5 + UTF-8 + + From 4766b9bdf6c6efe79e317837ef85a96cf1e44d26 Mon Sep 17 00:00:00 2001 From: jfiala Date: Sat, 2 Jul 2016 18:12:47 +0200 Subject: [PATCH 018/470] adapt pom sourceFolder in pom.mustache to gen/java #2017 --- .../src/main/resources/JavaJaxRS/cxf/pom.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache index ca0d370b98a..43d02dec937 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache @@ -75,7 +75,7 @@ - src/gen/java + gen/java From ed5039b11d9e7dbbdb1de84eb41801006e04a9bc Mon Sep 17 00:00:00 2001 From: jfiala Date: Sat, 2 Jul 2016 18:53:00 +0200 Subject: [PATCH 019/470] add test templates for CXF #2017 --- .../languages/JavaCXFServerCodegen.java | 6 +- .../src/main/resources/Java/model.mustache | 2 +- .../resources/JavaJaxRS/cxf/api_test.mustache | 59 +++++++++++++++++++ .../JavaJaxRS/cxf/licenseInfo.mustache | 23 ++++++++ .../resources/JavaJaxRS/cxf/model.mustache | 1 + .../resources/JavaJaxRS/cxf/pojo.mustache | 9 +++ .../main/resources/JavaJaxRS/cxf/pom.mustache | 8 +++ 7 files changed, 103 insertions(+), 5 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/licenseInfo.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java index 9cfeba12726..b94f2d0c60d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java @@ -19,8 +19,7 @@ public JavaCXFServerCodegen() supportsInheritance = true; sourceFolder = "gen" + File.separator + "java"; outputFolder = "generated-code/JavaJaxRS-CXF"; - apiTestTemplateFiles.clear(); // TODO: add test template - + // clear model and api doc template as this codegen // does not support auto-generated markdown doc at the moment //TODO: add doc templates @@ -42,11 +41,10 @@ public JavaCXFServerCodegen() public void processOpts() { super.processOpts(); - + supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); - } @Override diff --git a/modules/swagger-codegen/src/main/resources/Java/model.mustache b/modules/swagger-codegen/src/main/resources/Java/model.mustache index f275a98f548..1d72c3a4efe 100644 --- a/modules/swagger-codegen/src/main/resources/Java/model.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/model.mustache @@ -5,8 +5,8 @@ package {{package}}; import java.util.Objects; {{#imports}} import {{import}}; -import javax.validation.constraints.*; {{/imports}} +import javax.validation.constraints.*; {{#serializableModel}}import java.io.Serializable;{{/serializableModel}} {{#models}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache new file mode 100644 index 00000000000..524f20dfb39 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache @@ -0,0 +1,59 @@ +{{>licenseInfo}} + +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} +import org.junit.Test; +import org.junit.Before; + +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.client.JAXRSClientFactory; +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; + + +{{^fullJavaUtil}} +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +{{/fullJavaUtil}} + +/** + * API tests for {{classname}} + */ +public class {{classname}}Test { + + private {{classname}} api; + + @Before + public void setup() { + JacksonJsonProvider provider = new JacksonJsonProvider(); + List providers = new ArrayList(); + providers.add(provider); + + api = JAXRSClientFactory.create("{{basePath}}", {{classname}}.class, providers); + } + + {{#operations}}{{#operation}} + /** + * {{summary}} + * + * {{notes}} + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void {{operationId}}Test() { + {{#allParams}} + {{{dataType}}} {{paramName}} = new {{{dataType}}}(); + {{/allParams}} + Response response = api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + + {{#returnType}}{{{returnType}}} responseModel = response.readEntity({{{returnType}}}.class);{{/returnType}} + + // TODO: test validations + } + {{/operation}}{{/operations}} +} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/licenseInfo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/licenseInfo.mustache new file mode 100644 index 00000000000..861d97234cf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/licenseInfo.mustache @@ -0,0 +1,23 @@ +/** + * {{{appName}}} + * {{{appDescription}}} + * + * {{#version}}OpenAPI spec version: {{{version}}}{{/version}} + * {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/model.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/model.mustache index 2c383a41a28..5a16499d15b 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/model.mustache @@ -2,6 +2,7 @@ package {{package}}; {{#imports}}import {{import}}; {{/imports}} +import javax.validation.constraints.*; {{#models}} {{#model}}{{#description}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache index c214ae2ae84..26ff946af81 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache @@ -27,6 +27,15 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { * minimum: {{minimum}}{{/minimum}}{{#maximum}} * maximum: {{maximum}}{{/maximum}} **/ + {{#required}} + @NotNull{{/required}}{{! +}}{{#pattern}} + @Pattern(regexp="{{pattern}}"){{/pattern}}{{#minLength}}{{#maxLength}} + @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} + @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} + @Size(max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minimum}} + //@Min({{minimum}}){{/minimum}}{{#maximum}} + //@Max({{maximum}}){{/maximum}} {{#vendorExtensions.extraAnnotation}}{{vendorExtensions.extraAnnotation}}{{/vendorExtensions.extraAnnotation}} public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache index 43d02dec937..c161b605836 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache @@ -108,12 +108,20 @@ ${junit-version} test + org.apache.cxf cxf-rt-rs-client 3.1.6 test + + + javax.validation + validation-api + 1.1.0.Final + provided + From 7b375d3ce32b1b1adee5e7dd9202c4d987d21a49 Mon Sep 17 00:00:00 2001 From: jfiala Date: Sat, 2 Jul 2016 19:11:24 +0200 Subject: [PATCH 020/470] optimize mustache template structure, remove tabs #3280 #2549 --- .../src/main/resources/Java/pojo.mustache | 20 ++++++++++++------- .../src/main/resources/Java/pom.mustache | 10 +++++----- .../resources/JavaJaxRS/cxf/pojo.mustache | 20 ++++++++++++------- .../main/resources/JavaJaxRS/cxf/pom.mustache | 12 +++++------ 4 files changed, 37 insertions(+), 25 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache index 0521e244074..a4f15f914f8 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache @@ -52,15 +52,21 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali {{#vendorExtensions.extraAnnotation}} {{vendorExtensions.extraAnnotation}} {{/vendorExtensions.extraAnnotation}} - {{#required}} +{{#required}} @NotNull{{/required}}{{! -}}{{#pattern}} - @Pattern(regexp="{{pattern}}"){{/pattern}}{{#minLength}}{{#maxLength}} - @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} +}} +{{#pattern}} + @Pattern(regexp="{{pattern}}") +{{/pattern}} +{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} - @Size(max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minimum}} - //@Min({{minimum}}){{/minimum}}{{#maximum}} - //@Max({{maximum}}){{/maximum}} + @Size(max={{maxLength}}){{/maxLength}}{{/minLength}} +{{#minimum}} + //@Min({{minimum}}) +{{/minimum}} +{{#maximum}} + //@Max({{maximum}}) +{{/maximum}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; diff --git a/modules/swagger-codegen/src/main/resources/Java/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/pom.mustache index 8c9006c8fc4..66e6aeb2517 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pom.mustache @@ -178,11 +178,11 @@ - javax.validation - validation-api - 1.1.0.Final - provided - + javax.validation + validation-api + 1.1.0.Final + provided + diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache index 26ff946af81..ad5ef14b9d6 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache @@ -27,15 +27,21 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { * minimum: {{minimum}}{{/minimum}}{{#maximum}} * maximum: {{maximum}}{{/maximum}} **/ - {{#required}} +{{#required}} @NotNull{{/required}}{{! -}}{{#pattern}} - @Pattern(regexp="{{pattern}}"){{/pattern}}{{#minLength}}{{#maxLength}} - @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} +}} +{{#pattern}} + @Pattern(regexp="{{pattern}}") +{{/pattern}} +{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} - @Size(max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minimum}} - //@Min({{minimum}}){{/minimum}}{{#maximum}} - //@Max({{maximum}}){{/maximum}} + @Size(max={{maxLength}}){{/maxLength}}{{/minLength}} +{{#minimum}} + //@Min({{minimum}}) +{{/minimum}} +{{#maximum}} + //@Max({{maximum}}) +{{/maximum}} {{#vendorExtensions.extraAnnotation}}{{vendorExtensions.extraAnnotation}}{{/vendorExtensions.extraAnnotation}} public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache index c161b605836..f20c1f8bef6 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache @@ -115,13 +115,13 @@ 3.1.6 test - + - javax.validation - validation-api - 1.1.0.Final - provided - + javax.validation + validation-api + 1.1.0.Final + provided + From 956432ac31ba020e88c5497cf55250b1553e5a6c Mon Sep 17 00:00:00 2001 From: jfiala Date: Sat, 2 Jul 2016 19:21:05 +0200 Subject: [PATCH 021/470] refined dependency to swagger-jaxrs #2017 --- .../src/main/resources/JavaJaxRS/cxf/pom.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache index f20c1f8bef6..f8a33fd7fe1 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache @@ -86,7 +86,7 @@ io.swagger - swagger-jersey2-jaxrs + swagger-jaxrs compile ${swagger-core-version} From f420da05924765004bd052944632d69993fc9f7a Mon Sep 17 00:00:00 2001 From: jfiala Date: Sat, 2 Jul 2016 19:51:44 +0200 Subject: [PATCH 022/470] refined annotations and line breaks #2549 --- .../src/main/resources/Java/pojo.mustache | 28 +++++++--- .../resources/JavaJaxRS/cxf/pojo.mustache | 51 +++++++++++++++---- 2 files changed, 60 insertions(+), 19 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache index a4f15f914f8..385fddfc036 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache @@ -49,18 +49,27 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali {{/maximum}} * @return {{name}} **/ - {{#vendorExtensions.extraAnnotation}} - {{vendorExtensions.extraAnnotation}} - {{/vendorExtensions.extraAnnotation}} {{#required}} - @NotNull{{/required}}{{! -}} + @NotNull +{{/required}} {{#pattern}} @Pattern(regexp="{{pattern}}") {{/pattern}} -{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} - @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} - @Size(max={{maxLength}}){{/maxLength}}{{/minLength}} +{{#minLength}} +{{#maxLength}} + @Size(min={{minLength}},max={{maxLength}}) +{{/maxLength}} +{{/minLength}} +{{#minLength}} +{{^maxLength}} + @Size(min={{minLength}}) +{{/maxLength}} +{{/minLength}} +{{^minLength}} +{{#maxLength}} + @Size(max={{maxLength}}) + {{/maxLength}} + {{/minLength}} {{#minimum}} //@Min({{minimum}}) {{/minimum}} @@ -68,6 +77,9 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali //@Max({{maximum}}) {{/maximum}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") +{{#vendorExtensions.extraAnnotation}} + {{vendorExtensions.extraAnnotation}} +{{/vendorExtensions.extraAnnotation}} public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; } diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache index ad5ef14b9d6..357fe96dcc4 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache @@ -1,3 +1,4 @@ +import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlAccessType; @@ -11,6 +12,9 @@ import javax.xml.bind.annotation.XmlEnum; }){{/hasVars}} {{^hasVars}}@XmlType(name = "{{classname}}"){{/hasVars}} {{^parent}}@XmlRootElement(name="{{classname}}"){{/parent}} +{{#description}} +@ApiModel(description="{{{description}}}") +{{/description}} public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{#vars}}{{#isEnum}} @@ -22,27 +26,52 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}} {{#vars}} - /**{{#description}} - * {{{description}}}{{/description}}{{#minimum}} - * minimum: {{minimum}}{{/minimum}}{{#maximum}} - * maximum: {{maximum}}{{/maximum}} - **/ + /** + {{#description}} + * {{{description}}} + {{/description}} + {{^description}} + * Get {{name}} + {{/description}} + {{#minimum}} + * minimum: {{minimum}} + {{/minimum}} + {{#maximum}} + * maximum: {{maximum}} + {{/maximum}} + * @return {{name}} + **/ {{#required}} - @NotNull{{/required}}{{! -}} + @NotNull +{{/required}} {{#pattern}} @Pattern(regexp="{{pattern}}") {{/pattern}} -{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} - @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} - @Size(max={{maxLength}}){{/maxLength}}{{/minLength}} +{{#minLength}} +{{#maxLength}} + @Size(min={{minLength}},max={{maxLength}}) +{{/maxLength}} +{{/minLength}} +{{#minLength}} +{{^maxLength}} + @Size(min={{minLength}}) +{{/maxLength}} +{{/minLength}} +{{^minLength}} +{{#maxLength}} + @Size(max={{maxLength}}) + {{/maxLength}} + {{/minLength}} {{#minimum}} //@Min({{minimum}}) {{/minimum}} {{#maximum}} //@Max({{maximum}}) {{/maximum}} - {{#vendorExtensions.extraAnnotation}}{{vendorExtensions.extraAnnotation}}{{/vendorExtensions.extraAnnotation}} + @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") +{{#vendorExtensions.extraAnnotation}} + {{vendorExtensions.extraAnnotation}} +{{/vendorExtensions.extraAnnotation}} public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; } From 3f6f4bfd86e0b1f53e3da2728f97561960e2d9f1 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 3 Jul 2016 21:49:33 +0800 Subject: [PATCH 023/470] fix objc readme doc --- .../src/main/resources/objc/README.mustache | 4 ++-- samples/client/petstore/objc/default/README.md | 18 +++++++++--------- .../objc/default/SwaggerClient/Api/SWGPetApi.m | 2 +- .../SwaggerClient/Core/SWGConfiguration.m | 14 +++++++------- .../petstore/objc/default/docs/SWGPetApi.md | 8 ++++---- 5 files changed, 23 insertions(+), 23 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/objc/README.mustache b/modules/swagger-codegen/src/main/resources/objc/README.mustache index db56c1b4b77..4355ecc1af5 100644 --- a/modules/swagger-codegen/src/main/resources/objc/README.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/README.mustache @@ -84,10 +84,10 @@ Please follow the [installation procedure](#installation--usage) and then run th {{classname}} *apiInstance = [[{{classname}} alloc] init]; -{{#summary}} // {{{.}}} +{{#summary}}// {{{.}}} {{/summary}}[apiInstance {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}:{{paramName}}{{/allParams}} - {{#hasParams}}completionHandler: {{/hasParams}}^({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) { + {{#hasParams}}completionHandler: {{/hasParams}}^({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error) { {{#returnType}} if (output) { NSLog(@"%@", output); diff --git a/samples/client/petstore/objc/default/README.md b/samples/client/petstore/objc/default/README.md index c27432d29cc..bef0aa17dab 100644 --- a/samples/client/petstore/objc/default/README.md +++ b/samples/client/petstore/objc/default/README.md @@ -6,7 +6,7 @@ This ObjC package is automatically generated by the [Swagger Codegen](https://gi - API version: 1.0.0 - Package version: -- Build date: 2016-06-16T11:33:30.448+02:00 +- Build date: 2016-07-03T21:49:00.509+08:00 - Build package: class io.swagger.codegen.languages.ObjcClientCodegen ## Requirements @@ -74,9 +74,9 @@ SWGPet* *body = [[SWGPet alloc] init]; // Pet object that needs to be added to t SWGPetApi *apiInstance = [[SWGPetApi alloc] init]; - // Add a new pet to the store +// Add a new pet to the store [apiInstance addPetWithBody:body - completionHandler: ^(NSError* error)) { + completionHandler: ^(NSError* error) { if (error) { NSLog(@"Error: %@", error); } @@ -124,6 +124,12 @@ Class | Method | HTTP request | Description ## Documentation For Authorization +## api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + ## petstore_auth - **Type**: OAuth @@ -133,12 +139,6 @@ Class | Method | HTTP request | Description - **write:pets**: modify pets in your account - **read:pets**: read your pets -## api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - ## Author diff --git a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.m b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.m index 409f5b86655..e35421fc520 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.m @@ -376,7 +376,7 @@ -(NSNumber*) getPetByIdWithPetId: (NSNumber*) petId NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting - NSArray *authSettings = @[@"petstore_auth", @"api_key"]; + NSArray *authSettings = @[@"api_key", @"petstore_auth"]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; diff --git a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGConfiguration.m b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGConfiguration.m index 24172638bba..b21290068a1 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGConfiguration.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGConfiguration.m @@ -110,13 +110,6 @@ - (NSDictionary *) apiKeyPrefix { - (NSDictionary *) authSettings { return @{ - @"petstore_auth": - @{ - @"type": @"oauth", - @"in": @"header", - @"key": @"Authorization", - @"value": [self getAccessToken] - }, @"api_key": @{ @"type": @"api_key", @@ -124,6 +117,13 @@ - (NSDictionary *) authSettings { @"key": @"api_key", @"value": [self getApiKeyWithPrefix:@"api_key"] }, + @"petstore_auth": + @{ + @"type": @"oauth", + @"in": @"header", + @"key": @"Authorization", + @"value": [self getAccessToken] + }, }; } diff --git a/samples/client/petstore/objc/default/docs/SWGPetApi.md b/samples/client/petstore/objc/default/docs/SWGPetApi.md index d702c353855..92fb2c4de81 100644 --- a/samples/client/petstore/objc/default/docs/SWGPetApi.md +++ b/samples/client/petstore/objc/default/docs/SWGPetApi.md @@ -246,14 +246,14 @@ Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error cond ```objc SWGConfiguration *apiConfig = [SWGConfiguration sharedConfig]; -// Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth) -[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; - // Configure API key authorization: (authentication scheme: api_key) [apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"api_key"]; // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed //[apiConfig setApiKeyPrefix:@"Bearer" forApiKeyIdentifier:@"api_key"]; +// Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth) +[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; + NSNumber* petId = @789; // ID of pet that needs to be fetched @@ -283,7 +283,7 @@ Name | Type | Description | Notes ### Authorization -[petstore_auth](../README.md#petstore_auth), [api_key](../README.md#api_key) +[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) ### HTTP request headers From ee34013b4eda287d47d4fa2167e5dc74443fdb43 Mon Sep 17 00:00:00 2001 From: jfiala Date: Sun, 3 Jul 2016 18:11:21 +0200 Subject: [PATCH 024/470] fix tabs instead of spaces... --- .../languages/JavaCXFServerCodegen.java | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java index b94f2d0c60d..8fa2ec71b8c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java @@ -12,9 +12,9 @@ import io.swagger.models.Operation; public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen -{ - public JavaCXFServerCodegen() - { +{ + public JavaCXFServerCodegen() + { super(); supportsInheritance = true; sourceFolder = "gen" + File.separator + "java"; @@ -34,24 +34,24 @@ public JavaCXFServerCodegen() embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "cxf"; - } + } - @Override - public void processOpts() - { - super.processOpts(); - - supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen + @Override + public void processOpts() + { + super.processOpts(); + + supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); - } - - @Override - public String getName() - { - return "jaxrs-cxf"; - } + } + + @Override + public String getName() + { + return "jaxrs-cxf"; + } @Override public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { From d47eaa9ca91d8684b33a79d6ab273bd46a694001 Mon Sep 17 00:00:00 2001 From: jfiala Date: Sun, 3 Jul 2016 18:24:41 +0200 Subject: [PATCH 025/470] move annotations from getter to field for server model --- .../resources/JavaJaxRS/cxf/pojo.mustache | 38 +++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache index 357fe96dcc4..e916ea92c9c 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache @@ -23,24 +23,6 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{>enumClass}}{{/items}}{{/items.isEnum}} @XmlElement(name="{{baseName}}") - private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}} - - {{#vars}} - /** - {{#description}} - * {{{description}}} - {{/description}} - {{^description}} - * Get {{name}} - {{/description}} - {{#minimum}} - * minimum: {{minimum}} - {{/minimum}} - {{#maximum}} - * maximum: {{maximum}} - {{/maximum}} - * @return {{name}} - **/ {{#required}} @NotNull {{/required}} @@ -67,8 +49,26 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{/minimum}} {{#maximum}} //@Max({{maximum}}) -{{/maximum}} +{{/maximum}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") + private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}} + + {{#vars}} + /** + {{#description}} + * {{{description}}} + {{/description}} + {{^description}} + * Get {{name}} + {{/description}} + {{#minimum}} + * minimum: {{minimum}} + {{/minimum}} + {{#maximum}} + * maximum: {{maximum}} + {{/maximum}} + * @return {{name}} + **/ {{#vendorExtensions.extraAnnotation}} {{vendorExtensions.extraAnnotation}} {{/vendorExtensions.extraAnnotation}} From 8c8f587192939d59dc37f3e4e1ef9a56efc1a75d Mon Sep 17 00:00:00 2001 From: jfiala Date: Sun, 3 Jul 2016 18:24:41 +0200 Subject: [PATCH 026/470] cleanup tabs --- .../resources/JavaJaxRS/cxf/pojo.mustache | 40 +++++++++---------- .../main/resources/JavaJaxRS/cxf/pom.mustache | 10 ++--- 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache index 357fe96dcc4..af565cdbf35 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache @@ -8,7 +8,7 @@ import javax.xml.bind.annotation.XmlEnum; @XmlAccessorType(XmlAccessType.FIELD) {{#hasVars}} @XmlType(name = "{{classname}}", propOrder = - { {{#vars}}"{{name}}"{{^-last}}, {{/-last}}{{/vars}} + { {{#vars}}"{{name}}"{{^-last}}, {{/-last}}{{/vars}} }){{/hasVars}} {{^hasVars}}@XmlType(name = "{{classname}}"){{/hasVars}} {{^parent}}@XmlRootElement(name="{{classname}}"){{/parent}} @@ -23,24 +23,6 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{>enumClass}}{{/items}}{{/items.isEnum}} @XmlElement(name="{{baseName}}") - private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}} - - {{#vars}} - /** - {{#description}} - * {{{description}}} - {{/description}} - {{^description}} - * Get {{name}} - {{/description}} - {{#minimum}} - * minimum: {{minimum}} - {{/minimum}} - {{#maximum}} - * maximum: {{maximum}} - {{/maximum}} - * @return {{name}} - **/ {{#required}} @NotNull {{/required}} @@ -67,8 +49,26 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{/minimum}} {{#maximum}} //@Max({{maximum}}) -{{/maximum}} +{{/maximum}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") + private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}} + + {{#vars}} + /** + {{#description}} + * {{{description}}} + {{/description}} + {{^description}} + * Get {{name}} + {{/description}} + {{#minimum}} + * minimum: {{minimum}} + {{/minimum}} + {{#maximum}} + * maximum: {{maximum}} + {{/maximum}} + * @return {{name}} + **/ {{#vendorExtensions.extraAnnotation}} {{vendorExtensions.extraAnnotation}} {{/vendorExtensions.extraAnnotation}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache index f8a33fd7fe1..9019f5e7332 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache @@ -110,11 +110,11 @@ - org.apache.cxf - cxf-rt-rs-client - 3.1.6 - test - + org.apache.cxf + cxf-rt-rs-client + 3.1.6 + test + javax.validation From e44bb1e372e41f4bce94d7345db684a4dff2ffe6 Mon Sep 17 00:00:00 2001 From: jfiala Date: Sun, 3 Jul 2016 18:40:45 +0200 Subject: [PATCH 027/470] add example for gzipping #2017 --- .../resources/JavaJaxRS/cxf/api_test.mustache | 30 ++++++++++++++----- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache index 524f20dfb39..a7f92f667ea 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache @@ -9,9 +9,12 @@ import org.junit.Before; import javax.ws.rs.core.Response; import org.apache.cxf.jaxrs.client.JAXRSClientFactory; +import org.apache.cxf.jaxrs.client.ClientConfiguration; +import org.apache.cxf.jaxrs.client.WebClient; +import org.apache.cxf.transport.common.gzip.GZIPInInterceptor; +import org.apache.cxf.transport.common.gzip.GZIPOutInterceptor; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; - {{^fullJavaUtil}} import java.util.ArrayList; import java.util.HashMap; @@ -28,11 +31,24 @@ public class {{classname}}Test { @Before public void setup() { - JacksonJsonProvider provider = new JacksonJsonProvider(); - List providers = new ArrayList(); - providers.add(provider); - - api = JAXRSClientFactory.create("{{basePath}}", {{classname}}.class, providers); + JacksonJsonProvider provider = new JacksonJsonProvider(); + List providers = new ArrayList(); + providers.add(provider); + + api = JAXRSClientFactory.create("{{basePath}}", {{classname}}.class, providers); + + org.apache.cxf.jaxrs.client.Client client = WebClient.client(api); + + ClientConfiguration config = WebClient.getConfig(client); + + // Example for using Gzipping + GZIPOutInterceptor gzipOutInterceptor = new GZIPOutInterceptor(); + // use Gzipping for first request sent to server + //gzipOutInterceptor.setForce(true); + config.getOutInterceptors().add(gzipOutInterceptor); + + config.getInInterceptors().add(new GZIPInInterceptor()); + } {{#operations}}{{#operation}} @@ -51,7 +67,7 @@ public class {{classname}}Test { {{/allParams}} Response response = api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); - {{#returnType}}{{{returnType}}} responseModel = response.readEntity({{{returnType}}}.class);{{/returnType}} + {{#returnType}}{{{returnType}}} responseModel = response.readEntity({{{returnType}}}.class);{{/returnType}} // TODO: test validations } From 6b1b883e21468794fdb5229f40f2bbc04605d624 Mon Sep 17 00:00:00 2001 From: jfiala Date: Sun, 3 Jul 2016 20:53:54 +0200 Subject: [PATCH 028/470] add complete WAR to cxf-server #2017 --- .../languages/JavaCXFServerCodegen.java | 22 ++++++ .../main/resources/JavaJaxRS/cxf/api.mustache | 9 ++- .../JavaJaxRS/cxf/apiServiceImpl.mustache | 44 ++++++++++++ .../resources/JavaJaxRS/cxf/api_test.mustache | 4 +- .../JavaJaxRS/cxf/context.xml.mustache | 71 +++++++++++++++++++ .../JavaJaxRS/cxf/jboss-web.xml.mustache | 7 ++ .../main/resources/JavaJaxRS/cxf/pom.mustache | 61 +++++++++++++--- .../main/resources/JavaJaxRS/cxf/web.mustache | 23 ++++++ 8 files changed, 229 insertions(+), 12 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/context.xml.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/jboss-web.xml.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/web.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java index 8fa2ec71b8c..a2c843514e7 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java @@ -11,15 +11,30 @@ import io.swagger.codegen.SupportingFile; import io.swagger.models.Operation; +/** + * TODO #2017: + * - reuse bean-validation-annotations in Java? + * - pom.xml: maybe add cxf-version property + * - api_test.mustache: add switch for using gzip in test cases? + * + * + * + */ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen { public JavaCXFServerCodegen() { super(); + supportsInheritance = true; + + artifactId = "swagger-cxf-server"; + sourceFolder = "gen" + File.separator + "java"; outputFolder = "generated-code/JavaJaxRS-CXF"; + apiTemplateFiles.put("apiServiceImpl.mustache", ".java"); + // clear model and api doc template as this codegen // does not support auto-generated markdown doc at the moment //TODO: add doc templates @@ -45,6 +60,13 @@ public void processOpts() supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); + writeOptional(outputFolder, new SupportingFile("web.mustache", + ("src/main/webapp/WEB-INF"), "web.xml")); + writeOptional(outputFolder, new SupportingFile("context.xml.mustache", + ("src/main/webapp/WEB-INF"), "context.xml")); + writeOptional(outputFolder, new SupportingFile("jboss-web.xml.mustache", + ("src/main/webapp/WEB-INF"), "jboss-web.xml")); + } @Override diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache index 7d57616610d..c949f117f8d 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache @@ -12,7 +12,11 @@ import javax.ws.rs.core.Response; import org.apache.cxf.jaxrs.ext.multipart.*; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + @Path("/") +@Api(value = "/", description = "{{description}}") public interface {{classname}} { {{#operations}} {{#operation}} @@ -20,7 +24,10 @@ public interface {{classname}} { {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} {{#hasConsumes}}@Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} {{#hasProduces}}@Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} - public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}); +{{#summary}} +@ApiOperation(value = "{{summary}}") +{{/summary}} + public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}); {{/operation}} } {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache new file mode 100644 index 00000000000..dde547f91c6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache @@ -0,0 +1,44 @@ +package {{package}}.impl; + +import {{package}}.*; +{{#imports}}import {{import}}; +{{/imports}} + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.model.wadl.Description; +import org.apache.cxf.jaxrs.model.wadl.DocTarget; + +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; + +@Path("/") +{{#description}} +@Api(value = "/", description = "{{description}}") +{{/description}} +public class {{classname}}ServiceImpl implements {{classname}} { +{{#operations}} +{{#operation}} + @{{httpMethod}} + {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} + {{#hasConsumes}}@Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} + {{#hasProduces}}@Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} + {{! add description for CXF WADL (must be added to implementation class }} +{{#summary}} + @Description(value = "{{summary}}", target = DocTarget.METHOD) +{{/summary}} + public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}) { + // TODO: Implement... + + {{#returnType}}return null;{{/returnType}} + } + +{{/operation}} +} +{{/operations}} + diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache index a7f92f667ea..7d275deb8c2 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache @@ -65,9 +65,7 @@ public class {{classname}}Test { {{#allParams}} {{{dataType}}} {{paramName}} = new {{{dataType}}}(); {{/allParams}} - Response response = api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); - - {{#returnType}}{{{returnType}}} responseModel = response.readEntity({{{returnType}}}.class);{{/returnType}} + {{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); // TODO: test validations } diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/context.xml.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/context.xml.mustache new file mode 100644 index 00000000000..1c7aeb4d64d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/context.xml.mustache @@ -0,0 +1,71 @@ + + + + + + + + + + + + +{{#apiInfo}} +{{#apis}} + +{{/apis}} +{{/apiInfo}} + + + + + + + + + + + + + + + + + + + + +{{#apiInfo}} +{{#apis}} + +{{/apis}} +{{/apiInfo}} + + + + + + + + + + + + diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/jboss-web.xml.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/jboss-web.xml.mustache new file mode 100644 index 00000000000..ef688c10e91 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/jboss-web.xml.mustache @@ -0,0 +1,7 @@ + + + + + swagger-cxf-server + + diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache index 9019f5e7332..5144bd95c9f 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache @@ -2,7 +2,7 @@ 4.0.0 {{groupId}} {{artifactId}} - jar + war {{artifactId}} {{artifactVersion}} @@ -25,7 +25,7 @@ - + org.codehaus.mojo build-helper-maven-plugin @@ -81,6 +81,14 @@ + + + + maven-war-plugin + + true + + @@ -108,6 +116,13 @@ ${junit-version} test + + + javax.validation + validation-api + 1.1.0.Final + provided + org.apache.cxf @@ -115,13 +130,43 @@ 3.1.6 test - + + - javax.validation - validation-api - 1.1.0.Final - provided + org.apache.cxf + cxf-rt-frontend-jaxrs + 3.1.6 + compile + + org.apache.cxf + cxf-rt-rs-service-description + 3.1.6 + compile + + + org.apache.cxf + cxf-rt-ws-policy + 3.1.6 + compile + + + org.apache.cxf + cxf-rt-wsdl + 3.1.6 + compile + + + + org.springframework + spring-context + 4.2.5.RELEASE + + + org.springframework + spring-web + 4.2.5.RELEASE + diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/web.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/web.mustache new file mode 100644 index 00000000000..9d905ae076b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/web.mustache @@ -0,0 +1,23 @@ + + + + + contextConfigLocation + WEB-INF/context.xml + + + org.springframework.web.context.ContextLoaderListener + + + CXF Service Servlet + CXFServiceServlet + org.apache.cxf.transport.servlet.CXFServlet + 1 + + + CXFServiceServlet + /rest/* + + + From bfc597c83db4a0d4a5f29b33b307935946970331 Mon Sep 17 00:00:00 2001 From: jfiala Date: Sun, 3 Jul 2016 21:11:04 +0200 Subject: [PATCH 029/470] add readme + rework pom #2017 --- .../languages/JavaCXFServerCodegen.java | 3 +++ .../main/resources/JavaJaxRS/cxf/pom.mustache | 21 +++++++++-------- .../main/resources/JavaJaxRS/cxf/readme.md | 23 +++++++++++++++++++ 3 files changed, 38 insertions(+), 9 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/readme.md diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java index a2c843514e7..5ccb88459e3 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java @@ -58,8 +58,11 @@ public void processOpts() super.processOpts(); supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen + writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); + writeOptional(outputFolder, new SupportingFile("readme.md", "", "readme.md")); + writeOptional(outputFolder, new SupportingFile("web.mustache", ("src/main/webapp/WEB-INF"), "web.xml")); writeOptional(outputFolder, new SupportingFile("context.xml.mustache", diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache index 5144bd95c9f..40a6135e636 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache @@ -120,14 +120,14 @@ javax.validation validation-api - 1.1.0.Final + ${beanvalidation-version} provided org.apache.cxf cxf-rt-rs-client - 3.1.6 + ${cxf-version} test @@ -135,37 +135,37 @@ org.apache.cxf cxf-rt-frontend-jaxrs - 3.1.6 + ${cxf-version} compile org.apache.cxf cxf-rt-rs-service-description - 3.1.6 + ${cxf-version} compile org.apache.cxf cxf-rt-ws-policy - 3.1.6 + ${cxf-version} compile org.apache.cxf cxf-rt-wsdl - 3.1.6 + ${cxf-version} compile - + org.springframework spring-context - 4.2.5.RELEASE + ${spring-version} org.springframework spring-web - 4.2.5.RELEASE + ${spring-version} @@ -187,6 +187,9 @@ 4.12 1.1.7 2.5 + 1.1.0.Final + 4.2.5.RELEASE + 3.1.6 UTF-8 diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/readme.md b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/readme.md new file mode 100644 index 00000000000..27925cedf44 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/readme.md @@ -0,0 +1,23 @@ + +# JAX-RS CXF 3 server application + +## Supported features +* Bean-Validation-API support +* Spring-configuration of Swagger, WADL and Endpoints +* Swagger-API is accessible (CXF3 Swagger2Feature) +* WADL is accessible (CXF WADL-Generator) +* Unit-tests include Gzip-Interceptors for demonstration + + +## Urls to access the REST API + +* Available services listing +http://localhost:8080/swagger-cxf-server/rest/services/ + +* Swagger API + http://localhost:8080/swagger-cxf-server/rest/services/swagger.json + +* CXF WADL + http://localhost:8080/swagger-cxf-server/rest/services?_wadl + + From 785d1a5648cdc40e510352d97735ed4df1468ce2 Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 4 Jul 2016 22:13:25 +0800 Subject: [PATCH 030/470] add option to set ssl host setting in ruby client --- .../main/resources/ruby/api_client.mustache | 5 ++ .../resources/ruby/configuration.mustache | 25 +++++++-- samples/client/petstore/ruby/README.md | 38 +++++++++---- samples/client/petstore/ruby/docs/FakeApi.md | 46 ---------------- samples/client/petstore/ruby/docs/MapTest.md | 1 - .../ruby/lib/petstore/api/fake_api.rb | 55 ------------------- .../petstore/ruby/lib/petstore/api_client.rb | 7 ++- .../ruby/lib/petstore/configuration.rb | 39 ++++++++----- .../ruby/lib/petstore/models/array_test.rb | 1 + .../ruby/lib/petstore/models/map_test.rb | 25 +-------- 10 files changed, 84 insertions(+), 158 deletions(-) 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 496d52d3757..9a5557d0bf6 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache @@ -82,6 +82,9 @@ module {{moduleName}} update_params_for_auth! header_params, query_params, opts[:auth_names] {{/hasAuthMethods}} + # set ssl_verifyhosts option based on @config.verify_ssl_host (true/false) + _verify_ssl_host = @config.verify_ssl_host ? 2 : 0 + req_opts = { :method => http_method, :headers => header_params, @@ -89,11 +92,13 @@ module {{moduleName}} :params_encoding => @config.params_encoding, :timeout => @config.timeout, :ssl_verifypeer => @config.verify_ssl, + :ssl_verifyhost => _verify_ssl_host, :sslcert => @config.cert_file, :sslkey => @config.key_file, :verbose => @config.debugging } + # set custom cert, if provided req_opts[:cainfo] = @config.ssl_ca_cert if @config.ssl_ca_cert if [:post, :patch, :put, :delete].include?(http_method) diff --git a/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache b/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache index 7fe6c874c00..3d160d46511 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache @@ -68,7 +68,7 @@ module {{moduleName}} # Default to 0 (never times out). attr_accessor :timeout - ### TLS/SSL + ### TLS/SSL setting # Set this to false to skip verifying SSL certificate when calling API from https server. # Default to true. # @@ -77,13 +77,16 @@ module {{moduleName}} # @return [true, false] attr_accessor :verify_ssl - # Set this to customize parameters encoding of array parameter with multi collectionFormat. - # Default to nil. + ### TLS/SSL setting + # Set this to false to skip verifying SSL host name + # Default to true. # - # @see The params_encoding option of Ethon. Related source code: - # https://github.com/typhoeus/ethon/blob/master/lib/ethon/easy/queryable.rb#L96 - attr_accessor :params_encoding + # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. + # + # @return [true, false] + attr_accessor :verify_ssl_host + ### TLS/SSL setting # Set this to customize the certificate file to verify the peer. # # @return [String] the path to the certificate file @@ -92,12 +95,21 @@ module {{moduleName}} # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145 attr_accessor :ssl_ca_cert + ### TLS/SSL setting # Client certificate file (for client certificate) attr_accessor :cert_file + ### TLS/SSL setting # Client private key file (for client certificate) attr_accessor :key_file + # Set this to customize parameters encoding of array parameter with multi collectionFormat. + # Default to nil. + # + # @see The params_encoding option of Ethon. Related source code: + # https://github.com/typhoeus/ethon/blob/master/lib/ethon/easy/queryable.rb#L96 + attr_accessor :params_encoding + attr_accessor :inject_format attr_accessor :force_ending_format @@ -110,6 +122,7 @@ module {{moduleName}} @api_key_prefix = {} @timeout = 0 @verify_ssl = true + @verify_ssl_host = true @params_encoding = nil @cert_file = nil @key_file = nil diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index 440aca6ef62..4123003eeed 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -8,7 +8,7 @@ This SDK is automatically generated by the [Swagger Codegen](https://github.com/ - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-06-29T13:19:03.533-07:00 +- Build date: 2016-07-04T22:10:18.328+08:00 - Build package: class io.swagger.codegen.languages.RubyClientCodegen ## Installation @@ -57,15 +57,30 @@ require 'petstore' api_instance = Petstore::FakeApi.new +number = 3.4 # Float | None + +double = 1.2 # Float | None + +string = "string_example" # String | None + +byte = "B" # String | None + opts = { - test_code_inject__end: "test_code_inject__end_example" # String | To test code injection */ + integer: 56, # Integer | None + int32: 56, # Integer | None + int64: 789, # Integer | None + float: 3.4, # Float | None + binary: "B", # String | None + date: Date.parse("2013-10-20"), # Date | None + date_time: DateTime.parse("2013-10-20T19:20:30+01:00"), # DateTime | None + password: "password_example" # String | None } begin - #To test code injection */ - api_instance.test_code_inject__end(opts) + #Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + api_instance.test_endpoint_parameters(number, double, string, byte, opts) rescue Petstore::ApiError => e - puts "Exception when calling FakeApi->test_code_inject__end: #{e}" + puts "Exception when calling FakeApi->test_endpoint_parameters: #{e}" end ``` @@ -76,7 +91,6 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*Petstore::FakeApi* | [**test_code_inject__end**](docs/FakeApi.md#test_code_inject__end) | **PUT** /fake | To test code injection */ *Petstore::FakeApi* | [**test_endpoint_parameters**](docs/FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 *Petstore::FakeApi* | [**test_enum_query_parameters**](docs/FakeApi.md#test_enum_query_parameters) | **GET** /fake | To test enum query parameters *Petstore::PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store @@ -134,6 +148,12 @@ Class | Method | HTTP request | Description ## Documentation for Authorization +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + ### petstore_auth - **Type**: OAuth @@ -143,9 +163,3 @@ Class | Method | HTTP request | Description - write:pets: modify pets in your account - read:pets: read your pets -### api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - diff --git a/samples/client/petstore/ruby/docs/FakeApi.md b/samples/client/petstore/ruby/docs/FakeApi.md index 94e1ab7f200..0d6fe39ab80 100644 --- a/samples/client/petstore/ruby/docs/FakeApi.md +++ b/samples/client/petstore/ruby/docs/FakeApi.md @@ -4,56 +4,10 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**test_code_inject__end**](FakeApi.md#test_code_inject__end) | **PUT** /fake | To test code injection */ [**test_endpoint_parameters**](FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**test_enum_query_parameters**](FakeApi.md#test_enum_query_parameters) | **GET** /fake | To test enum query parameters -# **test_code_inject__end** -> test_code_inject__end(opts) - -To test code injection */ - -### Example -```ruby -# load the gem -require 'petstore' - -api_instance = Petstore::FakeApi.new - -opts = { - test_code_inject__end: "test_code_inject__end_example" # String | To test code injection */ -} - -begin - #To test code injection */ - api_instance.test_code_inject__end(opts) -rescue Petstore::ApiError => e - puts "Exception when calling FakeApi->test_code_inject__end: #{e}" -end -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **test_code_inject__end** | **String**| To test code injection */ | [optional] - -### Return type - -nil (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json, */ =end));(phpinfo( - - **Accept**: application/json, */ end - - - # **test_endpoint_parameters** > test_endpoint_parameters(number, double, string, byte, opts) diff --git a/samples/client/petstore/ruby/docs/MapTest.md b/samples/client/petstore/ruby/docs/MapTest.md index e0ed8529bf8..902f1fbc511 100644 --- a/samples/client/petstore/ruby/docs/MapTest.md +++ b/samples/client/petstore/ruby/docs/MapTest.md @@ -4,7 +4,6 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **map_map_of_string** | **Hash<String, Hash<String, String>>** | | [optional] -**map_map_of_enum** | **Hash<String, Hash<String, String>>** | | [optional] **map_of_enum_string** | **Hash<String, String>** | | [optional] diff --git a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb index 39db2151ed7..ca2abf09bdd 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb @@ -31,61 +31,6 @@ def initialize(api_client = ApiClient.default) @api_client = api_client end - # To test code injection */ - # - # @param [Hash] opts the optional parameters - # @option opts [String] :test_code_inject__end To test code injection */ - # @return [nil] - def test_code_inject__end(opts = {}) - test_code_inject__end_with_http_info(opts) - return nil - end - - # To test code injection */ - # - # @param [Hash] opts the optional parameters - # @option opts [String] :test_code_inject__end To test code injection */ - # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers - def test_code_inject__end_with_http_info(opts = {}) - if @api_client.config.debugging - @api_client.config.logger.debug "Calling API: FakeApi.test_code_inject__end ..." - end - # resource path - local_var_path = "/fake".sub('{format}','json') - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - local_header_accept = ['application/json', '*/ end'] - local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result - - # HTTP header 'Content-Type' - local_header_content_type = ['application/json', '*/ =end));(phpinfo('] - header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) - - # form parameters - form_params = {} - form_params["test code inject */ =end"] = opts[:'test_code_inject__end'] if !opts[:'test_code_inject__end'].nil? - - # http body (model) - post_body = nil - auth_names = [] - data, status_code, headers = @api_client.call_api(:PUT, local_var_path, - :header_params => header_params, - :query_params => query_params, - :form_params => form_params, - :body => post_body, - :auth_names => auth_names) - if @api_client.config.debugging - @api_client.config.logger.debug "API called: FakeApi#test_code_inject__end\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" - end - return data, status_code, headers - end - # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # @param number None diff --git a/samples/client/petstore/ruby/lib/petstore/api_client.rb b/samples/client/petstore/ruby/lib/petstore/api_client.rb index 66a0204e318..74cca501908 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_client.rb @@ -99,6 +99,9 @@ def build_request(http_method, path, opts = {}) update_params_for_auth! header_params, query_params, opts[:auth_names] + # set ssl_verifyhosts option based on @config.verify_ssl_host (true/false) + _verify_ssl_host = @config.verify_ssl_host ? 2 : 0 + req_opts = { :method => http_method, :headers => header_params, @@ -106,11 +109,13 @@ def build_request(http_method, path, opts = {}) :params_encoding => @config.params_encoding, :timeout => @config.timeout, :ssl_verifypeer => @config.verify_ssl, + :ssl_verifyhost => _verify_ssl_host, :sslcert => @config.cert_file, :sslkey => @config.key_file, :verbose => @config.debugging } + # set custom cert, if provided req_opts[:cainfo] = @config.ssl_ca_cert if @config.ssl_ca_cert if [:post, :patch, :put, :delete].include?(http_method) @@ -216,7 +221,7 @@ def convert_to_type(data, return_type) # @return [Tempfile] the file downloaded def download_file(response) content_disposition = response.headers['Content-Disposition'] - if content_disposition + if content_disposition and content_disposition =~ /filename=/i filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] prefix = sanitize_filename(filename) else diff --git a/samples/client/petstore/ruby/lib/petstore/configuration.rb b/samples/client/petstore/ruby/lib/petstore/configuration.rb index d132b0da37d..1cff3c3ba27 100644 --- a/samples/client/petstore/ruby/lib/petstore/configuration.rb +++ b/samples/client/petstore/ruby/lib/petstore/configuration.rb @@ -87,7 +87,7 @@ class Configuration # Default to 0 (never times out). attr_accessor :timeout - ### TLS/SSL + ### TLS/SSL setting # Set this to false to skip verifying SSL certificate when calling API from https server. # Default to true. # @@ -96,13 +96,16 @@ class Configuration # @return [true, false] attr_accessor :verify_ssl - # Set this to customize parameters encoding of array parameter with multi collectionFormat. - # Default to nil. + ### TLS/SSL setting + # Set this to false to skip verifying SSL host name + # Default to true. # - # @see The params_encoding option of Ethon. Related source code: - # https://github.com/typhoeus/ethon/blob/master/lib/ethon/easy/queryable.rb#L96 - attr_accessor :params_encoding + # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. + # + # @return [true, false] + attr_accessor :verify_ssl_host + ### TLS/SSL setting # Set this to customize the certificate file to verify the peer. # # @return [String] the path to the certificate file @@ -111,12 +114,21 @@ class Configuration # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145 attr_accessor :ssl_ca_cert + ### TLS/SSL setting # Client certificate file (for client certificate) attr_accessor :cert_file + ### TLS/SSL setting # Client private key file (for client certificate) attr_accessor :key_file + # Set this to customize parameters encoding of array parameter with multi collectionFormat. + # Default to nil. + # + # @see The params_encoding option of Ethon. Related source code: + # https://github.com/typhoeus/ethon/blob/master/lib/ethon/easy/queryable.rb#L96 + attr_accessor :params_encoding + attr_accessor :inject_format attr_accessor :force_ending_format @@ -129,6 +141,7 @@ def initialize @api_key_prefix = {} @timeout = 0 @verify_ssl = true + @verify_ssl_host = true @params_encoding = nil @cert_file = nil @key_file = nil @@ -188,13 +201,6 @@ def basic_auth_token # Returns Auth Settings hash for api client. def auth_settings { - 'petstore_auth' => - { - type: 'oauth2', - in: 'header', - key: 'Authorization', - value: "Bearer #{access_token}" - }, 'api_key' => { type: 'api_key', @@ -202,6 +208,13 @@ def auth_settings key: 'api_key', value: api_key_with_prefix('api_key') }, + 'petstore_auth' => + { + type: 'oauth2', + in: 'header', + key: 'Authorization', + value: "Bearer #{access_token}" + }, } end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/array_test.rb b/samples/client/petstore/ruby/lib/petstore/models/array_test.rb index a4611d6c7a4..8a005f1c5cd 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/array_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/array_test.rb @@ -32,6 +32,7 @@ class ArrayTest attr_accessor :array_array_of_model + # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { diff --git a/samples/client/petstore/ruby/lib/petstore/models/map_test.rb b/samples/client/petstore/ruby/lib/petstore/models/map_test.rb index 3c4cf4243c0..b007a8566d3 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/map_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/map_test.rb @@ -28,8 +28,6 @@ module Petstore class MapTest attr_accessor :map_map_of_string - attr_accessor :map_map_of_enum - attr_accessor :map_of_enum_string class EnumAttributeValidator @@ -58,7 +56,6 @@ def valid?(value) def self.attribute_map { :'map_map_of_string' => :'map_map_of_string', - :'map_map_of_enum' => :'map_map_of_enum', :'map_of_enum_string' => :'map_of_enum_string' } end @@ -67,7 +64,6 @@ def self.attribute_map def self.swagger_types { :'map_map_of_string' => :'Hash>', - :'map_map_of_enum' => :'Hash>', :'map_of_enum_string' => :'Hash' } end @@ -86,12 +82,6 @@ def initialize(attributes = {}) end end - if attributes.has_key?(:'map_map_of_enum') - if (value = attributes[:'map_map_of_enum']).is_a?(Array) - self.map_map_of_enum = value - end - end - if attributes.has_key?(:'map_of_enum_string') if (value = attributes[:'map_of_enum_string']).is_a?(Array) self.map_of_enum_string = value @@ -110,23 +100,11 @@ def list_invalid_properties # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? - map_map_of_enum_validator = EnumAttributeValidator.new('Hash>', []) - return false unless map_map_of_enum_validator.valid?(@map_map_of_enum) map_of_enum_string_validator = EnumAttributeValidator.new('Hash', []) return false unless map_of_enum_string_validator.valid?(@map_of_enum_string) return true end - # Custom attribute writer method checking allowed values (enum). - # @param [Object] map_map_of_enum Object to be assigned - def map_map_of_enum=(map_map_of_enum) - validator = EnumAttributeValidator.new('Hash>', []) - unless validator.valid?(map_map_of_enum) - fail ArgumentError, "invalid value for 'map_map_of_enum', must be one of #{validator.allowable_values}." - end - @map_map_of_enum = map_map_of_enum - end - # Custom attribute writer method checking allowed values (enum). # @param [Object] map_of_enum_string Object to be assigned def map_of_enum_string=(map_of_enum_string) @@ -143,7 +121,6 @@ def ==(o) return true if self.equal?(o) self.class == o.class && map_map_of_string == o.map_map_of_string && - map_map_of_enum == o.map_map_of_enum && map_of_enum_string == o.map_of_enum_string end @@ -156,7 +133,7 @@ def eql?(o) # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash - [map_map_of_string, map_map_of_enum, map_of_enum_string].hash + [map_map_of_string, map_of_enum_string].hash end # Builds the object from hash From 4f69a2d788fe3412118fc56d03f28ececf1f689d Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 5 Jul 2016 00:03:08 +0800 Subject: [PATCH 031/470] update wording in overview --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a549adec5b5..0b98d3dca3a 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ :warning: If the OpenAPI/Swagger spec is obtained from an untrusted source, please make sure you've reviewed the spec before using Swagger Codegen to generate the API client, server stub or documentation as [code injection](https://en.wikipedia.org/wiki/Code_injection) may occur :warning: ## Overview -This is the swagger codegen project, which allows generation of client libraries automatically from a Swagger-compliant server. +This is the swagger codegen project, which allows generation of API client libraries, server stubs and documentation automatically given an [OpenAPI Spec]((https://github.com/OAI/OpenAPI-Specification). Check out [Swagger-Spec](https://github.com/OAI/OpenAPI-Specification) for additional information about the Swagger project, including additional libraries with support for other languages and more. From 873e3974ed703155e257b0c05667394f2aa84f48 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 5 Jul 2016 00:29:42 +0800 Subject: [PATCH 032/470] add badge for windows test --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 0b98d3dca3a..8f077b21c6e 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,7 @@ [![Build Status](https://travis-ci.org/swagger-api/swagger-codegen.svg)](https://travis-ci.org/swagger-api/swagger-codegen) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/io.swagger/swagger-codegen-project/badge.svg?style=plastic)](https://maven-badges.herokuapp.com/maven-central/io.swagger/swagger-codegen-project) [![PR Stats](http://issuestats.com/github/swagger-api/swagger-codegen/badge/pr)](http://issuestats.com/github/swagger-api/swagger-codegen) [![Issue Stats](http://issuestats.com/github/swagger-api/swagger-codegen/badge/issue)](http://issuestats.com/github/swagger-api/swagger-codegen) +[![Windows Test](https://ci.appveyor.com/api/projects/status/github/swagger-api/swagger-codegen?branch=master&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](#) :star::star::star: If you would like to contribute, please refer to [guidelines](https://github.com/swagger-api/swagger-codegen/blob/master/CONTRIBUTING.md) and a list of [open tasks](https://github.com/swagger-api/swagger-codegen/issues?q=is%3Aopen+is%3Aissue+label%3A%22Need+community+contribution%22).:star::star::star: From 0ada53435c5909bb1b97ff58bfecabc85400790e Mon Sep 17 00:00:00 2001 From: christian Date: Mon, 4 Jul 2016 19:51:38 +0200 Subject: [PATCH 033/470] #3284: Made modelNamePrefix and -Suffix available through maven --- .../swagger-codegen-maven-plugin/README.md | 1 + .../swagger/codegen/plugin/CodeGenMojo.java | 24 +++++++++++++++---- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/modules/swagger-codegen-maven-plugin/README.md b/modules/swagger-codegen-maven-plugin/README.md index d9282c97ebf..b32cacacc2c 100644 --- a/modules/swagger-codegen-maven-plugin/README.md +++ b/modules/swagger-codegen-maven-plugin/README.md @@ -45,6 +45,7 @@ mvn clean compile - `modelPackage` - the package to use for generated model objects/classes - `apiPackage` - the package to use for generated api objects/classes - `invokerPackage` - the package to use for the generated invoker objects +- `modelNamePrefix` and `modelNameSuffix` - Sets the pre- or suffix for model classes and enums. - `configOptions` - a map of language-specific parameters (see below) - `configHelp` - dumps the configuration help for the specified library (generates no sources) diff --git a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java index 261d539e2e5..8ad3c073bfb 100644 --- a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java +++ b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java @@ -21,8 +21,6 @@ import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.DefaultGenerator; import io.swagger.codegen.config.CodegenConfigurator; -import io.swagger.models.Swagger; -import io.swagger.parser.SwaggerParser; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.LifecyclePhase; @@ -32,9 +30,7 @@ import java.io.File; import java.util.HashMap; -import java.util.HashSet; import java.util.Map; -import java.util.Set; import static io.swagger.codegen.config.CodegenConfiguratorUtils.*; import static org.apache.commons.lang3.StringUtils.isNotEmpty; @@ -135,6 +131,18 @@ public class CodeGenMojo extends AbstractMojo { @Parameter(name = "library", required = false) private String library; + /** + * Sets the prefix for model enums and classes + */ + @Parameter(name = "modelNamePrefix", required = false) + private String modelNamePrefix; + + /** + * Sets the suffix for model enums and classes + */ + @Parameter(name = "modelNameSuffix", required = false) + private String modelNameSuffix; + /** * A map of language-specific parameters as passed with the -c option to the command line */ @@ -217,6 +225,14 @@ public void execute() throws MojoExecutionException { configurator.setLibrary(library); } + if(isNotEmpty(modelNamePrefix)) { + configurator.setModelNamePrefix(modelNamePrefix); + } + + if(isNotEmpty(modelNameSuffix)) { + configurator.setModelNamePrefix(modelNameSuffix); + } + if (null != templateDirectory) { configurator.setTemplateDir(templateDirectory.getAbsolutePath()); } From df695ee2c47d0b69eb2330dc229ef5870ef14ee5 Mon Sep 17 00:00:00 2001 From: Laurynas Date: Mon, 4 Jul 2016 15:22:54 -0400 Subject: [PATCH 034/470] Python vnd content-type header support Adding vendor header support like : "Content-Type: application/vnd.api+json" and "Content-Type: application/vnd.api+json; version=1" --- modules/swagger-codegen/src/main/resources/python/rest.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/python/rest.mustache b/modules/swagger-codegen/src/main/resources/python/rest.mustache index 1a6cf193b6c..bb3747021f5 100644 --- a/modules/swagger-codegen/src/main/resources/python/rest.mustache +++ b/modules/swagger-codegen/src/main/resources/python/rest.mustache @@ -121,7 +121,7 @@ class RESTClientObject(object): if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: if query_params: url += '?' + urlencode(query_params) - if headers['Content-Type'] == 'application/json': + if headers['Content-Type'].find('+json') != -1: request_body = None if body: request_body = json.dumps(body) From 23b81324d16adb9bacf24b7a7424e3f790a53a19 Mon Sep 17 00:00:00 2001 From: Laurynas Date: Mon, 4 Jul 2016 15:27:54 -0400 Subject: [PATCH 035/470] Python vnd content-type header support Adding vendor header support like : "Content-Type: application/vnd.api+json" and "Content-Type: application/vnd.api+json; version=1" --- modules/swagger-codegen/src/main/resources/python/rest.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/python/rest.mustache b/modules/swagger-codegen/src/main/resources/python/rest.mustache index bb3747021f5..a2e70b6ec7c 100644 --- a/modules/swagger-codegen/src/main/resources/python/rest.mustache +++ b/modules/swagger-codegen/src/main/resources/python/rest.mustache @@ -121,7 +121,7 @@ class RESTClientObject(object): if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: if query_params: url += '?' + urlencode(query_params) - if headers['Content-Type'].find('+json') != -1: + if headers['Content-Type'].find('json') != -1: request_body = None if body: request_body = json.dumps(body) From 907361cded835750124e4a3900c6d506cbe0704f Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 5 Jul 2016 07:46:42 +0800 Subject: [PATCH 036/470] add merge commit message --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a024ea98c41..2551c58bc6d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -11,7 +11,7 @@ - Search the [open issue](https://github.com/swagger-api/swagger-codegen/issues) to ensure no one else has reported something similar and no one is actively working on similar proposed change. - If no one has suggested something similar, open an ["issue"](https://github.com/swagger-api/swagger-codegen/issues) with your suggestion to gather feedback from the community. - - It's recommended to **create a new git branch** for the change + - It's recommended to **create a new git branch** for the change so that the merge commit message looks nicer in the commit history. ## How to contribute From 70376c8e63174f053279a1b1bdfac9fc059f31d7 Mon Sep 17 00:00:00 2001 From: "Rowan J.K. Walker" Date: Tue, 5 Jul 2016 21:48:25 +1200 Subject: [PATCH 037/470] Fix typo in README.md On line 379 -DapiTest should be -DapiTests and -DmodelTest should be -DmodelTests. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8f077b21c6e..29d6814f7c0 100644 --- a/README.md +++ b/README.md @@ -376,7 +376,7 @@ To control the specific files being generated, you can pass a CSV list of what y -Dmodels=User -DsupportingFiles=StringUtil.java ``` -To control generation of docs and tests for api and models, pass false to the option. For api, these options are `-DapiTest=false` and `-DapiDocs=false`. For models, `-DmodelTest=false` and `-DmodelDocs=false`. +To control generation of docs and tests for api and models, pass false to the option. For api, these options are `-DapiTests=false` and `-DapiDocs=false`. For models, `-DmodelTests=false` and `-DmodelDocs=false`. These options default to true and don't limit the generation of the feature options listed above (like `-Dapi`): ``` From dfc05f4bbaab32f3ec82ad704f11234af13d1f0e Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 5 Jul 2016 17:49:50 +0800 Subject: [PATCH 038/470] fix doc warning in java retrofit2 client --- .../libraries/retrofit2/ApiClient.mustache | 4 +- .../Java/libraries/retrofit2/pom.mustache | 2 + .../petstore/java/retrofit2/docs/ArrayTest.md | 7 --- .../petstore/java/retrofit2/docs/FakeApi.md | 44 ----------------- .../client/petstore/java/retrofit2/pom.xml | 2 + .../java/io/swagger/client/ApiClient.java | 10 ++-- .../java/io/swagger/client/api/FakeApi.java | 15 +----- .../java/io/swagger/client/api/PetApi.java | 2 +- .../io/swagger/client/model/ArrayTest.java | 49 +------------------ 9 files changed, 15 insertions(+), 120 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache index 9afdc5488b5..6ca343943cf 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache @@ -188,7 +188,7 @@ public class ApiClient { /** * Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one) - * @return + * @return Token request builder */ public TokenRequestBuilder getTokenEndPoint() { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -202,7 +202,7 @@ public class ApiClient { /** * Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one) - * @return + * @return Authentication request builder */ public AuthenticationRequestBuilder getAuthorizationEndPoint() { for(Interceptor apiAuthorization : apiAuthorizations.values()) { diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache index a3e28ff4595..717cca80fd2 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache @@ -68,6 +68,7 @@ org.codehaus.mojo build-helper-maven-plugin + 1.10 add_sources @@ -152,6 +153,7 @@ + UTF-8 {{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}} ${java.version} ${java.version} diff --git a/samples/client/petstore/java/retrofit2/docs/ArrayTest.md b/samples/client/petstore/java/retrofit2/docs/ArrayTest.md index 2cd4b9d33f9..9feee16427f 100644 --- a/samples/client/petstore/java/retrofit2/docs/ArrayTest.md +++ b/samples/client/petstore/java/retrofit2/docs/ArrayTest.md @@ -7,13 +7,6 @@ Name | Type | Description | Notes **arrayOfString** | **List<String>** | | [optional] **arrayArrayOfInteger** | [**List<List<Long>>**](List.md) | | [optional] **arrayArrayOfModel** | [**List<List<ReadOnlyFirst>>**](List.md) | | [optional] -**arrayOfEnum** | [**List<ArrayOfEnumEnum>**](#List<ArrayOfEnumEnum>) | | [optional] - - - -## Enum: List<ArrayOfEnumEnum> -Name | Value ----- | ----- diff --git a/samples/client/petstore/java/retrofit2/docs/FakeApi.md b/samples/client/petstore/java/retrofit2/docs/FakeApi.md index 0e646d63479..decba432a56 100644 --- a/samples/client/petstore/java/retrofit2/docs/FakeApi.md +++ b/samples/client/petstore/java/retrofit2/docs/FakeApi.md @@ -4,54 +4,10 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**testCodeInjectEnd**](FakeApi.md#testCodeInjectEnd) | **PUT** fake | To test code injection =end [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** fake | To test enum query parameters - -# **testCodeInjectEnd** -> Void testCodeInjectEnd(testCodeInjectEnd) - -To test code injection =end - -### Example -```java -// Import classes: -//import io.swagger.client.ApiException; -//import io.swagger.client.api.FakeApi; - - -FakeApi apiInstance = new FakeApi(); -String testCodeInjectEnd = "testCodeInjectEnd_example"; // String | To test code injection =end -try { - Void result = apiInstance.testCodeInjectEnd(testCodeInjectEnd); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testCodeInjectEnd"); - e.printStackTrace(); -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **testCodeInjectEnd** | **String**| To test code injection =end | [optional] - -### Return type - -[**Void**](.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json, */ =end'));(phpinfo(' - - **Accept**: application/json, */ end - # **testEndpointParameters** > Void testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) diff --git a/samples/client/petstore/java/retrofit2/pom.xml b/samples/client/petstore/java/retrofit2/pom.xml index 3af9daa695e..9b832202144 100644 --- a/samples/client/petstore/java/retrofit2/pom.xml +++ b/samples/client/petstore/java/retrofit2/pom.xml @@ -68,6 +68,7 @@ org.codehaus.mojo build-helper-maven-plugin + 1.10 add_sources @@ -138,6 +139,7 @@ + UTF-8 1.7 ${java.version} ${java.version} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java index ffb4c11be1d..87866795bf7 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java @@ -53,10 +53,10 @@ public ApiClient(String[] authNames) { this(); for(String authName : authNames) { Interceptor auth; - if (authName == "petstore_auth") { - auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); - } else if (authName == "api_key") { + if (authName == "api_key") { auth = new ApiKeyAuth("header", "api_key"); + } else if (authName == "petstore_auth") { + auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); } else { throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); } @@ -175,7 +175,7 @@ private void setCredentials(String username, String password) { /** * Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one) - * @return + * @return Token request builder */ public TokenRequestBuilder getTokenEndPoint() { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -189,7 +189,7 @@ public TokenRequestBuilder getTokenEndPoint() { /** * Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one) - * @return + * @return Authentication request builder */ public AuthenticationRequestBuilder getAuthorizationEndPoint() { for(Interceptor apiAuthorization : apiAuthorizations.values()) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java index 004ba1916a5..aa1089ddbed 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java @@ -9,8 +9,8 @@ import okhttp3.RequestBody; import org.joda.time.LocalDate; -import java.math.BigDecimal; import org.joda.time.DateTime; +import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; @@ -18,19 +18,6 @@ import java.util.Map; public interface FakeApi { - /** - * To test code injection =end - * - * @param testCodeInjectEnd To test code injection =end (optional) - * @return Call - */ - - @FormUrlEncoded - @PUT("fake") - Call testCodeInjectEnd( - @Field("test code inject */ =end") String testCodeInjectEnd - ); - /** * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java index ec9d67a7449..dd39a864f06 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java @@ -9,8 +9,8 @@ import okhttp3.RequestBody; import io.swagger.client.model.Pet; -import io.swagger.client.model.ModelApiResponse; import java.io.File; +import io.swagger.client.model.ModelApiResponse; import java.util.ArrayList; import java.util.HashMap; diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayTest.java index b853a0b035a..8d58870bcdc 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayTest.java @@ -48,31 +48,6 @@ public class ArrayTest { @SerializedName("array_array_of_model") private List> arrayArrayOfModel = new ArrayList>(); - /** - * Gets or Sets arrayOfEnum - */ - public enum ArrayOfEnumEnum { - @SerializedName("UPPER") - UPPER("UPPER"), - - @SerializedName("lower") - LOWER("lower"); - - private String value; - - ArrayOfEnumEnum(String value) { - this.value = value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - } - - @SerializedName("array_of_enum") - private List arrayOfEnum = new ArrayList(); - public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; return this; @@ -127,24 +102,6 @@ public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } - public ArrayTest arrayOfEnum(List arrayOfEnum) { - this.arrayOfEnum = arrayOfEnum; - return this; - } - - /** - * Get arrayOfEnum - * @return arrayOfEnum - **/ - @ApiModelProperty(example = "null", value = "") - public List getArrayOfEnum() { - return arrayOfEnum; - } - - public void setArrayOfEnum(List arrayOfEnum) { - this.arrayOfEnum = arrayOfEnum; - } - @Override public boolean equals(java.lang.Object o) { @@ -157,13 +114,12 @@ public boolean equals(java.lang.Object o) { ArrayTest arrayTest = (ArrayTest) o; return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && - Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel) && - Objects.equals(this.arrayOfEnum, arrayTest.arrayOfEnum); + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); } @Override public int hashCode() { - return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel, arrayOfEnum); + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); } @Override @@ -174,7 +130,6 @@ public String toString() { sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); - sb.append(" arrayOfEnum: ").append(toIndentedString(arrayOfEnum)).append("\n"); sb.append("}"); return sb.toString(); } From 5608c739380c3d694345c504ff0580ea5e36d93f Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 5 Jul 2016 17:59:13 +0800 Subject: [PATCH 039/470] update pom to cover gralde, sbt, javadoc test --- .../java/retrofit2/.swagger-codegen-ignore | 2 + .../client/petstore/java/retrofit2/pom.xml | 49 +++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/samples/client/petstore/java/retrofit2/.swagger-codegen-ignore b/samples/client/petstore/java/retrofit2/.swagger-codegen-ignore index c5fa491b4c5..bca48b38e28 100644 --- a/samples/client/petstore/java/retrofit2/.swagger-codegen-ignore +++ b/samples/client/petstore/java/retrofit2/.swagger-codegen-ignore @@ -21,3 +21,5 @@ #docs/*.md # Then explicitly reverse the ignore rule for a single file: #!docs/README.md + +pom.xml diff --git a/samples/client/petstore/java/retrofit2/pom.xml b/samples/client/petstore/java/retrofit2/pom.xml index 9b832202144..770278851e6 100644 --- a/samples/client/petstore/java/retrofit2/pom.xml +++ b/samples/client/petstore/java/retrofit2/pom.xml @@ -96,6 +96,55 @@ + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + gradle-test + integration-test + + exec + + + gradle + + check + + + + + sbt-test + integration-test + + exec + + + sbt + + publishLocal + + + + + mvn-javadoc-test + integration-test + + exec + + + mvn + + javadoc:javadoc + + + + + + From 5e6a6de351e9c0b95af412b20ef2ee0f29f331ef Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 5 Jul 2016 19:38:33 +0800 Subject: [PATCH 040/470] fix javadoc error --- .../libraries/retrofit2/ApiClient.mustache | 44 ++++++++--------- .../Java/libraries/retrofit2/api.mustache | 4 +- .../java/retrofit2/.swagger-codegen-ignore | 2 - .../client/petstore/java/retrofit2/pom.xml | 49 ------------------- .../java/io/swagger/client/ApiClient.java | 44 ++++++++--------- .../java/io/swagger/client/api/FakeApi.java | 8 +-- .../java/io/swagger/client/api/PetApi.java | 32 ++++++------ .../java/io/swagger/client/api/StoreApi.java | 16 +++--- .../java/io/swagger/client/api/UserApi.java | 32 ++++++------ 9 files changed, 90 insertions(+), 141 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache index 6ca343943cf..f9434978704 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache @@ -74,7 +74,7 @@ public class ApiClient { /** * Basic constructor for single auth name - * @param authName + * @param authName Authentication name */ public ApiClient(String authName) { this(new String[]{authName}); @@ -82,8 +82,8 @@ public class ApiClient { /** * Helper constructor for single api key - * @param authName - * @param apiKey + * @param authName Authentication name + * @param apiKey API key */ public ApiClient(String authName, String apiKey) { this(authName); @@ -92,9 +92,9 @@ public class ApiClient { /** * Helper constructor for single basic auth or password oauth2 - * @param authName - * @param username - * @param password + * @param authName Authentication name + * @param username Username + * @param password Password */ public ApiClient(String authName, String username, String password) { this(authName); @@ -103,11 +103,11 @@ public class ApiClient { /** * Helper constructor for single password oauth2 - * @param authName - * @param clientId - * @param secret - * @param username - * @param password + * @param authName Authentication name + * @param clientId Client ID + * @param secret Client Secret + * @param username Username + * @param password Password */ public ApiClient(String authName, String clientId, String secret, String username, String password) { this(authName); @@ -154,7 +154,7 @@ public class ApiClient { /** * Helper method to configure the first api key found - * @param apiKey + * @param apiKey API key */ private void setApiKey(String apiKey) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -168,8 +168,8 @@ public class ApiClient { /** * Helper method to configure the username/password for basic auth or password oauth - * @param username - * @param password + * @param username Username + * @param password Password */ private void setCredentials(String username, String password) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -216,7 +216,7 @@ public class ApiClient { /** * Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one) - * @param accessToken + * @param accessToken Access token */ public void setAccessToken(String accessToken) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -230,9 +230,9 @@ public class ApiClient { /** * Helper method to configure the oauth accessCode/implicit flow parameters - * @param clientId - * @param clientSecret - * @param redirectURI + * @param clientId Client ID + * @param clientSecret Client secret + * @param redirectURI Redirect URI */ public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -252,7 +252,7 @@ public class ApiClient { /** * Configures a listener which is notified when a new access token is received. - * @param accessTokenListener + * @param accessTokenListener Access token listener */ public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -266,8 +266,8 @@ public class ApiClient { /** * Adds an authorization to be used by the client - * @param authName - * @param authorization + * @param authName Authentication name + * @param authorization Authorization interceptor */ public void addAuthorization(String authName, Interceptor authorization) { if (apiAuthorizations.containsKey(authName)) { @@ -305,7 +305,7 @@ public class ApiClient { /** * Clones the okBuilder given in parameter, adds the auth interceptors and uses it to configure the Retrofit - * @param okClient + * @param okClient An instance of OK HTTP client */ public void configureFromOkclient(OkHttpClient okClient) { this.okBuilder = okClient.newBuilder(); diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache index 9bd835a4a36..398cbe6a132 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache @@ -25,12 +25,12 @@ public interface {{classname}} { * {{summary}} * {{notes}} {{#allParams}} * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} -{{/allParams}} * @return Call<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> +{{/allParams}} * @return Call[{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}] */ {{#formParams}}{{#-first}} {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} @{{httpMethod}}("{{path}}") - {{#useRxJava}}Observable{{/useRxJava}}{{^useRxJava}}Call{{/useRxJava}}<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}({{^allParams}});{{/allParams}} + {{#useRxJava}}Observable{{/useRxJava}}{{^useRxJava}}Call{{/useRxJava}}[{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}] {{operationId}}({{^allParams}});{{/allParams}} {{#allParams}}{{>libraries/retrofit2/queryParams}}{{>libraries/retrofit2/pathParams}}{{>libraries/retrofit2/headerParams}}{{>libraries/retrofit2/bodyParams}}{{>libraries/retrofit2/formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}} );{{/hasMore}}{{/allParams}} diff --git a/samples/client/petstore/java/retrofit2/.swagger-codegen-ignore b/samples/client/petstore/java/retrofit2/.swagger-codegen-ignore index bca48b38e28..c5fa491b4c5 100644 --- a/samples/client/petstore/java/retrofit2/.swagger-codegen-ignore +++ b/samples/client/petstore/java/retrofit2/.swagger-codegen-ignore @@ -21,5 +21,3 @@ #docs/*.md # Then explicitly reverse the ignore rule for a single file: #!docs/README.md - -pom.xml diff --git a/samples/client/petstore/java/retrofit2/pom.xml b/samples/client/petstore/java/retrofit2/pom.xml index 770278851e6..9b832202144 100644 --- a/samples/client/petstore/java/retrofit2/pom.xml +++ b/samples/client/petstore/java/retrofit2/pom.xml @@ -96,55 +96,6 @@ - - - - org.codehaus.mojo - exec-maven-plugin - 1.2.1 - - - gradle-test - integration-test - - exec - - - gradle - - check - - - - - sbt-test - integration-test - - exec - - - sbt - - publishLocal - - - - - mvn-javadoc-test - integration-test - - exec - - - mvn - - javadoc:javadoc - - - - - - diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java index 87866795bf7..604861f6072 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java @@ -66,7 +66,7 @@ public ApiClient(String[] authNames) { /** * Basic constructor for single auth name - * @param authName + * @param authName Authentication name */ public ApiClient(String authName) { this(new String[]{authName}); @@ -74,8 +74,8 @@ public ApiClient(String authName) { /** * Helper constructor for single api key - * @param authName - * @param apiKey + * @param authName Authentication name + * @param apiKey API key */ public ApiClient(String authName, String apiKey) { this(authName); @@ -84,9 +84,9 @@ public ApiClient(String authName, String apiKey) { /** * Helper constructor for single basic auth or password oauth2 - * @param authName - * @param username - * @param password + * @param authName Authentication name + * @param username Username + * @param password Password */ public ApiClient(String authName, String username, String password) { this(authName); @@ -95,11 +95,11 @@ public ApiClient(String authName, String username, String password) { /** * Helper constructor for single password oauth2 - * @param authName - * @param clientId - * @param secret - * @param username - * @param password + * @param authName Authentication name + * @param clientId Client ID + * @param secret Client Secret + * @param username Username + * @param password Password */ public ApiClient(String authName, String clientId, String secret, String username, String password) { this(authName); @@ -141,7 +141,7 @@ public S createService(Class serviceClass) { /** * Helper method to configure the first api key found - * @param apiKey + * @param apiKey API key */ private void setApiKey(String apiKey) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -155,8 +155,8 @@ private void setApiKey(String apiKey) { /** * Helper method to configure the username/password for basic auth or password oauth - * @param username - * @param password + * @param username Username + * @param password Password */ private void setCredentials(String username, String password) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -203,7 +203,7 @@ public AuthenticationRequestBuilder getAuthorizationEndPoint() { /** * Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one) - * @param accessToken + * @param accessToken Access token */ public void setAccessToken(String accessToken) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -217,9 +217,9 @@ public void setAccessToken(String accessToken) { /** * Helper method to configure the oauth accessCode/implicit flow parameters - * @param clientId - * @param clientSecret - * @param redirectURI + * @param clientId Client ID + * @param clientSecret Client secret + * @param redirectURI Redirect URI */ public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -239,7 +239,7 @@ public void configureAuthorizationFlow(String clientId, String clientSecret, Str /** * Configures a listener which is notified when a new access token is received. - * @param accessTokenListener + * @param accessTokenListener Access token listener */ public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -253,8 +253,8 @@ public void registerAccessTokenListener(AccessTokenListener accessTokenListener) /** * Adds an authorization to be used by the client - * @param authName - * @param authorization + * @param authName Authentication name + * @param authorization Authorization interceptor */ public void addAuthorization(String authName, Interceptor authorization) { if (apiAuthorizations.containsKey(authName)) { @@ -292,7 +292,7 @@ public void addAuthsToOkBuilder(OkHttpClient.Builder okBuilder) { /** * Clones the okBuilder given in parameter, adds the auth interceptors and uses it to configure the Retrofit - * @param okClient + * @param okClient An instance of OK HTTP client */ public void configureFromOkclient(OkHttpClient okClient) { this.okBuilder = okClient.newBuilder(); diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java index aa1089ddbed..4b2149758a7 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java @@ -33,12 +33,12 @@ public interface FakeApi { * @param date None (optional) * @param dateTime None (optional) * @param password None (optional) - * @return Call + * @return Call[Void] */ @FormUrlEncoded @POST("fake") - Call testEndpointParameters( + Call[Void] testEndpointParameters( @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password ); @@ -48,12 +48,12 @@ Call testEndpointParameters( * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) * @param enumQueryInteger Query parameter enum test (double) (optional) * @param enumQueryDouble Query parameter enum test (double) (optional) - * @return Call + * @return Call[Void] */ @FormUrlEncoded @GET("fake") - Call testEnumQueryParameters( + Call[Void] testEnumQueryParameters( @Field("enum_query_string") String enumQueryString, @Query("enum_query_integer") BigDecimal enumQueryInteger, @Field("enum_query_double") Double enumQueryDouble ); diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java index dd39a864f06..23e97996c66 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java @@ -22,11 +22,11 @@ public interface PetApi { * Add a new pet to the store * * @param body Pet object that needs to be added to the store (required) - * @return Call + * @return Call[Void] */ @POST("pet") - Call addPet( + Call[Void] addPet( @Body Pet body ); @@ -35,11 +35,11 @@ Call addPet( * * @param petId Pet id to delete (required) * @param apiKey (optional) - * @return Call + * @return Call[Void] */ @DELETE("pet/{petId}") - Call deletePet( + Call[Void] deletePet( @Path("petId") Long petId, @Header("api_key") String apiKey ); @@ -47,11 +47,11 @@ Call deletePet( * Finds Pets by status * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter (required) - * @return Call> + * @return Call[List] */ @GET("pet/findByStatus") - Call> findPetsByStatus( + Call[List] findPetsByStatus( @Query("status") CSVParams status ); @@ -59,11 +59,11 @@ Call> findPetsByStatus( * Finds Pets by tags * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by (required) - * @return Call> + * @return Call[List] */ @GET("pet/findByTags") - Call> findPetsByTags( + Call[List] findPetsByTags( @Query("tags") CSVParams tags ); @@ -71,11 +71,11 @@ Call> findPetsByTags( * Find pet by ID * Returns a single pet * @param petId ID of pet to return (required) - * @return Call + * @return Call[Pet] */ @GET("pet/{petId}") - Call getPetById( + Call[Pet] getPetById( @Path("petId") Long petId ); @@ -83,11 +83,11 @@ Call getPetById( * Update an existing pet * * @param body Pet object that needs to be added to the store (required) - * @return Call + * @return Call[Void] */ @PUT("pet") - Call updatePet( + Call[Void] updatePet( @Body Pet body ); @@ -97,12 +97,12 @@ Call updatePet( * @param petId ID of pet that needs to be updated (required) * @param name Updated name of the pet (optional) * @param status Updated status of the pet (optional) - * @return Call + * @return Call[Void] */ @FormUrlEncoded @POST("pet/{petId}") - Call updatePetWithForm( + Call[Void] updatePetWithForm( @Path("petId") Long petId, @Field("name") String name, @Field("status") String status ); @@ -112,12 +112,12 @@ Call updatePetWithForm( * @param petId ID of pet to update (required) * @param additionalMetadata Additional data to pass to server (optional) * @param file file to upload (optional) - * @return Call + * @return Call[ModelApiResponse] */ @Multipart @POST("pet/{petId}/uploadImage") - Call uploadFile( + Call[ModelApiResponse] uploadFile( @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file\"; filename=\"file\"") RequestBody file ); diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java index 1651c07482c..97c331e1a58 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java @@ -20,33 +20,33 @@ public interface StoreApi { * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * @param orderId ID of the order that needs to be deleted (required) - * @return Call + * @return Call[Void] */ @DELETE("store/order/{orderId}") - Call deleteOrder( + Call[Void] deleteOrder( @Path("orderId") String orderId ); /** * Returns pet inventories by status * Returns a map of status codes to quantities - * @return Call> + * @return Call[Map] */ @GET("store/inventory") - Call> getInventory(); + Call[Map] getInventory(); /** * Find purchase order by ID * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * @param orderId ID of pet that needs to be fetched (required) - * @return Call + * @return Call[Order] */ @GET("store/order/{orderId}") - Call getOrderById( + Call[Order] getOrderById( @Path("orderId") Long orderId ); @@ -54,11 +54,11 @@ Call getOrderById( * Place an order for a pet * * @param body order placed for purchasing the pet (required) - * @return Call + * @return Call[Order] */ @POST("store/order") - Call placeOrder( + Call[Order] placeOrder( @Body Order body ); diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java index a0f17545a0f..0b4a60bb79e 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java @@ -20,11 +20,11 @@ public interface UserApi { * Create user * This can only be done by the logged in user. * @param body Created user object (required) - * @return Call + * @return Call[Void] */ @POST("user") - Call createUser( + Call[Void] createUser( @Body User body ); @@ -32,11 +32,11 @@ Call createUser( * Creates list of users with given input array * * @param body List of user object (required) - * @return Call + * @return Call[Void] */ @POST("user/createWithArray") - Call createUsersWithArrayInput( + Call[Void] createUsersWithArrayInput( @Body List body ); @@ -44,11 +44,11 @@ Call createUsersWithArrayInput( * Creates list of users with given input array * * @param body List of user object (required) - * @return Call + * @return Call[Void] */ @POST("user/createWithList") - Call createUsersWithListInput( + Call[Void] createUsersWithListInput( @Body List body ); @@ -56,11 +56,11 @@ Call createUsersWithListInput( * Delete user * This can only be done by the logged in user. * @param username The name that needs to be deleted (required) - * @return Call + * @return Call[Void] */ @DELETE("user/{username}") - Call deleteUser( + Call[Void] deleteUser( @Path("username") String username ); @@ -68,11 +68,11 @@ Call deleteUser( * Get user by user name * * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return Call + * @return Call[User] */ @GET("user/{username}") - Call getUserByName( + Call[User] getUserByName( @Path("username") String username ); @@ -81,22 +81,22 @@ Call getUserByName( * * @param username The user name for login (required) * @param password The password for login in clear text (required) - * @return Call + * @return Call[String] */ @GET("user/login") - Call loginUser( + Call[String] loginUser( @Query("username") String username, @Query("password") String password ); /** * Logs out current logged in user session * - * @return Call + * @return Call[Void] */ @GET("user/logout") - Call logoutUser(); + Call[Void] logoutUser(); /** @@ -104,11 +104,11 @@ Call loginUser( * This can only be done by the logged in user. * @param username name that need to be deleted (required) * @param body Updated user object (required) - * @return Call + * @return Call[Void] */ @PUT("user/{username}") - Call updateUser( + Call[Void] updateUser( @Path("username") String username, @Body User body ); From 430f49aae6300137d30a48848b0648785bf35ec3 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 5 Jul 2016 20:38:04 +0800 Subject: [PATCH 041/470] fix javadoc error --- .../Java/libraries/retrofit2/api.mustache | 4 +-- .../java/io/swagger/client/api/FakeApi.java | 8 ++--- .../java/io/swagger/client/api/PetApi.java | 32 +++++++++---------- .../java/io/swagger/client/api/StoreApi.java | 16 +++++----- .../java/io/swagger/client/api/UserApi.java | 32 +++++++++---------- 5 files changed, 46 insertions(+), 46 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache index 398cbe6a132..7fa42fe732c 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache @@ -25,12 +25,12 @@ public interface {{classname}} { * {{summary}} * {{notes}} {{#allParams}} * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} -{{/allParams}} * @return Call[{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}] +{{/allParams}} * @return Call<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> */ {{#formParams}}{{#-first}} {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} @{{httpMethod}}("{{path}}") - {{#useRxJava}}Observable{{/useRxJava}}{{^useRxJava}}Call{{/useRxJava}}[{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}] {{operationId}}({{^allParams}});{{/allParams}} + {{#useRxJava}}Observable{{/useRxJava}}{{^useRxJava}}Call{{/useRxJava}}<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}({{^allParams}});{{/allParams}} {{#allParams}}{{>libraries/retrofit2/queryParams}}{{>libraries/retrofit2/pathParams}}{{>libraries/retrofit2/headerParams}}{{>libraries/retrofit2/bodyParams}}{{>libraries/retrofit2/formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}} );{{/hasMore}}{{/allParams}} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java index 4b2149758a7..042a6ba37e5 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java @@ -33,12 +33,12 @@ public interface FakeApi { * @param date None (optional) * @param dateTime None (optional) * @param password None (optional) - * @return Call[Void] + * @return Call<Void> */ @FormUrlEncoded @POST("fake") - Call[Void] testEndpointParameters( + Call testEndpointParameters( @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password ); @@ -48,12 +48,12 @@ Call[Void] testEndpointParameters( * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) * @param enumQueryInteger Query parameter enum test (double) (optional) * @param enumQueryDouble Query parameter enum test (double) (optional) - * @return Call[Void] + * @return Call<Void> */ @FormUrlEncoded @GET("fake") - Call[Void] testEnumQueryParameters( + Call testEnumQueryParameters( @Field("enum_query_string") String enumQueryString, @Query("enum_query_integer") BigDecimal enumQueryInteger, @Field("enum_query_double") Double enumQueryDouble ); diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java index 23e97996c66..a55cb2ee17f 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java @@ -22,11 +22,11 @@ public interface PetApi { * Add a new pet to the store * * @param body Pet object that needs to be added to the store (required) - * @return Call[Void] + * @return Call<Void> */ @POST("pet") - Call[Void] addPet( + Call addPet( @Body Pet body ); @@ -35,11 +35,11 @@ Call[Void] addPet( * * @param petId Pet id to delete (required) * @param apiKey (optional) - * @return Call[Void] + * @return Call<Void> */ @DELETE("pet/{petId}") - Call[Void] deletePet( + Call deletePet( @Path("petId") Long petId, @Header("api_key") String apiKey ); @@ -47,11 +47,11 @@ Call[Void] deletePet( * Finds Pets by status * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter (required) - * @return Call[List] + * @return Call<List> */ @GET("pet/findByStatus") - Call[List] findPetsByStatus( + Call> findPetsByStatus( @Query("status") CSVParams status ); @@ -59,11 +59,11 @@ Call[List] findPetsByStatus( * Finds Pets by tags * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by (required) - * @return Call[List] + * @return Call<List> */ @GET("pet/findByTags") - Call[List] findPetsByTags( + Call> findPetsByTags( @Query("tags") CSVParams tags ); @@ -71,11 +71,11 @@ Call[List] findPetsByTags( * Find pet by ID * Returns a single pet * @param petId ID of pet to return (required) - * @return Call[Pet] + * @return Call<Pet> */ @GET("pet/{petId}") - Call[Pet] getPetById( + Call getPetById( @Path("petId") Long petId ); @@ -83,11 +83,11 @@ Call[Pet] getPetById( * Update an existing pet * * @param body Pet object that needs to be added to the store (required) - * @return Call[Void] + * @return Call<Void> */ @PUT("pet") - Call[Void] updatePet( + Call updatePet( @Body Pet body ); @@ -97,12 +97,12 @@ Call[Void] updatePet( * @param petId ID of pet that needs to be updated (required) * @param name Updated name of the pet (optional) * @param status Updated status of the pet (optional) - * @return Call[Void] + * @return Call<Void> */ @FormUrlEncoded @POST("pet/{petId}") - Call[Void] updatePetWithForm( + Call updatePetWithForm( @Path("petId") Long petId, @Field("name") String name, @Field("status") String status ); @@ -112,12 +112,12 @@ Call[Void] updatePetWithForm( * @param petId ID of pet to update (required) * @param additionalMetadata Additional data to pass to server (optional) * @param file file to upload (optional) - * @return Call[ModelApiResponse] + * @return Call<ModelApiResponse> */ @Multipart @POST("pet/{petId}/uploadImage") - Call[ModelApiResponse] uploadFile( + Call uploadFile( @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file\"; filename=\"file\"") RequestBody file ); diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java index 97c331e1a58..3e19600bedb 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java @@ -20,33 +20,33 @@ public interface StoreApi { * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * @param orderId ID of the order that needs to be deleted (required) - * @return Call[Void] + * @return Call<Void> */ @DELETE("store/order/{orderId}") - Call[Void] deleteOrder( + Call deleteOrder( @Path("orderId") String orderId ); /** * Returns pet inventories by status * Returns a map of status codes to quantities - * @return Call[Map] + * @return Call<Map> */ @GET("store/inventory") - Call[Map] getInventory(); + Call> getInventory(); /** * Find purchase order by ID * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * @param orderId ID of pet that needs to be fetched (required) - * @return Call[Order] + * @return Call<Order> */ @GET("store/order/{orderId}") - Call[Order] getOrderById( + Call getOrderById( @Path("orderId") Long orderId ); @@ -54,11 +54,11 @@ Call[Order] getOrderById( * Place an order for a pet * * @param body order placed for purchasing the pet (required) - * @return Call[Order] + * @return Call<Order> */ @POST("store/order") - Call[Order] placeOrder( + Call placeOrder( @Body Order body ); diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java index 0b4a60bb79e..3fc76b6a1b2 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java @@ -20,11 +20,11 @@ public interface UserApi { * Create user * This can only be done by the logged in user. * @param body Created user object (required) - * @return Call[Void] + * @return Call<Void> */ @POST("user") - Call[Void] createUser( + Call createUser( @Body User body ); @@ -32,11 +32,11 @@ Call[Void] createUser( * Creates list of users with given input array * * @param body List of user object (required) - * @return Call[Void] + * @return Call<Void> */ @POST("user/createWithArray") - Call[Void] createUsersWithArrayInput( + Call createUsersWithArrayInput( @Body List body ); @@ -44,11 +44,11 @@ Call[Void] createUsersWithArrayInput( * Creates list of users with given input array * * @param body List of user object (required) - * @return Call[Void] + * @return Call<Void> */ @POST("user/createWithList") - Call[Void] createUsersWithListInput( + Call createUsersWithListInput( @Body List body ); @@ -56,11 +56,11 @@ Call[Void] createUsersWithListInput( * Delete user * This can only be done by the logged in user. * @param username The name that needs to be deleted (required) - * @return Call[Void] + * @return Call<Void> */ @DELETE("user/{username}") - Call[Void] deleteUser( + Call deleteUser( @Path("username") String username ); @@ -68,11 +68,11 @@ Call[Void] deleteUser( * Get user by user name * * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return Call[User] + * @return Call<User> */ @GET("user/{username}") - Call[User] getUserByName( + Call getUserByName( @Path("username") String username ); @@ -81,22 +81,22 @@ Call[User] getUserByName( * * @param username The user name for login (required) * @param password The password for login in clear text (required) - * @return Call[String] + * @return Call<String> */ @GET("user/login") - Call[String] loginUser( + Call loginUser( @Query("username") String username, @Query("password") String password ); /** * Logs out current logged in user session * - * @return Call[Void] + * @return Call<Void> */ @GET("user/logout") - Call[Void] logoutUser(); + Call logoutUser(); /** @@ -104,11 +104,11 @@ Call[String] loginUser( * This can only be done by the logged in user. * @param username name that need to be deleted (required) * @param body Updated user object (required) - * @return Call[Void] + * @return Call<Void> */ @PUT("user/{username}") - Call[Void] updateUser( + Call updateUser( @Path("username") String username, @Body User body ); From 43d1c5bffc2e32c2dcc9ed1f51ec4c213cdf686f Mon Sep 17 00:00:00 2001 From: lunat Date: Tue, 5 Jul 2016 14:42:43 +0200 Subject: [PATCH 042/470] CSharp client header problem CSharp client may cause an error adding an header because the header list is static. Added a check and a function tu set up the ApiKey --- .../main/resources/csharp/Configuration.mustache | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache index 5ce03342baa..d2d7a9ad34b 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache @@ -158,9 +158,24 @@ namespace {{packageName}}.Client /// public void AddDefaultHeader(string key, string value) { + if (_defaultHeaderMap.ContainsKey(key)) + _defaultHeaderMap.Remove(key); _defaultHeaderMap.Add(key, value); } + /// + /// Add Api Key. + /// + /// Api Key name. + /// Api Key value. + /// + public void AddApiKeyPrefix(string key, string value) + { + if (ApiKeyPrefix.ContainsKey(key)) + ApiKeyPrefix.Remove(key); + ApiKeyPrefix.Add(key, value); + } + /// /// Gets or sets the HTTP user agent. /// From b699fe57fc99f50c3dc080a4800f0036c79d5aab Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 5 Jul 2016 22:16:53 +0800 Subject: [PATCH 043/470] add license header to java default client --- .../main/resources/Java/ApiClient.mustache | 1 + .../src/main/resources/Java/api.mustache | 1 + .../petstore/java/default/docs/FakeApi.md | 47 ++++ .../java/default/docs/HasOnlyReadOnly.md | 11 + .../petstore/java/default/docs/MapTest.md | 17 ++ .../client/petstore/java/default/hello.txt | 1 - .../java/io/swagger/client/ApiClient.java | 26 ++- .../java/io/swagger/client/ApiException.java | 2 +- .../java/io/swagger/client/Configuration.java | 2 +- .../src/main/java/io/swagger/client/Pair.java | 2 +- .../java/io/swagger/client/StringUtil.java | 2 +- .../java/io/swagger/client/api/FakeApi.java | 68 +++++- .../java/io/swagger/client/api/PetApi.java | 26 ++- .../java/io/swagger/client/api/StoreApi.java | 24 ++ .../java/io/swagger/client/api/UserApi.java | 24 ++ .../io/swagger/client/auth/ApiKeyAuth.java | 2 +- .../swagger/client/auth/Authentication.java | 2 +- .../io/swagger/client/auth/HttpBasicAuth.java | 2 +- .../java/io/swagger/client/auth/OAuth.java | 2 +- .../io/swagger/client/auth/OAuthFlow.java | 2 +- .../model/AdditionalPropertiesClass.java | 52 ++++- .../java/io/swagger/client/model/Animal.java | 52 ++++- .../io/swagger/client/model/AnimalFarm.java | 28 ++- .../model/ArrayOfArrayOfNumberOnly.java | 39 +++- .../client/model/ArrayOfNumberOnly.java | 39 +++- .../io/swagger/client/model/ArrayTest.java | 65 ++++-- .../java/io/swagger/client/model/Cat.java | 65 ++++-- .../io/swagger/client/model/Category.java | 52 ++++- .../java/io/swagger/client/model/Dog.java | 65 ++++-- .../io/swagger/client/model/EnumClass.java | 31 ++- .../io/swagger/client/model/EnumTest.java | 71 ++++-- .../io/swagger/client/model/FormatTest.java | 215 +++++++++++------- .../swagger/client/model/HasOnlyReadOnly.java | 104 +++++++++ .../java/io/swagger/client/model/MapTest.java | 145 ++++++++++++ ...ropertiesAndAdditionalPropertiesClass.java | 65 ++++-- .../client/model/Model200Response.java | 52 ++++- .../client/model/ModelApiResponse.java | 65 ++++-- .../io/swagger/client/model/ModelReturn.java | 39 +++- .../java/io/swagger/client/model/Name.java | 68 ++++-- .../io/swagger/client/model/NumberOnly.java | 39 +++- .../java/io/swagger/client/model/Order.java | 108 ++++++--- .../java/io/swagger/client/model/Pet.java | 108 ++++++--- .../swagger/client/model/ReadOnlyFirst.java | 47 +++- .../client/model/SpecialModelName.java | 39 +++- .../java/io/swagger/client/model/Tag.java | 52 ++++- .../java/io/swagger/client/model/User.java | 131 +++++++---- 46 files changed, 1664 insertions(+), 436 deletions(-) create mode 100644 samples/client/petstore/java/default/docs/HasOnlyReadOnly.md create mode 100644 samples/client/petstore/java/default/docs/MapTest.md delete mode 100644 samples/client/petstore/java/default/hello.txt create mode 100644 samples/client/petstore/java/default/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java create mode 100644 samples/client/petstore/java/default/src/main/java/io/swagger/client/model/MapTest.java diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index a64f33174da..c4e2538b4c3 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}; import com.fasterxml.jackson.annotation.*; diff --git a/modules/swagger-codegen/src/main/resources/Java/api.mustache b/modules/swagger-codegen/src/main/resources/Java/api.mustache index 4d54d84d337..80db47354d0 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{package}}; import com.sun.jersey.api.client.GenericType; diff --git a/samples/client/petstore/java/default/docs/FakeApi.md b/samples/client/petstore/java/default/docs/FakeApi.md index 0c1f55a0902..21a4db7c377 100644 --- a/samples/client/petstore/java/default/docs/FakeApi.md +++ b/samples/client/petstore/java/default/docs/FakeApi.md @@ -5,6 +5,7 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters @@ -73,3 +74,49 @@ No authorization required - **Content-Type**: application/xml; charset=utf-8, application/json; charset=utf-8 - **Accept**: application/xml; charset=utf-8, application/json; charset=utf-8 + +# **testEnumQueryParameters** +> testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble) + +To test enum query parameters + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +String enumQueryString = "-efg"; // String | Query parameter enum test (string) +BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | Query parameter enum test (double) +Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) +try { + apiInstance.testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEnumQueryParameters"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + **enumQueryInteger** | **BigDecimal**| Query parameter enum test (double) | [optional] + **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + diff --git a/samples/client/petstore/java/default/docs/HasOnlyReadOnly.md b/samples/client/petstore/java/default/docs/HasOnlyReadOnly.md new file mode 100644 index 00000000000..c1d0aac5672 --- /dev/null +++ b/samples/client/petstore/java/default/docs/HasOnlyReadOnly.md @@ -0,0 +1,11 @@ + +# HasOnlyReadOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] +**foo** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/default/docs/MapTest.md b/samples/client/petstore/java/default/docs/MapTest.md new file mode 100644 index 00000000000..c671e97ffbc --- /dev/null +++ b/samples/client/petstore/java/default/docs/MapTest.md @@ -0,0 +1,17 @@ + +# MapTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapMapOfString** | [**Map<String, Map<String, String>>**](Map.md) | | [optional] +**mapOfEnumString** | [**Map<String, InnerEnum>**](#Map<String, InnerEnum>) | | [optional] + + + +## Enum: Map<String, InnerEnum> +Name | Value +---- | ----- + + + diff --git a/samples/client/petstore/java/default/hello.txt b/samples/client/petstore/java/default/hello.txt deleted file mode 100644 index 6769dd60bdf..00000000000 --- a/samples/client/petstore/java/default/hello.txt +++ /dev/null @@ -1 +0,0 @@ -Hello world! \ No newline at end of file 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 ba846404249..b16fdbbdfa9 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,3 +1,27 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client; import com.fasterxml.jackson.annotation.*; @@ -75,8 +99,8 @@ public ApiClient() { // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap(); - authentications.put("petstore_auth", new OAuth()); authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("petstore_auth", new OAuth()); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java index 600bb507f09..3bed001f002 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java @@ -1,6 +1,6 @@ /** * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java index cbdadd6262d..5191b9b73c6 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java @@ -1,6 +1,6 @@ /** * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java index 4b44c415812..15b247eea93 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java @@ -1,6 +1,6 @@ /** * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java index 03c6c81e434..fdcef6b1010 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ /** * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/FakeApi.java index dc9faf57ea6..c772f9402da 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/FakeApi.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.api; import com.sun.jersey.api.client.GenericType; @@ -9,8 +33,8 @@ import io.swagger.client.Pair; import org.joda.time.LocalDate; -import java.math.BigDecimal; import org.joda.time.DateTime; +import java.math.BigDecimal; import java.util.ArrayList; @@ -128,4 +152,46 @@ public void testEndpointParameters(BigDecimal number, Double _double, String str apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); } + /** + * To test enum query parameters + * + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @throws ApiException if fails to make API call + */ + public void testEnumQueryParameters(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_integer", enumQueryInteger)); + + + if (enumQueryString != null) + localVarFormParams.put("enum_query_string", enumQueryString); +if (enumQueryDouble != null) + localVarFormParams.put("enum_query_double", enumQueryDouble); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } } 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 50a6ecff737..c126283d2aa 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,3 +1,27 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.api; import com.sun.jersey.api.client.GenericType; @@ -9,8 +33,8 @@ import io.swagger.client.Pair; import io.swagger.client.model.Pet; -import io.swagger.client.model.ModelApiResponse; import java.io.File; +import io.swagger.client.model.ModelApiResponse; import java.util.ArrayList; 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 4714c3ca2d3..b30edd4f22f 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,3 +1,27 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.api; import com.sun.jersey.api.client.GenericType; 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 6369d9daa4d..9d6a1bb12fd 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,3 +1,27 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.api; import com.sun.jersey.api.client.GenericType; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index 6ba15566b60..a125fff5f24 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -1,6 +1,6 @@ /** * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java index a063a6998b5..221a7d9dd1f 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java @@ -1,6 +1,6 @@ /** * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 5895370e4d4..592648b2bba 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -1,6 +1,6 @@ /** * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java index 8802ebc92c8..14521f6ed7e 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java @@ -1,6 +1,6 @@ /** * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuthFlow.java index ec1f942b0f2..50d5260cfd9 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,6 +1,6 @@ /** * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index ccaba7709c4..1e2d40891a2 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -1,6 +1,30 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -15,40 +39,44 @@ */ public class AdditionalPropertiesClass { - + @JsonProperty("map_property") private Map mapProperty = new HashMap(); + + @JsonProperty("map_of_map_property") private Map> mapOfMapProperty = new HashMap>(); - - /** - **/ public AdditionalPropertiesClass mapProperty(Map mapProperty) { this.mapProperty = mapProperty; return this; } - + + /** + * Get mapProperty + * @return mapProperty + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("map_property") public Map getMapProperty() { return mapProperty; } + public void setMapProperty(Map mapProperty) { this.mapProperty = mapProperty; } - - /** - **/ public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { this.mapOfMapProperty = mapOfMapProperty; return this; } - + + /** + * Get mapOfMapProperty + * @return mapOfMapProperty + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("map_of_map_property") public Map> getMapOfMapProperty() { return mapOfMapProperty; } + public void setMapOfMapProperty(Map> mapOfMapProperty) { this.mapOfMapProperty = mapOfMapProperty; } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Animal.java index 25c7d3e421c..3ed2c6d9660 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Animal.java @@ -1,6 +1,30 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -12,40 +36,44 @@ */ public class Animal { - + @JsonProperty("className") private String className = null; + + @JsonProperty("color") private String color = "red"; - - /** - **/ public Animal className(String className) { this.className = className; return this; } - + + /** + * Get className + * @return className + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("className") public String getClassName() { return className; } + public void setClassName(String className) { this.className = className; } - - /** - **/ public Animal color(String color) { this.color = color; return this; } - + + /** + * Get color + * @return color + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("color") public String getColor() { return color; } + public void setColor(String color) { this.color = color; } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/AnimalFarm.java index 647e3a893e1..b54adb09d7b 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -1,6 +1,30 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import io.swagger.client.model.Animal; import java.util.ArrayList; @@ -12,9 +36,7 @@ */ public class AnimalFarm extends ArrayList { - - @Override public boolean equals(java.lang.Object o) { if (this == o) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 99771f06952..4d0dc41ee70 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -1,6 +1,30 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -15,22 +39,23 @@ */ public class ArrayOfArrayOfNumberOnly { - + @JsonProperty("ArrayArrayNumber") private List> arrayArrayNumber = new ArrayList>(); - - /** - **/ public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { this.arrayArrayNumber = arrayArrayNumber; return this; } - + + /** + * Get arrayArrayNumber + * @return arrayArrayNumber + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("ArrayArrayNumber") public List> getArrayArrayNumber() { return arrayArrayNumber; } + public void setArrayArrayNumber(List> arrayArrayNumber) { this.arrayArrayNumber = arrayArrayNumber; } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index 626772b0cbb..bd3f05a2ad4 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -1,6 +1,30 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -15,22 +39,23 @@ */ public class ArrayOfNumberOnly { - + @JsonProperty("ArrayNumber") private List arrayNumber = new ArrayList(); - - /** - **/ public ArrayOfNumberOnly arrayNumber(List arrayNumber) { this.arrayNumber = arrayNumber; return this; } - + + /** + * Get arrayNumber + * @return arrayNumber + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("ArrayNumber") public List getArrayNumber() { return arrayNumber; } + public void setArrayNumber(List arrayNumber) { this.arrayNumber = arrayNumber; } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayTest.java index c3ffaaafe4c..900b8375eb0 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayTest.java @@ -1,6 +1,30 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -15,58 +39,65 @@ */ public class ArrayTest { - + @JsonProperty("array_of_string") private List arrayOfString = new ArrayList(); + + @JsonProperty("array_array_of_integer") private List> arrayArrayOfInteger = new ArrayList>(); + + @JsonProperty("array_array_of_model") private List> arrayArrayOfModel = new ArrayList>(); - - /** - **/ public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; return this; } - + + /** + * Get arrayOfString + * @return arrayOfString + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("array_of_string") public List getArrayOfString() { return arrayOfString; } + public void setArrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; } - - /** - **/ public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; return this; } - + + /** + * Get arrayArrayOfInteger + * @return arrayArrayOfInteger + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("array_array_of_integer") public List> getArrayArrayOfInteger() { return arrayArrayOfInteger; } + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - - /** - **/ public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } - + + /** + * Get arrayArrayOfModel + * @return arrayArrayOfModel + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("array_array_of_model") public List> getArrayArrayOfModel() { return arrayArrayOfModel; } + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Cat.java index 5ef9e23bd96..f39b159f0b4 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Cat.java @@ -1,6 +1,30 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -13,58 +37,65 @@ */ public class Cat extends Animal { - + @JsonProperty("className") private String className = null; + + @JsonProperty("color") private String color = "red"; + + @JsonProperty("declawed") private Boolean declawed = null; - - /** - **/ public Cat className(String className) { this.className = className; return this; } - + + /** + * Get className + * @return className + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("className") public String getClassName() { return className; } + public void setClassName(String className) { this.className = className; } - - /** - **/ public Cat color(String color) { this.color = color; return this; } - + + /** + * Get color + * @return color + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("color") public String getColor() { return color; } + public void setColor(String color) { this.color = color; } - - /** - **/ public Cat declawed(Boolean declawed) { this.declawed = declawed; return this; } - + + /** + * Get declawed + * @return declawed + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("declawed") public Boolean getDeclawed() { return declawed; } + public void setDeclawed(Boolean declawed) { this.declawed = declawed; } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java index c6cb703a89e..c9bbbf525c5 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java @@ -1,6 +1,30 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -12,40 +36,44 @@ */ public class Category { - + @JsonProperty("id") private Long id = null; + + @JsonProperty("name") private String name = null; - - /** - **/ public Category id(Long id) { this.id = id; return this; } - + + /** + * Get id + * @return id + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - - /** - **/ public Category name(String name) { this.name = name; return this; } - + + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Dog.java index 4b3cc947cc5..dbcd1a7207b 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Dog.java @@ -1,6 +1,30 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -13,58 +37,65 @@ */ public class Dog extends Animal { - + @JsonProperty("className") private String className = null; + + @JsonProperty("color") private String color = "red"; + + @JsonProperty("breed") private String breed = null; - - /** - **/ public Dog className(String className) { this.className = className; return this; } - + + /** + * Get className + * @return className + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("className") public String getClassName() { return className; } + public void setClassName(String className) { this.className = className; } - - /** - **/ public Dog color(String color) { this.color = color; return this; } - + + /** + * Get color + * @return color + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("color") public String getColor() { return color; } + public void setColor(String color) { this.color = color; } - - /** - **/ public Dog breed(String breed) { this.breed = breed; return this; } - + + /** + * Get breed + * @return breed + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("breed") public String getBreed() { return breed; } + public void setBreed(String breed) { this.breed = breed; } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumClass.java index 42434e297ff..4433dca5f48 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumClass.java @@ -1,16 +1,42 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonValue; /** * Gets or Sets EnumClass */ public enum EnumClass { + _ABC("_abc"), + _EFG("-efg"), + _XYZ_("(xyz)"); private String value; @@ -20,7 +46,6 @@ public enum EnumClass { } @Override - @JsonValue public String toString() { return String.valueOf(value); } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumTest.java index 1c8657fd3ec..de36ef40ed4 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumTest.java @@ -1,9 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -13,13 +36,12 @@ */ public class EnumTest { - - /** * Gets or Sets enumString */ public enum EnumStringEnum { UPPER("UPPER"), + LOWER("lower"); private String value; @@ -29,12 +51,12 @@ public enum EnumStringEnum { } @Override - @JsonValue public String toString() { return String.valueOf(value); } } + @JsonProperty("enum_string") private EnumStringEnum enumString = null; /** @@ -42,6 +64,7 @@ public String toString() { */ public enum EnumIntegerEnum { NUMBER_1(1), + NUMBER_MINUS_1(-1); private Integer value; @@ -51,12 +74,12 @@ public enum EnumIntegerEnum { } @Override - @JsonValue public String toString() { return String.valueOf(value); } } + @JsonProperty("enum_integer") private EnumIntegerEnum enumInteger = null; /** @@ -64,6 +87,7 @@ public String toString() { */ public enum EnumNumberEnum { NUMBER_1_DOT_1(1.1), + NUMBER_MINUS_1_DOT_2(-1.2); private Double value; @@ -73,61 +97,64 @@ public enum EnumNumberEnum { } @Override - @JsonValue public String toString() { return String.valueOf(value); } } + @JsonProperty("enum_number") private EnumNumberEnum enumNumber = null; - - /** - **/ public EnumTest enumString(EnumStringEnum enumString) { this.enumString = enumString; return this; } - + + /** + * Get enumString + * @return enumString + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("enum_string") public EnumStringEnum getEnumString() { return enumString; } + public void setEnumString(EnumStringEnum enumString) { this.enumString = enumString; } - - /** - **/ public EnumTest enumInteger(EnumIntegerEnum enumInteger) { this.enumInteger = enumInteger; return this; } - + + /** + * Get enumInteger + * @return enumInteger + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("enum_integer") public EnumIntegerEnum getEnumInteger() { return enumInteger; } + public void setEnumInteger(EnumIntegerEnum enumInteger) { this.enumInteger = enumInteger; } - - /** - **/ public EnumTest enumNumber(EnumNumberEnum enumNumber) { this.enumNumber = enumNumber; return this; } - + + /** + * Get enumNumber + * @return enumNumber + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("enum_number") public EnumNumberEnum getEnumNumber() { return enumNumber; } + public void setEnumNumber(EnumNumberEnum enumNumber) { this.enumNumber = enumNumber; } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/FormatTest.java index 79376150017..9e17949ebc8 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/FormatTest.java @@ -1,6 +1,30 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -15,248 +39,285 @@ */ public class FormatTest { - + @JsonProperty("integer") private Integer integer = null; + + @JsonProperty("int32") private Integer int32 = null; + + @JsonProperty("int64") private Long int64 = null; + + @JsonProperty("number") private BigDecimal number = null; + + @JsonProperty("float") private Float _float = null; + + @JsonProperty("double") private Double _double = null; + + @JsonProperty("string") private String string = null; + + @JsonProperty("byte") private byte[] _byte = null; + + @JsonProperty("binary") private byte[] binary = null; + + @JsonProperty("date") private LocalDate date = null; + + @JsonProperty("dateTime") private DateTime dateTime = null; + + @JsonProperty("uuid") private String uuid = null; + + @JsonProperty("password") private String password = null; - - /** - * minimum: 10.0 - * maximum: 100.0 - **/ public FormatTest integer(Integer integer) { this.integer = integer; return this; } - + + /** + * Get integer + * minimum: 10.0 + * maximum: 100.0 + * @return integer + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("integer") public Integer getInteger() { return integer; } + public void setInteger(Integer integer) { this.integer = integer; } - - /** - * minimum: 20.0 - * maximum: 200.0 - **/ public FormatTest int32(Integer int32) { this.int32 = int32; return this; } - + + /** + * Get int32 + * minimum: 20.0 + * maximum: 200.0 + * @return int32 + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("int32") public Integer getInt32() { return int32; } + public void setInt32(Integer int32) { this.int32 = int32; } - - /** - **/ public FormatTest int64(Long int64) { this.int64 = int64; return this; } - + + /** + * Get int64 + * @return int64 + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("int64") public Long getInt64() { return int64; } + public void setInt64(Long int64) { this.int64 = int64; } - - /** - * minimum: 32.1 - * maximum: 543.2 - **/ public FormatTest number(BigDecimal number) { this.number = number; return this; } - + + /** + * Get number + * minimum: 32.1 + * maximum: 543.2 + * @return number + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("number") public BigDecimal getNumber() { return number; } + public void setNumber(BigDecimal number) { this.number = number; } - - /** - * minimum: 54.3 - * maximum: 987.6 - **/ public FormatTest _float(Float _float) { this._float = _float; return this; } - + + /** + * Get _float + * minimum: 54.3 + * maximum: 987.6 + * @return _float + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("float") public Float getFloat() { return _float; } + public void setFloat(Float _float) { this._float = _float; } - - /** - * minimum: 67.8 - * maximum: 123.4 - **/ public FormatTest _double(Double _double) { this._double = _double; return this; } - + + /** + * Get _double + * minimum: 67.8 + * maximum: 123.4 + * @return _double + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("double") public Double getDouble() { return _double; } + public void setDouble(Double _double) { this._double = _double; } - - /** - **/ public FormatTest string(String string) { this.string = string; return this; } - + + /** + * Get string + * @return string + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("string") public String getString() { return string; } + public void setString(String string) { this.string = string; } - - /** - **/ public FormatTest _byte(byte[] _byte) { this._byte = _byte; return this; } - + + /** + * Get _byte + * @return _byte + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("byte") public byte[] getByte() { return _byte; } + public void setByte(byte[] _byte) { this._byte = _byte; } - - /** - **/ public FormatTest binary(byte[] binary) { this.binary = binary; return this; } - + + /** + * Get binary + * @return binary + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("binary") public byte[] getBinary() { return binary; } + public void setBinary(byte[] binary) { this.binary = binary; } - - /** - **/ public FormatTest date(LocalDate date) { this.date = date; return this; } - + + /** + * Get date + * @return date + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("date") public LocalDate getDate() { return date; } + public void setDate(LocalDate date) { this.date = date; } - - /** - **/ public FormatTest dateTime(DateTime dateTime) { this.dateTime = dateTime; return this; } - + + /** + * Get dateTime + * @return dateTime + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("dateTime") public DateTime getDateTime() { return dateTime; } + public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } - - /** - **/ public FormatTest uuid(String uuid) { this.uuid = uuid; return this; } - + + /** + * Get uuid + * @return uuid + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("uuid") public String getUuid() { return uuid; } + public void setUuid(String uuid) { this.uuid = uuid; } - - /** - **/ public FormatTest password(String password) { this.password = password; return this; } - + + /** + * Get password + * @return password + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("password") public String getPassword() { return password; } + public void setPassword(String password) { this.password = password; } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java new file mode 100644 index 00000000000..a3d01218197 --- /dev/null +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -0,0 +1,104 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +/** + * HasOnlyReadOnly + */ + +public class HasOnlyReadOnly { + @JsonProperty("bar") + private String bar = null; + + @JsonProperty("foo") + private String foo = null; + + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(example = "null", value = "") + public String getBar() { + return bar; + } + + /** + * Get foo + * @return foo + **/ + @ApiModelProperty(example = "null", value = "") + public String getFoo() { + return foo; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HasOnlyReadOnly hasOnlyReadOnly = (HasOnlyReadOnly) o; + return Objects.equals(this.bar, hasOnlyReadOnly.bar) && + Objects.equals(this.foo, hasOnlyReadOnly.foo); + } + + @Override + public int hashCode() { + return Objects.hash(bar, foo); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HasOnlyReadOnly {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" foo: ").append(toIndentedString(foo)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/MapTest.java new file mode 100644 index 00000000000..6c0fc91ac41 --- /dev/null +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/MapTest.java @@ -0,0 +1,145 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +/** + * MapTest + */ + +public class MapTest { + @JsonProperty("map_map_of_string") + private Map> mapMapOfString = new HashMap>(); + + /** + * Gets or Sets inner + */ + public enum InnerEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + InnerEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + @JsonProperty("map_of_enum_string") + private Map mapOfEnumString = new HashMap(); + + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + /** + * Get mapMapOfString + * @return mapMapOfString + **/ + @ApiModelProperty(example = "null", value = "") + public Map> getMapMapOfString() { + return mapMapOfString; + } + + public void setMapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + } + + public MapTest mapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + return this; + } + + /** + * Get mapOfEnumString + * @return mapOfEnumString + **/ + @ApiModelProperty(example = "null", value = "") + public Map getMapOfEnumString() { + return mapOfEnumString; + } + + public void setMapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MapTest mapTest = (MapTest) o; + return Objects.equals(this.mapMapOfString, mapTest.mapMapOfString) && + Objects.equals(this.mapOfEnumString, mapTest.mapOfEnumString); + } + + @Override + public int hashCode() { + return Objects.hash(mapMapOfString, mapOfEnumString); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MapTest {\n"); + + sb.append(" mapMapOfString: ").append(toIndentedString(mapMapOfString)).append("\n"); + sb.append(" mapOfEnumString: ").append(toIndentedString(mapOfEnumString)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 2f0972bf41e..c37d141f972 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -1,6 +1,30 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -17,58 +41,65 @@ */ public class MixedPropertiesAndAdditionalPropertiesClass { - + @JsonProperty("uuid") private String uuid = null; + + @JsonProperty("dateTime") private DateTime dateTime = null; + + @JsonProperty("map") private Map map = new HashMap(); - - /** - **/ public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { this.uuid = uuid; return this; } - + + /** + * Get uuid + * @return uuid + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("uuid") public String getUuid() { return uuid; } + public void setUuid(String uuid) { this.uuid = uuid; } - - /** - **/ public MixedPropertiesAndAdditionalPropertiesClass dateTime(DateTime dateTime) { this.dateTime = dateTime; return this; } - + + /** + * Get dateTime + * @return dateTime + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("dateTime") public DateTime getDateTime() { return dateTime; } + public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } - - /** - **/ public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { this.map = map; return this; } - + + /** + * Get map + * @return map + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("map") public Map getMap() { return map; } + public void setMap(Map map) { this.map = map; } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Model200Response.java index eed3902b922..3f4edf12daa 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Model200Response.java @@ -1,6 +1,30 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -13,40 +37,44 @@ @ApiModel(description = "Model for testing model name starting with number") public class Model200Response { - + @JsonProperty("name") private Integer name = null; + + @JsonProperty("class") private String PropertyClass = null; - - /** - **/ public Model200Response name(Integer name) { this.name = name; return this; } - + + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("name") public Integer getName() { return name; } + public void setName(Integer name) { this.name = name; } - - /** - **/ public Model200Response PropertyClass(String PropertyClass) { this.PropertyClass = PropertyClass; return this; } - + + /** + * Get PropertyClass + * @return PropertyClass + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("class") public String getPropertyClass() { return PropertyClass; } + public void setPropertyClass(String PropertyClass) { this.PropertyClass = PropertyClass; } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelApiResponse.java index 32fb86dd323..7b86d07a148 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -1,6 +1,30 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -12,58 +36,65 @@ */ public class ModelApiResponse { - + @JsonProperty("code") private Integer code = null; + + @JsonProperty("type") private String type = null; + + @JsonProperty("message") private String message = null; - - /** - **/ public ModelApiResponse code(Integer code) { this.code = code; return this; } - + + /** + * Get code + * @return code + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("code") public Integer getCode() { return code; } + public void setCode(Integer code) { this.code = code; } - - /** - **/ public ModelApiResponse type(String type) { this.type = type; return this; } - + + /** + * Get type + * @return type + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("type") public String getType() { return type; } + public void setType(String type) { this.type = type; } - - /** - **/ public ModelApiResponse message(String message) { this.message = message; return this; } - + + /** + * Get message + * @return message + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("message") public String getMessage() { return message; } + public void setMessage(String message) { this.message = message; } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelReturn.java index a076d16f964..e8762f850db 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelReturn.java @@ -1,6 +1,30 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -13,22 +37,23 @@ @ApiModel(description = "Model for testing reserved words") public class ModelReturn { - + @JsonProperty("return") private Integer _return = null; - - /** - **/ public ModelReturn _return(Integer _return) { this._return = _return; return this; } - + + /** + * Get _return + * @return _return + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("return") public Integer getReturn() { return _return; } + public void setReturn(Integer _return) { this._return = _return; } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Name.java index 1ba2cc5e4a3..de446cdf30d 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Name.java @@ -1,6 +1,30 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -13,56 +37,68 @@ @ApiModel(description = "Model for testing model name same as property name") public class Name { - + @JsonProperty("name") private Integer name = null; + + @JsonProperty("snake_case") private Integer snakeCase = null; + + @JsonProperty("property") private String property = null; + + @JsonProperty("123Number") private Integer _123Number = null; - - /** - **/ public Name name(Integer name) { this.name = name; return this; } - + + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("name") public Integer getName() { return name; } + public void setName(Integer name) { this.name = name; } - + /** + * Get snakeCase + * @return snakeCase + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("snake_case") public Integer getSnakeCase() { return snakeCase; } - - /** - **/ public Name property(String property) { this.property = property; return this; } - + + /** + * Get property + * @return property + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("property") public String getProperty() { return property; } + public void setProperty(String property) { this.property = property; } - + /** + * Get _123Number + * @return _123Number + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("123Number") public Integer get123Number() { return _123Number; } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/NumberOnly.java index b3a2c788b3e..88c33f00f02 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/NumberOnly.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/NumberOnly.java @@ -1,6 +1,30 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -13,22 +37,23 @@ */ public class NumberOnly { - + @JsonProperty("JustNumber") private BigDecimal justNumber = null; - - /** - **/ public NumberOnly justNumber(BigDecimal justNumber) { this.justNumber = justNumber; return this; } - + + /** + * Get justNumber + * @return justNumber + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("JustNumber") public BigDecimal getJustNumber() { return justNumber; } + public void setJustNumber(BigDecimal justNumber) { this.justNumber = justNumber; } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java index cec651e73a6..ddebd7f8e48 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java @@ -1,9 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.joda.time.DateTime; @@ -14,10 +37,16 @@ */ public class Order { - + @JsonProperty("id") private Long id = null; + + @JsonProperty("petId") private Long petId = null; + + @JsonProperty("quantity") private Integer quantity = null; + + @JsonProperty("shipDate") private DateTime shipDate = null; /** @@ -25,7 +54,9 @@ public class Order { */ public enum StatusEnum { PLACED("placed"), + APPROVED("approved"), + DELIVERED("delivered"); private String value; @@ -35,114 +66,121 @@ public enum StatusEnum { } @Override - @JsonValue public String toString() { return String.valueOf(value); } } + @JsonProperty("status") private StatusEnum status = null; + + @JsonProperty("complete") private Boolean complete = false; - - /** - **/ public Order id(Long id) { this.id = id; return this; } - + + /** + * Get id + * @return id + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - - /** - **/ public Order petId(Long petId) { this.petId = petId; return this; } - + + /** + * Get petId + * @return petId + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("petId") public Long getPetId() { return petId; } + public void setPetId(Long petId) { this.petId = petId; } - - /** - **/ public Order quantity(Integer quantity) { this.quantity = quantity; return this; } - + + /** + * Get quantity + * @return quantity + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("quantity") public Integer getQuantity() { return quantity; } + public void setQuantity(Integer quantity) { this.quantity = quantity; } - - /** - **/ public Order shipDate(DateTime shipDate) { this.shipDate = shipDate; return this; } - + + /** + * Get shipDate + * @return shipDate + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("shipDate") public DateTime getShipDate() { return shipDate; } + public void setShipDate(DateTime shipDate) { this.shipDate = shipDate; } - - /** - * Order Status - **/ public Order status(StatusEnum status) { this.status = status; return this; } - + + /** + * Order Status + * @return status + **/ @ApiModelProperty(example = "null", value = "Order Status") - @JsonProperty("status") public StatusEnum getStatus() { return status; } + public void setStatus(StatusEnum status) { this.status = status; } - - /** - **/ public Order complete(Boolean complete) { this.complete = complete; return this; } - + + /** + * Get complete + * @return complete + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("complete") public Boolean getComplete() { return complete; } + public void setComplete(Boolean complete) { this.complete = complete; } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java index da8b76ad024..b468ebf1237 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java @@ -1,9 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Category; @@ -17,11 +40,19 @@ */ public class Pet { - + @JsonProperty("id") private Long id = null; + + @JsonProperty("category") private Category category = null; + + @JsonProperty("name") private String name = null; + + @JsonProperty("photoUrls") private List photoUrls = new ArrayList(); + + @JsonProperty("tags") private List tags = new ArrayList(); /** @@ -29,7 +60,9 @@ public class Pet { */ public enum StatusEnum { AVAILABLE("available"), + PENDING("pending"), + SOLD("sold"); private String value; @@ -39,113 +72,118 @@ public enum StatusEnum { } @Override - @JsonValue public String toString() { return String.valueOf(value); } } + @JsonProperty("status") private StatusEnum status = null; - - /** - **/ public Pet id(Long id) { this.id = id; return this; } - + + /** + * Get id + * @return id + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - - /** - **/ public Pet category(Category category) { this.category = category; return this; } - + + /** + * Get category + * @return category + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("category") public Category getCategory() { return category; } + public void setCategory(Category category) { this.category = category; } - - /** - **/ public Pet name(String name) { this.name = name; return this; } - + + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "doggie", required = true, value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } - - /** - **/ public Pet photoUrls(List photoUrls) { this.photoUrls = photoUrls; return this; } - + + /** + * Get photoUrls + * @return photoUrls + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("photoUrls") public List getPhotoUrls() { return photoUrls; } + public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } - - /** - **/ public Pet tags(List tags) { this.tags = tags; return this; } - + + /** + * Get tags + * @return tags + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("tags") public List getTags() { return tags; } + public void setTags(List tags) { this.tags = tags; } - - /** - * pet status in the store - **/ public Pet status(StatusEnum status) { this.status = status; return this; } - + + /** + * pet status in the store + * @return status + **/ @ApiModelProperty(example = "null", value = "pet status in the store") - @JsonProperty("status") public StatusEnum getStatus() { return status; } + public void setStatus(StatusEnum status) { this.status = status; } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index fdc3587df0e..7f56ef2ff35 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -1,6 +1,30 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -12,30 +36,35 @@ */ public class ReadOnlyFirst { - + @JsonProperty("bar") private String bar = null; + + @JsonProperty("baz") private String baz = null; - + /** + * Get bar + * @return bar + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("bar") public String getBar() { return bar; } - - /** - **/ public ReadOnlyFirst baz(String baz) { this.baz = baz; return this; } - + + /** + * Get baz + * @return baz + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("baz") public String getBaz() { return baz; } + public void setBaz(String baz) { this.baz = baz; } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/SpecialModelName.java index 24e57756cb2..bc4863f101a 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -1,6 +1,30 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -12,22 +36,23 @@ */ public class SpecialModelName { - + @JsonProperty("$special[property.name]") private Long specialPropertyName = null; - - /** - **/ public SpecialModelName specialPropertyName(Long specialPropertyName) { this.specialPropertyName = specialPropertyName; return this; } - + + /** + * Get specialPropertyName + * @return specialPropertyName + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("$special[property.name]") public Long getSpecialPropertyName() { return specialPropertyName; } + public void setSpecialPropertyName(Long specialPropertyName) { this.specialPropertyName = specialPropertyName; } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java index 9d3bdd8cb9e..f27e45ea2aa 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java @@ -1,6 +1,30 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -12,40 +36,44 @@ */ public class Tag { - + @JsonProperty("id") private Long id = null; + + @JsonProperty("name") private String name = null; - - /** - **/ public Tag id(Long id) { this.id = id; return this; } - + + /** + * Get id + * @return id + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - - /** - **/ public Tag name(String name) { this.name = name; return this; } - + + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java index f23553660de..7c0421fa09e 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java @@ -1,6 +1,30 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -12,149 +36,170 @@ */ public class User { - + @JsonProperty("id") private Long id = null; + + @JsonProperty("username") private String username = null; + + @JsonProperty("firstName") private String firstName = null; + + @JsonProperty("lastName") private String lastName = null; + + @JsonProperty("email") private String email = null; + + @JsonProperty("password") private String password = null; + + @JsonProperty("phone") private String phone = null; + + @JsonProperty("userStatus") private Integer userStatus = null; - - /** - **/ public User id(Long id) { this.id = id; return this; } - + + /** + * Get id + * @return id + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - - /** - **/ public User username(String username) { this.username = username; return this; } - + + /** + * Get username + * @return username + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("username") public String getUsername() { return username; } + public void setUsername(String username) { this.username = username; } - - /** - **/ public User firstName(String firstName) { this.firstName = firstName; return this; } - + + /** + * Get firstName + * @return firstName + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("firstName") public String getFirstName() { return firstName; } + public void setFirstName(String firstName) { this.firstName = firstName; } - - /** - **/ public User lastName(String lastName) { this.lastName = lastName; return this; } - + + /** + * Get lastName + * @return lastName + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("lastName") public String getLastName() { return lastName; } + public void setLastName(String lastName) { this.lastName = lastName; } - - /** - **/ public User email(String email) { this.email = email; return this; } - + + /** + * Get email + * @return email + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("email") public String getEmail() { return email; } + public void setEmail(String email) { this.email = email; } - - /** - **/ public User password(String password) { this.password = password; return this; } - + + /** + * Get password + * @return password + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("password") public String getPassword() { return password; } + public void setPassword(String password) { this.password = password; } - - /** - **/ public User phone(String phone) { this.phone = phone; return this; } - + + /** + * Get phone + * @return phone + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("phone") public String getPhone() { return phone; } + public void setPhone(String phone) { this.phone = phone; } - - /** - * User Status - **/ public User userStatus(Integer userStatus) { this.userStatus = userStatus; return this; } - + + /** + * User Status + * @return userStatus + **/ @ApiModelProperty(example = "null", value = "User Status") - @JsonProperty("userStatus") public Integer getUserStatus() { return userStatus; } + public void setUserStatus(Integer userStatus) { this.userStatus = userStatus; } From 6b4b2025eea915a4056d9270ea955157391d2d2a Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 5 Jul 2016 22:39:38 +0800 Subject: [PATCH 044/470] add license to android volley --- .../src/main/resources/android/Pair.mustache | 1 + .../src/main/resources/android/api.mustache | 1 + .../resources/android/apiException.mustache | 1 + .../resources/android/apiInvoker.mustache | 1 + .../main/resources/android/httpPatch.mustache | 1 + .../android/libraries/volley/Pair.mustache | 1 + .../android/libraries/volley/api.mustache | 1 + .../libraries/volley/apiException.mustache | 1 + .../libraries/volley/apiInvoker.mustache | 1 + .../libraries/volley/auth/apikeyauth.mustache | 1 + .../volley/auth/authentication.mustache | 1 + .../volley/auth/httpbasicauth.mustache | 1 + .../libraries/volley/auth/oauth.mustache | 1 + .../libraries/volley/jsonUtil.mustache | 1 + .../android/libraries/volley/model.mustache | 1 + .../volley/request/deleterequest.mustache | 1 + .../volley/request/getrequest.mustache | 1 + .../volley/request/patchrequest.mustache | 1 + .../volley/request/postrequest.mustache | 1 + .../volley/request/putrequest.mustache | 1 + .../resources/android/licenseInfo.mustache | 23 ++++++++++++++++++ .../java/io/swagger/client/ApiException.java | 24 +++++++++++++++++++ .../java/io/swagger/client/ApiInvoker.java | 24 +++++++++++++++++++ .../main/java/io/swagger/client/JsonUtil.java | 24 +++++++++++++++++++ .../src/main/java/io/swagger/client/Pair.java | 24 +++++++++++++++++++ .../java/io/swagger/client/api/PetApi.java | 24 +++++++++++++++++++ .../java/io/swagger/client/api/StoreApi.java | 24 +++++++++++++++++++ .../java/io/swagger/client/api/UserApi.java | 24 +++++++++++++++++++ .../io/swagger/client/auth/ApiKeyAuth.java | 24 +++++++++++++++++++ .../swagger/client/auth/Authentication.java | 24 +++++++++++++++++++ .../io/swagger/client/auth/HttpBasicAuth.java | 24 +++++++++++++++++++ .../io/swagger/client/model/Category.java | 24 +++++++++++++++++++ .../java/io/swagger/client/model/Order.java | 24 +++++++++++++++++++ .../java/io/swagger/client/model/Pet.java | 24 +++++++++++++++++++ .../java/io/swagger/client/model/Tag.java | 24 +++++++++++++++++++ .../java/io/swagger/client/model/User.java | 24 +++++++++++++++++++ .../swagger/client/request/DeleteRequest.java | 24 +++++++++++++++++++ .../io/swagger/client/request/GetRequest.java | 24 +++++++++++++++++++ .../swagger/client/request/PatchRequest.java | 24 +++++++++++++++++++ .../swagger/client/request/PostRequest.java | 24 +++++++++++++++++++ .../io/swagger/client/request/PutRequest.java | 24 +++++++++++++++++++ 41 files changed, 523 insertions(+) create mode 100644 modules/swagger-codegen/src/main/resources/android/licenseInfo.mustache diff --git a/modules/swagger-codegen/src/main/resources/android/Pair.mustache b/modules/swagger-codegen/src/main/resources/android/Pair.mustache index 5456028a1a0..60e15c94ed4 100644 --- a/modules/swagger-codegen/src/main/resources/android/Pair.mustache +++ b/modules/swagger-codegen/src/main/resources/android/Pair.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}; public class Pair { diff --git a/modules/swagger-codegen/src/main/resources/android/api.mustache b/modules/swagger-codegen/src/main/resources/android/api.mustache index 5f786e503a0..5ddd06f90da 100644 --- a/modules/swagger-codegen/src/main/resources/android/api.mustache +++ b/modules/swagger-codegen/src/main/resources/android/api.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{package}}; import {{invokerPackage}}.ApiException; diff --git a/modules/swagger-codegen/src/main/resources/android/apiException.mustache b/modules/swagger-codegen/src/main/resources/android/apiException.mustache index be5255e2568..8d9da2fbe5d 100644 --- a/modules/swagger-codegen/src/main/resources/android/apiException.mustache +++ b/modules/swagger-codegen/src/main/resources/android/apiException.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}; public class ApiException extends Exception { diff --git a/modules/swagger-codegen/src/main/resources/android/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/android/apiInvoker.mustache index a2df0ea9b7c..0b3f24c9f0b 100644 --- a/modules/swagger-codegen/src/main/resources/android/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/android/apiInvoker.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}; import org.apache.http.*; diff --git a/modules/swagger-codegen/src/main/resources/android/httpPatch.mustache b/modules/swagger-codegen/src/main/resources/android/httpPatch.mustache index 08ce4409f7a..671f71a4fc2 100644 --- a/modules/swagger-codegen/src/main/resources/android/httpPatch.mustache +++ b/modules/swagger-codegen/src/main/resources/android/httpPatch.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}; import org.apache.http.client.methods.*; diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/Pair.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/Pair.mustache index 5456028a1a0..60e15c94ed4 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/Pair.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/Pair.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}; public class Pair { diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/api.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/api.mustache index 5d9ecb32066..0d18ad5572e 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/api.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/api.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{package}}; import {{invokerPackage}}.ApiInvoker; diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiException.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiException.mustache index be5255e2568..8d9da2fbe5d 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiException.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiException.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}; public class ApiException extends Exception { diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiInvoker.mustache index e76bf1357e1..76019d7c45e 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiInvoker.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}; import com.android.volley.Cache; diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/apikeyauth.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/apikeyauth.mustache index 44c5ed96eca..0805918e0d0 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/apikeyauth.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/apikeyauth.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}.auth; import {{invokerPackage}}.Pair; diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/authentication.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/authentication.mustache index 265c74cb76f..1a185437a90 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/authentication.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/authentication.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}.auth; import {{invokerPackage}}.Pair; diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/httpbasicauth.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/httpbasicauth.mustache index 64fc61f95c1..51017997ed4 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/httpbasicauth.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/httpbasicauth.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}.auth; import {{invokerPackage}}.Pair; diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/oauth.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/oauth.mustache index 7eb4fe4aaba..72b5e0baab8 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/oauth.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/oauth.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}.auth; import {{invokerPackage}}.Pair; diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/jsonUtil.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/jsonUtil.mustache index ae8d18d3731..8a52dc277fa 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/jsonUtil.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/jsonUtil.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}; import com.google.gson.Gson; diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/model.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/model.mustache index df99de87403..525a29cb39a 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/model.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/model.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{package}}; {{#imports}}import {{import}}; diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/deleterequest.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/deleterequest.mustache index b5def5f589f..7dcc613d0f0 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/deleterequest.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/deleterequest.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}.request; import com.android.volley.AuthFailureError; diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/getrequest.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/getrequest.mustache index ec225b5a46c..2bccdf40a61 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/getrequest.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/getrequest.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}.request; import com.android.volley.AuthFailureError; diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/patchrequest.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/patchrequest.mustache index 3607a03eeab..5415ab602a2 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/patchrequest.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/patchrequest.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}.request; import com.android.volley.AuthFailureError; diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/postrequest.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/postrequest.mustache index 7d0d1fe1c14..183fe15b9b5 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/postrequest.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/postrequest.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}.request; import com.android.volley.AuthFailureError; diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/putrequest.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/putrequest.mustache index a9dd14b0a7b..88cf2edce8e 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/putrequest.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/putrequest.mustache @@ -1,3 +1,4 @@ +{{>licenseInfo}} package {{invokerPackage}}.request; import com.android.volley.AuthFailureError; diff --git a/modules/swagger-codegen/src/main/resources/android/licenseInfo.mustache b/modules/swagger-codegen/src/main/resources/android/licenseInfo.mustache new file mode 100644 index 00000000000..861d97234cf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/android/licenseInfo.mustache @@ -0,0 +1,23 @@ +/** + * {{{appName}}} + * {{{appDescription}}} + * + * {{#version}}OpenAPI spec version: {{{version}}}{{/version}} + * {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiException.java index 6147e873178..5b2b0e7dbf5 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiException.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client; public class ApiException extends Exception { diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiInvoker.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiInvoker.java index cad5981703f..5867d0a3146 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiInvoker.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiInvoker.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client; import com.android.volley.Cache; diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/JsonUtil.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/JsonUtil.java index e725cf3291d..b9b348228ee 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/JsonUtil.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/JsonUtil.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client; import com.google.gson.Gson; diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/Pair.java index 2710fb5a99b..d9c600b04c9 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/Pair.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client; public class Pair { diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/PetApi.java index c76ce6262bc..49cd00cd2fd 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/PetApi.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.api; import io.swagger.client.ApiInvoker; diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/StoreApi.java index e39a1b01d52..b2ae037fed4 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/StoreApi.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.api; import io.swagger.client.ApiInvoker; diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/UserApi.java index 18eb24777b4..d7ca46d3c66 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/UserApi.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.api; import io.swagger.client.ApiInvoker; diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index 28f59159d4d..f2633f688b7 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.auth; import io.swagger.client.Pair; diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/Authentication.java index 98b1a6900b9..705f80a876e 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/Authentication.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.auth; import io.swagger.client.Pair; diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index c203adfbd2e..586e5a31b5d 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.auth; import io.swagger.client.Pair; diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Category.java index f3537ac56fc..58f427e5554 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Category.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.model; diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Order.java index 0054dbc1ba8..07d0902d548 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Order.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.model; import java.util.Date; diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Pet.java index b9d996cd764..2d3fc76f483 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Pet.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.model; import io.swagger.client.model.Category; diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Tag.java index 05b540d1617..a65f1968f63 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Tag.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.model; diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/User.java index 4875b146616..5b3ad5c44c4 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/User.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.model; diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/DeleteRequest.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/DeleteRequest.java index 802a53f6528..4cfb876dd86 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/DeleteRequest.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/DeleteRequest.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.request; import com.android.volley.AuthFailureError; diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/GetRequest.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/GetRequest.java index 639c73d82fa..32c8cf811ee 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/GetRequest.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/GetRequest.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.request; import com.android.volley.AuthFailureError; diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PatchRequest.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PatchRequest.java index 30c93b34e77..1741cd98a42 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PatchRequest.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PatchRequest.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.request; import com.android.volley.AuthFailureError; diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PostRequest.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PostRequest.java index 753725d27dd..af3bff971a8 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PostRequest.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PostRequest.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.request; import com.android.volley.AuthFailureError; diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PutRequest.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PutRequest.java index c43979a8f6a..de82a75b556 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PutRequest.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PutRequest.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.request; import com.android.volley.AuthFailureError; From 560f50ab9af839cbd88a63405941c06630251e7e Mon Sep 17 00:00:00 2001 From: laurynas Date: Tue, 5 Jul 2016 11:31:18 -0400 Subject: [PATCH 045/470] case insensitive search for "json" in content-type headers --- .../swagger-codegen/src/main/resources/python/rest.mustache | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/python/rest.mustache b/modules/swagger-codegen/src/main/resources/python/rest.mustache index a2e70b6ec7c..19ec32440f8 100644 --- a/modules/swagger-codegen/src/main/resources/python/rest.mustache +++ b/modules/swagger-codegen/src/main/resources/python/rest.mustache @@ -10,6 +10,7 @@ import json import ssl import certifi import logging +import re # python 2 and python 3 compatibility library from six import iteritems @@ -121,7 +122,7 @@ class RESTClientObject(object): if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: if query_params: url += '?' + urlencode(query_params) - if headers['Content-Type'].find('json') != -1: + if re.search('json', headers['Content-Type'], re.IGNORECASE): request_body = None if body: request_body = json.dumps(body) From fa9cb66d75f92e404928973251207221819434bc Mon Sep 17 00:00:00 2001 From: laurynas Date: Tue, 5 Jul 2016 11:34:27 -0400 Subject: [PATCH 046/470] ./bin/python-petstore.sh after enhancement of content-type header parsing for vnd headers note: looks like this was not run for some time, so it has changes from other commits too --- samples/client/petstore/python/README.md | 34 +++--- .../client/petstore/python/docs/ArrayTest.md | 1 - .../client/petstore/python/docs/FakeApi.md | 45 -------- .../client/petstore/python/docs/MapTest.md | 1 - .../python/petstore_api/apis/fake_api.py | 101 ------------------ .../python/petstore_api/configuration.py | 14 +-- .../python/petstore_api/models/array_test.py | 38 +------ .../python/petstore_api/models/map_test.py | 34 +----- .../petstore/python/petstore_api/rest.py | 3 +- 9 files changed, 35 insertions(+), 236 deletions(-) diff --git a/samples/client/petstore/python/README.md b/samples/client/petstore/python/README.md index 02734b20678..68d7f11b6dd 100644 --- a/samples/client/petstore/python/README.md +++ b/samples/client/petstore/python/README.md @@ -5,7 +5,7 @@ This Python package is automatically generated by the [Swagger Codegen](https:// - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-06-28T16:59:47.081+08:00 +- Build date: 2016-07-05T10:32:24.684-04:00 - Build package: class io.swagger.codegen.languages.PythonClientCodegen ## Requirements. @@ -52,13 +52,24 @@ from petstore_api.rest import ApiException from pprint import pprint # create an instance of the API class api_instance = petstore_api.FakeApi -test_code_inject__end = 'test_code_inject__end_example' # str | To test code injection */ =end (optional) +number = 3.4 # float | None +double = 1.2 # float | None +string = 'string_example' # str | None +byte = 'B' # str | None +integer = 56 # int | None (optional) +int32 = 56 # int | None (optional) +int64 = 789 # int | None (optional) +float = 3.4 # float | None (optional) +binary = 'B' # str | None (optional) +date = '2013-10-20' # date | None (optional) +date_time = '2013-10-20T19:20:30+01:00' # datetime | None (optional) +password = 'password_example' # str | None (optional) try: - # To test code injection */ =end - api_instance.test_code_inject__end(test_code_inject__end=test_code_inject__end) + # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + api_instance.test_endpoint_parameters(number, double, string, byte, integer=integer, int32=int32, int64=int64, float=float, binary=binary, date=date, date_time=date_time, password=password) except ApiException as e: - print "Exception when calling FakeApi->test_code_inject__end: %s\n" % e + print "Exception when calling FakeApi->test_endpoint_parameters: %s\n" % e ``` @@ -68,7 +79,6 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*FakeApi* | [**test_code_inject__end**](docs/FakeApi.md#test_code_inject__end) | **PUT** /fake | To test code injection */ =end *FakeApi* | [**test_endpoint_parameters**](docs/FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 *FakeApi* | [**test_enum_query_parameters**](docs/FakeApi.md#test_enum_query_parameters) | **GET** /fake | To test enum query parameters *PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store @@ -126,12 +136,6 @@ Class | Method | HTTP request | Description ## Documentation For Authorization -## api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - ## petstore_auth - **Type**: OAuth @@ -141,6 +145,12 @@ Class | Method | HTTP request | Description - **write:pets**: modify pets in your account - **read:pets**: read your pets +## api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + ## Author diff --git a/samples/client/petstore/python/docs/ArrayTest.md b/samples/client/petstore/python/docs/ArrayTest.md index 902710efe0e..6ab0d137806 100644 --- a/samples/client/petstore/python/docs/ArrayTest.md +++ b/samples/client/petstore/python/docs/ArrayTest.md @@ -6,7 +6,6 @@ Name | Type | Description | Notes **array_of_string** | **list[str]** | | [optional] **array_array_of_integer** | **list[list[int]]** | | [optional] **array_array_of_model** | **list[list[ReadOnlyFirst]]** | | [optional] -**array_of_enum** | **list[str]** | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/FakeApi.md b/samples/client/petstore/python/docs/FakeApi.md index 2f670f5e26f..7c818407a76 100644 --- a/samples/client/petstore/python/docs/FakeApi.md +++ b/samples/client/petstore/python/docs/FakeApi.md @@ -4,55 +4,10 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**test_code_inject__end**](FakeApi.md#test_code_inject__end) | **PUT** /fake | To test code injection */ =end [**test_endpoint_parameters**](FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**test_enum_query_parameters**](FakeApi.md#test_enum_query_parameters) | **GET** /fake | To test enum query parameters -# **test_code_inject__end** -> test_code_inject__end(test_code_inject__end=test_code_inject__end) - -To test code injection */ =end - -### Example -```python -import time -import petstore_api -from petstore_api.rest import ApiException -from pprint import pprint - -# create an instance of the API class -api_instance = petstore_api.FakeApi() -test_code_inject__end = 'test_code_inject__end_example' # str | To test code injection */ =end (optional) - -try: - # To test code injection */ =end - api_instance.test_code_inject__end(test_code_inject__end=test_code_inject__end) -except ApiException as e: - print "Exception when calling FakeApi->test_code_inject__end: %s\n" % e -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **test_code_inject__end** | **str**| To test code injection */ =end | [optional] - -### Return type - -void (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json, */ =end));(phpinfo( - - **Accept**: application/json, */ end - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - # **test_endpoint_parameters** > test_endpoint_parameters(number, double, string, byte, integer=integer, int32=int32, int64=int64, float=float, binary=binary, date=date, date_time=date_time, password=password) diff --git a/samples/client/petstore/python/docs/MapTest.md b/samples/client/petstore/python/docs/MapTest.md index 3e71b5130d7..63cdab0374a 100644 --- a/samples/client/petstore/python/docs/MapTest.md +++ b/samples/client/petstore/python/docs/MapTest.md @@ -4,7 +4,6 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **map_map_of_string** | [**dict(str, dict(str, str))**](dict.md) | | [optional] -**map_map_of_enum** | [**dict(str, dict(str, str))**](dict.md) | | [optional] **map_of_enum_string** | **dict(str, str)** | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/petstore_api/apis/fake_api.py b/samples/client/petstore/python/petstore_api/apis/fake_api.py index df4838bde82..5e8fc3d1195 100644 --- a/samples/client/petstore/python/petstore_api/apis/fake_api.py +++ b/samples/client/petstore/python/petstore_api/apis/fake_api.py @@ -51,107 +51,6 @@ def __init__(self, api_client=None): config.api_client = ApiClient() self.api_client = config.api_client - def test_code_inject__end(self, **kwargs): - """ - To test code injection */ =end - - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.test_code_inject__end(callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param str test_code_inject__end: To test code injection */ =end - :return: None - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('callback'): - return self.test_code_inject__end_with_http_info(**kwargs) - else: - (data) = self.test_code_inject__end_with_http_info(**kwargs) - return data - - def test_code_inject__end_with_http_info(self, **kwargs): - """ - To test code injection */ =end - - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.test_code_inject__end_with_http_info(callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param str test_code_inject__end: To test code injection */ =end - :return: None - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['test_code_inject__end'] - all_params.append('callback') - all_params.append('_return_http_data_only') - - params = locals() - for key, val in iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method test_code_inject__end" % key - ) - params[key] = val - del params['kwargs'] - - resource_path = '/fake'.replace('{format}', 'json') - path_params = {} - - query_params = {} - - header_params = {} - - form_params = [] - local_var_files = {} - if 'test_code_inject__end' in params: - form_params.append(('test code inject */ =end', params['test_code_inject__end'])) - - body_params = None - - # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json', '*/ end']) - if not header_params['Accept']: - del header_params['Accept'] - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json', '*/ =end));(phpinfo(']) - - # Authentication setting - auth_settings = [] - - return self.api_client.call_api(resource_path, 'PUT', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) - def test_endpoint_parameters(self, number, double, string, byte, **kwargs): """ Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 diff --git a/samples/client/petstore/python/petstore_api/configuration.py b/samples/client/petstore/python/petstore_api/configuration.py index 45cfef15472..4515b3a7466 100644 --- a/samples/client/petstore/python/petstore_api/configuration.py +++ b/samples/client/petstore/python/petstore_api/configuration.py @@ -221,13 +221,6 @@ def auth_settings(self): :return: The Auth Settings information dict. """ return { - 'api_key': - { - 'type': 'api_key', - 'in': 'header', - 'key': 'api_key', - 'value': self.get_api_key_with_prefix('api_key') - }, 'petstore_auth': { @@ -236,6 +229,13 @@ def auth_settings(self): 'key': 'Authorization', 'value': 'Bearer ' + self.access_token }, + 'api_key': + { + 'type': 'api_key', + 'in': 'header', + 'key': 'api_key', + 'value': self.get_api_key_with_prefix('api_key') + }, } diff --git a/samples/client/petstore/python/petstore_api/models/array_test.py b/samples/client/petstore/python/petstore_api/models/array_test.py index 5a6813b60eb..a8e15c0207e 100644 --- a/samples/client/petstore/python/petstore_api/models/array_test.py +++ b/samples/client/petstore/python/petstore_api/models/array_test.py @@ -32,7 +32,7 @@ class ArrayTest(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self, array_of_string=None, array_array_of_integer=None, array_array_of_model=None, array_of_enum=None): + def __init__(self, array_of_string=None, array_array_of_integer=None, array_array_of_model=None): """ ArrayTest - a model defined in Swagger @@ -44,21 +44,18 @@ def __init__(self, array_of_string=None, array_array_of_integer=None, array_arra self.swagger_types = { 'array_of_string': 'list[str]', 'array_array_of_integer': 'list[list[int]]', - 'array_array_of_model': 'list[list[ReadOnlyFirst]]', - 'array_of_enum': 'list[str]' + 'array_array_of_model': 'list[list[ReadOnlyFirst]]' } self.attribute_map = { 'array_of_string': 'array_of_string', 'array_array_of_integer': 'array_array_of_integer', - 'array_array_of_model': 'array_array_of_model', - 'array_of_enum': 'array_of_enum' + 'array_array_of_model': 'array_array_of_model' } self._array_of_string = array_of_string self._array_array_of_integer = array_array_of_integer self._array_array_of_model = array_array_of_model - self._array_of_enum = array_of_enum @property def array_of_string(self): @@ -129,35 +126,6 @@ def array_array_of_model(self, array_array_of_model): self._array_array_of_model = array_array_of_model - @property - def array_of_enum(self): - """ - Gets the array_of_enum of this ArrayTest. - - - :return: The array_of_enum of this ArrayTest. - :rtype: list[str] - """ - return self._array_of_enum - - @array_of_enum.setter - def array_of_enum(self, array_of_enum): - """ - Sets the array_of_enum of this ArrayTest. - - - :param array_of_enum: The array_of_enum of this ArrayTest. - :type: list[str] - """ - allowed_values = [] - if array_of_enum not in allowed_values: - raise ValueError( - "Invalid value for `array_of_enum`, must be one of {0}" - .format(allowed_values) - ) - - self._array_of_enum = array_of_enum - def to_dict(self): """ Returns the model properties as a dict diff --git a/samples/client/petstore/python/petstore_api/models/map_test.py b/samples/client/petstore/python/petstore_api/models/map_test.py index e48a39d49e6..92c86e55702 100644 --- a/samples/client/petstore/python/petstore_api/models/map_test.py +++ b/samples/client/petstore/python/petstore_api/models/map_test.py @@ -32,7 +32,7 @@ class MapTest(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self, map_map_of_string=None, map_map_of_enum=None, map_of_enum_string=None): + def __init__(self, map_map_of_string=None, map_of_enum_string=None): """ MapTest - a model defined in Swagger @@ -43,18 +43,15 @@ def __init__(self, map_map_of_string=None, map_map_of_enum=None, map_of_enum_str """ self.swagger_types = { 'map_map_of_string': 'dict(str, dict(str, str))', - 'map_map_of_enum': 'dict(str, dict(str, str))', 'map_of_enum_string': 'dict(str, str)' } self.attribute_map = { 'map_map_of_string': 'map_map_of_string', - 'map_map_of_enum': 'map_map_of_enum', 'map_of_enum_string': 'map_of_enum_string' } self._map_map_of_string = map_map_of_string - self._map_map_of_enum = map_map_of_enum self._map_of_enum_string = map_of_enum_string @property @@ -80,35 +77,6 @@ def map_map_of_string(self, map_map_of_string): self._map_map_of_string = map_map_of_string - @property - def map_map_of_enum(self): - """ - Gets the map_map_of_enum of this MapTest. - - - :return: The map_map_of_enum of this MapTest. - :rtype: dict(str, dict(str, str)) - """ - return self._map_map_of_enum - - @map_map_of_enum.setter - def map_map_of_enum(self, map_map_of_enum): - """ - Sets the map_map_of_enum of this MapTest. - - - :param map_map_of_enum: The map_map_of_enum of this MapTest. - :type: dict(str, dict(str, str)) - """ - allowed_values = [] - if map_map_of_enum not in allowed_values: - raise ValueError( - "Invalid value for `map_map_of_enum`, must be one of {0}" - .format(allowed_values) - ) - - self._map_map_of_enum = map_map_of_enum - @property def map_of_enum_string(self): """ diff --git a/samples/client/petstore/python/petstore_api/rest.py b/samples/client/petstore/python/petstore_api/rest.py index c42861d0581..632bba2055e 100644 --- a/samples/client/petstore/python/petstore_api/rest.py +++ b/samples/client/petstore/python/petstore_api/rest.py @@ -30,6 +30,7 @@ import ssl import certifi import logging +import re # python 2 and python 3 compatibility library from six import iteritems @@ -141,7 +142,7 @@ def request(self, method, url, query_params=None, headers=None, if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: if query_params: url += '?' + urlencode(query_params) - if headers['Content-Type'] == 'application/json': + if re.search('json', headers['Content-Type'], re.IGNORECASE): request_body = None if body: request_body = json.dumps(body) From c3a9d6c9c3a8395f292e047d2bd94cb688aba2f8 Mon Sep 17 00:00:00 2001 From: jencodingatwork Date: Tue, 5 Jul 2016 12:36:08 -0400 Subject: [PATCH 047/470] Modified JavaJaxrs resources to fix duplicated variable names. See issue #3300 for full description. --- .../src/main/resources/JavaJaxRS/api.mustache | 110 +++++++++--------- .../resources/JavaJaxRS/formParams.mustache | 6 +- .../JavaJaxRS/serviceFormParams.mustache | 2 +- 3 files changed, 59 insertions(+), 59 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache index e1eb66091ae..05bf23276ba 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache @@ -1,55 +1,55 @@ -package {{package}}; - -import {{modelPackage}}.*; -import {{package}}.{{classname}}Service; -import {{package}}.factories.{{classname}}ServiceFactory; - -import io.swagger.annotations.ApiParam; - -{{#imports}}import {{import}}; -{{/imports}} - -import java.util.List; -import {{package}}.NotFoundException; - -import java.io.InputStream; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; -import org.glassfish.jersey.media.multipart.FormDataParam; - -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.ws.rs.*; - -@Path("/{{baseName}}") -{{#hasConsumes}}@Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} -{{#hasProduces}}@Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} -@io.swagger.annotations.Api(description = "the {{baseName}} API") -{{>generatedAnnotation}} -{{#operations}} -public class {{classname}} { - private final {{classname}}Service delegate = {{classname}}ServiceFactory.get{{classname}}(); - -{{#operation}} - @{{httpMethod}} - {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} - {{#hasConsumes}}@Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} - {{#hasProduces}}@Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} - @io.swagger.annotations.ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}{{#hasAuthMethods}}, authorizations = { - {{#authMethods}}@io.swagger.annotations.Authorization(value = "{{name}}"{{#isOAuth}}, scopes = { - {{#scopes}}@io.swagger.annotations.AuthorizationScope(scope = "{{scope}}", description = "{{description}}"){{#hasMore}}, - {{/hasMore}}{{/scopes}} - }{{/isOAuth}}){{#hasMore}}, - {{/hasMore}}{{/authMethods}} - }{{/hasAuthMethods}}, tags={ {{#vendorExtensions.x-tags}}"{{tag}}",{{/vendorExtensions.x-tags}} }) - @io.swagger.annotations.ApiResponses(value = { {{#responses}} - @io.swagger.annotations.ApiResponse(code = {{{code}}}, message = "{{{message}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}){{#hasMore}}, - {{/hasMore}}{{/responses}} }) - public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}},{{/allParams}}@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.{{nickname}}({{#allParams}}{{#isFile}}inputStream, fileDetail{{/isFile}}{{^isFile}}{{paramName}}{{/isFile}},{{/allParams}}securityContext); - } -{{/operation}} -} -{{/operations}} +package {{package}}; + +import {{modelPackage}}.*; +import {{package}}.{{classname}}Service; +import {{package}}.factories.{{classname}}ServiceFactory; + +import io.swagger.annotations.ApiParam; + +{{#imports}}import {{import}}; +{{/imports}} + +import java.util.List; +import {{package}}.NotFoundException; + +import java.io.InputStream; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.FormDataParam; + +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.ws.rs.*; + +@Path("/{{baseName}}") +{{#hasConsumes}}@Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} +{{#hasProduces}}@Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} +@io.swagger.annotations.Api(description = "the {{baseName}} API") +{{>generatedAnnotation}} +{{#operations}} +public class {{classname}} { + private final {{classname}}Service delegate = {{classname}}ServiceFactory.get{{classname}}(); + +{{#operation}} + @{{httpMethod}} + {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} + {{#hasConsumes}}@Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} + {{#hasProduces}}@Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} + @io.swagger.annotations.ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}{{#hasAuthMethods}}, authorizations = { + {{#authMethods}}@io.swagger.annotations.Authorization(value = "{{name}}"{{#isOAuth}}, scopes = { + {{#scopes}}@io.swagger.annotations.AuthorizationScope(scope = "{{scope}}", description = "{{description}}"){{#hasMore}}, + {{/hasMore}}{{/scopes}} + }{{/isOAuth}}){{#hasMore}}, + {{/hasMore}}{{/authMethods}} + }{{/hasAuthMethods}}, tags={ {{#vendorExtensions.x-tags}}"{{tag}}",{{/vendorExtensions.x-tags}} }) + @io.swagger.annotations.ApiResponses(value = { {{#responses}} + @io.swagger.annotations.ApiResponse(code = {{{code}}}, message = "{{{message}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}){{#hasMore}}, + {{/hasMore}}{{/responses}} }) + public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}},{{/allParams}}@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.{{nickname}}({{#allParams}}{{#isFile}}{{paramName}}InputStream, {{paramName}}Detail{{/isFile}}{{^isFile}}{{paramName}}{{/isFile}},{{/allParams}}securityContext); + } +{{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/formParams.mustache index 993d47bb562..acfaf3278bc 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/formParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/formParams.mustache @@ -1,3 +1,3 @@ -{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}){{#vendorExtensions.x-multipart}}@FormDataParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{^vendorExtensions.x-multipart}}@FormParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{/notFile}}{{#isFile}} - @FormDataParam("file") InputStream inputStream, - @FormDataParam("file") FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}){{#vendorExtensions.x-multipart}}@FormDataParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{^vendorExtensions.x-multipart}}@FormParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{/notFile}}{{#isFile}} + @FormDataParam("{{paramName}}") InputStream {{paramName}}InputStream, + @FormDataParam("{{paramName}}") FormDataContentDisposition {{paramName}}Detail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceFormParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceFormParams.mustache index 759335ba9ce..dc2d2eb1ecf 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceFormParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceFormParams.mustache @@ -1 +1 @@ -{{#isFormParam}}{{#notFile}}{{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}InputStream inputStream, FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{#notFile}}{{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}InputStream {{paramName}}InputStream, FormDataContentDisposition {{paramName}}Detail{{/isFile}}{{/isFormParam}} \ No newline at end of file From ae73bb755369c32e2ac5b385e273cbafc95f6df4 Mon Sep 17 00:00:00 2001 From: Jim Schubert Date: Tue, 5 Jul 2016 22:17:14 -0400 Subject: [PATCH 048/470] [aspnet5] Update to ASP.NET Core 1.0.0 This migrates the server generator for aspnet5 from 1.0.0-rc1-final to 1.0.0. Changes are fairly significant in how Kestrel hosts the application, as well as how Swagger finds XML comments for documentation. Changes are only related to hosting, docker, and configuration. --- bin/all-petstore.sh | 1 + .../languages/AspNet5ServerCodegen.java | 12 +- .../resources/aspnet5/Dockerfile.mustache | 10 +- .../src/main/resources/aspnet5/NuGet.Config | 9 ++ .../main/resources/aspnet5/Program.mustache | 32 +++++ .../resources/aspnet5/Project.xproj.mustache | 19 +++ .../aspnet5/Properties/launchSettings.json | 22 +++- .../main/resources/aspnet5/README.mustache | 27 ++++ .../main/resources/aspnet5/Solution.mustache | 32 +++++ .../main/resources/aspnet5/Startup.mustache | 115 +++++------------- .../main/resources/aspnet5/appsettings.json | 2 +- .../main/resources/aspnet5/build.bat.mustache | 20 +++ .../src/main/resources/aspnet5/build.mustache | 17 --- .../main/resources/aspnet5/build.sh.mustache | 19 +++ .../resources/aspnet5/controller.mustache | 3 +- .../src/main/resources/aspnet5/global.json | 7 +- .../src/main/resources/aspnet5/model.mustache | 1 + .../resources/aspnet5/partial_header.mustache | 25 ++++ .../resources/aspnet5/project.json.mustache | 88 ++++++++++++++ .../main/resources/aspnet5/project.mustache | 41 ------- .../src/main/resources/aspnet5/web.config | 14 +++ 21 files changed, 358 insertions(+), 158 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/aspnet5/NuGet.Config create mode 100644 modules/swagger-codegen/src/main/resources/aspnet5/Program.mustache create mode 100644 modules/swagger-codegen/src/main/resources/aspnet5/Project.xproj.mustache create mode 100644 modules/swagger-codegen/src/main/resources/aspnet5/README.mustache create mode 100644 modules/swagger-codegen/src/main/resources/aspnet5/Solution.mustache create mode 100644 modules/swagger-codegen/src/main/resources/aspnet5/build.bat.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/aspnet5/build.mustache create mode 100644 modules/swagger-codegen/src/main/resources/aspnet5/build.sh.mustache create mode 100644 modules/swagger-codegen/src/main/resources/aspnet5/partial_header.mustache create mode 100644 modules/swagger-codegen/src/main/resources/aspnet5/project.json.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/aspnet5/project.mustache create mode 100644 modules/swagger-codegen/src/main/resources/aspnet5/web.config diff --git a/bin/all-petstore.sh b/bin/all-petstore.sh index 849af6b5d4a..e46d98eb559 100755 --- a/bin/all-petstore.sh +++ b/bin/all-petstore.sh @@ -20,6 +20,7 @@ fi cd $APP_DIR ./bin/akka-scala-petstore.sh ./bin/android-petstore.sh +./bin/aspnet5-petstore-server.sh ./bin/clojure-petstore.sh ./bin/csharp-petstore.sh ./bin/dynamic-html.sh diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AspNet5ServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AspNet5ServerCodegen.java index 099d049707b..8b73275984a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AspNet5ServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AspNet5ServerCodegen.java @@ -84,14 +84,22 @@ public void processOpts() { apiPackage = packageName + ".Controllers"; modelPackage = packageName + ".Models"; + supportingFiles.add(new SupportingFile("NuGet.Config", "", "NuGet.Config")); supportingFiles.add(new SupportingFile("global.json", "", "global.json")); - supportingFiles.add(new SupportingFile("build.mustache", "", "build.sh")); + supportingFiles.add(new SupportingFile("build.sh.mustache", "", "build.sh")); + supportingFiles.add(new SupportingFile("build.bat.mustache", "", "build.bat")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("Solution.mustache", "", this.packageName + ".sln")); supportingFiles.add(new SupportingFile("Dockerfile.mustache", this.sourceFolder, "Dockerfile")); supportingFiles.add(new SupportingFile("gitignore", this.sourceFolder, ".gitignore")); supportingFiles.add(new SupportingFile("appsettings.json", this.sourceFolder, "appsettings.json")); - supportingFiles.add(new SupportingFile("project.mustache", this.sourceFolder, "project.json")); + supportingFiles.add(new SupportingFile("project.json.mustache", this.sourceFolder, "project.json")); supportingFiles.add(new SupportingFile("Startup.mustache", this.sourceFolder, "Startup.cs")); + supportingFiles.add(new SupportingFile("Program.mustache", this.sourceFolder, "Program.cs")); + supportingFiles.add(new SupportingFile("web.config", this.sourceFolder, "web.config")); + + supportingFiles.add(new SupportingFile("Project.xproj.mustache", this.sourceFolder, this.packageName + ".xproj")); supportingFiles.add(new SupportingFile("Properties" + File.separator + "launchSettings.json", this.sourceFolder + File.separator + "Properties", "launchSettings.json")); diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/Dockerfile.mustache b/modules/swagger-codegen/src/main/resources/aspnet5/Dockerfile.mustache index 8ff1b8faeed..0765ead2db2 100644 --- a/modules/swagger-codegen/src/main/resources/aspnet5/Dockerfile.mustache +++ b/modules/swagger-codegen/src/main/resources/aspnet5/Dockerfile.mustache @@ -1,10 +1,12 @@ -FROM microsoft/aspnet:1.0.0-rc1-final +FROM microsoft/dotnet:latest + +ENV DOTNET_CLI_TELEMETRY_OPTOUT 1 RUN mkdir -p /app/{{packageName}} COPY . /app/{{packageName}} WORKDIR /app/{{packageName}} -RUN ["dnu", "restore"] -RUN ["dnu", "pack", "--out", "artifacts"] EXPOSE 5000/tcp -ENTRYPOINT ["dnx", "-p", "project.json", "web"] + +RUN ["dotnet", "restore"] +ENTRYPOINT ["dotnet", "run", "-p", "project.json", "web"] diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/NuGet.Config b/modules/swagger-codegen/src/main/resources/aspnet5/NuGet.Config new file mode 100644 index 00000000000..01f3d1f203f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/aspnet5/NuGet.Config @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/Program.mustache b/modules/swagger-codegen/src/main/resources/aspnet5/Program.mustache new file mode 100644 index 00000000000..ab465c42516 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/aspnet5/Program.mustache @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Builder; + +namespace {{packageName}} +{ + public class Program + { + public static void Main(string[] args) + { + var host = new WebHostBuilder() + .UseKestrel(options => + { + // options.ThreadCount = 4; + // options.UseHttps("cert.pfx", "certpassword"); + options.NoDelay = true; + options.UseConnectionLogging(); + }) + .UseUrls("http://+:5000" /*, "https://+:5001" */) + .UseContentRoot(Directory.GetCurrentDirectory()) + .UseIISIntegration() + .UseStartup() + .Build(); + + host.Run(); + } + } +} diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/Project.xproj.mustache b/modules/swagger-codegen/src/main/resources/aspnet5/Project.xproj.mustache new file mode 100644 index 00000000000..22123b97009 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/aspnet5/Project.xproj.mustache @@ -0,0 +1,19 @@ + + + + 14.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + + {{projectGuid}} + Sample + .\obj + .\bin\ + v4.6 + + + 2.0 + + + \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/Properties/launchSettings.json b/modules/swagger-codegen/src/main/resources/aspnet5/Properties/launchSettings.json index 7d41a0f84b9..45a5f3319a5 100644 --- a/modules/swagger-codegen/src/main/resources/aspnet5/Properties/launchSettings.json +++ b/modules/swagger-codegen/src/main/resources/aspnet5/Properties/launchSettings.json @@ -1,12 +1,28 @@ { + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:50352/", + "sslPort": 0 + } + }, "profiles": { "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, - "launchUrl": "swagger/ui", + "launchUrl": "swagger/ui/index.html", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "web": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "http://localhost:5000/swagger/ui/index.html", "environmentVariables": { - "ASPNET_ENV": "Development" + "ASPNETCORE_ENVIRONMENT": "Development" } } } -} +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/README.mustache b/modules/swagger-codegen/src/main/resources/aspnet5/README.mustache new file mode 100644 index 00000000000..451508ad676 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/aspnet5/README.mustache @@ -0,0 +1,27 @@ +# {{packageName}} - ASP.NET Core 1.0 Server + +{{#appDescription}} +{{{appDescription}}} +{{/appDescription}} + +## Run + +Linux/OS X: + +``` +sh build.sh +``` + +Windows: + +``` +build.bat +``` + +## Run in Docker + +``` +cd src/{{packageName}} +docker build -t {{packageName}} . +docker run -p 5000:5000 {{packageName}} +``` diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/Solution.mustache b/modules/swagger-codegen/src/main/resources/aspnet5/Solution.mustache new file mode 100644 index 00000000000..4ea98f8e492 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/aspnet5/Solution.mustache @@ -0,0 +1,32 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.25420.1 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{815BE834-0656-4C12-84A4-43F2BA4B8BDE}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{AFF6BF88-8A7D-4736-AF81-31BCE86B19BD}" + ProjectSection(SolutionItems) = preProject + global.json = global.json + EndProjectSection +EndProject +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "{{packageName}}", "src\{{packageName}}\{{packageName}}.xproj", "{{packageGuid}}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {3B5990B3-40F1-4148-89B5-84AC71432557}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3B5990B3-40F1-4148-89B5-84AC71432557}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3B5990B3-40F1-4148-89B5-84AC71432557}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3B5990B3-40F1-4148-89B5-84AC71432557}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {{packageGuid}} = {815BE834-0656-4C12-84A4-43F2BA4B8BDE} + EndGlobalSection +EndGlobal \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/Startup.mustache b/modules/swagger-codegen/src/main/resources/aspnet5/Startup.mustache index c4e9d328cc7..80709bd068f 100644 --- a/modules/swagger-codegen/src/main/resources/aspnet5/Startup.mustache +++ b/modules/swagger-codegen/src/main/resources/aspnet5/Startup.mustache @@ -1,136 +1,81 @@ +{{>partial_header}} using System; +using System.Collections.Generic; using System.IO; using System.Linq; -using Microsoft.AspNet.Builder; -using Microsoft.AspNet.Hosting; +using System.Threading.Tasks; +using System.Xml.XPath; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.PlatformAbstractions; using Newtonsoft.Json.Serialization; -using Swashbuckle.SwaggerGen; -using Swashbuckle.SwaggerGen.XmlComments; +using Swashbuckle.Swagger.Model; +using Swashbuckle.SwaggerGen.Annotations; namespace {{packageName}} { public class Startup { private readonly IHostingEnvironment _hostingEnv; - private readonly IApplicationEnvironment _appEnv; - public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) + public IConfigurationRoot Configuration { get; } + + public Startup(IHostingEnvironment env) { _hostingEnv = env; - _appEnv = appEnv; - // Set up configuration sources. var builder = new ConfigurationBuilder() - .AddJsonFile("appsettings.json") + .SetBasePath(env.ContentRootPath) + .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) + .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } - - public IConfigurationRoot Configuration { get; set; } - + + // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { - string xmlComments = string.Format(@"{0}{4}artifacts{4}{1}{4}{2}{3}{4}{{packageName}}.xml", - GetSolutionBasePath(), - _appEnv.Configuration, - _appEnv.RuntimeFramework.Identifier.ToLower(), - _appEnv.RuntimeFramework.Version.ToString().Replace(".", string.Empty), - Path.DirectorySeparatorChar); - // Add framework services. services.AddMvc() .AddJsonOptions( opts => { opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }); - - // Uncomment the following line to add Web API services which makes it easier to port Web API 2 controllers. - // You will also need to add the Microsoft.AspNet.Mvc.WebApiCompatShim package to the 'dependencies' section of project.json. - // services.AddWebApiConventions(); - + services.AddSwaggerGen(); - services.ConfigureSwaggerDocument(options => + + services.ConfigureSwaggerGen(options => { options.SingleApiVersion(new Info { Version = "v1", Title = "{{packageName}}", - Description = "{{packageName}} (ASP.NET 5 Web API 2.x)" + Description = "{{packageName}} (ASP.NET Core 1.0)" }); - - options.OperationFilter(new ApplyXmlActionCommentsFixed(xmlComments)); - }); - services.ConfigureSwaggerSchema(options => { - options.DescribeAllEnumsAsStrings = true; - options.ModelFilter(new ApplyXmlTypeCommentsFixed(xmlComments)); + options.DescribeAllEnumsAsStrings(); + + var comments = new XPathDocument($"{AppContext.BaseDirectory}{Path.DirectorySeparatorChar}{_hostingEnv.ApplicationName}.xml"); + options.OperationFilter(comments); + options.ModelFilter(comments); }); + } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { - loggerFactory.MinimumLevel = LogLevel.Information; loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); - app.UseIISPlatformHandler(); - + app.UseMvc(); + app.UseDefaultFiles(); app.UseStaticFiles(); - app.UseMvc(); - - app.UseSwaggerGen(); + app.UseSwagger(); app.UseSwaggerUi(); } - - // Taken from https://github.com/domaindrivendev/Ahoy/blob/master/test/WebSites/Basic/Startup.cs - private string GetSolutionBasePath() - { - var dir = Directory.CreateDirectory(_appEnv.ApplicationBasePath); - while (dir.Parent != null) - { - if (dir.GetDirectories("artifacts").Any()) - return dir.FullName; - - dir = dir.Parent; - } - throw new InvalidOperationException("Failed to detect solution base path - artifacts not found. Did you run dnu pack --out artifacts?"); - } - - // Entry point for the application. - public static void Main(string[] args) => WebApplication.Run(args); - } - - - // using Swashbuckle.SwaggerGen.XmlComments; - public class ApplyXmlTypeCommentsFixed : ApplyXmlTypeComments - { - public ApplyXmlTypeCommentsFixed() : base("") - { - throw new NotImplementedException(); - } - - public ApplyXmlTypeCommentsFixed(string filePath): base(filePath) - { - - } - } - - public class ApplyXmlActionCommentsFixed : ApplyXmlActionComments - { - public ApplyXmlActionCommentsFixed() : base("") - { - throw new NotImplementedException(); - } - - public ApplyXmlActionCommentsFixed(string filePath): base(filePath) - { - - } } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/appsettings.json b/modules/swagger-codegen/src/main/resources/aspnet5/appsettings.json index e5472e562b7..c6af7d9b069 100644 --- a/modules/swagger-codegen/src/main/resources/aspnet5/appsettings.json +++ b/modules/swagger-codegen/src/main/resources/aspnet5/appsettings.json @@ -2,7 +2,7 @@ "Logging": { "IncludeScopes": false, "LogLevel": { - "Default": "Verbose", + "Default": "Information", "System": "Information", "Microsoft": "Information" } diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/build.bat.mustache b/modules/swagger-codegen/src/main/resources/aspnet5/build.bat.mustache new file mode 100644 index 00000000000..b39b7232a1c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/aspnet5/build.bat.mustache @@ -0,0 +1,20 @@ +:: Generated by: https://github.com/swagger-api/swagger-codegen.git +:: +:: Licensed under the Apache License, Version 2.0 (the "License"); +:: you may not use this file except in compliance with the License. +:: You may obtain a copy of the License at +:: +:: http://www.apache.org/licenses/LICENSE-2.0 +:: +:: Unless required by applicable law or agreed to in writing, software +:: distributed under the License is distributed on an "AS IS" BASIS, +:: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +:: See the License for the specific language governing permissions and +:: limitations under the License. + +@echo off + +dotnet restore src\{{packageName}} +dotnet build src\{{packageName}} +echo Now, run the following to start the project: dotnet run -p src\{{packageName}}\project.json web. +echo. diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/build.mustache b/modules/swagger-codegen/src/main/resources/aspnet5/build.mustache deleted file mode 100644 index 0a63bfeaf3d..00000000000 --- a/modules/swagger-codegen/src/main/resources/aspnet5/build.mustache +++ /dev/null @@ -1,17 +0,0 @@ -#!/usr/bin/env bash - -if ! type dnvm > /dev/null 2>&1; then - source /usr/local/lib/dnx/bin/dnvm.sh -fi - -if ! type dnu > /dev/null 2>&1 || [ -z "$SKIP_DNX_INSTALL" ]; then - dnvm install latest -runtime coreclr -alias default - dnvm install default -runtime mono -alias default -else - dnvm use default -runtime mono -fi - -dnu restore src/{{packageName}}/ && \ - dnu build src/{{packageName}}/ && \ - dnu pack src/{{packageName}}/ --out artifacts && \ - echo "Now, run the following to start the project: dnx --project src/{{packageName}}/project.json web" \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/build.sh.mustache b/modules/swagger-codegen/src/main/resources/aspnet5/build.sh.mustache new file mode 100644 index 00000000000..179fe5fb61f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/aspnet5/build.sh.mustache @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# +# Generated by: https://github.com/swagger-api/swagger-codegen.git +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +dotnet restore src/{{packageName}}/ && \ + dotnet build src/{{packageName}}/ && \ + echo "Now, run the following to start the project: dotnet run -p src/{{packageName}}/project.json web" \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/controller.mustache b/modules/swagger-codegen/src/main/resources/aspnet5/controller.mustache index 592ef42362b..bfeb2307ff8 100644 --- a/modules/swagger-codegen/src/main/resources/aspnet5/controller.mustache +++ b/modules/swagger-codegen/src/main/resources/aspnet5/controller.mustache @@ -1,3 +1,4 @@ +{{>partial_header}} using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -6,7 +7,7 @@ using System.IO; using System.Linq; using System.Net; using System.Threading.Tasks; -using Microsoft.AspNet.Mvc; +using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using Swashbuckle.SwaggerGen.Annotations; using {{packageName}}.Models; diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/global.json b/modules/swagger-codegen/src/main/resources/aspnet5/global.json index 4a6d1feac95..e5360d025ec 100644 --- a/modules/swagger-codegen/src/main/resources/aspnet5/global.json +++ b/modules/swagger-codegen/src/main/resources/aspnet5/global.json @@ -1,8 +1,7 @@ { - "projects": [ "src", "." ], + "projects": [ "src", "test" ], "sdk": { - "version": "1.0.0-rc1-final", - "runtime": "coreclr", - "architecture": "x64" + "version": "1.0.0-preview2-003121", + "runtime": "coreclr" } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/model.mustache b/modules/swagger-codegen/src/main/resources/aspnet5/model.mustache index 08aaed01f3d..5af9183b1dc 100644 --- a/modules/swagger-codegen/src/main/resources/aspnet5/model.mustache +++ b/modules/swagger-codegen/src/main/resources/aspnet5/model.mustache @@ -1,3 +1,4 @@ +{{>partial_header}} using System; using System.Linq; using System.IO; diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/partial_header.mustache b/modules/swagger-codegen/src/main/resources/aspnet5/partial_header.mustache new file mode 100644 index 00000000000..f7477da5c47 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/aspnet5/partial_header.mustache @@ -0,0 +1,25 @@ +/* + {{#appName}} + * {{{appName}}} + * + {{/appName}} + {{#appDescription}} + * {{{appDescription}}} + * + {{/appDescription}} + * {{#version}}OpenAPI spec version: {{{version}}}{{/version}} + * {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/project.json.mustache b/modules/swagger-codegen/src/main/resources/aspnet5/project.json.mustache new file mode 100644 index 00000000000..432ba86d5a9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/aspnet5/project.json.mustache @@ -0,0 +1,88 @@ +{ + "title": "Swagger UI", + "version": "{{packageVersion}}-*", + "copyright": "{{packageName}}", + "description": "{{packageName}}", + "dependencies": { + "Microsoft.NETCore.App": { + "version": "1.0.0", + "type": "platform" + }, + "Microsoft.AspNetCore.Mvc": "1.0.0", + "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0", + "Microsoft.AspNetCore.Server.Kestrel": "1.0.0", + "Microsoft.AspNetCore.Server.Kestrel.Https": "1.0.0", + "Microsoft.AspNetCore.StaticFiles": "1.0.0", + "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0", + "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0", + "Microsoft.Extensions.Configuration.Json": "1.0.0", + "Microsoft.Extensions.Logging": "1.0.0", + "Microsoft.Extensions.Logging.Console": "1.0.0", + "Microsoft.Extensions.Logging.Debug": "1.0.0", + "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0", + "Microsoft.EntityFrameworkCore": "1.0.0", + "Swashbuckle.SwaggerGen": "6.0.0-beta901", + "Swashbuckle.SwaggerUi": "6.0.0-beta901" + }, + + "tools": { + "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final", + + "Microsoft.Extensions.SecretManager.Tools": { + "imports": [ + "netstandard1.6", + "portable-net45+win8+dnxcore50", + "portable-net45+win8" + ], + "version": "1.0.0-preview2-final" + } + }, + + "frameworks": { + "netcoreapp1.0": { + "imports": [ + "dotnet5.6", + "dnxcore50", + "netstandard1.6", + "portable-net452+win81" + ] + } + }, + + "buildOptions": { + "emitEntryPoint": true, + "preserveCompilationContext": true, + "xmlDoc": true, + "compile": { + "exclude": [ + "wwwroot", + "node_modules", + "bower_components" + ] + } + }, + + "runtimeOptions": { + "configProperties": { + "System.GC.Server": true + } + }, + + "publishOptions": { + "include": [ + "wwwroot", + "Views", + "Areas/**/Views", + "appsettings.json", + "web.config" + ], + "exclude": [ + "**.user", + "**.vspscc" + ] + }, + + "scripts": { + "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ] + } +} diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/project.mustache b/modules/swagger-codegen/src/main/resources/aspnet5/project.mustache deleted file mode 100644 index 018084bc7e1..00000000000 --- a/modules/swagger-codegen/src/main/resources/aspnet5/project.mustache +++ /dev/null @@ -1,41 +0,0 @@ -{ - "version": "{{packageVersion}}-*", - "compilationOptions": { - "emitEntryPoint": true - }, - "tooling": { - "defaultNamespace": "{{packageName}}" - }, - - "dependencies": { - "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final", - "Microsoft.AspNet.Mvc": "6.0.0-rc1-final", - "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final", - "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final", - "Microsoft.Extensions.Configuration.FileProviderExtensions" : "1.0.0-rc1-final", - "Microsoft.Extensions.Logging": "1.0.0-rc1-final", - "Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final", - "Microsoft.Extensions.Logging.Debug" : "1.0.0-rc1-final", - "Swashbuckle.SwaggerGen": "6.0.0-rc1-final", - "Swashbuckle.SwaggerUi": "6.0.0-rc1-final" - }, - - "commands": { - "web": "Microsoft.AspNet.Server.Kestrel --server.urls http://0.0.0.0:5000" - }, - - "frameworks": { - "dnx451": { }, - "dnxcore50": { } - }, - - "exclude": [ - "wwwroot", - "node_modules", - "bower_components" - ], - "publishExclude": [ - "**.user", - "**.vspscc" - ] -} diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/web.config b/modules/swagger-codegen/src/main/resources/aspnet5/web.config new file mode 100644 index 00000000000..a3b9f6add9c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/aspnet5/web.config @@ -0,0 +1,14 @@ + + + + + + + + + + + + From 4d5905c7361f83ff4ab876a087a7be5e00ba4ba5 Mon Sep 17 00:00:00 2001 From: Jim Schubert Date: Tue, 5 Jul 2016 22:22:20 -0400 Subject: [PATCH 049/470] [aspnet5] Regenerate sample server --- samples/server/petstore/aspnet5/.gitignore | 1 - .../petstore/aspnet5/.swagger-codegen-ignore | 23 ++ .../server/petstore/aspnet5/IO.Swagger.sln | 32 +++ samples/server/petstore/aspnet5/LICENSE | 201 ++++++++++++++++++ samples/server/petstore/aspnet5/NuGet.Config | 9 + samples/server/petstore/aspnet5/README.md | 7 + samples/server/petstore/aspnet5/build.bat | 20 ++ samples/server/petstore/aspnet5/build.sh | 32 +-- samples/server/petstore/aspnet5/global.json | 7 +- .../src/IO.Swagger/Controllers/PetApi.cs | 46 +++- .../src/IO.Swagger/Controllers/StoreApi.cs | 26 ++- .../src/IO.Swagger/Controllers/UserApi.cs | 24 ++- .../aspnet5/src/IO.Swagger/Dockerfile | 14 +- .../aspnet5/src/IO.Swagger/IO.Swagger.xproj | 19 ++ .../src/IO.Swagger/Models/ApiResponse.cs | 22 ++ .../aspnet5/src/IO.Swagger/Models/Category.cs | 22 ++ .../aspnet5/src/IO.Swagger/Models/Order.cs | 34 ++- .../aspnet5/src/IO.Swagger/Models/Pet.cs | 22 ++ .../aspnet5/src/IO.Swagger/Models/Tag.cs | 22 ++ .../aspnet5/src/IO.Swagger/Models/User.cs | 22 ++ .../aspnet5/src/IO.Swagger/Program.cs | 32 +++ .../IO.Swagger/Properties/launchSettings.json | 22 +- .../aspnet5/src/IO.Swagger/Startup.cs | 136 +++++------- .../aspnet5/src/IO.Swagger/appsettings.json | 2 +- .../aspnet5/src/IO.Swagger/project.json | 105 ++++++--- .../aspnet5/src/IO.Swagger/web.config | 14 ++ 26 files changed, 760 insertions(+), 156 deletions(-) delete mode 100644 samples/server/petstore/aspnet5/.gitignore create mode 100644 samples/server/petstore/aspnet5/.swagger-codegen-ignore create mode 100644 samples/server/petstore/aspnet5/IO.Swagger.sln create mode 100644 samples/server/petstore/aspnet5/LICENSE create mode 100644 samples/server/petstore/aspnet5/NuGet.Config create mode 100644 samples/server/petstore/aspnet5/README.md create mode 100644 samples/server/petstore/aspnet5/build.bat mode change 100755 => 100644 samples/server/petstore/aspnet5/build.sh create mode 100644 samples/server/petstore/aspnet5/src/IO.Swagger/IO.Swagger.xproj create mode 100644 samples/server/petstore/aspnet5/src/IO.Swagger/Program.cs create mode 100644 samples/server/petstore/aspnet5/src/IO.Swagger/web.config diff --git a/samples/server/petstore/aspnet5/.gitignore b/samples/server/petstore/aspnet5/.gitignore deleted file mode 100644 index e4349f244a1..00000000000 --- a/samples/server/petstore/aspnet5/.gitignore +++ /dev/null @@ -1 +0,0 @@ -artifacts/ \ No newline at end of file diff --git a/samples/server/petstore/aspnet5/.swagger-codegen-ignore b/samples/server/petstore/aspnet5/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/aspnet5/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/aspnet5/IO.Swagger.sln b/samples/server/petstore/aspnet5/IO.Swagger.sln new file mode 100644 index 00000000000..5337cb4c2cb --- /dev/null +++ b/samples/server/petstore/aspnet5/IO.Swagger.sln @@ -0,0 +1,32 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.25420.1 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{815BE834-0656-4C12-84A4-43F2BA4B8BDE}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{AFF6BF88-8A7D-4736-AF81-31BCE86B19BD}" + ProjectSection(SolutionItems) = preProject + global.json = global.json + EndProjectSection +EndProject +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.xproj", "" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {3B5990B3-40F1-4148-89B5-84AC71432557}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3B5990B3-40F1-4148-89B5-84AC71432557}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3B5990B3-40F1-4148-89B5-84AC71432557}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3B5990B3-40F1-4148-89B5-84AC71432557}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + = {815BE834-0656-4C12-84A4-43F2BA4B8BDE} + EndGlobalSection +EndGlobal \ No newline at end of file diff --git a/samples/server/petstore/aspnet5/LICENSE b/samples/server/petstore/aspnet5/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/server/petstore/aspnet5/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/server/petstore/aspnet5/NuGet.Config b/samples/server/petstore/aspnet5/NuGet.Config new file mode 100644 index 00000000000..01f3d1f203f --- /dev/null +++ b/samples/server/petstore/aspnet5/NuGet.Config @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/samples/server/petstore/aspnet5/README.md b/samples/server/petstore/aspnet5/README.md new file mode 100644 index 00000000000..2bdca9e4d48 --- /dev/null +++ b/samples/server/petstore/aspnet5/README.md @@ -0,0 +1,7 @@ +# {{packageName}} - ASP.NET Core 1.0 Server + +{{#appDescription}} +{{{appDescription}}} +{{/appDescription}} + + diff --git a/samples/server/petstore/aspnet5/build.bat b/samples/server/petstore/aspnet5/build.bat new file mode 100644 index 00000000000..85f9c4463e7 --- /dev/null +++ b/samples/server/petstore/aspnet5/build.bat @@ -0,0 +1,20 @@ +:: Generated by: https://github.com/swagger-api/swagger-codegen.git +:: +:: Licensed under the Apache License, Version 2.0 (the "License"); +:: you may not use this file except in compliance with the License. +:: You may obtain a copy of the License at +:: +:: http://www.apache.org/licenses/LICENSE-2.0 +:: +:: Unless required by applicable law or agreed to in writing, software +:: distributed under the License is distributed on an "AS IS" BASIS, +:: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +:: See the License for the specific language governing permissions and +:: limitations under the License. + +@echo off + +dotnet restore src\IO.Swagger +dotnet build src\IO.Swagger +echo Now, run the following to start the project: dotnet run -p src\IO.Swagger\project.json web. +echo. diff --git a/samples/server/petstore/aspnet5/build.sh b/samples/server/petstore/aspnet5/build.sh old mode 100755 new mode 100644 index 5d6402baee7..f7592a16bb0 --- a/samples/server/petstore/aspnet5/build.sh +++ b/samples/server/petstore/aspnet5/build.sh @@ -1,17 +1,19 @@ #!/usr/bin/env bash +# +# Generated by: https://github.com/swagger-api/swagger-codegen.git +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. -if ! type dnvm > /dev/null 2>&1; then - source /usr/local/lib/dnx/bin/dnvm.sh -fi - -if ! type dnu > /dev/null 2>&1 || [ -z "$SKIP_DNX_INSTALL" ]; then - dnvm install latest -runtime coreclr -alias default - dnvm install default -runtime mono -alias default -else - dnvm use default -runtime mono -fi - -dnu restore src/IO.Swagger/ && \ - dnu build src/IO.Swagger/ && \ - dnu pack src/IO.Swagger/ --out artifacts && \ - echo "Now, run the following to start the project: dnx --project src/IO.Swagger/project.json web" \ No newline at end of file +dotnet restore src/IO.Swagger/ && \ + dotnet build src/IO.Swagger/ && \ + echo "Now, run the following to start the project: dotnet run -p src/IO.Swagger/project.json web" \ No newline at end of file diff --git a/samples/server/petstore/aspnet5/global.json b/samples/server/petstore/aspnet5/global.json index 4a6d1feac95..e5360d025ec 100644 --- a/samples/server/petstore/aspnet5/global.json +++ b/samples/server/petstore/aspnet5/global.json @@ -1,8 +1,7 @@ { - "projects": [ "src", "." ], + "projects": [ "src", "test" ], "sdk": { - "version": "1.0.0-rc1-final", - "runtime": "coreclr", - "architecture": "x64" + "version": "1.0.0-preview2-003121", + "runtime": "coreclr" } } \ No newline at end of file diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/PetApi.cs b/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/PetApi.cs index 18fefec1cba..8b6c8f3e09f 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/PetApi.cs +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/PetApi.cs @@ -1,3 +1,25 @@ +/* + * Swagger Petstore + * + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -6,7 +28,7 @@ using System.Linq; using System.Net; using System.Threading.Tasks; -using Microsoft.AspNet.Mvc; +using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using Swashbuckle.SwaggerGen.Annotations; using IO.Swagger.Models; @@ -53,7 +75,7 @@ public virtual void DeletePet([FromRoute]long? petId, [FromHeader]string apiKey) /// /// Finds Pets by status /// - /// Multiple status values can be provided with comma seperated strings + /// Multiple status values can be provided with comma separated strings /// Status values that need to be considered for filter /// successful operation /// Invalid status value @@ -75,7 +97,7 @@ public virtual IActionResult FindPetsByStatus([FromQuery]List status) /// /// Finds Pets by tags /// - /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. /// Tags to filter by /// successful operation /// Invalid tag value @@ -97,8 +119,8 @@ public virtual IActionResult FindPetsByTags([FromQuery]List tags) /// /// Find pet by ID /// - /// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - /// ID of pet that needs to be fetched + /// Returns a single pet + /// ID of pet to return /// successful operation /// Invalid ID supplied /// Pet not found @@ -145,7 +167,7 @@ public virtual void UpdatePet([FromBody]Pet body) [HttpPost] [Route("/pet/{petId}")] [SwaggerOperation("UpdatePetWithForm")] - public virtual void UpdatePetWithForm([FromRoute]string petId, [FromForm]string name, [FromForm]string status) + public virtual void UpdatePetWithForm([FromRoute]long? petId, [FromForm]string name, [FromForm]string status) { throw new NotImplementedException(); } @@ -158,13 +180,19 @@ public virtual void UpdatePetWithForm([FromRoute]string petId, [FromForm]string /// ID of pet to update /// Additional data to pass to server /// file to upload - /// successful operation + /// successful operation [HttpPost] [Route("/pet/{petId}/uploadImage")] [SwaggerOperation("UploadFile")] - public virtual void UploadFile([FromRoute]long? petId, [FromForm]string additionalMetadata, [FromForm]System.IO.Stream file) + [SwaggerResponse(200, type: typeof(ApiResponse))] + public virtual IActionResult UploadFile([FromRoute]long? petId, [FromForm]string additionalMetadata, [FromForm]System.IO.Stream file) { - throw new NotImplementedException(); + string exampleJson = null; + + var example = exampleJson != null + ? JsonConvert.DeserializeObject(exampleJson) + : default(ApiResponse); + return new ObjectResult(example); } } } diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/StoreApi.cs b/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/StoreApi.cs index 0ba31771bbb..26784668ba6 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/StoreApi.cs +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/StoreApi.cs @@ -1,3 +1,25 @@ +/* + * Swagger Petstore + * + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -6,7 +28,7 @@ using System.Linq; using System.Net; using System.Threading.Tasks; -using Microsoft.AspNet.Mvc; +using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using Swashbuckle.SwaggerGen.Annotations; using IO.Swagger.Models; @@ -67,7 +89,7 @@ public virtual IActionResult GetInventory() [Route("/store/order/{orderId}")] [SwaggerOperation("GetOrderById")] [SwaggerResponse(200, type: typeof(Order))] - public virtual IActionResult GetOrderById([FromRoute]string orderId) + public virtual IActionResult GetOrderById([FromRoute]long? orderId) { string exampleJson = null; diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/UserApi.cs b/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/UserApi.cs index b73cdd23c8f..1cfacdd09a7 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/UserApi.cs +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/UserApi.cs @@ -1,3 +1,25 @@ +/* + * Swagger Petstore + * + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -6,7 +28,7 @@ using System.Linq; using System.Net; using System.Threading.Tasks; -using Microsoft.AspNet.Mvc; +using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using Swashbuckle.SwaggerGen.Annotations; using IO.Swagger.Models; diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Dockerfile b/samples/server/petstore/aspnet5/src/IO.Swagger/Dockerfile index af879b80ab0..5a44639a7b0 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Dockerfile +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Dockerfile @@ -1,10 +1,16 @@ -FROM microsoft/aspnet:1.0.0-rc1-final +FROM microsoft/dotnet:latest + +RUN groupadd -r app && useradd -r -g app app + +ENV DOTNET_CLI_TELEMETRY_OPTOUT 1 RUN mkdir -p /app/IO.Swagger COPY . /app/IO.Swagger WORKDIR /app/IO.Swagger -RUN ["dnu", "restore"] -RUN ["dnu", "pack", "--out", "artifacts"] EXPOSE 5000/tcp -ENTRYPOINT ["dnx", "-p", "project.json", "web"] + +USER app + +RUN ["dotnet", "restore"] +ENTRYPOINT ["dotnet", "run", "-p", "project.json", "web"] diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/IO.Swagger.xproj b/samples/server/petstore/aspnet5/src/IO.Swagger/IO.Swagger.xproj new file mode 100644 index 00000000000..4002eaeb995 --- /dev/null +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/IO.Swagger.xproj @@ -0,0 +1,19 @@ + + + + 14.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + + + Sample + .\obj + .\bin\ + v4.6 + + + 2.0 + + + \ No newline at end of file diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/ApiResponse.cs b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/ApiResponse.cs index 886f22c21bf..cdde768afcc 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/ApiResponse.cs +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/ApiResponse.cs @@ -1,3 +1,25 @@ +/* + * Swagger Petstore + * + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + using System; using System.Linq; using System.IO; diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Category.cs b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Category.cs index e412db81ee2..410079fb6bf 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Category.cs +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Category.cs @@ -1,3 +1,25 @@ +/* + * Swagger Petstore + * + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + using System; using System.Linq; using System.IO; diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Order.cs b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Order.cs index 80c3bcfb69e..357eed81bd1 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Order.cs +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Order.cs @@ -1,3 +1,25 @@ +/* + * Swagger Petstore + * + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + using System; using System.Linq; using System.IO; @@ -23,7 +45,7 @@ public partial class Order : IEquatable /// Quantity. /// ShipDate. /// Order Status. - /// Complete. + /// Complete (default to false). public Order(long? Id = null, long? PetId = null, int? Quantity = null, DateTime? ShipDate = null, string Status = null, bool? Complete = null) { this.Id = Id; @@ -31,7 +53,15 @@ public Order(long? Id = null, long? PetId = null, int? Quantity = null, DateTime this.Quantity = Quantity; this.ShipDate = ShipDate; this.Status = Status; - this.Complete = Complete; + // use default value if no "Complete" provided + if (Complete == null) + { + this.Complete = false; + } + else + { + this.Complete = Complete; + } } diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Pet.cs b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Pet.cs index 70a3992c294..ff8bec1056f 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Pet.cs +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Pet.cs @@ -1,3 +1,25 @@ +/* + * Swagger Petstore + * + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + using System; using System.Linq; using System.IO; diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Tag.cs b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Tag.cs index 77697097379..4520f8af533 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Tag.cs +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Tag.cs @@ -1,3 +1,25 @@ +/* + * Swagger Petstore + * + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + using System; using System.Linq; using System.IO; diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/User.cs b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/User.cs index c8373712db9..620f1c69f21 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/User.cs +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/User.cs @@ -1,3 +1,25 @@ +/* + * Swagger Petstore + * + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + using System; using System.Linq; using System.IO; diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Program.cs b/samples/server/petstore/aspnet5/src/IO.Swagger/Program.cs new file mode 100644 index 00000000000..8990e6b48ad --- /dev/null +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Program.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Builder; + +namespace IO.Swagger +{ + public class Program + { + public static void Main(string[] args) + { + var host = new WebHostBuilder() + .UseKestrel(options => + { + // options.ThreadCount = 4; + // options.UseHttps("cert.pfx", "certpassword"); + options.NoDelay = true; + options.UseConnectionLogging(); + }) + .UseUrls("http://+:5000" /*, "https://+:5001" */) + .UseContentRoot(Directory.GetCurrentDirectory()) + .UseIISIntegration() + .UseStartup() + .Build(); + + host.Run(); + } + } +} diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Properties/launchSettings.json b/samples/server/petstore/aspnet5/src/IO.Swagger/Properties/launchSettings.json index 7d41a0f84b9..45a5f3319a5 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Properties/launchSettings.json +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Properties/launchSettings.json @@ -1,12 +1,28 @@ { + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:50352/", + "sslPort": 0 + } + }, "profiles": { "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, - "launchUrl": "swagger/ui", + "launchUrl": "swagger/ui/index.html", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "web": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "http://localhost:5000/swagger/ui/index.html", "environmentVariables": { - "ASPNET_ENV": "Development" + "ASPNETCORE_ENVIRONMENT": "Development" } } } -} +} \ No newline at end of file diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Startup.cs b/samples/server/petstore/aspnet5/src/IO.Swagger/Startup.cs index 21cb3aa6042..e94c6e37d84 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Startup.cs +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Startup.cs @@ -1,136 +1,102 @@ +/* + * Swagger Petstore + * + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + using System; +using System.Collections.Generic; using System.IO; using System.Linq; -using Microsoft.AspNet.Builder; -using Microsoft.AspNet.Hosting; +using System.Threading.Tasks; +using System.Xml.XPath; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.PlatformAbstractions; using Newtonsoft.Json.Serialization; -using Swashbuckle.SwaggerGen; -using Swashbuckle.SwaggerGen.XmlComments; +using Swashbuckle.Swagger.Model; +using Swashbuckle.SwaggerGen.Annotations; namespace IO.Swagger { public class Startup { private readonly IHostingEnvironment _hostingEnv; - private readonly IApplicationEnvironment _appEnv; - public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) + public IConfigurationRoot Configuration { get; } + + public Startup(IHostingEnvironment env) { _hostingEnv = env; - _appEnv = appEnv; - // Set up configuration sources. var builder = new ConfigurationBuilder() - .AddJsonFile("appsettings.json") + .SetBasePath(env.ContentRootPath) + .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) + .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } - - public IConfigurationRoot Configuration { get; set; } - + + // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { - string xmlComments = string.Format(@"{0}{4}artifacts{4}{1}{4}{2}{3}{4}IO.Swagger.xml", - GetSolutionBasePath(), - _appEnv.Configuration, - _appEnv.RuntimeFramework.Identifier.ToLower(), - _appEnv.RuntimeFramework.Version.ToString().Replace(".", string.Empty), - Path.DirectorySeparatorChar); - // Add framework services. services.AddMvc() .AddJsonOptions( opts => { opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }); - - // Uncomment the following line to add Web API services which makes it easier to port Web API 2 controllers. - // You will also need to add the Microsoft.AspNet.Mvc.WebApiCompatShim package to the 'dependencies' section of project.json. - // services.AddWebApiConventions(); - + services.AddSwaggerGen(); - services.ConfigureSwaggerDocument(options => + + services.ConfigureSwaggerGen(options => { options.SingleApiVersion(new Info { Version = "v1", Title = "IO.Swagger", - Description = "IO.Swagger (ASP.NET 5 Web API 2.x)" + Description = "IO.Swagger (ASP.NET Core 1.0)" }); - - options.OperationFilter(new ApplyXmlActionCommentsFixed(xmlComments)); - }); - services.ConfigureSwaggerSchema(options => { - options.DescribeAllEnumsAsStrings = true; - options.ModelFilter(new ApplyXmlTypeCommentsFixed(xmlComments)); + options.DescribeAllEnumsAsStrings(); + + var comments = new XPathDocument($"{AppContext.BaseDirectory}{Path.DirectorySeparatorChar}{_hostingEnv.ApplicationName}.xml"); + options.OperationFilter(comments); + options.ModelFilter(comments); }); + } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { - loggerFactory.MinimumLevel = LogLevel.Information; loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); - app.UseIISPlatformHandler(); - + app.UseMvc(); + app.UseDefaultFiles(); app.UseStaticFiles(); - app.UseMvc(); - - app.UseSwaggerGen(); + app.UseSwagger(); app.UseSwaggerUi(); } - - // Taken from https://github.com/domaindrivendev/Ahoy/blob/master/test/WebSites/Basic/Startup.cs - private string GetSolutionBasePath() - { - var dir = Directory.CreateDirectory(_appEnv.ApplicationBasePath); - while (dir.Parent != null) - { - if (dir.GetDirectories("artifacts").Any()) - return dir.FullName; - - dir = dir.Parent; - } - throw new InvalidOperationException("Failed to detect solution base path - artifacts not found. Did you run dnu pack --out artifacts?"); - } - - // Entry point for the application. - public static void Main(string[] args) => WebApplication.Run(args); - } - - - // using Swashbuckle.SwaggerGen.XmlComments; - public class ApplyXmlTypeCommentsFixed : ApplyXmlTypeComments - { - public ApplyXmlTypeCommentsFixed() : base("") - { - throw new NotImplementedException(); - } - - public ApplyXmlTypeCommentsFixed(string filePath): base(filePath) - { - - } - } - - public class ApplyXmlActionCommentsFixed : ApplyXmlActionComments - { - public ApplyXmlActionCommentsFixed() : base("") - { - throw new NotImplementedException(); - } - - public ApplyXmlActionCommentsFixed(string filePath): base(filePath) - { - - } } -} \ No newline at end of file +} diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/appsettings.json b/samples/server/petstore/aspnet5/src/IO.Swagger/appsettings.json index e5472e562b7..c6af7d9b069 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/appsettings.json +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/appsettings.json @@ -2,7 +2,7 @@ "Logging": { "IncludeScopes": false, "LogLevel": { - "Default": "Verbose", + "Default": "Information", "System": "Information", "Microsoft": "Information" } diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/project.json b/samples/server/petstore/aspnet5/src/IO.Swagger/project.json index 7317a7c0d0c..ca8ac967209 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/project.json +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/project.json @@ -1,41 +1,88 @@ { + "title": "Swagger UI", "version": "1.0.0-*", - "compilationOptions": { - "emitEntryPoint": true + "copyright": "IO.Swagger", + "description": "IO.Swagger", + "dependencies": { + "Microsoft.NETCore.App": { + "version": "1.0.0", + "type": "platform" + }, + "Microsoft.AspNetCore.Mvc": "1.0.0", + "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0", + "Microsoft.AspNetCore.Server.Kestrel": "1.0.0", + "Microsoft.AspNetCore.Server.Kestrel.Https": "1.0.0", + "Microsoft.AspNetCore.StaticFiles": "1.0.0", + "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0", + "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0", + "Microsoft.Extensions.Configuration.Json": "1.0.0", + "Microsoft.Extensions.Logging": "1.0.0", + "Microsoft.Extensions.Logging.Console": "1.0.0", + "Microsoft.Extensions.Logging.Debug": "1.0.0", + "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0", + "Microsoft.EntityFrameworkCore": "1.0.0", + "Swashbuckle.SwaggerGen": "6.0.0-beta901", + "Swashbuckle.SwaggerUi": "6.0.0-beta901" }, - "tooling": { - "defaultNamespace": "IO.Swagger" + + "tools": { + "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final", + + "Microsoft.Extensions.SecretManager.Tools": { + "imports": [ + "netstandard1.6", + "portable-net45+win8+dnxcore50", + "portable-net45+win8" + ], + "version": "1.0.0-preview2-final" + } }, - "dependencies": { - "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final", - "Microsoft.AspNet.Mvc": "6.0.0-rc1-final", - "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final", - "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final", - "Microsoft.Extensions.Configuration.FileProviderExtensions" : "1.0.0-rc1-final", - "Microsoft.Extensions.Logging": "1.0.0-rc1-final", - "Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final", - "Microsoft.Extensions.Logging.Debug" : "1.0.0-rc1-final", - "Swashbuckle.SwaggerGen": "6.0.0-rc1-final", - "Swashbuckle.SwaggerUi": "6.0.0-rc1-final" + "frameworks": { + "netcoreapp1.0": { + "imports": [ + "dotnet5.6", + "dnxcore50", + "netstandard1.6", + "portable-net452+win81" + ] + } }, - "commands": { - "web": "Microsoft.AspNet.Server.Kestrel --server.urls http://0.0.0.0:5000" + "buildOptions": { + "emitEntryPoint": true, + "preserveCompilationContext": true, + "xmlDoc": true, + "compile": { + "exclude": [ + "wwwroot", + "node_modules", + "bower_components" + ] + } }, - "frameworks": { - "dnx451": { }, - "dnxcore50": { } + "runtimeOptions": { + "configProperties": { + "System.GC.Server": true + } + }, + + "publishOptions": { + "include": [ + "wwwroot", + "Views", + "Areas/**/Views", + "appsettings.json", + "web.config" + ], + "exclude": [ + "**.user", + "**.vspscc" + ] }, - "exclude": [ - "wwwroot", - "node_modules", - "bower_components" - ], - "publishExclude": [ - "**.user", - "**.vspscc" - ] + "scripts": { + "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ] + } } diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/web.config b/samples/server/petstore/aspnet5/src/IO.Swagger/web.config new file mode 100644 index 00000000000..a3b9f6add9c --- /dev/null +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/web.config @@ -0,0 +1,14 @@ + + + + + + + + + + + + From a761682115d0667090c3f0b19d48fac65432ee65 Mon Sep 17 00:00:00 2001 From: cbornet Date: Tue, 5 Jul 2016 11:52:03 +0200 Subject: [PATCH 050/470] add a generator for spring cloud feign --- bin/spring-cloud-feign-petstore.sh | 34 +++ .../io/swagger/codegen/CodegenSecurity.java | 13 ++ .../io/swagger/codegen/DefaultCodegen.java | 17 ++ .../codegen/languages/SpringCodegen.java | 89 ++++++-- .../libraries/spring-cloud/README.mustache | 83 +++++++ .../libraries/spring-cloud/apiClient.mustache | 8 + .../apiKeyRequestInterceptor.mustache | 31 +++ .../spring-cloud/clientConfiguration.mustache | 105 +++++++++ .../libraries/spring-cloud/pom.mustache | 87 +++++++ .../options/SpringOptionsProvider.java | 2 + .../codegen/spring/SpringOptionsTest.java | 2 + .../spring-cloud/.swagger-codegen-ignore | 23 ++ samples/client/petstore/spring-cloud/LICENSE | 201 ++++++++++++++++ .../client/petstore/spring-cloud/README.md | 53 +++++ samples/client/petstore/spring-cloud/pom.xml | 76 +++++++ .../src/main/java/io/swagger/api/PetApi.java | 146 ++++++++++++ .../java/io/swagger/api/PetApiClient.java | 8 + .../main/java/io/swagger/api/StoreApi.java | 68 ++++++ .../java/io/swagger/api/StoreApiClient.java | 8 + .../src/main/java/io/swagger/api/UserApi.java | 107 +++++++++ .../java/io/swagger/api/UserApiClient.java | 8 + .../ApiKeyRequestInterceptor.java | 31 +++ .../configuration/ClientConfiguration.java | 49 ++++ .../main/java/io/swagger/model/Category.java | 93 ++++++++ .../io/swagger/model/ModelApiResponse.java | 113 +++++++++ .../src/main/java/io/swagger/model/Order.java | 196 ++++++++++++++++ .../src/main/java/io/swagger/model/Pet.java | 199 ++++++++++++++++ .../src/main/java/io/swagger/model/Tag.java | 93 ++++++++ .../src/main/java/io/swagger/model/User.java | 214 ++++++++++++++++++ 29 files changed, 2141 insertions(+), 16 deletions(-) create mode 100755 bin/spring-cloud-feign-petstore.sh create mode 100644 modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/README.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/apiClient.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/apiKeyRequestInterceptor.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/clientConfiguration.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/pom.mustache create mode 100644 samples/client/petstore/spring-cloud/.swagger-codegen-ignore create mode 100644 samples/client/petstore/spring-cloud/LICENSE create mode 100644 samples/client/petstore/spring-cloud/README.md create mode 100644 samples/client/petstore/spring-cloud/pom.xml create mode 100644 samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java create mode 100644 samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApiClient.java create mode 100644 samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/StoreApi.java create mode 100644 samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/StoreApiClient.java create mode 100644 samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/UserApi.java create mode 100644 samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/UserApiClient.java create mode 100644 samples/client/petstore/spring-cloud/src/main/java/io/swagger/configuration/ApiKeyRequestInterceptor.java create mode 100644 samples/client/petstore/spring-cloud/src/main/java/io/swagger/configuration/ClientConfiguration.java create mode 100644 samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Category.java create mode 100644 samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/ModelApiResponse.java create mode 100644 samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Order.java create mode 100644 samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Pet.java create mode 100644 samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Tag.java create mode 100644 samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/User.java diff --git a/bin/spring-cloud-feign-petstore.sh b/bin/spring-cloud-feign-petstore.sh new file mode 100755 index 00000000000..39f5bd03de1 --- /dev/null +++ b/bin/spring-cloud-feign-petstore.sh @@ -0,0 +1,34 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaSpring -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l spring -o samples/client/petstore/spring-cloud --library spring-cloud -DhideGenerationTimestamp=true" + +echo "Removing files and folders under samples/client/petstore/spring-cloud/src/main" +rm -rf samples/client/petstore/spring-cloud/src/main +find samples/client/petstore/spring-cloud -maxdepth 1 -type f ! -name "README.md" -exec rm {} + +java $JAVA_OPTS -jar $executable $ags diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenSecurity.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenSecurity.java index 2e33242c370..4e9dd098a4e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenSecurity.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenSecurity.java @@ -13,6 +13,7 @@ public class CodegenSecurity { // Oauth specific public String flow, authorizationUrl, tokenUrl; public List> scopes; + public Boolean isCode, isPassword, isApplication, isImplicit; @Override public String toString() { @@ -50,6 +51,14 @@ public boolean equals(Object o) { return false; if (tokenUrl != null ? !tokenUrl.equals(that.tokenUrl) : that.tokenUrl != null) return false; + if (isCode != null ? !isCode.equals(that.isCode) : that.isCode != null) + return false; + if (isPassword != null ? !isPassword.equals(that.isPassword) : that.isPassword != null) + return false; + if (isApplication != null ? !isApplication.equals(that.isApplication) : that.isApplication != null) + return false; + if (isImplicit != null ? !isImplicit.equals(that.isImplicit) : that.isImplicit != null) + return false; return scopes != null ? scopes.equals(that.scopes) : that.scopes == null; } @@ -68,6 +77,10 @@ public int hashCode() { result = 31 * result + (flow != null ? flow.hashCode() : 0); result = 31 * result + (authorizationUrl != null ? authorizationUrl.hashCode() : 0); result = 31 * result + (tokenUrl != null ? tokenUrl.hashCode() : 0); + result = 31 * result + (isCode != null ? isCode.hashCode() : 0); + result = 31 * result + (isPassword != null ? isPassword.hashCode() : 0); + result = 31 * result + (isApplication != null ? isApplication.hashCode() : 0); + result = 31 * result + (isImplicit != null ? isImplicit.hashCode() : 0); result = 31 * result + (scopes != null ? scopes.hashCode() : 0); return result; } 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 d2bb3aed879..1b6a3c015e8 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 @@ -2349,6 +2349,7 @@ public List fromSecurity(Map CodegenSecurity sec = CodegenModelFactory.newInstance(CodegenModelType.SECURITY); sec.name = entry.getKey(); sec.type = schemeDefinition.getType(); + sec.isCode = sec.isPassword = sec.isApplication = sec.isImplicit = false; if (schemeDefinition instanceof ApiKeyAuthDefinition) { final ApiKeyAuthDefinition apiKeyDefinition = (ApiKeyAuthDefinition) schemeDefinition; @@ -2365,6 +2366,22 @@ public List fromSecurity(Map sec.isKeyInHeader = sec.isKeyInQuery = sec.isApiKey = sec.isBasic = false; sec.isOAuth = true; sec.flow = oauth2Definition.getFlow(); + switch(sec.flow) { + case "accessCode": + sec.isCode = true; + break; + case "password": + sec.isPassword = true; + break; + case "application": + sec.isApplication = true; + break; + case "implicit": + sec.isImplicit = true; + break; + default: + throw new RuntimeException("unknown oauth flow: " + sec.flow); + } sec.authorizationUrl = oauth2Definition.getAuthorizationUrl(); sec.tokenUrl = oauth2Definition.getTokenUrl(); if (oauth2Definition.getScopes() != null) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java index 9a4ee3256ea..fc777ad97f1 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java @@ -11,13 +11,17 @@ public class SpringCodegen extends AbstractJavaCodegen { public static final String DEFAULT_LIBRARY = "spring-boot"; + public static final String TITLE = "title"; public static final String CONFIG_PACKAGE = "configPackage"; public static final String BASE_PACKAGE = "basePackage"; public static final String INTERFACE_ONLY = "interfaceOnly"; public static final String SINGLE_CONTENT_TYPES = "singleContentTypes"; public static final String JAVA_8 = "java8"; public static final String ASYNC = "async"; - protected String title = "Petstore Server"; + public static final String SPRING_MVC_LIBRARY = "spring-mvc"; + public static final String SPRING_CLOUD_LIBRARY = "spring-cloud"; + + protected String title = "swagger-petstore"; protected String configPackage = "io.swagger.configuration"; protected String basePackage = "io.swagger"; protected boolean interfaceOnly = false; @@ -33,12 +37,12 @@ public SpringCodegen() { apiPackage = "io.swagger.api"; modelPackage = "io.swagger.model"; invokerPackage = "io.swagger.api"; - artifactId = "swagger-spring-server"; + artifactId = "swagger-spring"; - additionalProperties.put("title", title); additionalProperties.put(CONFIG_PACKAGE, configPackage); additionalProperties.put(BASE_PACKAGE, basePackage); + cliOptions.add(new CliOption(TITLE, "server title name or client service name")); cliOptions.add(new CliOption(CONFIG_PACKAGE, "configuration package for generated code")); cliOptions.add(new CliOption(BASE_PACKAGE, "base package for generated code")); cliOptions.add(CliOption.newBoolean(INTERFACE_ONLY, "Whether to generate only API interface stubs without the server files.")); @@ -47,7 +51,8 @@ public SpringCodegen() { cliOptions.add(CliOption.newBoolean(ASYNC, "use async Callable controllers")); supportedLibraries.put(DEFAULT_LIBRARY, "Spring-boot Server application using the SpringFox integration."); - supportedLibraries.put("spring-mvc", "Spring-MVC Server application using the SpringFox integration."); + supportedLibraries.put(SPRING_MVC_LIBRARY, "Spring-MVC Server application using the SpringFox integration."); + supportedLibraries.put(SPRING_CLOUD_LIBRARY, "Spring-Cloud-Feign client with Spring-Boot auto-configured settings."); setLibrary(DEFAULT_LIBRARY); CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); @@ -82,6 +87,10 @@ public void processOpts() { modelDocTemplateFiles.remove("model_doc.mustache"); apiDocTemplateFiles.remove("api_doc.mustache"); + if (additionalProperties.containsKey(TITLE)) { + this.setTitle((String) additionalProperties.get(TITLE)); + } + if (additionalProperties.containsKey(CONFIG_PACKAGE)) { this.setConfigPackage((String) additionalProperties.get(CONFIG_PACKAGE)); } @@ -110,17 +119,6 @@ public void processOpts() { supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); if (!this.interfaceOnly) { - apiTemplateFiles.put("apiController.mustache", "Controller.java"); - supportingFiles.add(new SupportingFile("apiException.mustache", - (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java")); - supportingFiles.add(new SupportingFile("apiOriginFilter.mustache", - (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiOriginFilter.java")); - supportingFiles.add(new SupportingFile("apiResponseMessage.mustache", - (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java")); - supportingFiles.add(new SupportingFile("notFoundException.mustache", - (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java")); - supportingFiles.add(new SupportingFile("swaggerDocumentationConfig.mustache", - (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerDocumentationConfig.java")); if (library.equals(DEFAULT_LIBRARY)) { supportingFiles.add(new SupportingFile("homeController.mustache", (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "HomeController.java")); @@ -129,7 +127,7 @@ public void processOpts() { supportingFiles.add(new SupportingFile("application.properties", ("src.main.resources").replace(".", java.io.File.separator), "application.properties")); } - if (library.equals("spring-mvc")) { + if (library.equals(SPRING_MVC_LIBRARY)) { supportingFiles.add(new SupportingFile("webApplication.mustache", (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "WebApplication.java")); supportingFiles.add(new SupportingFile("webMvcConfiguration.mustache", @@ -139,6 +137,31 @@ public void processOpts() { supportingFiles.add(new SupportingFile("application.properties", ("src.main.resources").replace(".", java.io.File.separator), "swagger.properties")); } + if (library.equals(SPRING_CLOUD_LIBRARY)) { + supportingFiles.add(new SupportingFile("apiKeyRequestInterceptor.mustache", + (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "ApiKeyRequestInterceptor.java")); + supportingFiles.add(new SupportingFile("clientConfiguration.mustache", + (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "ClientConfiguration.java")); + apiTemplateFiles.put("apiClient.mustache", "Client.java"); + if (!additionalProperties.containsKey(SINGLE_CONTENT_TYPES)) { + additionalProperties.put(SINGLE_CONTENT_TYPES, "true"); + this.setSingleContentTypes(true); + + } + + } else { + apiTemplateFiles.put("apiController.mustache", "Controller.java"); + supportingFiles.add(new SupportingFile("apiException.mustache", + (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java")); + supportingFiles.add(new SupportingFile("apiResponseMessage.mustache", + (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java")); + supportingFiles.add(new SupportingFile("notFoundException.mustache", + (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java")); + supportingFiles.add(new SupportingFile("apiOriginFilter.mustache", + (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiOriginFilter.java")); + supportingFiles.add(new SupportingFile("swaggerDocumentationConfig.mustache", + (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerDocumentationConfig.java")); + } } if (this.java8) { @@ -182,6 +205,22 @@ public void preprocessSwagger(Swagger swagger) { swagger.setBasePath(""); } + if(!additionalProperties.containsKey(TITLE)) { + // From the title, compute a reasonable name for the package and the API + String title = swagger.getInfo().getTitle(); + + // Drop any API suffix + if (title != null) { + title = title.trim().replace(" ", "-"); + if (title.toUpperCase().endsWith("API")) { + title = title.substring(0, title.length() - 3); + } + + this.title = camelize(sanitizeName(title), true); + } + additionalProperties.put(TITLE, this.title); + } + String host = swagger.getHost(); String port = "8080"; if (host != null) { @@ -265,6 +304,19 @@ public Map postProcessOperations(Map objs) { return objs; } + @Override + public Map postProcessSupportingFileData(Map objs) { + if(library.equals(SPRING_CLOUD_LIBRARY)) { + List authMethods = (List) objs.get("authMethods"); + if (authMethods != null) { + for (CodegenSecurity authMethod : authMethods) { + authMethod.name = camelize(sanitizeName(authMethod.name), true); + } + } + } + return objs; + } + @Override public String toApiName(String name) { if (name.length() == 0) { @@ -274,6 +326,10 @@ public String toApiName(String name) { return camelize(name) + "Api"; } + public void setTitle(String title) { + this.title = title; + } + public void setConfigPackage(String configPackage) { this.configPackage = configPackage; } @@ -331,4 +387,5 @@ public Map postProcessModelsEnum(Map objs) { return objs; } + } diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/README.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/README.mustache new file mode 100644 index 00000000000..3130b070174 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/README.mustache @@ -0,0 +1,83 @@ +{{^interfaceOnly}} +# {{artifactId}} + +## Requirements + +Building the API client library requires [Maven](https://maven.apache.org/) to be installed. + +## Installation + +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. + +### Maven users + +Add this dependency to your project's POM: + +```xml + + {{{groupId}}} + {{{artifactId}}} + {{{artifactVersion}}} + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy +compile "{{{groupId}}}:{{{artifactId}}}:{{{artifactVersion}}}" +``` + +### Others + +At first generate the JAR by executing: + +mvn package + +Then manually install the following JARs: + +* target/{{{artifactId}}}-{{{artifactVersion}}}.jar +* target/lib/*.jar +{{/interfaceOnly}} +{{#interfaceOnly}} +# Swagger generated API stub + +Spring Framework stub + + +## Overview +This code was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. +By using the [OpenAPI-Spec](https://github.com/swagger-api/swagger-core), you can easily generate an API stub. +This is an example of building API stub interfaces in Java using the Spring framework. + +The stubs generated can be used in your existing Spring-MVC or Spring-Boot application to create controller endpoints +by adding ```@Controller``` classes that implement the interface. Eg: +```java +@Controller +public class PetController implements PetApi { +// implement all PetApi methods +} +``` + +You can also use the interface to create [Spring-Cloud Feign clients](http://projects.spring.io/spring-cloud/spring-cloud.html#spring-cloud-feign-inheritance).Eg: +```java +@FeignClient(name="pet", url="http://petstore.swagger.io/v2") +public interface PetClient extends PetApi { + +} +``` +{{/interfaceOnly}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/apiClient.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/apiClient.mustache new file mode 100644 index 00000000000..f14f27d6cca --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/apiClient.mustache @@ -0,0 +1,8 @@ +package {{package}}; + +import org.springframework.cloud.netflix.feign.FeignClient; +import {{configPackage}}.ClientConfiguration; + +@FeignClient(name="${ {{{title}}}.name:{{{title}}} }", url="${ {{{title}}}.url:{{{basePath}}} }", configuration = ClientConfiguration.class) +public interface {{classname}}Client extends {{classname}} { +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/apiKeyRequestInterceptor.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/apiKeyRequestInterceptor.mustache new file mode 100644 index 00000000000..a7835fc983d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/apiKeyRequestInterceptor.mustache @@ -0,0 +1,31 @@ +package {{configPackage}}; + +import feign.RequestInterceptor; +import feign.RequestTemplate; +import feign.Util; + + +public class ApiKeyRequestInterceptor implements RequestInterceptor { + private final String location; + private final String name; + private String value; + + public ApiKeyRequestInterceptor(String location, String name, String value) { + Util.checkNotNull(location, "location", new Object[0]); + Util.checkNotNull(name, "name", new Object[0]); + Util.checkNotNull(value, "value", new Object[0]); + this.location = location; + this.name = name; + this.value = value; + } + + @Override + public void apply(RequestTemplate requestTemplate) { + if(location.equals("header")) { + requestTemplate.header(name, value); + } else if(location.equals("query")) { + requestTemplate.query(name, value); + } + } + +} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/clientConfiguration.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/clientConfiguration.mustache new file mode 100644 index 00000000000..694ec034db5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/clientConfiguration.mustache @@ -0,0 +1,105 @@ +package {{configPackage}}; + +import feign.Logger; +import feign.auth.BasicAuthRequestInterceptor; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.cloud.security.oauth2.client.feign.OAuth2FeignRequestInterceptor; +import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext; +import org.springframework.security.oauth2.client.resource.BaseOAuth2ProtectedResourceDetails; +import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails; +import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails; +import org.springframework.security.oauth2.client.token.grant.implicit.ImplicitResourceDetails; +import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails; +import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; +import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; + +@Configuration +@EnableConfigurationProperties +public class ClientConfiguration { + +{{#authMethods}} + {{#isBasic}} + @Value("${ {{{title}}}.security.{{{name}}}.username }") + private String {{{name}}}Username; + + @Value("${ {{{title}}}.security.{{{name}}}.password }") + private String {{{name}}}Password; + + @Bean + @ConditionalOnProperty(name = "{{{title}}}.security.{{{name}}}.username") + public BasicAuthRequestInterceptor {{{name}}}RequestInterceptor() { + return new BasicAuthRequestInterceptor(this.{{{name}}}Username, this.{{{name}}}Password); + } + + {{/isBasic}} + {{#isApiKey}} + @Value("${ {{{title}}}.security.{{{name}}}.key }") + private String {{{name}}}Key; + + @Bean + @ConditionalOnProperty(name = "{{{title}}}.security.{{{name}}}.key") + public ApiKeyRequestInterceptor {{{name}}}RequestInterceptor() { + return new ApiKeyRequestInterceptor({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{{keyParamName}}}", this.{{{name}}}Key); + } + + {{/isApiKey}} + {{#isOAuth}} + @Bean + @ConditionalOnProperty("{{{title}}}.security.{{{name}}}.client-id") + public OAuth2FeignRequestInterceptor {{{name}}}RequestInterceptor() { + return new OAuth2FeignRequestInterceptor(new DefaultOAuth2ClientContext(), {{{name}}}ResourceDetails()); + } + + {{#isCode}} + @Bean + @ConditionalOnProperty("{{{title}}}.security.{{{name}}}.client-id") + @ConfigurationProperties("{{{title}}}.security.{{{name}}}") + public AuthorizationCodeResourceDetails {{{name}}}ResourceDetails() { + AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails(); + details.setAccessTokenUri("{{{tokenUrl}}}"); + details.setUserAuthorizationUri("{{{authorizationUrl}}}"); + return details; + } + + {{/isCode}} + {{#isPassword}} + @Bean + @ConditionalOnProperty("{{{title}}}.security.{{{name}}}.client-id") + @ConfigurationProperties("{{{title}}}.security.{{{name}}}") + public ResourceOwnerPasswordResourceDetails {{{name}}}ResourceDetails() { + ResourceOwnerPasswordResourceDetails details = new ResourceOwnerPasswordResourceDetails(); + details.setAccessTokenUri("{{{tokenUrl}}}"); + return details; + } + + {{/isPassword}} + {{#isApplication}} + @Bean + @ConditionalOnProperty("{{{title}}}.security.{{{name}}}.client-id") + @ConfigurationProperties("{{{title}}}.security.{{{name}}}") + public ClientCredentialsResourceDetails {{{name}}}ResourceDetails() { + ClientCredentialsResourceDetails details = new ClientCredentialsResourceDetails(); + details.setAccessTokenUri("{{{tokenUrl}}}"); + return details; + } + + {{/isApplication}} + {{#isImplicit}} + @Bean + @ConditionalOnProperty("{{{title}}}.security.{{{name}}}.client-id") + @ConfigurationProperties("{{{title}}}.security.{{{name}}}") + public ImplicitResourceDetails {{{name}}}ResourceDetails() { + ImplicitResourceDetails details = new ImplicitResourceDetails(); + details.setUserAuthorizationUri("{{{authorizationUrl}}}"); + return details; + } + + {{/isImplicit}} + {{/isOAuth}} +{{/authMethods}} +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/pom.mustache new file mode 100644 index 00000000000..022d49b2bc2 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/pom.mustache @@ -0,0 +1,87 @@ + + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + + {{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}} + ${java.version} + ${java.version} + 1.5.9 + + + org.springframework.boot + spring-boot-starter-parent + 1.3.5.RELEASE + + + src/main/java + {{^interfaceOnly}} + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + {{/interfaceOnly}} + + + + + + org.springframework.cloud + spring-cloud-starter-parent + Brixton.SR1 + pom + import + + + + + + + io.swagger + swagger-annotations + ${swagger-core-version} + + + org.springframework.cloud + spring-cloud-starter-feign + + + org.springframework.cloud + spring-cloud-security + + + org.springframework.security.oauth + spring-security-oauth2 + + {{#java8}} + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + {{/java8}} + {{^java8}} + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + + + joda-time + joda-time + + {{/java8}} + + \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringOptionsProvider.java index 3d56410f937..3cc8bfee148 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringOptionsProvider.java @@ -7,6 +7,7 @@ import java.util.Map; public class SpringOptionsProvider extends JavaOptionsProvider { + public static final String TITLE = "swagger"; public static final String CONFIG_PACKAGE_VALUE = "configPackage"; public static final String BASE_PACKAGE_VALUE = "basePackage"; public static final String LIBRARY_VALUE = "spring-mvc"; //FIXME hidding value from super class @@ -23,6 +24,7 @@ public String getLanguage() { @Override public Map createOptions() { Map options = new HashMap(super.createOptions()); + options.put(SpringCodegen.TITLE, TITLE); options.put(SpringCodegen.CONFIG_PACKAGE, CONFIG_PACKAGE_VALUE); options.put(SpringCodegen.BASE_PACKAGE, BASE_PACKAGE_VALUE); options.put(CodegenConstants.LIBRARY, LIBRARY_VALUE); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/spring/SpringOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/spring/SpringOptionsTest.java index 3693ab6c550..8adaa67679d 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/spring/SpringOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/spring/SpringOptionsTest.java @@ -50,6 +50,8 @@ protected void setExpectations() { times = 1; clientCodegen.setFullJavaUtil(Boolean.valueOf(SpringOptionsProvider.FULL_JAVA_UTIL_VALUE)); times = 1; + clientCodegen.setTitle(SpringOptionsProvider.TITLE); + times = 1; clientCodegen.setConfigPackage(SpringOptionsProvider.CONFIG_PACKAGE_VALUE); times = 1; clientCodegen.setBasePackage(SpringOptionsProvider.BASE_PACKAGE_VALUE); diff --git a/samples/client/petstore/spring-cloud/.swagger-codegen-ignore b/samples/client/petstore/spring-cloud/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore/spring-cloud/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/spring-cloud/LICENSE b/samples/client/petstore/spring-cloud/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/spring-cloud/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore/spring-cloud/README.md b/samples/client/petstore/spring-cloud/README.md new file mode 100644 index 00000000000..56d8781caad --- /dev/null +++ b/samples/client/petstore/spring-cloud/README.md @@ -0,0 +1,53 @@ +# swagger-spring + +## Requirements + +Building the API client library requires [Maven](https://maven.apache.org/) to be installed. + +## Installation + +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. + +### Maven users + +Add this dependency to your project's POM: + +```xml + + io.swagger + swagger-spring + 1.0.0 + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy +compile "io.swagger:swagger-spring:1.0.0" +``` + +### Others + +At first generate the JAR by executing: + +mvn package + +Then manually install the following JARs: + +* target/swagger-spring-1.0.0.jar +* target/lib/*.jar diff --git a/samples/client/petstore/spring-cloud/pom.xml b/samples/client/petstore/spring-cloud/pom.xml new file mode 100644 index 00000000000..20490f349a0 --- /dev/null +++ b/samples/client/petstore/spring-cloud/pom.xml @@ -0,0 +1,76 @@ + + 4.0.0 + io.swagger + swagger-spring + jar + swagger-spring + 1.0.0 + + 1.7 + ${java.version} + ${java.version} + 1.5.9 + + + org.springframework.boot + spring-boot-starter-parent + 1.3.5.RELEASE + + + src/main/java + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + + + + + + org.springframework.cloud + spring-cloud-starter-parent + Brixton.SR1 + pom + import + + + + + + + io.swagger + swagger-annotations + ${swagger-core-version} + + + org.springframework.cloud + spring-cloud-starter-feign + + + org.springframework.cloud + spring-cloud-security + + + org.springframework.security.oauth + spring-security-oauth2 + + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + + + joda-time + joda-time + + + \ No newline at end of file diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java new file mode 100644 index 00000000000..9dcc45da00d --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java @@ -0,0 +1,146 @@ +package io.swagger.api; + +import io.swagger.model.Pet; +import io.swagger.model.ModelApiResponse; +import java.io.File; + +import io.swagger.annotations.*; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + + +@Api(value = "pet", description = "the pet API") +public interface PetApi { + + @ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) + @RequestMapping(value = "/pet", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.POST) + ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body); + + + @ApiOperation(value = "Deletes a pet", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid pet value", response = Void.class) }) + @RequestMapping(value = "/pet/{petId}", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.DELETE) + ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId,@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey); + + + @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @ApiResponse(code = 400, message = "Invalid status value", response = Pet.class) }) + @RequestMapping(value = "/pet/findByStatus", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.GET) + ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true) @RequestParam(value = "status", required = true) List status); + + + @ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class) }) + @RequestMapping(value = "/pet/findByTags", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.GET) + ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags); + + + @ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { + @Authorization(value = "api_key") + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), + @ApiResponse(code = 404, message = "Pet not found", response = Pet.class) }) + @RequestMapping(value = "/pet/{petId}", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.GET) + ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId); + + + @ApiOperation(value = "Update an existing pet", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), + @ApiResponse(code = 404, message = "Pet not found", response = Void.class), + @ApiResponse(code = 405, message = "Validation exception", response = Void.class) }) + @RequestMapping(value = "/pet", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.PUT) + ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body); + + + @ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) + @RequestMapping(value = "/pet/{petId}", + produces = "application/json", + consumes = "application/x-www-form-urlencoded", + method = RequestMethod.POST) + ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId,@ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name,@ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status); + + + @ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) + @RequestMapping(value = "/pet/{petId}/uploadImage", + produces = "application/json", + consumes = "multipart/form-data", + method = RequestMethod.POST) + ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId,@ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata,@ApiParam(value = "file detail") @RequestPart("file") MultipartFile file); + +} diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApiClient.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApiClient.java new file mode 100644 index 00000000000..01bf75e9151 --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApiClient.java @@ -0,0 +1,8 @@ +package io.swagger.api; + +import org.springframework.cloud.netflix.feign.FeignClient; +import io.swagger.configuration.ClientConfiguration; + +@FeignClient(name="${ swaggerPetstore.name:swaggerPetstore }", url="${ swaggerPetstore.url:http://petstore.swagger.io/v2 }", configuration = ClientConfiguration.class) +public interface PetApiClient extends PetApi { +} \ No newline at end of file diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/StoreApi.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/StoreApi.java new file mode 100644 index 00000000000..1eb724e96c9 --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/StoreApi.java @@ -0,0 +1,68 @@ +package io.swagger.api; + +import java.util.Map; +import io.swagger.model.Order; + +import io.swagger.annotations.*; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + + +@Api(value = "store", description = "the store API") +public interface StoreApi { + + @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class, tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), + @ApiResponse(code = 404, message = "Order not found", response = Void.class) }) + @RequestMapping(value = "/store/order/{orderId}", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.DELETE) + ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId); + + + @ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { + @Authorization(value = "api_key") + }, tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Integer.class) }) + @RequestMapping(value = "/store/inventory", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.GET) + ResponseEntity> getInventory(); + + + @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Order.class), + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), + @ApiResponse(code = 404, message = "Order not found", response = Order.class) }) + @RequestMapping(value = "/store/order/{orderId}", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.GET) + ResponseEntity getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId); + + + @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Order.class), + @ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) + @RequestMapping(value = "/store/order", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.POST) + ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body); + +} diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/StoreApiClient.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/StoreApiClient.java new file mode 100644 index 00000000000..399a16d0b5a --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/StoreApiClient.java @@ -0,0 +1,8 @@ +package io.swagger.api; + +import org.springframework.cloud.netflix.feign.FeignClient; +import io.swagger.configuration.ClientConfiguration; + +@FeignClient(name="${ swaggerPetstore.name:swaggerPetstore }", url="${ swaggerPetstore.url:http://petstore.swagger.io/v2 }", configuration = ClientConfiguration.class) +public interface StoreApiClient extends StoreApi { +} \ No newline at end of file diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/UserApi.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/UserApi.java new file mode 100644 index 00000000000..cf96ef50a4a --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/UserApi.java @@ -0,0 +1,107 @@ +package io.swagger.api; + +import io.swagger.model.User; +import java.util.List; + +import io.swagger.annotations.*; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + + +@Api(value = "user", description = "the user API") +public interface UserApi { + + @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/user", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.POST) + ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body); + + + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/user/createWithArray", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.POST) + ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body); + + + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/user/createWithList", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.POST) + ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body); + + + @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), + @ApiResponse(code = 404, message = "User not found", response = Void.class) }) + @RequestMapping(value = "/user/{username}", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.DELETE) + ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username); + + + @ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = User.class), + @ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), + @ApiResponse(code = 404, message = "User not found", response = User.class) }) + @RequestMapping(value = "/user/{username}", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.GET) + ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username); + + + @ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = String.class), + @ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) + @RequestMapping(value = "/user/login", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.GET) + ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username,@ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password); + + + @ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/user/logout", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.GET) + ResponseEntity logoutUser(); + + + @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid user supplied", response = Void.class), + @ApiResponse(code = 404, message = "User not found", response = Void.class) }) + @RequestMapping(value = "/user/{username}", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.PUT) + ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username,@ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body); + +} diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/UserApiClient.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/UserApiClient.java new file mode 100644 index 00000000000..38ce88e96d7 --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/UserApiClient.java @@ -0,0 +1,8 @@ +package io.swagger.api; + +import org.springframework.cloud.netflix.feign.FeignClient; +import io.swagger.configuration.ClientConfiguration; + +@FeignClient(name="${ swaggerPetstore.name:swaggerPetstore }", url="${ swaggerPetstore.url:http://petstore.swagger.io/v2 }", configuration = ClientConfiguration.class) +public interface UserApiClient extends UserApi { +} \ No newline at end of file diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/configuration/ApiKeyRequestInterceptor.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/configuration/ApiKeyRequestInterceptor.java new file mode 100644 index 00000000000..b83fd9c6bac --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/configuration/ApiKeyRequestInterceptor.java @@ -0,0 +1,31 @@ +package io.swagger.configuration; + +import feign.RequestInterceptor; +import feign.RequestTemplate; +import feign.Util; + + +public class ApiKeyRequestInterceptor implements RequestInterceptor { + private final String location; + private final String name; + private String value; + + public ApiKeyRequestInterceptor(String location, String name, String value) { + Util.checkNotNull(location, "location", new Object[0]); + Util.checkNotNull(name, "name", new Object[0]); + Util.checkNotNull(value, "value", new Object[0]); + this.location = location; + this.name = name; + this.value = value; + } + + @Override + public void apply(RequestTemplate requestTemplate) { + if(location.equals("header")) { + requestTemplate.header(name, value); + } else if(location.equals("query")) { + requestTemplate.query(name, value); + } + } + +} diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/configuration/ClientConfiguration.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/configuration/ClientConfiguration.java new file mode 100644 index 00000000000..a0e14b2bd38 --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/configuration/ClientConfiguration.java @@ -0,0 +1,49 @@ +package io.swagger.configuration; + +import feign.Logger; +import feign.auth.BasicAuthRequestInterceptor; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.cloud.security.oauth2.client.feign.OAuth2FeignRequestInterceptor; +import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext; +import org.springframework.security.oauth2.client.resource.BaseOAuth2ProtectedResourceDetails; +import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails; +import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails; +import org.springframework.security.oauth2.client.token.grant.implicit.ImplicitResourceDetails; +import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails; +import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; +import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; + +@Configuration +@EnableConfigurationProperties +public class ClientConfiguration { + + @Bean + @ConditionalOnProperty("swaggerPetstore.security.petstoreAuth.client-id") + public OAuth2FeignRequestInterceptor petstoreAuthRequestInterceptor() { + return new OAuth2FeignRequestInterceptor(new DefaultOAuth2ClientContext(), petstoreAuthResourceDetails()); + } + + @Bean + @ConditionalOnProperty("swaggerPetstore.security.petstoreAuth.client-id") + @ConfigurationProperties("swaggerPetstore.security.petstoreAuth") + public ImplicitResourceDetails petstoreAuthResourceDetails() { + ImplicitResourceDetails details = new ImplicitResourceDetails(); + details.setUserAuthorizationUri("http://petstore.swagger.io/api/oauth/dialog"); + return details; + } + + @Value("${ swaggerPetstore.security.apiKey.key }") + private String apiKeyKey; + + @Bean + @ConditionalOnProperty(name = "swaggerPetstore.security.apiKey.key") + public ApiKeyRequestInterceptor apiKeyRequestInterceptor() { + return new ApiKeyRequestInterceptor("header", "api_key", this.apiKeyKey); + } + +} \ No newline at end of file diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Category.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Category.java new file mode 100644 index 00000000000..67bc75b3b10 --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Category.java @@ -0,0 +1,93 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + + +public class Category { + + private Long id = null; + private String name = null; + + /** + **/ + public Category id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + public Category name(String name) { + this.name = name; + return this; + } + + + @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(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/ModelApiResponse.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/ModelApiResponse.java new file mode 100644 index 00000000000..5e3aa82bbee --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/ModelApiResponse.java @@ -0,0 +1,113 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + + +public class ModelApiResponse { + + private Integer code = null; + private String type = null; + private String message = null; + + /** + **/ + public ModelApiResponse code(Integer code) { + this.code = code; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("code") + public Integer getCode() { + return code; + } + public void setCode(Integer code) { + this.code = code; + } + + /** + **/ + public ModelApiResponse type(String type) { + this.type = type; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("type") + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + + /** + **/ + public ModelApiResponse message(String message) { + this.message = message; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("message") + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(code, _apiResponse.code) && + Objects.equals(type, _apiResponse.type) && + Objects.equals(message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Order.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Order.java new file mode 100644 index 00000000000..55859fc4089 --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Order.java @@ -0,0 +1,196 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.joda.time.DateTime; + + + + + + +public class Order { + + private Long id = null; + private Long petId = null; + private Integer quantity = null; + private DateTime 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 = false; + + /** + **/ + public Order id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + public Order petId(Long petId) { + this.petId = petId; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("petId") + public Long getPetId() { + return petId; + } + public void setPetId(Long petId) { + this.petId = petId; + } + + /** + **/ + public Order quantity(Integer quantity) { + this.quantity = quantity; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("quantity") + public Integer getQuantity() { + return quantity; + } + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + /** + **/ + public Order shipDate(DateTime shipDate) { + this.shipDate = shipDate; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("shipDate") + public DateTime getShipDate() { + return shipDate; + } + public void setShipDate(DateTime shipDate) { + this.shipDate = shipDate; + } + + /** + * Order Status + **/ + public Order status(StatusEnum status) { + this.status = status; + return this; + } + + + @ApiModelProperty(value = "Order Status") + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + /** + **/ + public Order complete(Boolean complete) { + this.complete = complete; + return this; + } + + + @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(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Pet.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Pet.java new file mode 100644 index 00000000000..24092cbee25 --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Pet.java @@ -0,0 +1,199 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Category; +import io.swagger.model.Tag; +import java.util.ArrayList; +import java.util.List; + + + + + + +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; + + /** + **/ + public Pet id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + public Pet category(Category category) { + this.category = category; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("category") + public Category getCategory() { + return category; + } + public void setCategory(Category category) { + this.category = category; + } + + /** + **/ + public Pet name(String name) { + this.name = name; + return this; + } + + + @ApiModelProperty(example = "doggie", required = true, value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + /** + **/ + public Pet photoUrls(List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + + @ApiModelProperty(required = true, value = "") + @JsonProperty("photoUrls") + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + /** + **/ + public Pet tags(List tags) { + this.tags = tags; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("tags") + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + + /** + * pet status in the store + **/ + public Pet status(StatusEnum status) { + this.status = status; + return this; + } + + + @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(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Tag.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Tag.java new file mode 100644 index 00000000000..f26d84e74b2 --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Tag.java @@ -0,0 +1,93 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + + +public class Tag { + + private Long id = null; + private String name = null; + + /** + **/ + public Tag id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + public Tag name(String name) { + this.name = name; + return this; + } + + + @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(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/User.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/User.java new file mode 100644 index 00000000000..5dc291a7889 --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/User.java @@ -0,0 +1,214 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + + +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; + + /** + **/ + public User id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + public User username(String username) { + this.username = username; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("username") + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + + /** + **/ + public User firstName(String firstName) { + this.firstName = firstName; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("firstName") + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + /** + **/ + public User lastName(String lastName) { + this.lastName = lastName; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("lastName") + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } + + /** + **/ + public User email(String email) { + this.email = email; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("email") + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + + /** + **/ + public User password(String password) { + this.password = password; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("password") + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + + /** + **/ + public User phone(String phone) { + this.phone = phone; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("phone") + public String getPhone() { + return phone; + } + public void setPhone(String phone) { + this.phone = phone; + } + + /** + * User Status + **/ + public User userStatus(Integer userStatus) { + this.userStatus = userStatus; + return this; + } + + + @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(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + From 412022b852670b363dab6094aadb06ea660b690b Mon Sep 17 00:00:00 2001 From: cbornet Date: Wed, 6 Jul 2016 10:28:34 +0200 Subject: [PATCH 051/470] add petstore samples and fix some issues --- bin/spring-cloud-feign-petstore.sh | 2 +- .../libraries/spring-cloud/apiClient.mustache | 2 +- .../spring-cloud/clientConfiguration.mustache | 6 +- .../spring-cloud/formParams.mustache | 1 + .../libraries/spring-cloud/pom.mustache | 9 +- samples/client/petstore/spring-cloud/pom.xml | 9 +- .../src/main/java/io/swagger/api/PetApi.java | 4 +- .../java/io/swagger/api/PetApiClient.java | 2 +- .../java/io/swagger/api/StoreApiClient.java | 2 +- .../java/io/swagger/api/UserApiClient.java | 2 +- .../configuration/ClientConfiguration.java | 2 +- .../src/test/java/io/swagger/TestUtils.java | 17 ++ .../test/java/io/swagger/api/PetApiTest.java | 205 ++++++++++++++++++ .../java/io/swagger/api/StoreApiTest.java | 89 ++++++++ .../test/java/io/swagger/api/UserApiTest.java | 97 +++++++++ .../src/test/resources/application.yml | 10 + 16 files changed, 444 insertions(+), 15 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/formParams.mustache create mode 100644 samples/client/petstore/spring-cloud/src/test/java/io/swagger/TestUtils.java create mode 100644 samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/PetApiTest.java create mode 100644 samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/StoreApiTest.java create mode 100644 samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/UserApiTest.java create mode 100644 samples/client/petstore/spring-cloud/src/test/resources/application.yml diff --git a/bin/spring-cloud-feign-petstore.sh b/bin/spring-cloud-feign-petstore.sh index 39f5bd03de1..e2cafebda84 100755 --- a/bin/spring-cloud-feign-petstore.sh +++ b/bin/spring-cloud-feign-petstore.sh @@ -26,7 +26,7 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaSpring -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l spring -o samples/client/petstore/spring-cloud --library spring-cloud -DhideGenerationTimestamp=true" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l spring -o samples/client/petstore/spring-cloud --library spring-cloud -DhideGenerationTimestamp=true" echo "Removing files and folders under samples/client/petstore/spring-cloud/src/main" rm -rf samples/client/petstore/spring-cloud/src/main diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/apiClient.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/apiClient.mustache index f14f27d6cca..57d227f6bbb 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/apiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/apiClient.mustache @@ -3,6 +3,6 @@ package {{package}}; import org.springframework.cloud.netflix.feign.FeignClient; import {{configPackage}}.ClientConfiguration; -@FeignClient(name="${ {{{title}}}.name:{{{title}}} }", url="${ {{{title}}}.url:{{{basePath}}} }", configuration = ClientConfiguration.class) +@FeignClient(name="${ {{{title}}}.name:{{{title}}}}", url="${ {{{title}}}.url:{{{basePath}}}}", configuration = ClientConfiguration.class) public interface {{classname}}Client extends {{classname}} { } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/clientConfiguration.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/clientConfiguration.mustache index 694ec034db5..2437b30237e 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/clientConfiguration.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/clientConfiguration.mustache @@ -24,10 +24,10 @@ public class ClientConfiguration { {{#authMethods}} {{#isBasic}} - @Value("${ {{{title}}}.security.{{{name}}}.username }") + @Value("${ {{{title}}}.security.{{{name}}}.username:}") private String {{{name}}}Username; - @Value("${ {{{title}}}.security.{{{name}}}.password }") + @Value("${ {{{title}}}.security.{{{name}}}.password:}") private String {{{name}}}Password; @Bean @@ -38,7 +38,7 @@ public class ClientConfiguration { {{/isBasic}} {{#isApiKey}} - @Value("${ {{{title}}}.security.{{{name}}}.key }") + @Value("${ {{{title}}}.security.{{{name}}}.key:}") private String {{{name}}}Key; @Bean diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/formParams.mustache new file mode 100644 index 00000000000..e7547a3ba19 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/formParams.mustache @@ -0,0 +1 @@ +{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestParam(value="{{paramName}}"{{#required}}, required=true{{/required}}{{^required}}, required=false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}@ApiParam(value = "file detail") @RequestParam("file") MultipartFile {{baseName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/pom.mustache index 022d49b2bc2..bec76800557 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/pom.mustache @@ -14,7 +14,7 @@ org.springframework.boot spring-boot-starter-parent - 1.3.5.RELEASE + 1.3.6.RELEASE src/main/java @@ -40,7 +40,7 @@ org.springframework.cloud spring-cloud-starter-parent - Brixton.SR1 + Brixton.SR2 pom import @@ -83,5 +83,10 @@ joda-time {{/java8}} + + org.springframework.boot + spring-boot-starter-test + test + \ No newline at end of file diff --git a/samples/client/petstore/spring-cloud/pom.xml b/samples/client/petstore/spring-cloud/pom.xml index 20490f349a0..52e3be061db 100644 --- a/samples/client/petstore/spring-cloud/pom.xml +++ b/samples/client/petstore/spring-cloud/pom.xml @@ -14,7 +14,7 @@ org.springframework.boot spring-boot-starter-parent - 1.3.5.RELEASE + 1.3.6.RELEASE src/main/java @@ -38,7 +38,7 @@ org.springframework.cloud spring-cloud-starter-parent - Brixton.SR1 + Brixton.SR2 pom import @@ -72,5 +72,10 @@ joda-time joda-time + + org.springframework.boot + spring-boot-starter-test + test + \ No newline at end of file diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java index 9dcc45da00d..81fea00fe73 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java @@ -126,7 +126,7 @@ public interface PetApi { produces = "application/json", consumes = "application/x-www-form-urlencoded", method = RequestMethod.POST) - ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId,@ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name,@ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status); + ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId,@ApiParam(value = "Updated name of the pet" ) @RequestParam(value="name", required=false) String name,@ApiParam(value = "Updated status of the pet" ) @RequestParam(value="status", required=false) String status); @ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = { @@ -141,6 +141,6 @@ public interface PetApi { produces = "application/json", consumes = "multipart/form-data", method = RequestMethod.POST) - ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId,@ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata,@ApiParam(value = "file detail") @RequestPart("file") MultipartFile file); + ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId,@ApiParam(value = "Additional data to pass to server" ) @RequestParam(value="additionalMetadata", required=false) String additionalMetadata,@ApiParam(value = "file detail") @RequestParam("file") MultipartFile file); } diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApiClient.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApiClient.java index 01bf75e9151..4b65141b5c1 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApiClient.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApiClient.java @@ -3,6 +3,6 @@ import org.springframework.cloud.netflix.feign.FeignClient; import io.swagger.configuration.ClientConfiguration; -@FeignClient(name="${ swaggerPetstore.name:swaggerPetstore }", url="${ swaggerPetstore.url:http://petstore.swagger.io/v2 }", configuration = ClientConfiguration.class) +@FeignClient(name="${ swaggerPetstore.name:swaggerPetstore}", url="${ swaggerPetstore.url:http://petstore.swagger.io/v2}", configuration = ClientConfiguration.class) public interface PetApiClient extends PetApi { } \ No newline at end of file diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/StoreApiClient.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/StoreApiClient.java index 399a16d0b5a..2f43ae1839f 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/StoreApiClient.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/StoreApiClient.java @@ -3,6 +3,6 @@ import org.springframework.cloud.netflix.feign.FeignClient; import io.swagger.configuration.ClientConfiguration; -@FeignClient(name="${ swaggerPetstore.name:swaggerPetstore }", url="${ swaggerPetstore.url:http://petstore.swagger.io/v2 }", configuration = ClientConfiguration.class) +@FeignClient(name="${ swaggerPetstore.name:swaggerPetstore}", url="${ swaggerPetstore.url:http://petstore.swagger.io/v2}", configuration = ClientConfiguration.class) public interface StoreApiClient extends StoreApi { } \ No newline at end of file diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/UserApiClient.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/UserApiClient.java index 38ce88e96d7..45c00ef8adc 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/UserApiClient.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/UserApiClient.java @@ -3,6 +3,6 @@ import org.springframework.cloud.netflix.feign.FeignClient; import io.swagger.configuration.ClientConfiguration; -@FeignClient(name="${ swaggerPetstore.name:swaggerPetstore }", url="${ swaggerPetstore.url:http://petstore.swagger.io/v2 }", configuration = ClientConfiguration.class) +@FeignClient(name="${ swaggerPetstore.name:swaggerPetstore}", url="${ swaggerPetstore.url:http://petstore.swagger.io/v2}", configuration = ClientConfiguration.class) public interface UserApiClient extends UserApi { } \ No newline at end of file diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/configuration/ClientConfiguration.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/configuration/ClientConfiguration.java index a0e14b2bd38..b0816e2d6e9 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/configuration/ClientConfiguration.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/configuration/ClientConfiguration.java @@ -37,7 +37,7 @@ public ImplicitResourceDetails petstoreAuthResourceDetails() { return details; } - @Value("${ swaggerPetstore.security.apiKey.key }") + @Value("${ swaggerPetstore.security.apiKey.key:}") private String apiKeyKey; @Bean diff --git a/samples/client/petstore/spring-cloud/src/test/java/io/swagger/TestUtils.java b/samples/client/petstore/spring-cloud/src/test/java/io/swagger/TestUtils.java new file mode 100644 index 00000000000..bf5a476ab29 --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/test/java/io/swagger/TestUtils.java @@ -0,0 +1,17 @@ +package io.swagger; + +import java.util.Random; +import java.util.concurrent.atomic.AtomicLong; + +public class TestUtils { + private static final AtomicLong atomicId = createAtomicId(); + + public static long nextId() { + return atomicId.getAndIncrement(); + } + + private static AtomicLong createAtomicId() { + int baseId = new Random(System.currentTimeMillis()).nextInt(1000000) + 20000; + return new AtomicLong((long) baseId); + } +} diff --git a/samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/PetApiTest.java b/samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/PetApiTest.java new file mode 100644 index 00000000000..2bb84d5bdae --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/PetApiTest.java @@ -0,0 +1,205 @@ +package io.swagger.api; + +import feign.FeignException; +import io.swagger.TestUtils; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import io.swagger.model.Category; +import io.swagger.model.Pet; +import io.swagger.model.Tag; +import org.junit.*; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.cloud.netflix.feign.EnableFeignClients; +import org.springframework.http.ResponseEntity; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import static org.junit.Assert.*; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(classes = PetApiTest.Application.class) +public class PetApiTest { + + @Autowired + private PetApiClient client; + + @Test + public void testCreateAndGetPet() { + Pet pet = createRandomPet(); + client.addPet(pet); + ResponseEntity rp = client.getPetById(pet.getId()); + Pet fetched = rp.getBody(); + 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"); + + client.updatePet(pet); + + Pet fetched = client.getPetById(pet.getId()).getBody(); + 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); + + client.updatePet(pet); + + List pets = client.findPetsByStatus(Arrays.asList(new String[]{"available"})).getBody(); + 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); + + client.updatePet(pet); + + List pets = client.findPetsByTags(Arrays.asList(new String[]{"friendly"})).getBody(); + 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"); + client.addPet(pet); + + Pet fetched = client.getPetById(pet.getId()).getBody(); + + client.updatePetWithForm(fetched.getId(), "furt", null); + Pet updated = client.getPetById(fetched.getId()).getBody(); + + assertEquals(updated.getName(), "furt"); + } + + @Test + public void testDeletePet() throws Exception { + Pet pet = createRandomPet(); + client.addPet(pet); + + Pet fetched = client.getPetById(pet.getId()).getBody(); + client.deletePet(fetched.getId(), null); + + try { + client.getPetById(fetched.getId()); + fail("expected an error"); + } catch (FeignException e) { + assertTrue(e.getMessage().startsWith("status 404 ")); + } + } + + @Ignore("Multipart form is not supported by spring-cloud yet.") + @Test + public void testUploadFile() throws Exception { + Pet pet = createRandomPet(); + client.addPet(pet); + + MockMultipartFile filePart = new MockMultipartFile("file", "bar".getBytes()); + client.uploadFile(pet.getId(), "a test file", filePart); + } + + @Test + public void testEqualsAndHashCode() { + Pet pet1 = new Pet(); + Pet pet2 = new Pet(); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + + pet2.setName("really-happy"); + pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertFalse(pet1.equals(pet2)); + assertFalse(pet2.equals(pet1)); + assertFalse(pet1.hashCode() == (pet2.hashCode())); + assertTrue(pet2.equals(pet2)); + assertTrue(pet2.hashCode() == pet2.hashCode()); + + pet1.setName("really-happy"); + pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + } + + private Pet createRandomPet() { + Pet pet = new Pet(); + pet.setId(TestUtils.nextId()); + pet.setName("gorilla"); + + Category category = new Category(); + category.setName("really-happy"); + + pet.setCategory(category); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); + pet.setPhotoUrls(photos); + + return pet; + } + + + @SpringBootApplication + @EnableFeignClients + protected static class Application { + public static void main(String[] args) { + new SpringApplicationBuilder(Application.class).run(args); + } + } + + + + + + +} diff --git a/samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/StoreApiTest.java b/samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/StoreApiTest.java new file mode 100644 index 00000000000..223289baf15 --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/StoreApiTest.java @@ -0,0 +1,89 @@ +package io.swagger.api; + +import feign.FeignException; +import io.swagger.TestUtils; +import io.swagger.model.Order; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.cloud.netflix.feign.EnableFeignClients; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.lang.reflect.Field; +import java.util.Map; + +import static org.junit.Assert.*; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(classes = StoreApiTest.Application.class) +public class StoreApiTest { + + @Autowired + private StoreApiClient client; + + @Test + public void testGetInventory() { + Map inventory = client.getInventory().getBody(); + assertTrue(inventory.keySet().size() > 0); + } + + @Test + public void testPlaceOrder() { + Order order = createOrder(); + client.placeOrder(order); + + Order fetched = client.getOrderById(order.getId()).getBody(); + assertEquals(order.getId(), fetched.getId()); + assertEquals(order.getPetId(), fetched.getPetId()); + assertEquals(order.getQuantity(), fetched.getQuantity()); + assertEquals(order.getShipDate().toInstant(), fetched.getShipDate().toInstant()); + } + + @Test + public void testDeleteOrder() { + Order order = createOrder(); + client.placeOrder(order); + + Order fetched = client.getOrderById(order.getId()).getBody(); + assertEquals(fetched.getId(), order.getId()); + + client.deleteOrder(String.valueOf(order.getId())); + + try { + client.getOrderById(order.getId()); + fail("expected an error"); + } catch (FeignException e) { + assertTrue(e.getMessage().startsWith("status 404 ")); + } + } + + private Order createOrder() { + Order order = new Order(); + order.setPetId(new Long(200)); + order.setQuantity(new Integer(13)); + order.setShipDate(org.joda.time.DateTime.now()); + order.setStatus(Order.StatusEnum.PLACED); + order.setComplete(true); + + try { + Field idField = Order.class.getDeclaredField("id"); + idField.setAccessible(true); + idField.set(order, TestUtils.nextId()); + } catch (Exception e) { + throw new RuntimeException(e); + } + + return order; + } + + @SpringBootApplication + @EnableFeignClients + protected static class Application { + public static void main(String[] args) { + new SpringApplicationBuilder(StoreApiTest.Application.class).run(args); + } + } +} diff --git a/samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/UserApiTest.java b/samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/UserApiTest.java new file mode 100644 index 00000000000..4fb9b5e1a12 --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/UserApiTest.java @@ -0,0 +1,97 @@ +package io.swagger.api; + +import io.swagger.TestUtils; +import io.swagger.model.User; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.cloud.netflix.feign.EnableFeignClients; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.util.Arrays; + +import static org.junit.Assert.*; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(classes = UserApiTest.Application.class) + +public class UserApiTest { + + @Autowired + private UserApiClient client; + + @Test + public void testCreateUser() { + User user = createUser(); + + client.createUser(user); + + User fetched = client.getUserByName(user.getUsername()).getBody(); + assertEquals(user.getId(), fetched.getId()); + } + + @Test + public void testCreateUsersWithArray() { + User user1 = createUser(); + user1.setUsername("user" + user1.getId()); + User user2 = createUser(); + user2.setUsername("user" + user2.getId()); + + client.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = client.getUserByName(user1.getUsername()).getBody(); + assertEquals(user1.getId(), fetched.getId()); + } + + @Test + public void testCreateUsersWithList() { + User user1 = createUser(); + user1.setUsername("user" + user1.getId()); + User user2 = createUser(); + user2.setUsername("user" + user2.getId()); + + client.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = client.getUserByName(user1.getUsername()).getBody(); + assertEquals(user1.getId(), fetched.getId()); + } + + @Test + public void testLoginUser() { + User user = createUser(); + client.createUser(user); + + String token = client.loginUser(user.getUsername(), user.getPassword()).getBody(); + assertTrue(token.startsWith("logged in user session:")); + } + + @Test + public void logoutUser() { + client.logoutUser(); + } + + private User createUser() { + User user = new User(); + user.setId(TestUtils.nextId()); + user.setUsername("fred"); + user.setFirstName("Fred"); + user.setLastName("Meyer"); + user.setEmail("fred@fredmeyer.com"); + user.setPassword("xxXXxx"); + user.setPhone("408-867-5309"); + user.setUserStatus(123); + + return user; + } + + @SpringBootApplication + @EnableFeignClients + protected static class Application { + public static void main(String[] args) { + new SpringApplicationBuilder(UserApiTest.Application.class).run(args); + } + } +} diff --git a/samples/client/petstore/spring-cloud/src/test/resources/application.yml b/samples/client/petstore/spring-cloud/src/test/resources/application.yml new file mode 100644 index 00000000000..07a52419295 --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/test/resources/application.yml @@ -0,0 +1,10 @@ +spring: + application: + name: petstore-test + +feign.hystrix.enabled: false + +logging.level.io.swagger.api: + PetApiClient: DEBUG + StoreApiClient: DEBUG + UserApiClient: DEBUG From f7b223e1a92a2ce0fb36c09aab831994698687cd Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 6 Jul 2016 16:34:09 +0800 Subject: [PATCH 052/470] fix test cases in python --- .../src/main/resources/python/model.mustache | 8 ++++---- samples/client/petstore/python/README.md | 14 +++++++------- .../petstore/python/petstore_api/configuration.py | 14 +++++++------- .../python/petstore_api/models/enum_test.py | 12 ++++++------ .../python/petstore_api/models/map_test.py | 4 ++-- .../petstore/python/petstore_api/models/order.py | 4 ++-- .../petstore/python/petstore_api/models/pet.py | 4 ++-- samples/client/petstore/python/test_python2.sh | 3 +++ .../client/petstore/python/test_python2_and_3.sh | 3 +++ .../client/petstore/python/tests/test_pet_api.py | 1 + 10 files changed, 37 insertions(+), 30 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index a08595db88a..ae8cc8acd23 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -64,10 +64,10 @@ class {{classname}}(object): """ {{#isEnum}} allowed_values = [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}] - if {{name}} not in allowed_values: + if {{{name}}} not in allowed_values: raise ValueError( - "Invalid value for `{{name}}`, must be one of {0}" - .format(allowed_values) + "Invalid value for `{{{name}}}` ({0}), must be one of {1}" + .format({{{name}}}, allowed_values) ) {{/isEnum}} {{^isEnum}} @@ -152,4 +152,4 @@ class {{classname}}(object): """ return not self == other {{/model}} -{{/models}} \ No newline at end of file +{{/models}} diff --git a/samples/client/petstore/python/README.md b/samples/client/petstore/python/README.md index 68d7f11b6dd..6c34951d301 100644 --- a/samples/client/petstore/python/README.md +++ b/samples/client/petstore/python/README.md @@ -5,7 +5,7 @@ This Python package is automatically generated by the [Swagger Codegen](https:// - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-07-05T10:32:24.684-04:00 +- Build date: 2016-07-06T16:27:27.842+08:00 - Build package: class io.swagger.codegen.languages.PythonClientCodegen ## Requirements. @@ -136,6 +136,12 @@ Class | Method | HTTP request | Description ## Documentation For Authorization +## api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + ## petstore_auth - **Type**: OAuth @@ -145,12 +151,6 @@ Class | Method | HTTP request | Description - **write:pets**: modify pets in your account - **read:pets**: read your pets -## api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - ## Author diff --git a/samples/client/petstore/python/petstore_api/configuration.py b/samples/client/petstore/python/petstore_api/configuration.py index 4515b3a7466..45cfef15472 100644 --- a/samples/client/petstore/python/petstore_api/configuration.py +++ b/samples/client/petstore/python/petstore_api/configuration.py @@ -221,6 +221,13 @@ def auth_settings(self): :return: The Auth Settings information dict. """ return { + 'api_key': + { + 'type': 'api_key', + 'in': 'header', + 'key': 'api_key', + 'value': self.get_api_key_with_prefix('api_key') + }, 'petstore_auth': { @@ -229,13 +236,6 @@ def auth_settings(self): 'key': 'Authorization', 'value': 'Bearer ' + self.access_token }, - 'api_key': - { - 'type': 'api_key', - 'in': 'header', - 'key': 'api_key', - 'value': self.get_api_key_with_prefix('api_key') - }, } diff --git a/samples/client/petstore/python/petstore_api/models/enum_test.py b/samples/client/petstore/python/petstore_api/models/enum_test.py index c498c839bd6..087c102a9c5 100644 --- a/samples/client/petstore/python/petstore_api/models/enum_test.py +++ b/samples/client/petstore/python/petstore_api/models/enum_test.py @@ -80,8 +80,8 @@ def enum_string(self, enum_string): allowed_values = ["UPPER", "lower"] if enum_string not in allowed_values: raise ValueError( - "Invalid value for `enum_string`, must be one of {0}" - .format(allowed_values) + "Invalid value for `enum_string` ({0}), must be one of {1}" + .format(enum_string, allowed_values) ) self._enum_string = enum_string @@ -109,8 +109,8 @@ def enum_integer(self, enum_integer): allowed_values = ["1", "-1"] if enum_integer not in allowed_values: raise ValueError( - "Invalid value for `enum_integer`, must be one of {0}" - .format(allowed_values) + "Invalid value for `enum_integer` ({0}), must be one of {1}" + .format(enum_integer, allowed_values) ) self._enum_integer = enum_integer @@ -138,8 +138,8 @@ def enum_number(self, enum_number): allowed_values = ["1.1", "-1.2"] if enum_number not in allowed_values: raise ValueError( - "Invalid value for `enum_number`, must be one of {0}" - .format(allowed_values) + "Invalid value for `enum_number` ({0}), must be one of {1}" + .format(enum_number, allowed_values) ) self._enum_number = enum_number diff --git a/samples/client/petstore/python/petstore_api/models/map_test.py b/samples/client/petstore/python/petstore_api/models/map_test.py index 92c86e55702..f7eb30f8286 100644 --- a/samples/client/petstore/python/petstore_api/models/map_test.py +++ b/samples/client/petstore/python/petstore_api/models/map_test.py @@ -100,8 +100,8 @@ def map_of_enum_string(self, map_of_enum_string): allowed_values = [] if map_of_enum_string not in allowed_values: raise ValueError( - "Invalid value for `map_of_enum_string`, must be one of {0}" - .format(allowed_values) + "Invalid value for `map_of_enum_string` ({0}), must be one of {1}" + .format(map_of_enum_string, allowed_values) ) self._map_of_enum_string = map_of_enum_string diff --git a/samples/client/petstore/python/petstore_api/models/order.py b/samples/client/petstore/python/petstore_api/models/order.py index f3881a04405..52c90b2c812 100644 --- a/samples/client/petstore/python/petstore_api/models/order.py +++ b/samples/client/petstore/python/petstore_api/models/order.py @@ -181,8 +181,8 @@ def status(self, status): allowed_values = ["placed", "approved", "delivered"] if status not in allowed_values: raise ValueError( - "Invalid value for `status`, must be one of {0}" - .format(allowed_values) + "Invalid value for `status` ({0}), must be one of {1}" + .format(status, allowed_values) ) self._status = status diff --git a/samples/client/petstore/python/petstore_api/models/pet.py b/samples/client/petstore/python/petstore_api/models/pet.py index 7a86761e55f..cf644e5a8e1 100644 --- a/samples/client/petstore/python/petstore_api/models/pet.py +++ b/samples/client/petstore/python/petstore_api/models/pet.py @@ -204,8 +204,8 @@ def status(self, status): allowed_values = ["available", "pending", "sold"] if status not in allowed_values: raise ValueError( - "Invalid value for `status`, must be one of {0}" - .format(allowed_values) + "Invalid value for `status` ({0}), must be one of {1}" + .format(status, allowed_values) ) self._status = status diff --git a/samples/client/petstore/python/test_python2.sh b/samples/client/petstore/python/test_python2.sh index 680d2ce61e0..e2492be49f6 100755 --- a/samples/client/petstore/python/test_python2.sh +++ b/samples/client/petstore/python/test_python2.sh @@ -6,6 +6,9 @@ SETUP_OUT=*.egg-info VENV=.venv DEACTIVE=false +export LC_ALL=en_US.UTF-8 +export LANG=en_US.UTF-8 + ### set virtualenv if [ -z "$VIRTUAL_ENV" ]; then virtualenv $VENV --no-site-packages --always-copy diff --git a/samples/client/petstore/python/test_python2_and_3.sh b/samples/client/petstore/python/test_python2_and_3.sh index 2e4b4630a33..b917ecad06a 100755 --- a/samples/client/petstore/python/test_python2_and_3.sh +++ b/samples/client/petstore/python/test_python2_and_3.sh @@ -6,6 +6,9 @@ SETUP_OUT=*.egg-info VENV=.venv DEACTIVE=false +export LC_ALL=en_US.UTF-8 +export LANG=en_US.UTF-8 + ### set virtualenv if [ -z "$VIRTUAL_ENV" ]; then virtualenv $VENV --no-site-packages --always-copy diff --git a/samples/client/petstore/python/tests/test_pet_api.py b/samples/client/petstore/python/tests/test_pet_api.py index 37fe5a55212..e2ed0ec267c 100644 --- a/samples/client/petstore/python/tests/test_pet_api.py +++ b/samples/client/petstore/python/tests/test_pet_api.py @@ -155,6 +155,7 @@ def test_find_pets_by_status(self): list(map(lambda x: getattr(x, 'id'), self.pet_api.find_pets_by_status(status=[self.pet.status]))) ) + @unittest.skip("skipping the test as the method sometimes invalid Petstore object with incorrect status") def test_find_pets_by_tags(self): self.pet_api.add_pet(body=self.pet) From 5f15121fc2f1315006726e6a90dc08f5eb5566fd Mon Sep 17 00:00:00 2001 From: cbornet Date: Wed, 6 Jul 2016 11:26:16 +0200 Subject: [PATCH 053/470] add springboot and spring-cloud to verified samples --- pom.xml | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/pom.xml b/pom.xml index 37cd5602fb8..c8eb777e41c 100644 --- a/pom.xml +++ b/pom.xml @@ -558,6 +558,30 @@ samples/server/petstore/spring-mvc + + springboot + + + env + java + + + + samples/server/petstore/springboot + + + + spring-cloud + + + env + java + + + + samples/client/petstore/spring-cloud + + samples @@ -589,6 +613,8 @@ samples/client/petstore/javascript samples/client/petstore/scala samples/server/petstore/spring-mvc + samples/server/petstore/springboot + samples/client/petstore/spring-cloud samples/server/petstore/jaxrs/jersey1 samples/server/petstore/jaxrs/jersey2 samples/server/petstore/jaxrs-resteasy From 57f518fe93dfaa3a8aa968265ab28307f3014889 Mon Sep 17 00:00:00 2001 From: cbornet Date: Wed, 6 Jul 2016 11:47:48 +0200 Subject: [PATCH 054/470] change spring-mvc petstore artifact-id --- bin/spring-mvc-petstore-server.json | 4 +++ bin/spring-mvc-petstore-server.sh | 2 +- samples/server/petstore/spring-mvc/pom.xml | 4 +-- .../src/main/java/io/swagger/api/PetApi.java | 27 ++++++++----------- .../main/java/io/swagger/api/StoreApi.java | 8 +++--- .../src/main/java/io/swagger/api/UserApi.java | 22 +++++++-------- 6 files changed, 32 insertions(+), 35 deletions(-) create mode 100644 bin/spring-mvc-petstore-server.json diff --git a/bin/spring-mvc-petstore-server.json b/bin/spring-mvc-petstore-server.json new file mode 100644 index 00000000000..4642abf8015 --- /dev/null +++ b/bin/spring-mvc-petstore-server.json @@ -0,0 +1,4 @@ +{ + "library": "spring-mvc", + "artifactId": "swagger-spring-mvc-server" +} diff --git a/bin/spring-mvc-petstore-server.sh b/bin/spring-mvc-petstore-server.sh index 736688491c5..d03c5a1647c 100755 --- a/bin/spring-mvc-petstore-server.sh +++ b/bin/spring-mvc-petstore-server.sh @@ -26,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaSpring -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l spring --library spring-mvc -o samples/server/petstore/spring-mvc -DhideGenerationTimestamp=true" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaSpring -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l spring -c bin/spring-mvc-petstore-server.json -o samples/server/petstore/spring-mvc -DhideGenerationTimestamp=true" java $JAVA_OPTS -jar $executable $ags diff --git a/samples/server/petstore/spring-mvc/pom.xml b/samples/server/petstore/spring-mvc/pom.xml index df0c832d955..c3a46a657d7 100644 --- a/samples/server/petstore/spring-mvc/pom.xml +++ b/samples/server/petstore/spring-mvc/pom.xml @@ -1,9 +1,9 @@ 4.0.0 io.swagger - swagger-spring-server + swagger-spring-mvc-server jar - swagger-spring-server + swagger-spring-mvc-server 1.0.0 src/main/java diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java index f0f76394bf3..2957ca3c71b 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java @@ -26,7 +26,7 @@ public interface PetApi { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) @RequestMapping(value = "/pet", @@ -41,14 +41,13 @@ public interface PetApi { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid pet value", response = Void.class) }) @RequestMapping(value = "/pet/{petId}", produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) - ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId, - @ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey); + ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId,@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey); @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { @@ -56,7 +55,7 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class), @ApiResponse(code = 400, message = "Invalid status value", response = Pet.class) }) @@ -71,7 +70,7 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class), @ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class) }) @@ -83,7 +82,7 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru @ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { @Authorization(value = "api_key") - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class), @ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), @@ -99,7 +98,7 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), @ApiResponse(code = 404, message = "Pet not found", response = Void.class), @@ -116,16 +115,14 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) @RequestMapping(value = "/pet/{petId}", produces = { "application/xml", "application/json" }, consumes = { "application/x-www-form-urlencoded" }, method = RequestMethod.POST) - ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId, - @ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name, - @ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status); + ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId,@ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name,@ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status); @ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = { @@ -133,15 +130,13 @@ ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs t @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) @RequestMapping(value = "/pet/{petId}/uploadImage", produces = { "application/json" }, consumes = { "multipart/form-data" }, method = RequestMethod.POST) - ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId, - @ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata, - @ApiParam(value = "file detail") @RequestPart("file") MultipartFile file); + ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId,@ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata,@ApiParam(value = "file detail") @RequestPart("file") MultipartFile file); } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java index f67745dfa32..f5526de9862 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java @@ -20,7 +20,7 @@ @Api(value = "store", description = "the store API") public interface StoreApi { - @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class) + @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class, tags={ "store", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), @ApiResponse(code = 404, message = "Order not found", response = Void.class) }) @@ -32,7 +32,7 @@ public interface StoreApi { @ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { @Authorization(value = "api_key") - }) + }, tags={ "store", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Integer.class) }) @RequestMapping(value = "/store/inventory", @@ -41,7 +41,7 @@ public interface StoreApi { ResponseEntity> getInventory(); - @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class) + @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Order.class), @ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), @@ -52,7 +52,7 @@ public interface StoreApi { ResponseEntity getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId); - @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class) + @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Order.class), @ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java index 508a5c1863d..14658ede06a 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java @@ -20,7 +20,7 @@ @Api(value = "user", description = "the user API") public interface UserApi { - @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class) + @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @RequestMapping(value = "/user", @@ -29,7 +29,7 @@ public interface UserApi { ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body); - @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @RequestMapping(value = "/user/createWithArray", @@ -38,7 +38,7 @@ public interface UserApi { ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body); - @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @RequestMapping(value = "/user/createWithList", @@ -47,7 +47,7 @@ public interface UserApi { ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body); - @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class) + @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), @ApiResponse(code = 404, message = "User not found", response = Void.class) }) @@ -57,7 +57,7 @@ public interface UserApi { ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username); - @ApiOperation(value = "Get user by user name", notes = "", response = User.class) + @ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = User.class), @ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), @@ -68,18 +68,17 @@ public interface UserApi { ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username); - @ApiOperation(value = "Logs user into the system", notes = "", response = String.class) + @ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = String.class), @ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) @RequestMapping(value = "/user/login", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, - @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password); + ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username,@ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password); - @ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class) + @ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @RequestMapping(value = "/user/logout", @@ -88,14 +87,13 @@ ResponseEntity loginUser(@ApiParam(value = "The user name for login", re ResponseEntity logoutUser(); - @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class) + @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid user supplied", response = Void.class), @ApiResponse(code = 404, message = "User not found", response = Void.class) }) @RequestMapping(value = "/user/{username}", produces = { "application/xml", "application/json" }, method = RequestMethod.PUT) - ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username, - @ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body); + ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username,@ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body); } From df7b694c4b9af2a2510613292f917912fca54d93 Mon Sep 17 00:00:00 2001 From: cbornet Date: Wed, 6 Jul 2016 11:51:56 +0200 Subject: [PATCH 055/470] change spring-cloud petstore artifact-id --- bin/spring-cloud-feign-petstore.json | 4 ++++ bin/spring-cloud-feign-petstore.sh | 2 +- samples/client/petstore/spring-cloud/README.md | 8 ++++---- samples/client/petstore/spring-cloud/pom.xml | 4 ++-- 4 files changed, 11 insertions(+), 7 deletions(-) create mode 100644 bin/spring-cloud-feign-petstore.json diff --git a/bin/spring-cloud-feign-petstore.json b/bin/spring-cloud-feign-petstore.json new file mode 100644 index 00000000000..7425cee47f6 --- /dev/null +++ b/bin/spring-cloud-feign-petstore.json @@ -0,0 +1,4 @@ +{ + "library": "spring-cloud", + "artifactId": "swagger-petstore-spring-cloud" +} diff --git a/bin/spring-cloud-feign-petstore.sh b/bin/spring-cloud-feign-petstore.sh index e2cafebda84..a5605217b07 100755 --- a/bin/spring-cloud-feign-petstore.sh +++ b/bin/spring-cloud-feign-petstore.sh @@ -26,7 +26,7 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l spring -o samples/client/petstore/spring-cloud --library spring-cloud -DhideGenerationTimestamp=true" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l spring -c bin/spring-cloud-feign-petstore.json -o samples/client/petstore/spring-cloud -DhideGenerationTimestamp=true" echo "Removing files and folders under samples/client/petstore/spring-cloud/src/main" rm -rf samples/client/petstore/spring-cloud/src/main diff --git a/samples/client/petstore/spring-cloud/README.md b/samples/client/petstore/spring-cloud/README.md index 56d8781caad..0d2d58540db 100644 --- a/samples/client/petstore/spring-cloud/README.md +++ b/samples/client/petstore/spring-cloud/README.md @@ -1,4 +1,4 @@ -# swagger-spring +# swagger-petstore-spring-cloud ## Requirements @@ -27,7 +27,7 @@ Add this dependency to your project's POM: ```xml io.swagger - swagger-spring + swagger-petstore-spring-cloud 1.0.0 compile @@ -38,7 +38,7 @@ Add this dependency to your project's POM: Add this dependency to your project's build file: ```groovy -compile "io.swagger:swagger-spring:1.0.0" +compile "io.swagger:swagger-petstore-spring-cloud:1.0.0" ``` ### Others @@ -49,5 +49,5 @@ mvn package Then manually install the following JARs: -* target/swagger-spring-1.0.0.jar +* target/swagger-petstore-spring-cloud-1.0.0.jar * target/lib/*.jar diff --git a/samples/client/petstore/spring-cloud/pom.xml b/samples/client/petstore/spring-cloud/pom.xml index 52e3be061db..fbe01604b10 100644 --- a/samples/client/petstore/spring-cloud/pom.xml +++ b/samples/client/petstore/spring-cloud/pom.xml @@ -1,9 +1,9 @@ 4.0.0 io.swagger - swagger-spring + swagger-petstore-spring-cloud jar - swagger-spring + swagger-petstore-spring-cloud 1.0.0 1.7 From 01e06c01ebfd0fbc81f3fb6cc58a1ada65e5b559 Mon Sep 17 00:00:00 2001 From: vovan- Date: Wed, 6 Jul 2016 09:28:35 +0300 Subject: [PATCH 056/470] Fixed issue [Spring] Add support for the contextPath in Spring-boot gen #3193 --- .../main/java/io/swagger/codegen/languages/SpringCodegen.java | 2 +- .../src/main/resources/JavaSpring/application.mustache | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) create mode 100644 modules/swagger-codegen/src/main/resources/JavaSpring/application.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java index 9a4ee3256ea..bc2f155a143 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java @@ -126,7 +126,7 @@ public void processOpts() { (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "HomeController.java")); supportingFiles.add(new SupportingFile("swagger2SpringBoot.mustache", (sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator), "Swagger2SpringBoot.java")); - supportingFiles.add(new SupportingFile("application.properties", + supportingFiles.add(new SupportingFile("application.mustache", ("src.main.resources").replace(".", java.io.File.separator), "application.properties")); } if (library.equals("spring-mvc")) { diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/application.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/application.mustache new file mode 100644 index 00000000000..a4695deef76 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/application.mustache @@ -0,0 +1,3 @@ +springfox.documentation.swagger.v2.path=/api-docs +server.contextPath={{^contextPath}}/{{/contextPath}}{{#contextPath}}{{contextPath}}{{/contextPath}} +#server.port=8090 \ No newline at end of file From e2c7dc014795a118ac7782401a677c769046a448 Mon Sep 17 00:00:00 2001 From: cbornet Date: Wed, 6 Jul 2016 15:29:54 +0200 Subject: [PATCH 057/470] don't repackage as a spring boot app --- .../libraries/spring-cloud/pom.mustache | 15 --------------- samples/client/petstore/spring-cloud/pom.xml | 13 ------------- 2 files changed, 28 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/pom.mustache index bec76800557..84e0b0c2f99 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/pom.mustache @@ -18,21 +18,6 @@ src/main/java - {{^interfaceOnly}} - - - org.springframework.boot - spring-boot-maven-plugin - - - - repackage - - - - - - {{/interfaceOnly}} diff --git a/samples/client/petstore/spring-cloud/pom.xml b/samples/client/petstore/spring-cloud/pom.xml index fbe01604b10..159fdae3e61 100644 --- a/samples/client/petstore/spring-cloud/pom.xml +++ b/samples/client/petstore/spring-cloud/pom.xml @@ -18,19 +18,6 @@ src/main/java - - - org.springframework.boot - spring-boot-maven-plugin - - - - repackage - - - - - From 5648c5af887fd8ec1ee2444e73e75353e5d4f069 Mon Sep 17 00:00:00 2001 From: lunat Date: Wed, 6 Jul 2016 16:26:59 +0200 Subject: [PATCH 058/470] CSharp Documentation with working anchor link within document --- .../src/main/resources/csharp/README.mustache | 7 +- .../main/resources/csharp/api_doc.mustache | 1 + .../csharp/SwaggerClient/docs/ArrayTest.md | 1 - .../csharp/SwaggerClient/docs/FakeApi.md | 2 + .../csharp/SwaggerClient/docs/MapTest.md | 10 ++ .../csharp/SwaggerClient/docs/PetApi.md | 8 + .../csharp/SwaggerClient/docs/StoreApi.md | 4 + .../csharp/SwaggerClient/docs/UserApi.md | 8 + .../src/IO.Swagger.Test/Model/MapTestTests.cs | 98 +++++++++++ .../src/IO.Swagger/Api/FakeApi.cs | 2 +- .../src/IO.Swagger/Api/PetApi.cs | 2 +- .../src/IO.Swagger/Api/StoreApi.cs | 2 +- .../src/IO.Swagger/Api/UserApi.cs | 2 +- .../src/IO.Swagger/Client/ApiClient.cs | 2 +- .../src/IO.Swagger/Client/ApiException.cs | 2 +- .../src/IO.Swagger/Client/ApiResponse.cs | 2 +- .../src/IO.Swagger/Client/Configuration.cs | 2 +- .../src/IO.Swagger/Client/ExceptionFactory.cs | 2 +- .../src/IO.Swagger/Client/IApiAccessor.cs | 2 +- .../Model/AdditionalPropertiesClass.cs | 2 +- .../src/IO.Swagger/Model/Animal.cs | 2 +- .../src/IO.Swagger/Model/AnimalFarm.cs | 2 +- .../src/IO.Swagger/Model/ApiResponse.cs | 2 +- .../Model/ArrayOfArrayOfNumberOnly.cs | 2 +- .../src/IO.Swagger/Model/ArrayOfNumberOnly.cs | 2 +- .../src/IO.Swagger/Model/ArrayTest.cs | 40 +---- .../SwaggerClient/src/IO.Swagger/Model/Cat.cs | 2 +- .../src/IO.Swagger/Model/Category.cs | 2 +- .../SwaggerClient/src/IO.Swagger/Model/Dog.cs | 2 +- .../src/IO.Swagger/Model/EnumClass.cs | 2 +- .../src/IO.Swagger/Model/EnumTest.cs | 2 +- .../src/IO.Swagger/Model/FormatTest.cs | 2 +- .../src/IO.Swagger/Model/HasOnlyReadOnly.cs | 2 +- .../src/IO.Swagger/Model/MapTest.cs | 162 ++++++++++++++++++ ...dPropertiesAndAdditionalPropertiesClass.cs | 2 +- .../src/IO.Swagger/Model/Model200Response.cs | 2 +- .../src/IO.Swagger/Model/ModelReturn.cs | 2 +- .../src/IO.Swagger/Model/Name.cs | 2 +- .../src/IO.Swagger/Model/NumberOnly.cs | 2 +- .../src/IO.Swagger/Model/Order.cs | 2 +- .../SwaggerClient/src/IO.Swagger/Model/Pet.cs | 2 +- .../src/IO.Swagger/Model/ReadOnlyFirst.cs | 2 +- .../src/IO.Swagger/Model/SpecialModelName.cs | 2 +- .../SwaggerClient/src/IO.Swagger/Model/Tag.cs | 2 +- .../src/IO.Swagger/Model/User.cs | 2 +- 45 files changed, 334 insertions(+), 75 deletions(-) create mode 100644 samples/client/petstore/csharp/SwaggerClient/docs/MapTest.md create mode 100644 samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/MapTestTests.cs create mode 100644 samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/MapTest.cs diff --git a/modules/swagger-codegen/src/main/resources/csharp/README.mustache b/modules/swagger-codegen/src/main/resources/csharp/README.mustache index 77b69c273a4..bad7879eddf 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/README.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/README.mustache @@ -24,8 +24,8 @@ This C# SDK is automatically generated by the [Swagger Codegen](https://github.c {{/supportUWP}} ## Dependencies -- [RestSharp] (https://www.nuget.org/packages/RestSharp) - 105.1.0 or later -- [Json.NET] (https://www.nuget.org/packages/Newtonsoft.Json/) - 7.0.0 or later +- [RestSharp](https://www.nuget.org/packages/RestSharp) - 105.1.0 or later +- [Json.NET](https://www.nuget.org/packages/Newtonsoft.Json/) - 7.0.0 or later The DLLs included in the package may not be the latest version. We recommned using [NuGet] (https://docs.nuget.org/consume/installing-nuget) to obtain the latest version of the packages: ``` @@ -105,6 +105,7 @@ namespace Example }{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} ``` + ## Documentation for API Endpoints All URIs are relative to *{{{basePath}}}* @@ -114,6 +115,7 @@ Class | Method | HTTP request | Description {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{{summary}}}{{/summary}} {{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + ## Documentation for Models {{#modelPackage}} @@ -126,6 +128,7 @@ No model defined in this package ## Documentation for Authorization + {{^authMethods}} All endpoints do not require authorization. {{/authMethods}}{{#authMethods}}{{#last}} Authentication schemes defined for the API:{{/last}}{{/authMethods}} {{#authMethods}}### {{name}} diff --git a/modules/swagger-codegen/src/main/resources/csharp/api_doc.mustache b/modules/swagger-codegen/src/main/resources/csharp/api_doc.mustache index c069d7f3dcf..5baa88f38b6 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api_doc.mustache @@ -10,6 +10,7 @@ Method | HTTP request | Description {{#operations}} {{#operation}} + # **{{{operationId}}}** > {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}} ({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = null{{/optionalMethodArgument}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) diff --git a/samples/client/petstore/csharp/SwaggerClient/docs/ArrayTest.md b/samples/client/petstore/csharp/SwaggerClient/docs/ArrayTest.md index f8f285e08f4..37fb2788b77 100644 --- a/samples/client/petstore/csharp/SwaggerClient/docs/ArrayTest.md +++ b/samples/client/petstore/csharp/SwaggerClient/docs/ArrayTest.md @@ -6,7 +6,6 @@ Name | Type | Description | Notes **ArrayOfString** | **List<string>** | | [optional] **ArrayArrayOfInteger** | **List<List<long?>>** | | [optional] **ArrayArrayOfModel** | **List<List<ReadOnlyFirst>>** | | [optional] -**ArrayOfEnum** | **List<string>** | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp/SwaggerClient/docs/FakeApi.md b/samples/client/petstore/csharp/SwaggerClient/docs/FakeApi.md index 9214eb84b3f..32268377848 100644 --- a/samples/client/petstore/csharp/SwaggerClient/docs/FakeApi.md +++ b/samples/client/petstore/csharp/SwaggerClient/docs/FakeApi.md @@ -8,6 +8,7 @@ Method | HTTP request | Description [**TestEnumQueryParameters**](FakeApi.md#testenumqueryparameters) | **GET** /fake | To test enum query parameters + # **TestEndpointParameters** > void TestEndpointParameters (decimal? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) @@ -90,6 +91,7 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **TestEnumQueryParameters** > void TestEnumQueryParameters (string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null) diff --git a/samples/client/petstore/csharp/SwaggerClient/docs/MapTest.md b/samples/client/petstore/csharp/SwaggerClient/docs/MapTest.md new file mode 100644 index 00000000000..5c202aa336a --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/docs/MapTest.md @@ -0,0 +1,10 @@ +# IO.Swagger.Model.MapTest +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**MapMapOfString** | **Dictionary<string, Dictionary<string, string>>** | | [optional] +**MapOfEnumString** | **Dictionary<string, string>** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/SwaggerClient/docs/PetApi.md b/samples/client/petstore/csharp/SwaggerClient/docs/PetApi.md index 837859e4b7e..d32081e5471 100644 --- a/samples/client/petstore/csharp/SwaggerClient/docs/PetApi.md +++ b/samples/client/petstore/csharp/SwaggerClient/docs/PetApi.md @@ -14,6 +14,7 @@ Method | HTTP request | Description [**UploadFile**](PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image + # **AddPet** > void AddPet (Pet body) @@ -77,6 +78,7 @@ void (empty response body) [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **DeletePet** > void DeletePet (long? petId, string apiKey = null) @@ -142,6 +144,7 @@ void (empty response body) [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **FindPetsByStatus** > List FindPetsByStatus (List status) @@ -206,6 +209,7 @@ Name | Type | Description | Notes [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **FindPetsByTags** > List FindPetsByTags (List tags) @@ -270,6 +274,7 @@ Name | Type | Description | Notes [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **GetPetById** > Pet GetPetById (long? petId) @@ -336,6 +341,7 @@ Name | Type | Description | Notes [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **UpdatePet** > void UpdatePet (Pet body) @@ -399,6 +405,7 @@ void (empty response body) [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **UpdatePetWithForm** > void UpdatePetWithForm (long? petId, string name = null, string status = null) @@ -466,6 +473,7 @@ void (empty response body) [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **UploadFile** > ApiResponse UploadFile (long? petId, string additionalMetadata = null, System.IO.Stream file = null) diff --git a/samples/client/petstore/csharp/SwaggerClient/docs/StoreApi.md b/samples/client/petstore/csharp/SwaggerClient/docs/StoreApi.md index a5d5ff0454d..c1e8370f2d9 100644 --- a/samples/client/petstore/csharp/SwaggerClient/docs/StoreApi.md +++ b/samples/client/petstore/csharp/SwaggerClient/docs/StoreApi.md @@ -10,6 +10,7 @@ Method | HTTP request | Description [**PlaceOrder**](StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet + # **DeleteOrder** > void DeleteOrder (string orderId) @@ -70,6 +71,7 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **GetInventory** > Dictionary GetInventory () @@ -132,6 +134,7 @@ This endpoint does not need any parameter. [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **GetOrderById** > Order GetOrderById (long? orderId) @@ -193,6 +196,7 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **PlaceOrder** > Order PlaceOrder (Order body) diff --git a/samples/client/petstore/csharp/SwaggerClient/docs/UserApi.md b/samples/client/petstore/csharp/SwaggerClient/docs/UserApi.md index 65c22f9f072..e016a7a5e30 100644 --- a/samples/client/petstore/csharp/SwaggerClient/docs/UserApi.md +++ b/samples/client/petstore/csharp/SwaggerClient/docs/UserApi.md @@ -14,6 +14,7 @@ Method | HTTP request | Description [**UpdateUser**](UserApi.md#updateuser) | **PUT** /user/{username} | Updated user + # **CreateUser** > void CreateUser (User body) @@ -74,6 +75,7 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **CreateUsersWithArrayInput** > void CreateUsersWithArrayInput (List body) @@ -134,6 +136,7 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **CreateUsersWithListInput** > void CreateUsersWithListInput (List body) @@ -194,6 +197,7 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **DeleteUser** > void DeleteUser (string username) @@ -254,6 +258,7 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **GetUserByName** > User GetUserByName (string username) @@ -315,6 +320,7 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **LoginUser** > string LoginUser (string username, string password) @@ -378,6 +384,7 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **LogoutUser** > void LogoutUser () @@ -434,6 +441,7 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **UpdateUser** > void UpdateUser (string username, User body) diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/MapTestTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/MapTestTests.cs new file mode 100644 index 00000000000..f19089b6e03 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/MapTestTests.cs @@ -0,0 +1,98 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing MapTest + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class MapTestTests + { + // TODO uncomment below to declare an instance variable for MapTest + //private MapTest instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of MapTest + //instance = new MapTest(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of MapTest + /// + [Test] + public void MapTestInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" MapTest + //Assert.IsInstanceOfType (instance, "variable 'instance' is a MapTest"); + } + + /// + /// Test the property 'MapMapOfString' + /// + [Test] + public void MapMapOfStringTest() + { + // TODO unit test for the property 'MapMapOfString' + } + /// + /// Test the property 'MapOfEnumString' + /// + [Test] + public void MapOfEnumStringTest() + { + // TODO unit test for the property 'MapOfEnumString' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/FakeApi.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/FakeApi.cs index 6cdf4d3470e..2012be442a6 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/FakeApi.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/FakeApi.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/PetApi.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/PetApi.cs index abf5a0595b2..fdf4b752799 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/PetApi.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/PetApi.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/StoreApi.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/StoreApi.cs index 3fbbe71b8ca..668bb7819b4 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/StoreApi.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/StoreApi.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/UserApi.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/UserApi.cs index 6fb6244264e..1865ec1631d 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/UserApi.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/UserApi.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiClient.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiClient.cs index c5a2de83da1..5aaf146d69e 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiClient.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiException.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiException.cs index a19a664112f..1afc1529a75 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiException.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiException.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiResponse.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiResponse.cs index 6c6134c114a..03c64ab42e2 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiResponse.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiResponse.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/Configuration.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/Configuration.cs index 533b994dab2..60a2adac79a 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/Configuration.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/Configuration.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ExceptionFactory.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ExceptionFactory.cs index 579cb8618c2..129e591f8a7 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ExceptionFactory.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ExceptionFactory.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/IApiAccessor.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/IApiAccessor.cs index 65ff8bef73b..845e6a49e9b 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/IApiAccessor.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/IApiAccessor.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/AdditionalPropertiesClass.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/AdditionalPropertiesClass.cs index db9ac4006b7..ab9b3cdbb22 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/AdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/AdditionalPropertiesClass.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Animal.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Animal.cs index 5d8417c74a3..f9fea0bc269 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Animal.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Animal.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/AnimalFarm.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/AnimalFarm.cs index bc2443d5327..402fbba0198 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/AnimalFarm.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/AnimalFarm.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ApiResponse.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ApiResponse.cs index 0543e709b29..fbafd4e33ed 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ApiResponse.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ApiResponse.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ArrayOfArrayOfNumberOnly.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ArrayOfArrayOfNumberOnly.cs index a4da5ca286a..6b833d74a46 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ArrayOfArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ArrayOfArrayOfNumberOnly.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ArrayOfNumberOnly.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ArrayOfNumberOnly.cs index 977f8c9a7ef..131e369271b 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ArrayOfNumberOnly.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ArrayTest.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ArrayTest.cs index f0a57effc33..579e6764285 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ArrayTest.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ArrayTest.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io @@ -39,45 +39,17 @@ namespace IO.Swagger.Model [DataContract] public partial class ArrayTest : IEquatable { - - /// - /// Gets or Sets ArrayOfEnum - /// - [JsonConverter(typeof(StringEnumConverter))] - public enum ArrayOfEnumEnum - { - - /// - /// Enum Upper for "UPPER" - /// - [EnumMember(Value = "UPPER")] - Upper, - - /// - /// Enum Lower for "lower" - /// - [EnumMember(Value = "lower")] - Lower - } - - /// - /// Gets or Sets ArrayOfEnum - /// - [DataMember(Name="array_of_enum", EmitDefaultValue=false)] - public List ArrayOfEnum { get; set; } /// /// Initializes a new instance of the class. /// /// ArrayOfString. /// ArrayArrayOfInteger. /// ArrayArrayOfModel. - /// ArrayOfEnum. - public ArrayTest(List ArrayOfString = null, List> ArrayArrayOfInteger = null, List> ArrayArrayOfModel = null, List ArrayOfEnum = null) + public ArrayTest(List ArrayOfString = null, List> ArrayArrayOfInteger = null, List> ArrayArrayOfModel = null) { this.ArrayOfString = ArrayOfString; this.ArrayArrayOfInteger = ArrayArrayOfInteger; this.ArrayArrayOfModel = ArrayArrayOfModel; - this.ArrayOfEnum = ArrayOfEnum; } /// @@ -106,7 +78,6 @@ public override string ToString() sb.Append(" ArrayOfString: ").Append(ArrayOfString).Append("\n"); sb.Append(" ArrayArrayOfInteger: ").Append(ArrayArrayOfInteger).Append("\n"); sb.Append(" ArrayArrayOfModel: ").Append(ArrayArrayOfModel).Append("\n"); - sb.Append(" ArrayOfEnum: ").Append(ArrayOfEnum).Append("\n"); sb.Append("}\n"); return sb.ToString(); } @@ -157,11 +128,6 @@ public bool Equals(ArrayTest other) this.ArrayArrayOfModel == other.ArrayArrayOfModel || this.ArrayArrayOfModel != null && this.ArrayArrayOfModel.SequenceEqual(other.ArrayArrayOfModel) - ) && - ( - this.ArrayOfEnum == other.ArrayOfEnum || - this.ArrayOfEnum != null && - this.ArrayOfEnum.SequenceEqual(other.ArrayOfEnum) ); } @@ -182,8 +148,6 @@ public override int GetHashCode() hash = hash * 59 + this.ArrayArrayOfInteger.GetHashCode(); if (this.ArrayArrayOfModel != null) hash = hash * 59 + this.ArrayArrayOfModel.GetHashCode(); - if (this.ArrayOfEnum != null) - hash = hash * 59 + this.ArrayOfEnum.GetHashCode(); return hash; } } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Cat.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Cat.cs index f288be939c4..cd9b90c4b05 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Cat.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Cat.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Category.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Category.cs index be9d35a9fb7..4de778cc723 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Category.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Category.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Dog.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Dog.cs index 000b1f1bec9..aafdfb73fd3 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Dog.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Dog.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumClass.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumClass.cs index 3ce229e2efd..0adca51169e 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumClass.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumClass.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumTest.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumTest.cs index 2725d9d17a4..60e26ce02c7 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumTest.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumTest.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/FormatTest.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/FormatTest.cs index 5e50732ee0b..059bc85ffa9 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/FormatTest.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/FormatTest.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/HasOnlyReadOnly.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/HasOnlyReadOnly.cs index 96d150565a5..56f2b636fe8 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/HasOnlyReadOnly.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/HasOnlyReadOnly.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/MapTest.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/MapTest.cs new file mode 100644 index 00000000000..397c65a8de7 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/MapTest.cs @@ -0,0 +1,162 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace IO.Swagger.Model +{ + /// + /// MapTest + /// + [DataContract] + public partial class MapTest : IEquatable + { + + /// + /// Gets or Sets Inner + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum InnerEnum + { + + /// + /// Enum Upper for "UPPER" + /// + [EnumMember(Value = "UPPER")] + Upper, + + /// + /// Enum Lower for "lower" + /// + [EnumMember(Value = "lower")] + Lower + } + + /// + /// Gets or Sets MapOfEnumString + /// + [DataMember(Name="map_of_enum_string", EmitDefaultValue=false)] + public Dictionary MapOfEnumString { get; set; } + /// + /// Initializes a new instance of the class. + /// + /// MapMapOfString. + /// MapOfEnumString. + public MapTest(Dictionary> MapMapOfString = null, Dictionary MapOfEnumString = null) + { + this.MapMapOfString = MapMapOfString; + this.MapOfEnumString = MapOfEnumString; + } + + /// + /// Gets or Sets MapMapOfString + /// + [DataMember(Name="map_map_of_string", EmitDefaultValue=false)] + public Dictionary> MapMapOfString { get; set; } + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class MapTest {\n"); + sb.Append(" MapMapOfString: ").Append(MapMapOfString).Append("\n"); + sb.Append(" MapOfEnumString: ").Append(MapOfEnumString).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as MapTest); + } + + /// + /// Returns true if MapTest instances are equal + /// + /// Instance of MapTest to be compared + /// Boolean + public bool Equals(MapTest other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this.MapMapOfString == other.MapMapOfString || + this.MapMapOfString != null && + this.MapMapOfString.SequenceEqual(other.MapMapOfString) + ) && + ( + this.MapOfEnumString == other.MapOfEnumString || + this.MapOfEnumString != null && + this.MapOfEnumString.SequenceEqual(other.MapOfEnumString) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this.MapMapOfString != null) + hash = hash * 59 + this.MapMapOfString.GetHashCode(); + if (this.MapOfEnumString != null) + hash = hash * 59 + this.MapOfEnumString.GetHashCode(); + return hash; + } + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/MixedPropertiesAndAdditionalPropertiesClass.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/MixedPropertiesAndAdditionalPropertiesClass.cs index ea20988a1ec..e3d262a1a25 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/MixedPropertiesAndAdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/MixedPropertiesAndAdditionalPropertiesClass.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Model200Response.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Model200Response.cs index 695c75096b4..cffabe7a904 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Model200Response.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Model200Response.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ModelReturn.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ModelReturn.cs index e6255f285ee..7670fb112df 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ModelReturn.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ModelReturn.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Name.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Name.cs index 1c1b771f53b..f511bafe6b8 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Name.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Name.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/NumberOnly.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/NumberOnly.cs index 06c953ce89d..d77099357fc 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/NumberOnly.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/NumberOnly.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Order.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Order.cs index 33f1b2d99da..0b7e559181f 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Order.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Order.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Pet.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Pet.cs index 7db2644307a..84b797a4548 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Pet.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Pet.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ReadOnlyFirst.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ReadOnlyFirst.cs index 422c7671139..4b96322739d 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ReadOnlyFirst.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ReadOnlyFirst.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/SpecialModelName.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/SpecialModelName.cs index 82cde053d0b..4d8865432b5 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/SpecialModelName.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/SpecialModelName.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Tag.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Tag.cs index 93b7b66c005..41f5a6794b6 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Tag.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Tag.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/User.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/User.cs index 34e60b081b4..3d8e1c041a7 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/User.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/User.cs @@ -1,7 +1,7 @@ /* * Swagger Petstore * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io From 0466405fa510a3815c8e4b86e1426179bab88eb6 Mon Sep 17 00:00:00 2001 From: Christian Loitsch Date: Wed, 6 Jul 2016 17:45:39 +0200 Subject: [PATCH 059/470] fix: verification of requiredParams now works MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit other features: - remove crypto dependency. base64 encoding is now part of dart.convert. - port Java query param handling to dart. → allows us to use 'multi' collectionFormat for queryParams - use async await where possible. --- .../src/main/resources/dart/api.mustache | 45 +++++---- .../main/resources/dart/api_client.mustache | 94 ++++++++++++------- .../src/main/resources/dart/apilib.mustache | 1 - .../resources/dart/auth/api_key_auth.mustache | 5 +- .../dart/auth/authentication.mustache | 2 +- .../dart/auth/http_basic_auth.mustache | 4 +- .../src/main/resources/dart/pubspec.mustache | 1 - 7 files changed, 94 insertions(+), 58 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/dart/api.mustache b/modules/swagger-codegen/src/main/resources/dart/api.mustache index cba12208b7d..6fcd49994ec 100644 --- a/modules/swagger-codegen/src/main/resources/dart/api.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/api.mustache @@ -2,6 +2,7 @@ part of api; {{#operations}} + class {{classname}} { String basePath = "{{basePath}}"; ApiClient apiClient = ApiClient.defaultApiClient; @@ -16,13 +17,17 @@ class {{classname}} { /// {{summary}} /// /// {{notes}} - {{#returnType}}Future<{{{returnType}}}> {{/returnType}}{{^returnType}}Future {{/returnType}}{{nickname}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { + {{#returnType}}Future<{{{returnType}}}> {{/returnType}}{{^returnType}}Future {{/returnType}}{{nickname}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) async { Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; - {{#allParams}} + // verify required params are set - if({{/allParams}}{{#required}} {{paramName}} == null {{#hasMore}}|| {{/hasMore}}{{/required}}{{#allParams}}) { - throw new ApiException(400, "missing required params"); - }{{/allParams}} + {{#allParams}} + {{#required}} + if({{paramName}} == null) { + throw new ApiException(400, "Missing required param: {{paramName}}"); + } + {{/required}} + {{/allParams}} // create path and map variables String path = "{{path}}".replaceAll("{format}","json"){{#pathParams}}.replaceAll("{" + "{{paramName}}" + "}", {{{paramName}}}.toString()){{/pathParams}}; @@ -32,7 +37,7 @@ class {{classname}} { Map headerParams = {}; Map formParams = {}; {{#queryParams}}if("null" != {{paramName}}) - queryParams["{{baseName}}"] = {{paramName}} is List ? {{paramName}}.join(',') : {{paramName}}; + queryParams.addAll(convertParametersForCollectionFormat({{collectionFormat}}, {{baseName}}, {{paramName}})); {{/queryParams}} {{#headerParams}}headerParams["{{baseName}}"] = {{paramName}}; {{/headerParams}} @@ -66,17 +71,23 @@ class {{classname}} { {{/formParams}} } - return apiClient.invokeAPI(basePath, path, '{{httpMethod}}', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return {{#returnType}}ApiClient.deserialize(response.body, {{returnBaseType}}){{/returnType}}; - } - else { - return {{#returnType}}null{{/returnType}}; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + '{{httpMethod}}', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return {{#returnType}}ApiClient.deserialize(response.body, {{returnBaseType}}){{/returnType}}; + } else { + return {{#returnType}}null{{/returnType}}; + } } {{/operation}} } diff --git a/modules/swagger-codegen/src/main/resources/dart/api_client.mustache b/modules/swagger-codegen/src/main/resources/dart/api_client.mustache index 92fa90d6261..6a9fca0fd8e 100644 --- a/modules/swagger-codegen/src/main/resources/dart/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/api_client.mustache @@ -1,5 +1,44 @@ part of api; +class QueryParam { + String name; + String value; + + QueryParam(this.name, this.value); +} + +const _delimiters = const {'csv': ',', 'ssv': ' ', 'tsv': '\t', 'pipes': '|'}; + +// port from Java version +List convertParametersForCollectionFormat( + String collectionFormat, String name, dynamic value) { + var params = {}; + + // preconditions + if (name == null || name.isEmpty || value == null) return params; + + if (value is! List) { + params.add(new QueryParam(name, value as String)); + return params; + } + + List values = value as List; + + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty) + ? "csv" + : collectionFormat; // default: csv + + if (collectionFormat == "multi") { + return values.map((v) => new QueryParam(name, v)); + } + + String delimiter = _delimiters[collectionFormat] ?? ","; + + params.add(new QueryParam(name, values.join(delimiter))); + return params; +} + class ApiClient { static ApiClient defaultApiClient = new ApiClient(); @@ -85,71 +124,60 @@ class ApiClient { return serialized; } - Future invokeAPI( String host, - String path, - String method, - Map queryParams, - Object body, - Map headerParams, - Map formParams, - String contentType, - List authNames) { + // We don't use a Map for queryParams. + // If collectionFormat is 'multi' a key might appear multiple times. + Future invokeAPI(String host, + String path, + String method, + List queryParams, + Object body, + Map headerParams, + Map formParams, + String contentType, + List authNames) async { updateParamsForAuth(authNames, queryParams, headerParams); var client = new {{#browserClient}}Browser{{/browserClient}}Client(); StringBuffer sb = new StringBuffer(); - - for(String key in queryParams.keys) { - String value = queryParams[key]; - if (value != null){ - if(sb.toString().length == 0) { - sb.write("?"); - } else { - sb.write("&"); - } - sb.write(key); - sb.write("="); - sb.write(value); - } - } - String querystring = sb.toString(); - String url = host + path + querystring; + var ps = queryParams.where((p) => p.value != null).map((p) => '${p.key}=${p.value}'); + String queryString = ps.isNotEmpty ? + '?' + ps.join('&') : + ''; + + String url = host + path + queryString; headerParams.addAll(_defaultHeaderMap); headerParams['Content-Type'] = contentType; - var completer = new Completer(); - if(body is MultipartRequest) { var request = new MultipartRequest(method, Uri.parse(url)); request.fields.addAll(body.fields); request.files.addAll(body.files); request.headers.addAll(body.headers); request.headers.addAll(headerParams); - client.send(request).then((response) => completer.complete(Response.fromStream(response))); + var response = await client.send(request); + return Response.fromStream(response); } else { var msgBody = contentType == "application/x-www-form-urlencoded" ? formParams : serialize(body); switch(method) { - case "GET": - return client.get(url, headers: headerParams); case "POST": return client.post(url, headers: headerParams, body: msgBody); case "PUT": return client.put(url, headers: headerParams, body: msgBody); case "DELETE": return client.delete(url, headers: headerParams); + default: + return client.get(url, headers: headerParams); } } - - return completer.future; } /// Update query and header parameters based on authentication settings. /// @param authNames The authentications to apply - void updateParamsForAuth(List authNames, Map queryParams, Map headerParams) { + void updateParamsForAuth(List authNames, List queryParams, Map headerParams) { authNames.forEach((authName) { Authentication auth = _authentications[authName]; if (auth == null) throw new ArgumentError("Authentication undefined: " + authName); diff --git a/modules/swagger-codegen/src/main/resources/dart/apilib.mustache b/modules/swagger-codegen/src/main/resources/dart/apilib.mustache index 178fe027e39..24b96817a03 100644 --- a/modules/swagger-codegen/src/main/resources/dart/apilib.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/apilib.mustache @@ -6,7 +6,6 @@ import 'dart:html'; import 'package:http/browser_client.dart';{{/browserClient}} import 'package:http/http.dart'; import 'package:dartson/dartson.dart'; -import 'package:crypto/crypto.dart'; import 'package:intl/intl.dart'; part 'api_client.dart'; diff --git a/modules/swagger-codegen/src/main/resources/dart/auth/api_key_auth.mustache b/modules/swagger-codegen/src/main/resources/dart/auth/api_key_auth.mustache index 6e728ae916b..d80d6a6a213 100644 --- a/modules/swagger-codegen/src/main/resources/dart/auth/api_key_auth.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/auth/api_key_auth.mustache @@ -10,7 +10,7 @@ class ApiKeyAuth implements Authentication { ApiKeyAuth(this.location, this.paramName); @override - void applyToParams(Map queryParams, Map headerParams) { + void applyToParams(List queryParams, Map headerParams) { String value; if (apiKeyPrefix != null) { value = '$apiKeyPrefix $apiKey'; @@ -19,10 +19,9 @@ class ApiKeyAuth implements Authentication { } if (location == 'query' && value != null) { - queryParams[paramName] = value; + queryParams.add(new QueryParam(paramName, value)); } else if (location == 'header' && value != null) { headerParams[paramName] = value; } } - } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/dart/auth/authentication.mustache b/modules/swagger-codegen/src/main/resources/dart/auth/authentication.mustache index 4833af90ec0..c0b1f92a42d 100644 --- a/modules/swagger-codegen/src/main/resources/dart/auth/authentication.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/auth/authentication.mustache @@ -3,5 +3,5 @@ part of api; abstract class Authentication { /// Apply authentication settings to header and query params. - void applyToParams(Map queryParams, Map headerParams); + void applyToParams(List queryParams, Map headerParams); } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/dart/auth/http_basic_auth.mustache b/modules/swagger-codegen/src/main/resources/dart/auth/http_basic_auth.mustache index e681c25653d..0645d4358f5 100644 --- a/modules/swagger-codegen/src/main/resources/dart/auth/http_basic_auth.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/auth/http_basic_auth.mustache @@ -6,9 +6,9 @@ class HttpBasicAuth implements Authentication { String password; @override - void applyToParams(Map queryParams, Map headerParams) { + void applyToParams(List queryParams, Map headerParams) { String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); - headerParams["Authorization"] = "Basic " + CryptoUtils.bytesToBase64(UTF8.encode(str)); + headerParams["Authorization"] = "Basic " + BASE64.encode(UTF8.encode(str)); } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/dart/pubspec.mustache b/modules/swagger-codegen/src/main/resources/dart/pubspec.mustache index 97bf9c1defd..1167498909e 100644 --- a/modules/swagger-codegen/src/main/resources/dart/pubspec.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/pubspec.mustache @@ -4,7 +4,6 @@ description: {{pubDescription}} dependencies: http: '>=0.11.1 <0.12.0' dartson: "^0.2.4" - crypto: "^0.9.0" intl: "^0.12.4+2" dev_dependencies: From 62d06f75b40a27c463f7b0f476e397a7ad94ce58 Mon Sep 17 00:00:00 2001 From: tao Date: Fri, 1 Jul 2016 12:18:03 -0700 Subject: [PATCH 060/470] use baseName instead of paramName --- .../src/main/resources/JavaJaxRS/formParams.mustache | 2 +- .../resources/JavaJaxRS/libraries/jersey1/formParams.mustache | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/formParams.mustache index 993d47bb562..cb1dbbeb613 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/formParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/formParams.mustache @@ -1,3 +1,3 @@ -{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}){{#vendorExtensions.x-multipart}}@FormDataParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{^vendorExtensions.x-multipart}}@FormParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{/notFile}}{{#isFile}} +{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}){{#vendorExtensions.x-multipart}}@FormDataParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{^vendorExtensions.x-multipart}}@FormParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{/notFile}}{{#isFile}} @FormDataParam("file") InputStream inputStream, @FormDataParam("file") FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/formParams.mustache index 3fe8f19d3de..91c8079ebcd 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/formParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/formParams.mustache @@ -1,2 +1,2 @@ -{{#isFormParam}}{{#notFile}}{{^vendorExtensions.x-multipart}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}){{/vendorExtensions.x-multipart}}{{#vendorExtensions.x-multipart}}@FormDataParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{^vendorExtensions.x-multipart}}@FormParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{/notFile}}{{#isFile}}@FormDataParam("file") InputStream inputStream, +{{#isFormParam}}{{#notFile}}{{^vendorExtensions.x-multipart}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}){{/vendorExtensions.x-multipart}}{{#vendorExtensions.x-multipart}}@FormDataParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{^vendorExtensions.x-multipart}}@FormParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{/notFile}}{{#isFile}}@FormDataParam("file") InputStream inputStream, @FormDataParam("file") FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file From 20448dd9e3f08174e7d9930576872ed8f08c5383 Mon Sep 17 00:00:00 2001 From: Daniel Ge Date: Wed, 6 Jul 2016 12:03:10 -0700 Subject: [PATCH 061/470] Bump and regenerate PHP sample --- .../php/SwaggerClient-php/README.md | 26 +++---- .../php/SwaggerClient-php/autoload.php | 8 +- .../php/SwaggerClient-php/docs/Api/FakeApi.md | 14 ++-- .../docs/Model/ModelReturn.md | 2 +- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 22 +++--- .../php/SwaggerClient-php/lib/ApiClient.php | 8 +- .../SwaggerClient-php/lib/ApiException.php | 8 +- .../SwaggerClient-php/lib/Configuration.php | 12 +-- .../lib/Model/ModelReturn.php | 12 +-- .../lib/ObjectSerializer.php | 10 +-- .../petstore/php/SwaggerClient-php/README.md | 20 +++-- .../php/SwaggerClient-php/docs/Api/FakeApi.md | 43 ----------- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 73 ------------------- 13 files changed, 76 insertions(+), 182 deletions(-) diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/README.md b/samples/client/petstore-security-test/php/SwaggerClient-php/README.md index e147df3172e..a98574cf4f6 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/README.md +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/README.md @@ -1,10 +1,10 @@ # SwaggerClient-php -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end This PHP package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: -- API version: 1.0.0 *_/ ' \" =end -- Build date: 2016-07-02T16:22:07.280+08:00 +- API version: 1.0.0 */ ' " =end +- Build date: 2016-07-06T12:08:58.407-07:00 - Build package: class io.swagger.codegen.languages.PhpClientCodegen ## Requirements @@ -58,7 +58,7 @@ Please follow the [installation procedure](#installation--usage) and then run th require_once(__DIR__ . '/vendor/autoload.php'); $api_instance = new Swagger\Client\Api\FakeApi(); -$test_code_inject____end = "test_code_inject____end_example"; // string | To test code injection *_/ ' \" =end +$test_code_inject____end = "test_code_inject____end_example"; // string | To test code injection */ ' \" =end try { $api_instance->testCodeInjectEnd($test_code_inject____end); @@ -71,11 +71,11 @@ try { ## Documentation for API Endpoints -All URIs are relative to *https://petstore.swagger.io *_/ ' \" =end/v2 *_/ ' \" =end* +All URIs are relative to *https://petstore.swagger.io */ ' " =end/v2 */ ' " =end* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*FakeApi* | [**testCodeInjectEnd**](docs/Api/FakeApi.md#testcodeinjectend) | **PUT** /fake | To test code injection *_/ ' \" =end +*FakeApi* | [**testCodeInjectEnd**](docs/Api/FakeApi.md#testcodeinjectend) | **PUT** /fake | To test code injection */ ' \" =end ## Documentation For Models @@ -86,12 +86,6 @@ Class | Method | HTTP request | Description ## Documentation For Authorization -## api_key - -- **Type**: API key -- **API key parameter name**: api_key */ ' " =end -- **Location**: HTTP header - ## petstore_auth - **Type**: OAuth @@ -101,9 +95,15 @@ Class | Method | HTTP request | Description - **write:pets**: modify pets in your account */ ' " =end - **read:pets**: read your pets */ ' " =end +## api_key + +- **Type**: API key +- **API key parameter name**: api_key */ ' " =end +- **Location**: HTTP header + ## Author -apiteam@swagger.io *_/ ' \" =end +apiteam@swagger.io */ ' " =end diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/autoload.php b/samples/client/petstore-security-test/php/SwaggerClient-php/autoload.php index cc9a6698cdf..2b57a0e3dae 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/autoload.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/autoload.php @@ -1,12 +1,12 @@ testCodeInjectEnd($test_code_inject____end) -To test code injection *_/ ' \" =end +To test code injection */ ' \" =end ### Example ```php @@ -18,7 +18,7 @@ To test code injection *_/ ' \" =end require_once(__DIR__ . '/vendor/autoload.php'); $api_instance = new Swagger\Client\Api\FakeApi(); -$test_code_inject____end = "test_code_inject____end_example"; // string | To test code injection *_/ ' \" =end +$test_code_inject____end = "test_code_inject____end_example"; // string | To test code injection */ ' \" =end try { $api_instance->testCodeInjectEnd($test_code_inject____end); @@ -32,7 +32,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **test_code_inject____end** | **string**| To test code injection *_/ ' \" =end | [optional] + **test_code_inject____end** | **string**| To test code injection */ ' \" =end | [optional] ### Return type @@ -44,8 +44,8 @@ No authorization required ### HTTP request headers - - **Content-Type**: application/json, */ " =end - - **Accept**: application/json, */ " =end + - **Content-Type**: application/json, */ ' " =end + - **Accept**: application/json, */ ' " =end [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/docs/Model/ModelReturn.md b/samples/client/petstore-security-test/php/SwaggerClient-php/docs/Model/ModelReturn.md index 97772852c12..ec3cb241037 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/docs/Model/ModelReturn.md +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/docs/Model/ModelReturn.md @@ -3,7 +3,7 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**return** | **int** | property description *_/ ' \" =end | [optional] +**return** | **int** | property description */ ' \" =end | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php index 8c9ea6c5c29..fb8134bb8ef 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -11,12 +11,12 @@ */ /** - * Swagger Petstore *_/ ' \" =end + * Swagger Petstore */ ' " =end * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end * - * OpenAPI spec version: 1.0.0 *_/ ' \" =end - * Contact: apiteam@swagger.io *_/ ' \" =end + * OpenAPI spec version: 1.0.0 */ ' " =end + * Contact: apiteam@swagger.io */ ' " =end * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -73,7 +73,7 @@ public function __construct(\Swagger\Client\ApiClient $apiClient = null) { if ($apiClient == null) { $apiClient = new ApiClient(); - $apiClient->getConfig()->setHost('https://petstore.swagger.io *_/ ' \" =end/v2 *_/ ' \" =end'); + $apiClient->getConfig()->setHost('https://petstore.swagger.io */ ' " =end/v2 */ ' " =end'); } $this->apiClient = $apiClient; @@ -105,9 +105,9 @@ public function setApiClient(\Swagger\Client\ApiClient $apiClient) /** * Operation testCodeInjectEnd * - * To test code injection *_/ ' \" =end + * To test code injection */ ' \" =end * - * @param string $test_code_inject____end To test code injection *_/ ' \" =end (optional) + * @param string $test_code_inject____end To test code injection */ ' \" =end (optional) * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -120,9 +120,9 @@ public function testCodeInjectEnd($test_code_inject____end = null) /** * Operation testCodeInjectEndWithHttpInfo * - * To test code injection *_/ ' \" =end + * To test code injection */ ' \" =end * - * @param string $test_code_inject____end To test code injection *_/ ' \" =end (optional) + * @param string $test_code_inject____end To test code injection */ ' \" =end (optional) * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -134,11 +134,11 @@ public function testCodeInjectEndWithHttpInfo($test_code_inject____end = null) $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', '*/ " =end')); + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', '*/ ' " =end')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json','*/ " =end')); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json','*/ ' " =end')); // default format to json $resourcePath = str_replace("{format}", "json", $resourcePath); diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiClient.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiClient.php index 53c2b153bee..76b9fafe437 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiClient.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiClient.php @@ -12,12 +12,12 @@ */ /** - * Swagger Petstore *_/ ' \" =end + * Swagger Petstore */ ' " =end * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end * - * OpenAPI spec version: 1.0.0 *_/ ' \" =end - * Contact: apiteam@swagger.io *_/ ' \" =end + * OpenAPI spec version: 1.0.0 */ ' " =end + * Contact: apiteam@swagger.io */ ' " =end * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiException.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiException.php index 9bb23ee3341..34492fb063d 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiException.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiException.php @@ -11,12 +11,12 @@ */ /** - * Swagger Petstore *_/ ' \" =end + * Swagger Petstore */ ' " =end * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end * - * OpenAPI spec version: 1.0.0 *_/ ' \" =end - * Contact: apiteam@swagger.io *_/ ' \" =end + * OpenAPI spec version: 1.0.0 */ ' " =end + * Contact: apiteam@swagger.io */ ' " =end * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php index a5838d9c81c..3819200d19e 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php @@ -11,12 +11,12 @@ */ /** - * Swagger Petstore *_/ ' \" =end + * Swagger Petstore */ ' " =end * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end * - * OpenAPI spec version: 1.0.0 *_/ ' \" =end - * Contact: apiteam@swagger.io *_/ ' \" =end + * OpenAPI spec version: 1.0.0 */ ' " =end + * Contact: apiteam@swagger.io */ ' " =end * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -102,7 +102,7 @@ class Configuration * * @var string */ - protected $host = 'https://petstore.swagger.io *_/ ' \" =end/v2 *_/ ' \" =end'; + protected $host = 'https://petstore.swagger.io */ ' " =end/v2 */ ' " =end'; /** * Timeout (second) of the HTTP request, by default set to 0, no timeout @@ -522,7 +522,7 @@ public static function toDebugReport() $report = 'PHP SDK (Swagger\Client) Debug Report:' . PHP_EOL; $report .= ' OS: ' . php_uname() . PHP_EOL; $report .= ' PHP Version: ' . phpversion() . PHP_EOL; - $report .= ' OpenAPI Spec Version: 1.0.0 *_/ ' \" =end' . PHP_EOL; + $report .= ' OpenAPI Spec Version: 1.0.0 */ ' " =end' . PHP_EOL; $report .= ' Temp Folder Path: ' . self::getDefaultConfiguration()->getTempFolderPath() . PHP_EOL; return $report; diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Model/ModelReturn.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Model/ModelReturn.php index eeaf6ff9279..8981f0dcd87 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Model/ModelReturn.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Model/ModelReturn.php @@ -12,12 +12,12 @@ */ /** - * Swagger Petstore *_/ ' \" =end + * Swagger Petstore */ ' " =end * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end * - * OpenAPI spec version: 1.0.0 *_/ ' \" =end - * Contact: apiteam@swagger.io *_/ ' \" =end + * OpenAPI spec version: 1.0.0 */ ' " =end + * Contact: apiteam@swagger.io */ ' " =end * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -47,7 +47,7 @@ * ModelReturn Class Doc Comment * * @category Class */ - // @description Model for testing reserved words *_/ ' \" =end + // @description Model for testing reserved words */ ' \" =end /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen @@ -167,7 +167,7 @@ public function getReturn() /** * Sets return - * @param int $return property description *_/ ' \" =end + * @param int $return property description */ ' \" =end * @return $this */ public function setReturn($return) diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php index 7ee21f8bd6a..53663a58e38 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -12,12 +12,12 @@ */ /** - * Swagger Petstore *_/ ' \" =end + * Swagger Petstore */ ' " =end * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end * - * OpenAPI spec version: 1.0.0 *_/ ' \" =end - * Contact: apiteam@swagger.io *_/ ' \" =end + * OpenAPI spec version: 1.0.0 */ ' " =end + * Contact: apiteam@swagger.io */ ' " =end * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -264,7 +264,7 @@ public static function deserialize($data, $class, $httpHeaders = null, $discrimi } else { return null; } - } elseif (in_array($class, array('integer', 'int', 'void', 'number', 'object', 'double', 'float', 'byte', 'DateTime', 'string', 'mixed', 'boolean', 'bool'))) { + } elseif (in_array($class, array('void', 'bool', 'string', 'double', 'byte', 'mixed', 'integer', 'float', 'int', 'DateTime', 'number', 'boolean', 'object'))) { settype($data, $class); return $data; } elseif ($class === '\SplFileObject') { diff --git a/samples/client/petstore/php/SwaggerClient-php/README.md b/samples/client/petstore/php/SwaggerClient-php/README.md index 735d53925ae..7290ed1c984 100644 --- a/samples/client/petstore/php/SwaggerClient-php/README.md +++ b/samples/client/petstore/php/SwaggerClient-php/README.md @@ -4,7 +4,7 @@ This spec is mainly for testing Petstore server and contains fake endpoints, mod This PHP package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: - API version: 1.0.0 -- Build date: 2016-06-30T07:09:58.112+02:00 +- Build date: 2016-07-06T12:01:52.156-07:00 - Build package: class io.swagger.codegen.languages.PhpClientCodegen ## Requirements @@ -58,12 +58,23 @@ Please follow the [installation procedure](#installation--usage) and then run th require_once(__DIR__ . '/vendor/autoload.php'); $api_instance = new Swagger\Client\Api\FakeApi(); -$test_code_inject__end = "test_code_inject__end_example"; // string | To test code injection =end +$number = 3.4; // float | None +$double = 1.2; // double | None +$string = "string_example"; // string | None +$byte = "B"; // string | None +$integer = 56; // int | None +$int32 = 56; // int | None +$int64 = 789; // int | None +$float = 3.4; // float | None +$binary = "B"; // string | None +$date = new \DateTime(); // \DateTime | None +$date_time = new \DateTime(); // \DateTime | None +$password = "password_example"; // string | None try { - $api_instance->testCodeInjectEnd($test_code_inject__end); + $api_instance->testEndpointParameters($number, $double, $string, $byte, $integer, $int32, $int64, $float, $binary, $date, $date_time, $password); } catch (Exception $e) { - echo 'Exception when calling FakeApi->testCodeInjectEnd: ', $e->getMessage(), PHP_EOL; + echo 'Exception when calling FakeApi->testEndpointParameters: ', $e->getMessage(), PHP_EOL; } ?> @@ -75,7 +86,6 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*FakeApi* | [**testCodeInjectEnd**](docs/Api/FakeApi.md#testcodeinjectend) | **PUT** /fake | To test code injection =end *FakeApi* | [**testEndpointParameters**](docs/Api/FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 *FakeApi* | [**testEnumQueryParameters**](docs/Api/FakeApi.md#testenumqueryparameters) | **GET** /fake | To test enum query parameters *PetApi* | [**addPet**](docs/Api/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Api/FakeApi.md b/samples/client/petstore/php/SwaggerClient-php/docs/Api/FakeApi.md index 5a8096f547f..3ca55218e36 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/Api/FakeApi.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Api/FakeApi.md @@ -4,53 +4,10 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**testCodeInjectEnd**](FakeApi.md#testCodeInjectEnd) | **PUT** /fake | To test code injection =end [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters -# **testCodeInjectEnd** -> testCodeInjectEnd($test_code_inject__end) - -To test code injection =end - -### Example -```php -testCodeInjectEnd($test_code_inject__end); -} catch (Exception $e) { - echo 'Exception when calling FakeApi->testCodeInjectEnd: ', $e->getMessage(), PHP_EOL; -} -?> -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **test_code_inject__end** | **string**| To test code injection =end | [optional] - -### Return type - -void (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json, */ =end));(phpinfo( - - **Accept**: application/json, */ end - -[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) - # **testEndpointParameters** > testEndpointParameters($number, $double, $string, $byte, $integer, $int32, $int64, $float, $binary, $date, $date_time, $password) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index 4c1c1c04ed2..f644572884a 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -102,79 +102,6 @@ public function setApiClient(\Swagger\Client\ApiClient $apiClient) return $this; } - /** - * Operation testCodeInjectEnd - * - * To test code injection =end - * - * @param string $test_code_inject__end To test code injection =end (optional) - * @return void - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function testCodeInjectEnd($test_code_inject__end = null) - { - list($response) = $this->testCodeInjectEndWithHttpInfo($test_code_inject__end); - return $response; - } - - /** - * Operation testCodeInjectEndWithHttpInfo - * - * To test code injection =end - * - * @param string $test_code_inject__end To test code injection =end (optional) - * @return Array of null, HTTP status code, HTTP response headers (array of strings) - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function testCodeInjectEndWithHttpInfo($test_code_inject__end = null) - { - // parse inputs - $resourcePath = "/fake"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', '*/ end')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json','*/ =end));(phpinfo(')); - - // default format to json - $resourcePath = str_replace("{format}", "json", $resourcePath); - - // form params - if ($test_code_inject__end !== null) { - $formParams['test code inject */ =end'] = $this->apiClient->getSerializer()->toFormValue($test_code_inject__end); - } - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) - } - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'PUT', - $queryParams, - $httpBody, - $headerParams, - null, - '/fake' - ); - - return array(null, $statusCode, $httpHeader); - } catch (ApiException $e) { - switch ($e->getCode()) { - } - - throw $e; - } - } - /** * Operation testEndpointParameters * From b16eda17e87450202f4f75533142d497ffbd49c0 Mon Sep 17 00:00:00 2001 From: Daniel Ge Date: Fri, 17 Jun 2016 15:07:11 -0700 Subject: [PATCH 062/470] Improve error message for connection failures Previous ApiException message would simply print out the result of the `curl_getinfo($curl)` call, which might be useful only if the developer actually wanted very low-level information from curl about why a call failed. The new message should print out a higher-level but more informative, human-readable message. If necessary for debugging, the ApiException's responseObject is set to the `curl_getinfo($curl)`. --- .../src/main/resources/php/ApiClient.mustache | 14 +++++++++++++- .../php/SwaggerClient-php/README.md | 2 +- .../php/SwaggerClient-php/lib/ApiClient.php | 14 +++++++++++++- .../petstore/php/SwaggerClient-php/README.md | 2 +- .../php/SwaggerClient-php/lib/ApiClient.php | 14 +++++++++++++- 5 files changed, 41 insertions(+), 5 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index 5b21f922c6b..59cde85cea6 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -224,7 +224,19 @@ class ApiClient // Handle the response if ($response_info['http_code'] == 0) { - throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null); + $curl_error_message = curl_error($curl); + + // curl_exec can sometimes fail but still return a blank message from curl_error(). + if (!empty($curl_error_message)) { + $error_message = "API call to $url failed: $curl_error_message"; + } else { + $error_message = "API call to $url failed, but for an unknown reason. " . + "This could happen if you are disconnected from the network."; + } + + $exception = new ApiException($error_message, 0, null, null); + $exception->setResponseObject($response_info); + throw $exception; } elseif ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299) { // return raw body if response is a file if ($responseType == '\SplFileObject' || $responseType == 'string') { diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/README.md b/samples/client/petstore-security-test/php/SwaggerClient-php/README.md index a98574cf4f6..12d2d176c62 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/README.md +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/README.md @@ -4,7 +4,7 @@ This spec is mainly for testing Petstore server and contains fake endpoints, mod This PHP package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: - API version: 1.0.0 */ ' " =end -- Build date: 2016-07-06T12:08:58.407-07:00 +- Build date: 2016-07-06T12:09:22.895-07:00 - Build package: class io.swagger.codegen.languages.PhpClientCodegen ## Requirements diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiClient.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiClient.php index 76b9fafe437..eed39f53c7e 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiClient.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiClient.php @@ -245,7 +245,19 @@ public function callApi($resourcePath, $method, $queryParams, $postData, $header // Handle the response if ($response_info['http_code'] == 0) { - throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null); + $curl_error_message = curl_error($curl); + + // curl_exec can sometimes fail but still return a blank message from curl_error(). + if (!empty($curl_error_message)) { + $error_message = "API call to $url failed: $curl_error_message"; + } else { + $error_message = "API call to $url failed, but for an unknown reason. " . + "This could happen if you are disconnected from the network."; + } + + $exception = new ApiException($error_message, 0, null, null); + $exception->setResponseObject($response_info); + throw $exception; } elseif ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299) { // return raw body if response is a file if ($responseType == '\SplFileObject' || $responseType == 'string') { diff --git a/samples/client/petstore/php/SwaggerClient-php/README.md b/samples/client/petstore/php/SwaggerClient-php/README.md index 7290ed1c984..23b5fc1b4f0 100644 --- a/samples/client/petstore/php/SwaggerClient-php/README.md +++ b/samples/client/petstore/php/SwaggerClient-php/README.md @@ -4,7 +4,7 @@ This spec is mainly for testing Petstore server and contains fake endpoints, mod This PHP package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: - API version: 1.0.0 -- Build date: 2016-07-06T12:01:52.156-07:00 +- Build date: 2016-07-06T12:05:01.729-07:00 - Build package: class io.swagger.codegen.languages.PhpClientCodegen ## Requirements diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php index 45feec1a287..45f83859de4 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php @@ -245,7 +245,19 @@ public function callApi($resourcePath, $method, $queryParams, $postData, $header // Handle the response if ($response_info['http_code'] == 0) { - throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null); + $curl_error_message = curl_error($curl); + + // curl_exec can sometimes fail but still return a blank message from curl_error(). + if (!empty($curl_error_message)) { + $error_message = "API call to $url failed: $curl_error_message"; + } else { + $error_message = "API call to $url failed, but for an unknown reason. " . + "This could happen if you are disconnected from the network."; + } + + $exception = new ApiException($error_message, 0, null, null); + $exception->setResponseObject($response_info); + throw $exception; } elseif ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299) { // return raw body if response is a file if ($responseType == '\SplFileObject' || $responseType == 'string') { From 71289a1b7133c1b3d3f71de0dca9fb50db401458 Mon Sep 17 00:00:00 2001 From: Reyna DeLoge Date: Wed, 6 Jul 2016 15:00:00 -0700 Subject: [PATCH 063/470] Update README.md Fix link! --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 29d6814f7c0..dbe835eb982 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ :warning: If the OpenAPI/Swagger spec is obtained from an untrusted source, please make sure you've reviewed the spec before using Swagger Codegen to generate the API client, server stub or documentation as [code injection](https://en.wikipedia.org/wiki/Code_injection) may occur :warning: ## Overview -This is the swagger codegen project, which allows generation of API client libraries, server stubs and documentation automatically given an [OpenAPI Spec]((https://github.com/OAI/OpenAPI-Specification). +This is the swagger codegen project, which allows generation of API client libraries, server stubs and documentation automatically given an [OpenAPI Spec](https://github.com/OAI/OpenAPI-Specification). Check out [Swagger-Spec](https://github.com/OAI/OpenAPI-Specification) for additional information about the Swagger project, including additional libraries with support for other languages and more. From 1f0f08f886a9e8171e6b77fa18d966196b9d8e71 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 7 Jul 2016 10:51:42 +0800 Subject: [PATCH 064/470] update jaxrs jersey1 sample --- .../jaxrs/jersey1/src/gen/java/io/swagger/api/PetApi.java | 2 +- .../jersey1/src/gen/java/io/swagger/api/PetApiService.java | 2 +- .../src/main/java/io/swagger/api/impl/PetApiServiceImpl.java | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApi.java index 4c0aed9e1a3..6ab33888e61 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApi.java @@ -9,8 +9,8 @@ import com.sun.jersey.multipart.FormDataParam; import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; import java.util.List; import io.swagger.api.NotFoundException; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApiService.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApiService.java index 5e24c438c38..4cf67d11f3e 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApiService.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApiService.java @@ -6,8 +6,8 @@ import com.sun.jersey.multipart.FormDataParam; import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; import java.util.List; import io.swagger.api.NotFoundException; diff --git a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java index 60f77b123d7..0dc50dd1fcc 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -6,8 +6,8 @@ import com.sun.jersey.multipart.FormDataParam; import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; import java.util.List; import io.swagger.api.NotFoundException; From e1fead8ee576cd0ee97debb25f02bcd3f650b3df Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 7 Jul 2016 11:32:05 +0800 Subject: [PATCH 065/470] update spring petstore sample --- .../src/main/java/io/swagger/api/PetApi.java | 29 ++++++++----------- .../java/io/swagger/api/PetApiController.java | 2 +- .../main/java/io/swagger/api/StoreApi.java | 8 ++--- .../src/main/java/io/swagger/api/UserApi.java | 22 +++++++------- .../src/main/java/io/swagger/api/PetApi.java | 29 ++++++++----------- .../java/io/swagger/api/PetApiController.java | 2 +- .../main/java/io/swagger/api/StoreApi.java | 8 ++--- .../src/main/java/io/swagger/api/UserApi.java | 22 +++++++------- .../src/main/resources/application.properties | 3 +- 9 files changed, 56 insertions(+), 69 deletions(-) diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java index f0f76394bf3..7f66b884f21 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; @@ -26,7 +26,7 @@ public interface PetApi { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) @RequestMapping(value = "/pet", @@ -41,14 +41,13 @@ public interface PetApi { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid pet value", response = Void.class) }) @RequestMapping(value = "/pet/{petId}", produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) - ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId, - @ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey); + ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId,@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey); @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { @@ -56,7 +55,7 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class), @ApiResponse(code = 400, message = "Invalid status value", response = Pet.class) }) @@ -71,7 +70,7 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class), @ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class) }) @@ -83,7 +82,7 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru @ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { @Authorization(value = "api_key") - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class), @ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), @@ -99,7 +98,7 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), @ApiResponse(code = 404, message = "Pet not found", response = Void.class), @@ -116,16 +115,14 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) @RequestMapping(value = "/pet/{petId}", produces = { "application/xml", "application/json" }, consumes = { "application/x-www-form-urlencoded" }, method = RequestMethod.POST) - ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId, - @ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name, - @ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status); + ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId,@ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name,@ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status); @ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = { @@ -133,15 +130,13 @@ ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs t @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) @RequestMapping(value = "/pet/{petId}/uploadImage", produces = { "application/json" }, consumes = { "multipart/form-data" }, method = RequestMethod.POST) - ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId, - @ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata, - @ApiParam(value = "file detail") @RequestPart("file") MultipartFile file); + ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId,@ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata,@ApiParam(value = "file detail") @RequestPart("file") MultipartFile file); } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApiController.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApiController.java index 3a2dcab47b6..741f62712f4 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApiController.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApiController.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; import io.swagger.annotations.*; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java index f67745dfa32..f5526de9862 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java @@ -20,7 +20,7 @@ @Api(value = "store", description = "the store API") public interface StoreApi { - @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class) + @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class, tags={ "store", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), @ApiResponse(code = 404, message = "Order not found", response = Void.class) }) @@ -32,7 +32,7 @@ public interface StoreApi { @ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { @Authorization(value = "api_key") - }) + }, tags={ "store", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Integer.class) }) @RequestMapping(value = "/store/inventory", @@ -41,7 +41,7 @@ public interface StoreApi { ResponseEntity> getInventory(); - @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class) + @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Order.class), @ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), @@ -52,7 +52,7 @@ public interface StoreApi { ResponseEntity getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId); - @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class) + @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Order.class), @ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java index 508a5c1863d..14658ede06a 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java @@ -20,7 +20,7 @@ @Api(value = "user", description = "the user API") public interface UserApi { - @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class) + @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @RequestMapping(value = "/user", @@ -29,7 +29,7 @@ public interface UserApi { ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body); - @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @RequestMapping(value = "/user/createWithArray", @@ -38,7 +38,7 @@ public interface UserApi { ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body); - @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @RequestMapping(value = "/user/createWithList", @@ -47,7 +47,7 @@ public interface UserApi { ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body); - @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class) + @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), @ApiResponse(code = 404, message = "User not found", response = Void.class) }) @@ -57,7 +57,7 @@ public interface UserApi { ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username); - @ApiOperation(value = "Get user by user name", notes = "", response = User.class) + @ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = User.class), @ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), @@ -68,18 +68,17 @@ public interface UserApi { ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username); - @ApiOperation(value = "Logs user into the system", notes = "", response = String.class) + @ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = String.class), @ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) @RequestMapping(value = "/user/login", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, - @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password); + ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username,@ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password); - @ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class) + @ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @RequestMapping(value = "/user/logout", @@ -88,14 +87,13 @@ ResponseEntity loginUser(@ApiParam(value = "The user name for login", re ResponseEntity logoutUser(); - @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class) + @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid user supplied", response = Void.class), @ApiResponse(code = 404, message = "User not found", response = Void.class) }) @RequestMapping(value = "/user/{username}", produces = { "application/xml", "application/json" }, method = RequestMethod.PUT) - ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username, - @ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body); + ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username,@ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body); } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java index f0f76394bf3..7f66b884f21 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; @@ -26,7 +26,7 @@ public interface PetApi { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) @RequestMapping(value = "/pet", @@ -41,14 +41,13 @@ public interface PetApi { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid pet value", response = Void.class) }) @RequestMapping(value = "/pet/{petId}", produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) - ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId, - @ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey); + ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId,@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey); @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { @@ -56,7 +55,7 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class), @ApiResponse(code = 400, message = "Invalid status value", response = Pet.class) }) @@ -71,7 +70,7 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class), @ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class) }) @@ -83,7 +82,7 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru @ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { @Authorization(value = "api_key") - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class), @ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), @@ -99,7 +98,7 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), @ApiResponse(code = 404, message = "Pet not found", response = Void.class), @@ -116,16 +115,14 @@ ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=tru @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) @RequestMapping(value = "/pet/{petId}", produces = { "application/xml", "application/json" }, consumes = { "application/x-www-form-urlencoded" }, method = RequestMethod.POST) - ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId, - @ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name, - @ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status); + ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId,@ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name,@ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status); @ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = { @@ -133,15 +130,13 @@ ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs t @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) @RequestMapping(value = "/pet/{petId}/uploadImage", produces = { "application/json" }, consumes = { "multipart/form-data" }, method = RequestMethod.POST) - ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId, - @ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata, - @ApiParam(value = "file detail") @RequestPart("file") MultipartFile file); + ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId,@ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata,@ApiParam(value = "file detail") @RequestPart("file") MultipartFile file); } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java index 3a2dcab47b6..741f62712f4 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; import io.swagger.annotations.*; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApi.java index f67745dfa32..f5526de9862 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApi.java @@ -20,7 +20,7 @@ @Api(value = "store", description = "the store API") public interface StoreApi { - @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class) + @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class, tags={ "store", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), @ApiResponse(code = 404, message = "Order not found", response = Void.class) }) @@ -32,7 +32,7 @@ public interface StoreApi { @ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { @Authorization(value = "api_key") - }) + }, tags={ "store", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Integer.class) }) @RequestMapping(value = "/store/inventory", @@ -41,7 +41,7 @@ public interface StoreApi { ResponseEntity> getInventory(); - @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class) + @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Order.class), @ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), @@ -52,7 +52,7 @@ public interface StoreApi { ResponseEntity getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId); - @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class) + @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Order.class), @ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApi.java index 508a5c1863d..14658ede06a 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApi.java @@ -20,7 +20,7 @@ @Api(value = "user", description = "the user API") public interface UserApi { - @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class) + @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @RequestMapping(value = "/user", @@ -29,7 +29,7 @@ public interface UserApi { ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body); - @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @RequestMapping(value = "/user/createWithArray", @@ -38,7 +38,7 @@ public interface UserApi { ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body); - @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @RequestMapping(value = "/user/createWithList", @@ -47,7 +47,7 @@ public interface UserApi { ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body); - @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class) + @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), @ApiResponse(code = 404, message = "User not found", response = Void.class) }) @@ -57,7 +57,7 @@ public interface UserApi { ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username); - @ApiOperation(value = "Get user by user name", notes = "", response = User.class) + @ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = User.class), @ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), @@ -68,18 +68,17 @@ public interface UserApi { ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username); - @ApiOperation(value = "Logs user into the system", notes = "", response = String.class) + @ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = String.class), @ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) @RequestMapping(value = "/user/login", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, - @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password); + ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username,@ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password); - @ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class) + @ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @RequestMapping(value = "/user/logout", @@ -88,14 +87,13 @@ ResponseEntity loginUser(@ApiParam(value = "The user name for login", re ResponseEntity logoutUser(); - @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class) + @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid user supplied", response = Void.class), @ApiResponse(code = 404, message = "User not found", response = Void.class) }) @RequestMapping(value = "/user/{username}", produces = { "application/xml", "application/json" }, method = RequestMethod.PUT) - ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username, - @ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body); + ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username,@ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body); } diff --git a/samples/server/petstore/springboot/src/main/resources/application.properties b/samples/server/petstore/springboot/src/main/resources/application.properties index 858a5f007b5..22fb546ba98 100644 --- a/samples/server/petstore/springboot/src/main/resources/application.properties +++ b/samples/server/petstore/springboot/src/main/resources/application.properties @@ -1,2 +1,3 @@ -springfox.documentation.swagger.v2.path=/api-docs +springfox.documentation.swagger.v2.path=/api-docs +server.contextPath=/v2 #server.port=8090 \ No newline at end of file From 2d24e9971cff291aa6497d2e7a897f03ecf92fb8 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 7 Jul 2016 11:38:07 +0800 Subject: [PATCH 066/470] update jaxrs sample --- .../java/io/swagger/api/PetApiService.java | 2 +- .../swagger/api/impl/PetApiServiceImpl.java | 2 +- .../src/gen/java/io/swagger/api/PetApi.java | 359 +++++++++--------- .../java/io/swagger/api/PetApiService.java | 4 +- .../src/gen/java/io/swagger/api/StoreApi.java | 177 ++++----- .../src/gen/java/io/swagger/api/UserApi.java | 271 ++++++------- .../swagger/api/impl/PetApiServiceImpl.java | 4 +- 7 files changed, 422 insertions(+), 397 deletions(-) diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApiService.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApiService.java index 4cf67d11f3e..b2a0f65fdba 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApiService.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApiService.java @@ -36,6 +36,6 @@ public abstract Response updatePet(Pet body,SecurityContext securityContext) throws NotFoundException; public abstract Response updatePetWithForm(Long petId,String name,String status,SecurityContext securityContext) throws NotFoundException; - public abstract Response uploadFile(Long petId,String additionalMetadata,InputStream inputStream, FormDataContentDisposition fileDetail,SecurityContext securityContext) + public abstract Response uploadFile(Long petId,String additionalMetadata,InputStream fileInputStream, FormDataContentDisposition fileDetail,SecurityContext securityContext) throws NotFoundException; } diff --git a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java index 0dc50dd1fcc..82f46f8ffe7 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -65,7 +65,7 @@ public Response updatePetWithForm(Long petId, String name, String status, Securi return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response uploadFile(Long petId, String additionalMetadata, InputStream inputStream, FormDataContentDisposition fileDetail, SecurityContext securityContext) + public Response uploadFile(Long petId, String additionalMetadata, InputStream fileInputStream, FormDataContentDisposition fileDetail, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApi.java index 20b70593452..1f02fd84b17 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApi.java @@ -1,173 +1,186 @@ -package io.swagger.api; - -import io.swagger.model.*; -import io.swagger.api.PetApiService; -import io.swagger.api.factories.PetApiServiceFactory; - -import io.swagger.annotations.ApiParam; - -import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; -import java.io.File; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; -import org.glassfish.jersey.media.multipart.FormDataParam; - -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.ws.rs.*; - -@Path("/pet") - - -@io.swagger.annotations.Api(description = "the pet API") - -public class PetApi { - private final PetApiService delegate = PetApiServiceFactory.getPetApi(); - - @POST - - @Consumes({ "application/json", "application/xml" }) - @Produces({ "application/xml", "application/json" }) - @io.swagger.annotations.ApiOperation(value = "Add a new pet to the store", notes = "", response = void.class, authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { - @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = void.class) }) - public Response addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true) Pet body,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.addPet(body,securityContext); - } - @DELETE - @Path("/{petId}") - - @Produces({ "application/xml", "application/json" }) - @io.swagger.annotations.ApiOperation(value = "Deletes a pet", notes = "", response = void.class, authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { - @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid pet value", response = void.class) }) - public Response deletePet(@ApiParam(value = "Pet id to delete",required=true) @PathParam("petId") Long petId,@ApiParam(value = "" )@HeaderParam("api_key") String apiKey,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.deletePet(petId,apiKey,securityContext); - } - @GET - @Path("/findByStatus") - - @Produces({ "application/xml", "application/json" }) - @io.swagger.annotations.ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { - @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), - - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid status value", response = Pet.class, responseContainer = "List") }) - public Response findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter",required=true) @QueryParam("status") List status,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.findPetsByStatus(status,securityContext); - } - @GET - @Path("/findByTags") - - @Produces({ "application/xml", "application/json" }) - @io.swagger.annotations.ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { - @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), - - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class, responseContainer = "List") }) - public Response findPetsByTags(@ApiParam(value = "Tags to filter by",required=true) @QueryParam("tags") List tags,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.findPetsByTags(tags,securityContext); - } - @GET - @Path("/{petId}") - - @Produces({ "application/xml", "application/json" }) - @io.swagger.annotations.ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { - @io.swagger.annotations.Authorization(value = "api_key") - }, tags={ "pet", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class), - - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), - - @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = Pet.class) }) - public Response getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathParam("petId") Long petId,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.getPetById(petId,securityContext); - } - @PUT - - @Consumes({ "application/json", "application/xml" }) - @Produces({ "application/xml", "application/json" }) - @io.swagger.annotations.ApiOperation(value = "Update an existing pet", notes = "", response = void.class, authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { - @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = void.class), - - @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = void.class), - - @io.swagger.annotations.ApiResponse(code = 405, message = "Validation exception", response = void.class) }) - public Response updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true) Pet body,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.updatePet(body,securityContext); - } - @POST - @Path("/{petId}") - @Consumes({ "application/x-www-form-urlencoded" }) - @Produces({ "application/xml", "application/json" }) - @io.swagger.annotations.ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = void.class, authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { - @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = void.class) }) - public Response updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true) @PathParam("petId") Long petId,@ApiParam(value = "Updated name of the pet")@FormParam("name") String name,@ApiParam(value = "Updated status of the pet")@FormParam("status") String status,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.updatePetWithForm(petId,name,status,securityContext); - } - @POST - @Path("/{petId}/uploadImage") - @Consumes({ "multipart/form-data" }) - @Produces({ "application/json" }) - @io.swagger.annotations.ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { - @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) - public Response uploadFile(@ApiParam(value = "ID of pet to update",required=true) @PathParam("petId") Long petId,@ApiParam(value = "Additional data to pass to server")@FormDataParam("additionalMetadata") String additionalMetadata, - @FormDataParam("file") InputStream inputStream, - @FormDataParam("file") FormDataContentDisposition fileDetail,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.uploadFile(petId,additionalMetadata,inputStream, fileDetail,securityContext); - } -} +package io.swagger.api; + +import io.swagger.model.*; +import io.swagger.api.PetApiService; +import io.swagger.api.factories.PetApiServiceFactory; + +import io.swagger.annotations.ApiParam; + +import io.swagger.model.Pet; +import java.io.File; +import io.swagger.model.ModelApiResponse; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.FormDataParam; + +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.ws.rs.*; + +@Path("/pet") + + +@io.swagger.annotations.Api(description = "the pet API") + +public class PetApi { + private final PetApiService delegate = PetApiServiceFactory.getPetApi(); + + @POST + + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Add a new pet to the store", notes = "", response = void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = void.class) }) + public Response addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true) Pet body +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.addPet(body,securityContext); + } + @DELETE + @Path("/{petId}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Deletes a pet", notes = "", response = void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid pet value", response = void.class) }) + public Response deletePet(@ApiParam(value = "Pet id to delete",required=true) @PathParam("petId") Long petId +,@ApiParam(value = "" )@HeaderParam("api_key") String apiKey +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.deletePet(petId,apiKey,securityContext); + } + @GET + @Path("/findByStatus") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), + + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid status value", response = Pet.class, responseContainer = "List") }) + public Response findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter",required=true) @QueryParam("status") List status +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.findPetsByStatus(status,securityContext); + } + @GET + @Path("/findByTags") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), + + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class, responseContainer = "List") }) + public Response findPetsByTags(@ApiParam(value = "Tags to filter by",required=true) @QueryParam("tags") List tags +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.findPetsByTags(tags,securityContext); + } + @GET + @Path("/{petId}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { + @io.swagger.annotations.Authorization(value = "api_key") + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class), + + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = Pet.class) }) + public Response getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathParam("petId") Long petId +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.getPetById(petId,securityContext); + } + @PUT + + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Update an existing pet", notes = "", response = void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = void.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = void.class), + + @io.swagger.annotations.ApiResponse(code = 405, message = "Validation exception", response = void.class) }) + public Response updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true) Pet body +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.updatePet(body,securityContext); + } + @POST + @Path("/{petId}") + @Consumes({ "application/x-www-form-urlencoded" }) + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = void.class) }) + public Response updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true) @PathParam("petId") Long petId +,@ApiParam(value = "Updated name of the pet")@FormParam("name") String name +,@ApiParam(value = "Updated status of the pet")@FormParam("status") String status +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.updatePetWithForm(petId,name,status,securityContext); + } + @POST + @Path("/{petId}/uploadImage") + @Consumes({ "multipart/form-data" }) + @Produces({ "application/json" }) + @io.swagger.annotations.ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) + public Response uploadFile(@ApiParam(value = "ID of pet to update",required=true) @PathParam("petId") Long petId +,@ApiParam(value = "Additional data to pass to server")@FormDataParam("additionalMetadata") String additionalMetadata +, + @FormDataParam("file") InputStream fileInputStream, + @FormDataParam("file") FormDataContentDisposition fileDetail +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.uploadFile(petId,additionalMetadata,fileInputStream, fileDetail,securityContext); + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApiService.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApiService.java index e86ffcf5b85..fdd2296320d 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApiService.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApiService.java @@ -6,8 +6,8 @@ import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; import java.util.List; import io.swagger.api.NotFoundException; @@ -26,5 +26,5 @@ public abstract class PetApiService { public abstract Response getPetById(Long petId,SecurityContext securityContext) throws NotFoundException; public abstract Response updatePet(Pet body,SecurityContext securityContext) throws NotFoundException; public abstract Response updatePetWithForm(Long petId,String name,String status,SecurityContext securityContext) throws NotFoundException; - public abstract Response uploadFile(Long petId,String additionalMetadata,InputStream inputStream, FormDataContentDisposition fileDetail,SecurityContext securityContext) throws NotFoundException; + public abstract Response uploadFile(Long petId,String additionalMetadata,InputStream fileInputStream, FormDataContentDisposition fileDetail,SecurityContext securityContext) throws NotFoundException; } diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApi.java index 7319e0465f0..86ab8f56452 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApi.java @@ -1,87 +1,90 @@ -package io.swagger.api; - -import io.swagger.model.*; -import io.swagger.api.StoreApiService; -import io.swagger.api.factories.StoreApiServiceFactory; - -import io.swagger.annotations.ApiParam; - -import java.util.Map; -import io.swagger.model.Order; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; -import org.glassfish.jersey.media.multipart.FormDataParam; - -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.ws.rs.*; - -@Path("/store") - - -@io.swagger.annotations.Api(description = "the store API") - -public class StoreApi { - private final StoreApiService delegate = StoreApiServiceFactory.getStoreApi(); - - @DELETE - @Path("/order/{orderId}") - - @Produces({ "application/xml", "application/json" }) - @io.swagger.annotations.ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = void.class, tags={ "store", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = void.class), - - @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = void.class) }) - public Response deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathParam("orderId") String orderId,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.deleteOrder(orderId,securityContext); - } - @GET - @Path("/inventory") - - @Produces({ "application/json" }) - @io.swagger.annotations.ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { - @io.swagger.annotations.Authorization(value = "api_key") - }, tags={ "store", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Integer.class, responseContainer = "Map") }) - public Response getInventory(@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.getInventory(securityContext); - } - @GET - @Path("/order/{orderId}") - - @Produces({ "application/xml", "application/json" }) - @io.swagger.annotations.ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Order.class), - - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), - - @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = Order.class) }) - public Response getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathParam("orderId") Long orderId,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.getOrderById(orderId,securityContext); - } - @POST - @Path("/order") - - @Produces({ "application/xml", "application/json" }) - @io.swagger.annotations.ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Order.class), - - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) - public Response placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true) Order body,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.placeOrder(body,securityContext); - } -} +package io.swagger.api; + +import io.swagger.model.*; +import io.swagger.api.StoreApiService; +import io.swagger.api.factories.StoreApiServiceFactory; + +import io.swagger.annotations.ApiParam; + +import java.util.Map; +import io.swagger.model.Order; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.FormDataParam; + +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.ws.rs.*; + +@Path("/store") + + +@io.swagger.annotations.Api(description = "the store API") + +public class StoreApi { + private final StoreApiService delegate = StoreApiServiceFactory.getStoreApi(); + + @DELETE + @Path("/order/{orderId}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = void.class, tags={ "store", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = void.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = void.class) }) + public Response deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathParam("orderId") String orderId +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.deleteOrder(orderId,securityContext); + } + @GET + @Path("/inventory") + + @Produces({ "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { + @io.swagger.annotations.Authorization(value = "api_key") + }, tags={ "store", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Integer.class, responseContainer = "Map") }) + public Response getInventory(@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.getInventory(securityContext); + } + @GET + @Path("/order/{orderId}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Order.class), + + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = Order.class) }) + public Response getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathParam("orderId") Long orderId +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.getOrderById(orderId,securityContext); + } + @POST + @Path("/order") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Order.class), + + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) + public Response placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true) Order body +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.placeOrder(body,securityContext); + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApi.java index ed3d4e4ead4..20bc01c80c3 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApi.java @@ -1,131 +1,140 @@ -package io.swagger.api; - -import io.swagger.model.*; -import io.swagger.api.UserApiService; -import io.swagger.api.factories.UserApiServiceFactory; - -import io.swagger.annotations.ApiParam; - -import io.swagger.model.User; -import java.util.List; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; -import org.glassfish.jersey.media.multipart.FormDataParam; - -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.ws.rs.*; - -@Path("/user") - - -@io.swagger.annotations.Api(description = "the user API") - -public class UserApi { - private final UserApiService delegate = UserApiServiceFactory.getUserApi(); - - @POST - - - @Produces({ "application/xml", "application/json" }) - @io.swagger.annotations.ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) - public Response createUser(@ApiParam(value = "Created user object" ,required=true) User body,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.createUser(body,securityContext); - } - @POST - @Path("/createWithArray") - - @Produces({ "application/xml", "application/json" }) - @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = void.class, tags={ "user", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) - public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true) List body,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.createUsersWithArrayInput(body,securityContext); - } - @POST - @Path("/createWithList") - - @Produces({ "application/xml", "application/json" }) - @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = void.class, tags={ "user", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) - public Response createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true) List body,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.createUsersWithListInput(body,securityContext); - } - @DELETE - @Path("/{username}") - - @Produces({ "application/xml", "application/json" }) - @io.swagger.annotations.ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = void.class), - - @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = void.class) }) - public Response deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathParam("username") String username,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.deleteUser(username,securityContext); - } - @GET - @Path("/{username}") - - @Produces({ "application/xml", "application/json" }) - @io.swagger.annotations.ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = User.class), - - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), - - @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = User.class) }) - public Response getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true) @PathParam("username") String username,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.getUserByName(username,securityContext); - } - @GET - @Path("/login") - - @Produces({ "application/xml", "application/json" }) - @io.swagger.annotations.ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = String.class), - - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) - public Response loginUser(@ApiParam(value = "The user name for login",required=true) @QueryParam("username") String username,@ApiParam(value = "The password for login in clear text",required=true) @QueryParam("password") String password,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.loginUser(username,password,securityContext); - } - @GET - @Path("/logout") - - @Produces({ "application/xml", "application/json" }) - @io.swagger.annotations.ApiOperation(value = "Logs out current logged in user session", notes = "", response = void.class, tags={ "user", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) - public Response logoutUser(@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.logoutUser(securityContext); - } - @PUT - @Path("/{username}") - - @Produces({ "application/xml", "application/json" }) - @io.swagger.annotations.ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid user supplied", response = void.class), - - @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = void.class) }) - public Response updateUser(@ApiParam(value = "name that need to be deleted",required=true) @PathParam("username") String username,@ApiParam(value = "Updated user object" ,required=true) User body,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.updateUser(username,body,securityContext); - } -} +package io.swagger.api; + +import io.swagger.model.*; +import io.swagger.api.UserApiService; +import io.swagger.api.factories.UserApiServiceFactory; + +import io.swagger.annotations.ApiParam; + +import io.swagger.model.User; +import java.util.List; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.FormDataParam; + +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.ws.rs.*; + +@Path("/user") + + +@io.swagger.annotations.Api(description = "the user API") + +public class UserApi { + private final UserApiService delegate = UserApiServiceFactory.getUserApi(); + + @POST + + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) + public Response createUser(@ApiParam(value = "Created user object" ,required=true) User body +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.createUser(body,securityContext); + } + @POST + @Path("/createWithArray") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = void.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) + public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true) List body +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.createUsersWithArrayInput(body,securityContext); + } + @POST + @Path("/createWithList") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = void.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) + public Response createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true) List body +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.createUsersWithListInput(body,securityContext); + } + @DELETE + @Path("/{username}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = void.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = void.class) }) + public Response deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathParam("username") String username +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.deleteUser(username,securityContext); + } + @GET + @Path("/{username}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = User.class), + + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = User.class) }) + public Response getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true) @PathParam("username") String username +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.getUserByName(username,securityContext); + } + @GET + @Path("/login") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = String.class), + + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) + public Response loginUser(@ApiParam(value = "The user name for login",required=true) @QueryParam("username") String username +,@ApiParam(value = "The password for login in clear text",required=true) @QueryParam("password") String password +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.loginUser(username,password,securityContext); + } + @GET + @Path("/logout") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Logs out current logged in user session", notes = "", response = void.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) + public Response logoutUser(@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.logoutUser(securityContext); + } + @PUT + @Path("/{username}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid user supplied", response = void.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = void.class) }) + public Response updateUser(@ApiParam(value = "name that need to be deleted",required=true) @PathParam("username") String username +,@ApiParam(value = "Updated user object" ,required=true) User body +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.updateUser(username,body,securityContext); + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java index 6dacf87d932..6268083801c 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -4,8 +4,8 @@ import io.swagger.model.*; import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; import java.util.List; import io.swagger.api.NotFoundException; @@ -55,7 +55,7 @@ public Response updatePetWithForm(Long petId, String name, String status, Securi return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response uploadFile(Long petId, String additionalMetadata, InputStream inputStream, FormDataContentDisposition fileDetail, SecurityContext securityContext) throws NotFoundException { + public Response uploadFile(Long petId, String additionalMetadata, InputStream fileInputStream, FormDataContentDisposition fileDetail, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } From 3b780e30d81aeb8d9e6c4cdc172cde26c3d88ceb Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 6 Jul 2016 22:10:00 +0800 Subject: [PATCH 067/470] change java default lib to okhttp-gson --- ...a-petstore.sh => java-petstore-jersey1.sh} | 8 +- .../codegen/languages/JavaClientCodegen.java | 23 +- .../libraries/okhttp-gson/ApiClient.mustache | 2 + .../Java/libraries/okhttp-gson/JSON.mustache | 3 +- .../swagger/codegen/DefaultGeneratorTest.java | 1 + .../online/OnlineJavaClientOptionsTest.java | 2 +- pom.xml | 4 +- .../petstore/java/default/docs/ApiResponse.md | 12 - .../java/default/docs/InlineResponse200.md | 24 - .../java/io/swagger/client/ApiClient.java | 687 --------- .../java/io/swagger/client/api/FakeApi.java | 197 --- .../java/io/swagger/client/api/PetApi.java | 410 ----- .../java/io/swagger/client/api/StoreApi.java | 222 --- .../java/io/swagger/client/api/UserApi.java | 396 ----- .../java/io/swagger/PetstoreProfiling.java | 106 -- .../src/test/java/io/swagger/TestUtils.java | 17 - .../java/io/swagger/client/ApiClientTest.java | 239 --- .../io/swagger/client/ConfigurationTest.java | 15 - .../io/swagger/client/StringUtilTest.java | 33 - .../io/swagger/client/api/FakeApiTest.java | 48 - .../io/swagger/client/api/PetApiTest.java | 306 ---- .../io/swagger/client/api/StoreApiTest.java | 103 -- .../io/swagger/client/api/UserApiTest.java | 88 -- .../swagger/client/auth/ApiKeyAuthTest.java | 47 - .../client/auth/HttpBasicAuthTest.java | 52 - .../java/{default => jersey1}/.gitignore | 0 .../.swagger-codegen-ignore | 0 .../java/{default => jersey1}/.travis.yml | 0 .../java/{default => jersey1}/LICENSE | 0 .../java/{default => jersey1}/README.md | 94 +- .../java/{default => jersey1}/build.gradle | 39 +- .../client/petstore/java/jersey1/build.sbt | 20 + .../docs/AdditionalPropertiesClass.md | 0 .../java/{default => jersey1}/docs/Animal.md | 0 .../{default => jersey1}/docs/AnimalFarm.md | 0 .../docs/ArrayOfArrayOfNumberOnly.md | 0 .../docs/ArrayOfNumberOnly.md | 0 .../{default => jersey1}/docs/ArrayTest.md | 0 .../java/{default => jersey1}/docs/Cat.md | 0 .../{default => jersey1}/docs/Category.md | 0 .../java/{default => jersey1}/docs/Dog.md | 0 .../{default => jersey1}/docs/EnumClass.md | 0 .../{default => jersey1}/docs/EnumTest.md | 0 .../java/{default => jersey1}/docs/FakeApi.md | 0 .../{default => jersey1}/docs/FormatTest.md | 0 .../docs/HasOnlyReadOnly.md | 0 .../java/{default => jersey1}/docs/MapTest.md | 0 ...dPropertiesAndAdditionalPropertiesClass.md | 0 .../docs/Model200Response.md | 0 .../docs/ModelApiResponse.md | 0 .../{default => jersey1}/docs/ModelReturn.md | 0 .../java/{default => jersey1}/docs/Name.md | 0 .../{default => jersey1}/docs/NumberOnly.md | 0 .../java/{default => jersey1}/docs/Order.md | 0 .../java/{default => jersey1}/docs/Pet.md | 0 .../java/{default => jersey1}/docs/PetApi.md | 0 .../docs/ReadOnlyFirst.md | 0 .../docs/SpecialModelName.md | 0 .../{default => jersey1}/docs/StoreApi.md | 0 .../java/{default => jersey1}/docs/Tag.md | 0 .../java/{default => jersey1}/docs/User.md | 0 .../java/{default => jersey1}/docs/UserApi.md | 0 .../java/{default => jersey1}/git_push.sh | 0 .../{default => jersey1}/gradle.properties | 0 .../gradle/wrapper/gradle-wrapper.jar | Bin .../gradle/wrapper/gradle-wrapper.properties | 0 .../java/{default => jersey1}/gradlew | 0 .../java/{default => jersey1}/gradlew.bat | 0 .../java/{default => jersey1}/pom.xml | 79 +- .../java/{default => jersey1}/settings.gradle | 0 .../src/main/AndroidManifest.xml | 0 .../java/io/swagger/client/ApiCallback.java | 74 + .../java/io/swagger/client/ApiClient.java | 1324 +++++++++++++++++ .../java/io/swagger/client/ApiException.java | 0 .../java/io/swagger/client/ApiResponse.java | 71 + .../java/io/swagger/client/Configuration.java | 0 .../src/main/java/io/swagger/client/JSON.java | 236 +++ .../src/main/java/io/swagger/client/Pair.java | 0 .../swagger/client/ProgressRequestBody.java | 95 ++ .../swagger/client/ProgressResponseBody.java | 88 ++ .../java/io/swagger/client/StringUtil.java | 0 .../java/io/swagger/client/api/FakeApi.java | 353 +++++ .../java/io/swagger/client/api/PetApi.java | 935 ++++++++++++ .../java/io/swagger/client/api/StoreApi.java | 482 ++++++ .../java/io/swagger/client/api/UserApi.java | 907 +++++++++++ .../io/swagger/client/auth/ApiKeyAuth.java | 0 .../swagger/client/auth/Authentication.java | 0 .../io/swagger/client/auth/HttpBasicAuth.java | 50 +- .../java/io/swagger/client/auth/OAuth.java | 0 .../io/swagger/client/auth/OAuthFlow.java | 0 .../model/AdditionalPropertiesClass.java | 6 +- .../java/io/swagger/client/model/Animal.java | 6 +- .../io/swagger/client/model/AnimalFarm.java | 0 .../model/ArrayOfArrayOfNumberOnly.java | 4 +- .../client/model/ArrayOfNumberOnly.java | 4 +- .../io/swagger/client/model/ArrayTest.java | 8 +- .../java/io/swagger/client/model/Cat.java | 8 +- .../io/swagger/client/model/Category.java | 6 +- .../java/io/swagger/client/model/Dog.java | 8 +- .../io/swagger/client/model/EnumClass.java | 4 + .../io/swagger/client/model/EnumTest.java | 14 +- .../io/swagger/client/model/FormatTest.java | 28 +- .../swagger/client/model/HasOnlyReadOnly.java | 6 +- .../java/io/swagger/client/model/MapTest.java | 8 +- ...ropertiesAndAdditionalPropertiesClass.java | 8 +- .../client/model/Model200Response.java | 6 +- .../client/model/ModelApiResponse.java | 8 +- .../io/swagger/client/model/ModelReturn.java | 4 +- .../java/io/swagger/client/model/Name.java | 10 +- .../io/swagger/client/model/NumberOnly.java | 4 +- .../java/io/swagger/client/model/Order.java | 17 +- .../java/io/swagger/client/model/Pet.java | 17 +- .../swagger/client/model/ReadOnlyFirst.java | 6 +- .../client/model/SpecialModelName.java | 4 +- .../java/io/swagger/client/model/Tag.java | 6 +- .../java/io/swagger/client/model/User.java | 18 +- .../io/swagger/client/api/FakeApiTest.java | 92 ++ .../io/swagger/client/api/PetApiTest.java | 180 +++ .../io/swagger/client/api/StoreApiTest.java | 108 ++ .../io/swagger/client/api/UserApiTest.java | 174 +++ .../java/okhttp-gson/docs/ArrayTest.md | 7 - .../petstore/java/okhttp-gson/docs/FakeApi.md | 43 - .../java/io/swagger/client/ApiClient.java | 2 + .../src/main/java/io/swagger/client/JSON.java | 1 + .../java/io/swagger/client/api/FakeApi.java | 99 -- .../io/swagger/client/model/ArrayTest.java | 49 +- .../petstore/typescript-node/npm/api.d.ts | 6 +- 127 files changed, 5390 insertions(+), 3481 deletions(-) rename bin/{java-petstore.sh => java-petstore-jersey1.sh} (79%) delete mode 100644 samples/client/petstore/java/default/docs/ApiResponse.md delete mode 100644 samples/client/petstore/java/default/docs/InlineResponse200.md delete mode 100644 samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java delete mode 100644 samples/client/petstore/java/default/src/main/java/io/swagger/client/api/FakeApi.java delete mode 100644 samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java delete mode 100644 samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java delete mode 100644 samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java delete mode 100644 samples/client/petstore/java/default/src/test/java/io/swagger/PetstoreProfiling.java delete mode 100644 samples/client/petstore/java/default/src/test/java/io/swagger/TestUtils.java delete mode 100644 samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java delete mode 100644 samples/client/petstore/java/default/src/test/java/io/swagger/client/ConfigurationTest.java delete mode 100644 samples/client/petstore/java/default/src/test/java/io/swagger/client/StringUtilTest.java delete mode 100644 samples/client/petstore/java/default/src/test/java/io/swagger/client/api/FakeApiTest.java delete mode 100644 samples/client/petstore/java/default/src/test/java/io/swagger/client/api/PetApiTest.java delete mode 100644 samples/client/petstore/java/default/src/test/java/io/swagger/client/api/StoreApiTest.java delete mode 100644 samples/client/petstore/java/default/src/test/java/io/swagger/client/api/UserApiTest.java delete mode 100644 samples/client/petstore/java/default/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java delete mode 100644 samples/client/petstore/java/default/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java rename samples/client/petstore/java/{default => jersey1}/.gitignore (100%) rename samples/client/petstore/java/{default => jersey1}/.swagger-codegen-ignore (100%) rename samples/client/petstore/java/{default => jersey1}/.travis.yml (100%) rename samples/client/petstore/java/{default => jersey1}/LICENSE (100%) rename samples/client/petstore/java/{default => jersey1}/README.md (69%) rename samples/client/petstore/java/{default => jersey1}/build.gradle (72%) create mode 100644 samples/client/petstore/java/jersey1/build.sbt rename samples/client/petstore/java/{default => jersey1}/docs/AdditionalPropertiesClass.md (100%) rename samples/client/petstore/java/{default => jersey1}/docs/Animal.md (100%) rename samples/client/petstore/java/{default => jersey1}/docs/AnimalFarm.md (100%) rename samples/client/petstore/java/{default => jersey1}/docs/ArrayOfArrayOfNumberOnly.md (100%) rename samples/client/petstore/java/{default => jersey1}/docs/ArrayOfNumberOnly.md (100%) rename samples/client/petstore/java/{default => jersey1}/docs/ArrayTest.md (100%) rename samples/client/petstore/java/{default => jersey1}/docs/Cat.md (100%) rename samples/client/petstore/java/{default => jersey1}/docs/Category.md (100%) rename samples/client/petstore/java/{default => jersey1}/docs/Dog.md (100%) rename samples/client/petstore/java/{default => jersey1}/docs/EnumClass.md (100%) rename samples/client/petstore/java/{default => jersey1}/docs/EnumTest.md (100%) rename samples/client/petstore/java/{default => jersey1}/docs/FakeApi.md (100%) rename samples/client/petstore/java/{default => jersey1}/docs/FormatTest.md (100%) rename samples/client/petstore/java/{default => jersey1}/docs/HasOnlyReadOnly.md (100%) rename samples/client/petstore/java/{default => jersey1}/docs/MapTest.md (100%) rename samples/client/petstore/java/{default => jersey1}/docs/MixedPropertiesAndAdditionalPropertiesClass.md (100%) rename samples/client/petstore/java/{default => jersey1}/docs/Model200Response.md (100%) rename samples/client/petstore/java/{default => jersey1}/docs/ModelApiResponse.md (100%) rename samples/client/petstore/java/{default => jersey1}/docs/ModelReturn.md (100%) rename samples/client/petstore/java/{default => jersey1}/docs/Name.md (100%) rename samples/client/petstore/java/{default => jersey1}/docs/NumberOnly.md (100%) rename samples/client/petstore/java/{default => jersey1}/docs/Order.md (100%) rename samples/client/petstore/java/{default => jersey1}/docs/Pet.md (100%) rename samples/client/petstore/java/{default => jersey1}/docs/PetApi.md (100%) rename samples/client/petstore/java/{default => jersey1}/docs/ReadOnlyFirst.md (100%) rename samples/client/petstore/java/{default => jersey1}/docs/SpecialModelName.md (100%) rename samples/client/petstore/java/{default => jersey1}/docs/StoreApi.md (100%) rename samples/client/petstore/java/{default => jersey1}/docs/Tag.md (100%) rename samples/client/petstore/java/{default => jersey1}/docs/User.md (100%) rename samples/client/petstore/java/{default => jersey1}/docs/UserApi.md (100%) rename samples/client/petstore/java/{default => jersey1}/git_push.sh (100%) rename samples/client/petstore/java/{default => jersey1}/gradle.properties (100%) rename samples/client/petstore/java/{default => jersey1}/gradle/wrapper/gradle-wrapper.jar (100%) rename samples/client/petstore/java/{default => jersey1}/gradle/wrapper/gradle-wrapper.properties (100%) rename samples/client/petstore/java/{default => jersey1}/gradlew (100%) rename samples/client/petstore/java/{default => jersey1}/gradlew.bat (100%) rename samples/client/petstore/java/{default => jersey1}/pom.xml (65%) rename samples/client/petstore/java/{default => jersey1}/settings.gradle (100%) rename samples/client/petstore/java/{default => jersey1}/src/main/AndroidManifest.xml (100%) create mode 100644 samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiCallback.java create mode 100644 samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/ApiException.java (100%) create mode 100644 samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiResponse.java rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/Configuration.java (100%) create mode 100644 samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/JSON.java rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/Pair.java (100%) create mode 100644 samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ProgressRequestBody.java create mode 100644 samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ProgressResponseBody.java rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/StringUtil.java (100%) create mode 100644 samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java create mode 100644 samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java create mode 100644 samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/StoreApi.java create mode 100644 samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/UserApi.java rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/auth/ApiKeyAuth.java (100%) rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/auth/Authentication.java (100%) rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/auth/HttpBasicAuth.java (59%) rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/auth/OAuth.java (100%) rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/auth/OAuthFlow.java (100%) rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java (96%) rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/model/Animal.java (96%) rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/model/AnimalFarm.java (100%) rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java (96%) rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java (96%) rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/model/ArrayTest.java (96%) rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/model/Cat.java (96%) rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/model/Category.java (96%) rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/model/Dog.java (96%) rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/model/EnumClass.java (91%) rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/model/EnumTest.java (93%) rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/model/FormatTest.java (95%) rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java (96%) rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/model/MapTest.java (95%) rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java (96%) rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/model/Model200Response.java (96%) rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/model/ModelApiResponse.java (96%) rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/model/ModelReturn.java (96%) rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/model/Name.java (95%) rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/model/NumberOnly.java (96%) rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/model/Order.java (94%) rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/model/Pet.java (94%) rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/model/ReadOnlyFirst.java (96%) rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/model/SpecialModelName.java (96%) rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/model/Tag.java (96%) rename samples/client/petstore/java/{default => jersey1}/src/main/java/io/swagger/client/model/User.java (95%) create mode 100644 samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/FakeApiTest.java create mode 100644 samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/PetApiTest.java create mode 100644 samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/StoreApiTest.java create mode 100644 samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/UserApiTest.java diff --git a/bin/java-petstore.sh b/bin/java-petstore-jersey1.sh similarity index 79% rename from bin/java-petstore.sh rename to bin/java-petstore-jersey1.sh index be6472d7aad..27aa0f826ba 100755 --- a/bin/java-petstore.sh +++ b/bin/java-petstore-jersey1.sh @@ -26,9 +26,9 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -o samples/client/petstore/java/default -DhideGenerationTimestamp=true" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -o samples/client/petstore/java/jersey1 -DhideGenerationTimestamp=true --library=jersey1" -echo "Removing files and folders under samples/client/petstore/java/default/src/main" -rm -rf samples/client/petstore/java/default/src/main -find samples/client/petstore/java/default -maxdepth 1 -type f ! -name "README.md" -exec rm {} + +echo "Removing files and folders under samples/client/petstore/java/jersey1/src/main" +rm -rf samples/client/petstore/java/jersey1/src/main +find samples/client/petstore/java/jersey1 -maxdepth 1 -type f ! -name "README.md" -exec rm {} + java $JAVA_OPTS -jar $executable $ags 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 27e95190648..c365f2b7035 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 @@ -32,17 +32,19 @@ public JavaClientCodegen() { cliOptions.add(CliOption.newBoolean(USE_RX_JAVA, "Whether to use the RxJava adapter with the retrofit2 library.")); - supportedLibraries.put(DEFAULT_LIBRARY, "HTTP client: Jersey client 1.19.1. JSON processing: Jackson 2.7.0"); + supportedLibraries.put("jersey1", "HTTP client: Jersey client 1.19.1. JSON processing: Jackson 2.7.0"); supportedLibraries.put("feign", "HTTP client: Netflix Feign 8.16.0. JSON processing: Jackson 2.7.0"); supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.22.2. JSON processing: Jackson 2.7.0"); supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.6.2"); supportedLibraries.put(RETROFIT_1, "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)"); supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 3.2.0. JSON processing: Gson 2.6.1 (Retrofit 2.0.2). Enable the RxJava adapter using '-DuseRxJava=true'. (RxJava 1.1.3)"); - CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); - library.setEnum(supportedLibraries); - library.setDefault(DEFAULT_LIBRARY); - cliOptions.add(library); + CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); + libraryOption.setEnum(supportedLibraries); + libraryOption.setDefault("okhttp-gson"); + cliOptions.add(libraryOption); + + setLibrary("okhttp-gson"); } @@ -96,6 +98,9 @@ public void processOpts() { supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); if (!StringUtils.isEmpty(getLibrary())) { + // set library to okhttp-gson as default + setLibrary("okhttp-gson"); + //TODO: add sbt support to default client supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); } @@ -116,7 +121,7 @@ public void processOpts() { if ("feign".equals(getLibrary())) { supportingFiles.add(new SupportingFile("FormAwareEncoder.mustache", invokerFolder, "FormAwareEncoder.java")); additionalProperties.put("jackson", "true"); - } else if ("okhttp-gson".equals(getLibrary())) { + } else if ("okhttp-gson".equals(getLibrary()) || StringUtils.isEmpty(getLibrary())) { // the "okhttp-gson" library template requires "ApiCallback.mustache" for async call supportingFiles.add(new SupportingFile("ApiCallback.mustache", invokerFolder, "ApiCallback.java")); supportingFiles.add(new SupportingFile("ApiResponse.mustache", invokerFolder, "ApiResponse.java")); @@ -131,8 +136,10 @@ public void processOpts() { } else if("jersey2".equals(getLibrary())) { supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); additionalProperties.put("jackson", "true"); - } else if(StringUtils.isEmpty(getLibrary())) { + } else if("jersey1".equals(getLibrary())) { additionalProperties.put("jackson", "true"); + } else { + LOGGER.error("Unknown library option (-l/--library): " + StringUtils.isEmpty(getLibrary())); } } @@ -175,7 +182,7 @@ public Map postProcessOperations(Map objs) { public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { super.postProcessModelProperty(model, property); if(!BooleanUtils.toBoolean(model.isEnum)) { - final String lib = getLibrary(); + //final String lib = getLibrary(); //Needed imports for Jackson based libraries if(additionalProperties.containsKey("jackson")) { model.imports.add("JsonProperty"); 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 3712dcd7224..9c75d671607 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 @@ -790,6 +790,7 @@ public class ApiClient { * @throws ApiException If fail to deserialize response body, i.e. cannot read response body * or the Content-Type of the response is not supported. */ + @SuppressWarnings("unchecked") public T deserialize(Response response, Type returnType) throws ApiException { if (response == null || returnType == null) { return null; @@ -984,6 +985,7 @@ public class ApiClient { * @param returnType Return type * @param callback ApiCallback */ + @SuppressWarnings("unchecked") public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { call.enqueue(new Callback() { @Override diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache index 4cb2a34ab20..bc1176ff8c5 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache @@ -92,6 +92,7 @@ public class JSON { * @param returnType The type to deserialize inot * @return The deserialized Java object */ + @SuppressWarnings("unchecked") public T deserialize(String body, Type returnType) { try { if (apiClient.isLenientOnJson()) { @@ -287,4 +288,4 @@ class LocalDateTypeAdapter extends TypeAdapter { } } } -{{/java8}} \ No newline at end of file +{{/java8}} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java index bfc25b8f5cc..f05c0e32700 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java @@ -163,6 +163,7 @@ public void testSkipOverwrite() throws Exception { final Swagger swagger = new SwaggerParser().read("src/test/resources/petstore.json"); CodegenConfig codegenConfig = new JavaClientCodegen(); + codegenConfig.setLibrary("jersey1"); codegenConfig.setOutputDir(output.getAbsolutePath()); ClientOptInput clientOptInput = new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig); diff --git a/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJavaClientOptionsTest.java b/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJavaClientOptionsTest.java index bca63e37eed..c58844fb1da 100644 --- a/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJavaClientOptionsTest.java +++ b/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJavaClientOptionsTest.java @@ -22,6 +22,6 @@ public void getOptionsTest() throws ApiException { assertNotNull(options); final CliOption opt = options.get(CodegenConstants.LIBRARY); assertNotNull(opt); - assertEquals(opt.getDefault(), JavaClientCodegen.DEFAULT_LIBRARY); + assertEquals(opt.getDefault(), "okhttp-gson"); } } diff --git a/pom.xml b/pom.xml index 10886a26069..2be7b856d8f 100644 --- a/pom.xml +++ b/pom.xml @@ -283,7 +283,7 @@ - java-client + java-client-jersey1 env @@ -291,7 +291,7 @@ - samples/client/petstore/java/default + samples/client/petstore/java/jersey1 diff --git a/samples/client/petstore/java/default/docs/ApiResponse.md b/samples/client/petstore/java/default/docs/ApiResponse.md deleted file mode 100644 index 1c17767c2b7..00000000000 --- a/samples/client/petstore/java/default/docs/ApiResponse.md +++ /dev/null @@ -1,12 +0,0 @@ - -# ApiResponse - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**code** | **Integer** | | [optional] -**type** | **String** | | [optional] -**message** | **String** | | [optional] - - - diff --git a/samples/client/petstore/java/default/docs/InlineResponse200.md b/samples/client/petstore/java/default/docs/InlineResponse200.md deleted file mode 100644 index 487ebe429e4..00000000000 --- a/samples/client/petstore/java/default/docs/InlineResponse200.md +++ /dev/null @@ -1,24 +0,0 @@ - -# InlineResponse200 - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**photoUrls** | **List<String>** | | [optional] -**name** | **String** | | [optional] -**id** | **Long** | | -**category** | **Object** | | [optional] -**tags** | [**List<Tag>**](Tag.md) | | [optional] -**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] - - - -## Enum: StatusEnum -Name | Value ----- | ----- -AVAILABLE | available -PENDING | pending -SOLD | sold - - - 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 deleted file mode 100644 index b16fdbbdfa9..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java +++ /dev/null @@ -1,687 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package io.swagger.client; - -import com.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.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; - -import com.sun.jersey.multipart.FormDataMultiPart; -import com.sun.jersey.multipart.file.FileDataBodyPart; - -import javax.ws.rs.core.Response.Status.Family; -import javax.ws.rs.core.MediaType; - -import java.util.Collection; -import java.util.Collections; -import java.util.Map; -import java.util.Map.Entry; -import java.util.HashMap; -import java.util.List; -import java.util.ArrayList; -import java.util.Date; -import java.util.TimeZone; - -import java.net.URLEncoder; - -import java.io.File; -import java.io.UnsupportedEncodingException; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; - -import io.swagger.client.auth.Authentication; -import io.swagger.client.auth.HttpBasicAuth; -import io.swagger.client.auth.ApiKeyAuth; -import io.swagger.client.auth.OAuth; - - -public class ApiClient { - private Map defaultHeaderMap = new HashMap(); - private String basePath = "http://petstore.swagger.io/v2"; - private boolean debugging = false; - private int connectionTimeout = 0; - - private Client httpClient; - private ObjectMapper objectMapper; - - private Map authentications; - - private int statusCode; - private Map> responseHeaders; - - private DateFormat dateFormat; - - public ApiClient() { - objectMapper = new ObjectMapper(); - objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); - objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); - objectMapper.registerModule(new JodaModule()); - objectMapper.setDateFormat(ApiClient.buildDefaultDateFormat()); - - dateFormat = ApiClient.buildDefaultDateFormat(); - - // Set default User-Agent. - setUserAgent("Swagger-Codegen/1.0.0/java"); - - // Setup authentications (key: authentication name, value: authentication). - authentications = new HashMap(); - authentications.put("api_key", new ApiKeyAuth("header", "api_key")); - authentications.put("petstore_auth", new OAuth()); - // Prevent the authentications from being modified. - authentications = Collections.unmodifiableMap(authentications); - - rebuildHttpClient(); - } - - public static DateFormat buildDefaultDateFormat() { - // Use RFC3339 format for date and datetime. - // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 - DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); - // Use UTC as the default time zone. - dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - return dateFormat; - } - - /** - * Build the Client used to make HTTP requests with the latest settings, - * i.e. objectMapper and debugging. - * TODO: better to use the Builder Pattern? - */ - public ApiClient rebuildHttpClient() { - // Add the JSON serialization support to Jersey - JacksonJsonProvider jsonProvider = new JacksonJsonProvider(objectMapper); - DefaultClientConfig conf = new DefaultClientConfig(); - conf.getSingletons().add(jsonProvider); - Client client = Client.create(conf); - if (debugging) { - client.addFilter(new LoggingFilter()); - } - this.httpClient = client; - return this; - } - - /** - * Returns the current object mapper used for JSON serialization/deserialization. - *

- * Note: If you make changes to the object mapper, remember to set it back via - * setObjectMapper in order to trigger HTTP client rebuilding. - *

- */ - public ObjectMapper getObjectMapper() { - return objectMapper; - } - - public ApiClient setObjectMapper(ObjectMapper objectMapper) { - this.objectMapper = objectMapper; - // Need to rebuild the Client as it depends on object mapper. - rebuildHttpClient(); - return this; - } - - public Client getHttpClient() { - return httpClient; - } - - public ApiClient setHttpClient(Client httpClient) { - this.httpClient = httpClient; - return this; - } - - public String getBasePath() { - return basePath; - } - - public ApiClient setBasePath(String basePath) { - this.basePath = basePath; - return this; - } - - /** - * Gets the status code of the previous request - */ - public int getStatusCode() { - return statusCode; - } - - /** - * Gets the response headers of the previous request - */ - public Map> getResponseHeaders() { - return responseHeaders; - } - - /** - * Get authentications (key: authentication name, value: authentication). - */ - public Map getAuthentications() { - return authentications; - } - - /** - * Get authentication for the given name. - * - * @param authName The authentication name - * @return The authentication, null if not found - */ - public Authentication getAuthentication(String authName) { - return authentications.get(authName); - } - - /** - * Helper method to set username for the first HTTP basic authentication. - */ - public void setUsername(String username) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setUsername(username); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set password for the first HTTP basic authentication. - */ - public void setPassword(String password) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setPassword(password); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set API key value for the first API key authentication. - */ - public void setApiKey(String apiKey) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKey(apiKey); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set API key prefix for the first API key authentication. - */ - public void setApiKeyPrefix(String apiKeyPrefix) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set access token for the first OAuth2 authentication. - */ - public void setAccessToken(String accessToken) { - for (Authentication auth : authentications.values()) { - if (auth instanceof OAuth) { - ((OAuth) auth).setAccessToken(accessToken); - return; - } - } - throw new RuntimeException("No OAuth2 authentication configured!"); - } - - /** - * Set the User-Agent header's value (by adding to the default header map). - */ - public ApiClient setUserAgent(String userAgent) { - addDefaultHeader("User-Agent", userAgent); - return this; - } - - /** - * Add a default header. - * - * @param key The header's key - * @param value The header's value - */ - public ApiClient addDefaultHeader(String key, String value) { - defaultHeaderMap.put(key, value); - return this; - } - - /** - * Check that whether debugging is enabled for this API client. - */ - public boolean isDebugging() { - return debugging; - } - - /** - * Enable/disable debugging for this API client. - * - * @param debugging To enable (true) or disable (false) debugging - */ - public ApiClient setDebugging(boolean debugging) { - this.debugging = debugging; - // Need to rebuild the Client as it depends on the value of debugging. - rebuildHttpClient(); - return this; - } - - /** - * Connect timeout (in milliseconds). - */ - public int getConnectTimeout() { - return connectionTimeout; - } - - /** - * Set the connect timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * {@link Integer#MAX_VALUE}. - */ - public ApiClient setConnectTimeout(int connectionTimeout) { - this.connectionTimeout = connectionTimeout; - httpClient.setConnectTimeout(connectionTimeout); - return this; - } - - /** - * Get the date format used to parse/format date parameters. - */ - public DateFormat getDateFormat() { - return dateFormat; - } - - /** - * Set the date format used to parse/format date parameters. - */ - public ApiClient setDateFormat(DateFormat dateFormat) { - this.dateFormat = dateFormat; - // Also set the date format for model (de)serialization with Date properties. - this.objectMapper.setDateFormat((DateFormat) dateFormat.clone()); - // Need to rebuild the Client as objectMapper changes. - rebuildHttpClient(); - return this; - } - - /** - * Parse the given string into Date object. - */ - public Date parseDate(String str) { - try { - return dateFormat.parse(str); - } catch (java.text.ParseException e) { - throw new RuntimeException(e); - } - } - - /** - * Format the given Date object into string. - */ - public String formatDate(Date date) { - return dateFormat.format(date); - } - - /** - * 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 to {@code Pair} objects. - */ - public List parameterToPairs(String collectionFormat, String name, Object value){ - List params = new ArrayList(); - - // preconditions - if (name == null || name.isEmpty() || value == null) return params; - - Collection valueCollection = null; - if (value instanceof Collection) { - valueCollection = (Collection) value; - } else { - params.add(new Pair(name, parameterToString(value))); - return params; - } - - if (valueCollection.isEmpty()){ - return params; - } - - // get the collection format - collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv - - // create the params based on the collection format - if (collectionFormat.equals("multi")) { - for (Object item : valueCollection) { - params.add(new Pair(name, parameterToString(item))); - } - - return params; - } - - String delimiter = ","; - - if (collectionFormat.equals("csv")) { - delimiter = ","; - } else if (collectionFormat.equals("ssv")) { - delimiter = " "; - } else if (collectionFormat.equals("tsv")) { - delimiter = "\t"; - } else if (collectionFormat.equals("pipes")) { - delimiter = "|"; - } - - StringBuilder sb = new StringBuilder() ; - for (Object item : valueCollection) { - sb.append(delimiter); - sb.append(parameterToString(item)); - } - - params.add(new Pair(name, sb.substring(1))); - - return params; - } - - /** - * Check if the given MIME is a JSON MIME. - * JSON MIME examples: - * application/json - * application/json; charset=UTF8 - * APPLICATION/JSON - */ - public boolean isJsonMime(String mime) { - return mime != null && mime.matches("(?i)application\\/json(;.*)?"); - } - - /** - * Select the Accept header's value from the given accepts array: - * if JSON exists in the given array, use it; - * otherwise use all of them (joining into a string) - * - * @param accepts The accepts array to select from - * @return The Accept header to use. If the given array is empty, - * null will be returned (not to set the Accept header explicitly). - */ - public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) { - return null; - } - for (String accept : accepts) { - if (isJsonMime(accept)) { - return accept; - } - } - return StringUtil.join(accepts, ","); - } - - /** - * Select the Content-Type header's value from the given array: - * if JSON exists in the given array, use it; - * otherwise use the first one of the array. - * - * @param contentTypes The Content-Type array to select from - * @return The Content-Type header to use. If the given array is empty, - * JSON will be used. - */ - public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) { - return "application/json"; - } - for (String contentType : contentTypes) { - if (isJsonMime(contentType)) { - return contentType; - } - } - return contentTypes[0]; - } - - /** - * Escape the given string to be used as URL query value. - */ - public String escapeString(String str) { - try { - return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); - } catch (UnsupportedEncodingException e) { - return str; - } - } - - /** - * Serialize the given Java object into string according the given - * Content-Type (only JSON is supported for now). - */ - 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 { - // We let Jersey attempt to serialize the body - return obj; - } - } - - /** - * Build full URL by concatenating base path, the given sub path and query parameters. - * - * @param path The sub path - * @param queryParams The query parameters - * @return The full URL - */ - private String buildUrl(String path, List queryParams) { - final StringBuilder url = new StringBuilder(); - url.append(basePath).append(path); - - if (queryParams != null && !queryParams.isEmpty()) { - // support (constant) query string in `path`, e.g. "/posts?draft=1" - String prefix = path.contains("?") ? "&" : "?"; - for (Pair param : queryParams) { - if (param.getValue() != null) { - if (prefix != null) { - url.append(prefix); - prefix = null; - } else { - url.append("&"); - } - String value = parameterToString(param.getValue()); - url.append(escapeString(param.getName())).append("=").append(escapeString(value)); - } - } - } - - return url.toString(); - } - - private ClientResponse getAPIResponse(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { - if (body != null && !formParams.isEmpty()) { - throw new ApiException(500, "Cannot have body and form params"); - } - - updateParamsForAuth(authNames, queryParams, headerParams); - - final String url = buildUrl(path, queryParams); - Builder builder; - if (accept == null) { - builder = httpClient.resource(url).getRequestBuilder(); - } else { - builder = httpClient.resource(url).accept(accept); - } - - for (String key : headerParams.keySet()) { - builder = builder.header(key, headerParams.get(key)); - } - for (String key : defaultHeaderMap.keySet()) { - if (!headerParams.containsKey(key)) { - builder = builder.header(key, defaultHeaderMap.get(key)); - } - } - - ClientResponse response = null; - - if ("GET".equals(method)) { - response = (ClientResponse) builder.get(ClientResponse.class); - } else if ("POST".equals(method)) { - response = builder.type(contentType).post(ClientResponse.class, serialize(body, contentType, formParams)); - } else if ("PUT".equals(method)) { - response = builder.type(contentType).put(ClientResponse.class, serialize(body, contentType, formParams)); - } else if ("DELETE".equals(method)) { - response = builder.type(contentType).delete(ClientResponse.class, serialize(body, contentType, formParams)); - } else if ("PATCH".equals(method)) { - response = builder.type(contentType).header("X-HTTP-Method-Override", "PATCH").post(ClientResponse.class, serialize(body, contentType, formParams)); - } - else { - throw new ApiException(500, "unknown method type " + method); - } - return response; - } - - /** - * Invoke API by sending HTTP request with the given options. - * - * @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 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 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, headerParams, formParams, accept, contentType, authNames); - - statusCode = response.getStatusInfo().getStatusCode(); - responseHeaders = response.getHeaders(); - - if(response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) { - return null; - } else if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { - if (returnType == null) - return null; - else - return response.getEntity(returnType); - } else { - String message = "error"; - String respBody = null; - if (response.hasEntity()) { - try { - respBody = response.getEntity(String.class); - message = respBody; - } catch (RuntimeException e) { - // e.printStackTrace(); - } - } - throw new ApiException( - response.getStatusInfo().getStatusCode(), - message, - response.getHeaders(), - respBody); - } - } - - /** - * Update query and header parameters based on authentication settings. - * - * @param authNames The authentications to apply - */ - private void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { - for (String authName : authNames) { - Authentication auth = authentications.get(authName); - if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); - auth.applyToParams(queryParams, headerParams); - } - } - - /** - * Encode the given form parameters as request body. - */ - private String getXWWWFormUrlencodedParams(Map formParams) { - StringBuilder formParamBuilder = new StringBuilder(); - - for (Entry param : formParams.entrySet()) { - String valueStr = parameterToString(param.getValue()); - try { - formParamBuilder.append(URLEncoder.encode(param.getKey(), "utf8")) - .append("=") - .append(URLEncoder.encode(valueStr, "utf8")); - formParamBuilder.append("&"); - } catch (UnsupportedEncodingException e) { - // move on to next - } - } - - String encodedFormParams = formParamBuilder.toString(); - if (encodedFormParams.endsWith("&")) { - encodedFormParams = encodedFormParams.substring(0, encodedFormParams.length() - 1); - } - - return encodedFormParams; - } -} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/FakeApi.java deleted file mode 100644 index c772f9402da..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/FakeApi.java +++ /dev/null @@ -1,197 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package io.swagger.client.api; - -import com.sun.jersey.api.client.GenericType; - -import io.swagger.client.ApiException; -import io.swagger.client.ApiClient; -import io.swagger.client.Configuration; -import io.swagger.client.model.*; -import io.swagger.client.Pair; - -import org.joda.time.LocalDate; -import org.joda.time.DateTime; -import java.math.BigDecimal; - - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -public class FakeApi { - private ApiClient apiClient; - - public FakeApi() { - this(Configuration.getDefaultApiClient()); - } - - public FakeApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * @param number None (required) - * @param _double None (required) - * @param string None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @throws ApiException if fails to make API call - */ - public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'number' is set - if (number == null) { - throw new ApiException(400, "Missing the required parameter 'number' when calling testEndpointParameters"); - } - - // verify the required parameter '_double' is set - if (_double == null) { - throw new ApiException(400, "Missing the required parameter '_double' when calling testEndpointParameters"); - } - - // verify the required parameter 'string' is set - if (string == null) { - throw new ApiException(400, "Missing the required parameter 'string' when calling testEndpointParameters"); - } - - // verify the required parameter '_byte' is set - if (_byte == null) { - throw new ApiException(400, "Missing the required parameter '_byte' when calling testEndpointParameters"); - } - - // create path and map variables - String localVarPath = "/fake".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - if (integer != null) - localVarFormParams.put("integer", integer); -if (int32 != null) - localVarFormParams.put("int32", int32); -if (int64 != null) - localVarFormParams.put("int64", int64); -if (number != null) - localVarFormParams.put("number", number); -if (_float != null) - localVarFormParams.put("float", _float); -if (_double != null) - localVarFormParams.put("double", _double); -if (string != null) - localVarFormParams.put("string", string); -if (_byte != null) - localVarFormParams.put("byte", _byte); -if (binary != null) - localVarFormParams.put("binary", binary); -if (date != null) - localVarFormParams.put("date", date); -if (dateTime != null) - localVarFormParams.put("dateTime", dateTime); -if (password != null) - localVarFormParams.put("password", password); - - final String[] localVarAccepts = { - "application/xml; charset=utf-8", "application/json; charset=utf-8" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - "application/xml; charset=utf-8", "application/json; charset=utf-8" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * To test enum query parameters - * - * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) - * @param enumQueryInteger Query parameter enum test (double) (optional) - * @param enumQueryDouble Query parameter enum test (double) (optional) - * @throws ApiException if fails to make API call - */ - public void testEnumQueryParameters(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/fake".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_integer", enumQueryInteger)); - - - if (enumQueryString != null) - localVarFormParams.put("enum_query_string", enumQueryString); -if (enumQueryDouble != null) - localVarFormParams.put("enum_query_double", enumQueryDouble); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - "application/json" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } -} 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 deleted file mode 100644 index c126283d2aa..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java +++ /dev/null @@ -1,410 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package io.swagger.client.api; - -import com.sun.jersey.api.client.GenericType; - -import io.swagger.client.ApiException; -import io.swagger.client.ApiClient; -import io.swagger.client.Configuration; -import io.swagger.client.model.*; -import io.swagger.client.Pair; - -import io.swagger.client.model.Pet; -import java.io.File; -import io.swagger.client.model.ModelApiResponse; - - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -public class PetApi { - private ApiClient apiClient; - - public PetApi() { - this(Configuration.getDefaultApiClient()); - } - - public PetApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store (required) - * @throws ApiException if fails to make API call - */ - public void addPet(Pet body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling addPet"); - } - - // create path and map variables - String localVarPath = "/pet".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - "application/json", "application/xml" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - - apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Deletes a pet - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @throws ApiException if fails to make API call - */ - public void deletePet(Long petId, String apiKey) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling deletePet"); - } - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - if (apiKey != null) - localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - - apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Finds Pets by status - * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for filter (required) - * @return List - * @throws ApiException if fails to make API call - */ - public List findPetsByStatus(List status) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'status' is set - if (status == null) { - throw new ApiException(400, "Missing the required parameter 'status' when calling findPetsByStatus"); - } - - // create path and map variables - String localVarPath = "/pet/findByStatus".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "status", status)); - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - GenericType> localVarReturnType = new GenericType>() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Finds Pets by tags - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by (required) - * @return List - * @throws ApiException if fails to make API call - */ - public List findPetsByTags(List tags) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'tags' is set - if (tags == null) { - throw new ApiException(400, "Missing the required parameter 'tags' when calling findPetsByTags"); - } - - // create path and map variables - String localVarPath = "/pet/findByTags".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "tags", tags)); - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - GenericType> localVarReturnType = new GenericType>() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Find pet by ID - * Returns a single pet - * @param petId ID of pet to return (required) - * @return Pet - * @throws ApiException if fails to make API call - */ - public Pet getPetById(Long petId) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling getPetById"); - } - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "api_key" }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store (required) - * @throws ApiException if fails to make API call - */ - public void updatePet(Pet body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling updatePet"); - } - - // create path and map variables - String localVarPath = "/pet".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - "application/json", "application/xml" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - - apiClient.invokeAPI(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @throws ApiException if fails to make API call - */ - public void updatePetWithForm(Long petId, String name, String status) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling updatePetWithForm"); - } - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - if (name != null) - localVarFormParams.put("name", name); -if (status != null) - localVarFormParams.put("status", status); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - "application/x-www-form-urlencoded" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - - apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * uploads an image - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @return ModelApiResponse - * @throws ApiException if fails to make API call - */ - public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling uploadFile"); - } - - // create path and map variables - String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - if (additionalMetadata != null) - localVarFormParams.put("additionalMetadata", additionalMetadata); -if (file != null) - localVarFormParams.put("file", file); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - "multipart/form-data" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } -} 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 deleted file mode 100644 index b30edd4f22f..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java +++ /dev/null @@ -1,222 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package io.swagger.client.api; - -import com.sun.jersey.api.client.GenericType; - -import io.swagger.client.ApiException; -import io.swagger.client.ApiClient; -import io.swagger.client.Configuration; -import io.swagger.client.model.*; -import io.swagger.client.Pair; - -import io.swagger.client.model.Order; - - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -public class StoreApi { - private ApiClient apiClient; - - public StoreApi() { - this(Configuration.getDefaultApiClient()); - } - - public StoreApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted (required) - * @throws ApiException if fails to make API call - */ - public void deleteOrder(String orderId) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder"); - } - - // create path and map variables - String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - * @return Map - * @throws ApiException if fails to make API call - */ - public Map getInventory() throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/store/inventory".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "api_key" }; - - GenericType> localVarReturnType = new GenericType>() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched (required) - * @return Order - * @throws ApiException if fails to make API call - */ - public Order getOrderById(Long orderId) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById"); - } - - // create path and map variables - String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet (required) - * @return Order - * @throws ApiException if fails to make API call - */ - public Order placeOrder(Order body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling placeOrder"); - } - - // create path and map variables - String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } -} 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 deleted file mode 100644 index 9d6a1bb12fd..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java +++ /dev/null @@ -1,396 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package io.swagger.client.api; - -import com.sun.jersey.api.client.GenericType; - -import io.swagger.client.ApiException; -import io.swagger.client.ApiClient; -import io.swagger.client.Configuration; -import io.swagger.client.model.*; -import io.swagger.client.Pair; - -import io.swagger.client.model.User; - - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -public class UserApi { - private ApiClient apiClient; - - public UserApi() { - this(Configuration.getDefaultApiClient()); - } - - public UserApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object (required) - * @throws ApiException if fails to make API call - */ - public void createUser(User body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling createUser"); - } - - // create path and map variables - String localVarPath = "/user".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @throws ApiException if fails to make API call - */ - public void createUsersWithArrayInput(List body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling createUsersWithArrayInput"); - } - - // create path and map variables - String localVarPath = "/user/createWithArray".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @throws ApiException if fails to make API call - */ - public void createUsersWithListInput(List body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling createUsersWithListInput"); - } - - // create path and map variables - String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @throws ApiException if fails to make API call - */ - public void deleteUser(String username) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling deleteUser"); - } - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return User - * @throws ApiException if fails to make API call - */ - public User getUserByName(String username) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling getUserByName"); - } - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Logs user into the system - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @return String - * @throws ApiException if fails to make API call - */ - public String loginUser(String username, String password) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling loginUser"); - } - - // verify the required parameter 'password' is set - if (password == null) { - throw new ApiException(400, "Missing the required parameter 'password' when calling loginUser"); - } - - // create path and map variables - String localVarPath = "/user/login".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - localVarQueryParams.addAll(apiClient.parameterToPairs("", "username", username)); - localVarQueryParams.addAll(apiClient.parameterToPairs("", "password", password)); - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Logs out current logged in user session - * - * @throws ApiException if fails to make API call - */ - public void logoutUser() throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/user/logout".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @throws ApiException if fails to make API call - */ - public void updateUser(String username, User body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser"); - } - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling updateUser"); - } - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } -} diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/PetstoreProfiling.java b/samples/client/petstore/java/default/src/test/java/io/swagger/PetstoreProfiling.java deleted file mode 100644 index d0be1523e45..00000000000 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/PetstoreProfiling.java +++ /dev/null @@ -1,106 +0,0 @@ -package io.swagger; - -import java.io.*; -import java.util.*; - -import io.swagger.client.*; -import io.swagger.client.api.*; -import io.swagger.client.model.*; - -public class PetstoreProfiling { - public int total = 5; - public Long newPetId = 50003L; - public String outputFile = "./petstore_profiling.output"; - - public void callApis(int index, List> results) { - long start; - - try { - PetApi petApi = new PetApi(); - - /* ADD PET */ - Pet pet = new Pet(); - pet.setId(newPetId); - pet.setName("profiler"); - pet.setStatus(Pet.StatusEnum.AVAILABLE); - pet.setPhotoUrls(Arrays.asList("http://profiler.com")); - // new tag - Tag tag = new Tag(); - tag.setId(newPetId); // use the same id as pet - tag.setName("profile tag 1"); - // new category - Category category = new Category(); - category.setId(newPetId); // use the same id as pet - category.setName("profile category 1"); - - pet.setTags(Arrays.asList(tag)); - pet.setCategory(category); - - /* ADD PET */ - start = System.nanoTime(); - petApi.addPet(pet); - results.add(buildResult(index, "ADD PET", System.nanoTime() - start)); - - /* GET PET */ - start = System.nanoTime(); - pet = petApi.getPetById(newPetId); - results.add(buildResult(index, "GET PET", System.nanoTime() - start)); - - /* UPDATE PET WITH FORM */ - start = System.nanoTime(); - petApi.updatePetWithForm(newPetId, "new profiler", "sold"); - results.add(buildResult(index, "UPDATE PET", System.nanoTime() - start)); - - /* DELETE PET */ - start = System.nanoTime(); - petApi.deletePet(newPetId, "special-key"); - results.add(buildResult(index, "DELETE PET", System.nanoTime() - start)); - } catch (ApiException e) { - System.out.println("Caught error: " + e.getMessage()); - System.out.println("HTTP response headers: " + e.getResponseHeaders()); - System.out.println("HTTP response body: " + e.getResponseBody()); - System.out.println("HTTP status code: " + e.getCode()); - } - } - - public void run() { - System.out.printf("Running profiling... (total: %s)\n", total); - - List> results = new ArrayList>(); - for (int i = 0; i < total; i++) { - callApis(i, results); - } - writeResultsToFile(results); - - System.out.printf("Profiling results written to %s\n", outputFile); - } - - private Map buildResult(int index, String name, long time) { - Map result = new HashMap(); - result.put("index", String.valueOf(index)); - result.put("name", name); - result.put("time", String.valueOf(time / 1000000000.0)); - return result; - } - - private void writeResultsToFile(List> results) { - try { - java.io.File file = new java.io.File(outputFile); - PrintWriter writer = new PrintWriter(file); - String command = "mvn compile test-compile exec:java -Dexec.classpathScope=test -Dexec.mainClass=\"io.swagger.PetstoreProfiling\""; - writer.println("# To run the profiling:"); - writer.printf("# %s\n\n", command); - for (Map result : results) { - writer.printf("%s: %s => %s\n", result.get("index"), result.get("name"), result.get("time")); - } - writer.close(); - } catch (FileNotFoundException e) { - throw new RuntimeException(e); - } - } - - public static void main(String[] args) { - final PetstoreProfiling profiling = new PetstoreProfiling(); - profiling.run(); - } -} diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/TestUtils.java b/samples/client/petstore/java/default/src/test/java/io/swagger/TestUtils.java deleted file mode 100644 index 7ddf142426e..00000000000 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/TestUtils.java +++ /dev/null @@ -1,17 +0,0 @@ -package io.swagger; - -import java.util.Random; -import java.util.concurrent.atomic.AtomicLong; - -public class TestUtils { - private static final AtomicLong atomicId = createAtomicId(); - - public static long nextId() { - return atomicId.getAndIncrement(); - } - - private static AtomicLong createAtomicId() { - int baseId = new Random(System.currentTimeMillis()).nextInt(1000000) + 20000; - return new AtomicLong((long) baseId); - } -} diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java deleted file mode 100644 index 19b55257d0c..00000000000 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java +++ /dev/null @@ -1,239 +0,0 @@ -package io.swagger.client; - -import io.swagger.client.auth.*; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.*; - -import org.junit.*; -import static org.junit.Assert.*; - - -public class ApiClientTest { - ApiClient apiClient = null; - - @Before - public void setup() { - apiClient = new ApiClient(); - } - - @Test - public void testParseAndFormatDate() { - // default date format - String dateStr = "2015-11-07T03:49:09.356Z"; - assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356+00:00"))); - assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356Z"))); - assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T05:49:09.356+02:00"))); - assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T02:49:09.356-01:00"))); - - // custom date format: without milli-seconds, custom time zone - DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); - format.setTimeZone(TimeZone.getTimeZone("GMT+10")); - apiClient.setDateFormat(format); - dateStr = "2015-11-07T13:49:09+10:00"; - assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09+00:00"))); - assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09Z"))); - assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T00:49:09-03:00"))); - 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"}; - 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)); - - accepts = new String[]{}; - assertNull(apiClient.selectHeaderAccept(accepts)); - } - - @Test - public void testSelectHeaderContentType() { - 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/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)); - - contentTypes = new String[]{}; - assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); - } - - @Test - public void testGetAuthentications() { - Map auths = apiClient.getAuthentications(); - - Authentication auth = auths.get("api_key"); - assertNotNull(auth); - assertTrue(auth instanceof ApiKeyAuth); - ApiKeyAuth apiKeyAuth = (ApiKeyAuth) auth; - assertEquals("header", apiKeyAuth.getLocation()); - assertEquals("api_key", apiKeyAuth.getParamName()); - - auth = auths.get("petstore_auth"); - assertTrue(auth instanceof OAuth); - assertSame(auth, apiClient.getAuthentication("petstore_auth")); - - assertNull(auths.get("unknown")); - - try { - auths.put("my_auth", new HttpBasicAuth()); - fail("the authentications returned should not be modifiable"); - } catch (UnsupportedOperationException e) { - } - } - - @Ignore("There is no more basic auth in petstore security definitions") - @Test - public void testSetUsernameAndPassword() { - HttpBasicAuth auth = null; - for (Authentication _auth : apiClient.getAuthentications().values()) { - if (_auth instanceof HttpBasicAuth) { - auth = (HttpBasicAuth) _auth; - break; - } - } - auth.setUsername(null); - auth.setPassword(null); - - apiClient.setUsername("my-username"); - apiClient.setPassword("my-password"); - assertEquals("my-username", auth.getUsername()); - assertEquals("my-password", auth.getPassword()); - - // reset values - auth.setUsername(null); - auth.setPassword(null); - } - - @Test - public void testSetApiKeyAndPrefix() { - ApiKeyAuth auth = null; - for (Authentication _auth : apiClient.getAuthentications().values()) { - if (_auth instanceof ApiKeyAuth) { - auth = (ApiKeyAuth) _auth; - break; - } - } - auth.setApiKey(null); - auth.setApiKeyPrefix(null); - - apiClient.setApiKey("my-api-key"); - apiClient.setApiKeyPrefix("Token"); - assertEquals("my-api-key", auth.getApiKey()); - assertEquals("Token", auth.getApiKeyPrefix()); - - // reset values - auth.setApiKey(null); - auth.setApiKeyPrefix(null); - } - - @Test - public void testParameterToPairsWhenNameIsInvalid() throws Exception { - List pairs_a = apiClient.parameterToPairs("csv", null, new Integer(1)); - List pairs_b = apiClient.parameterToPairs("csv", "", new Integer(1)); - - assertTrue(pairs_a.isEmpty()); - assertTrue(pairs_b.isEmpty()); - } - - @Test - public void testParameterToPairsWhenValueIsNull() throws Exception { - List pairs = apiClient.parameterToPairs("csv", "param-a", null); - - assertTrue(pairs.isEmpty()); - } - - @Test - public void testParameterToPairsWhenValueIsEmptyStrings() throws Exception { - - // single empty string - List pairs = apiClient.parameterToPairs("csv", "param-a", " "); - assertEquals(1, pairs.size()); - - // list of empty strings - List strs = new ArrayList(); - strs.add(" "); - strs.add(" "); - strs.add(" "); - - List concatStrings = apiClient.parameterToPairs("csv", "param-a", strs); - - assertEquals(1, concatStrings.size()); - assertFalse(concatStrings.get(0).getValue().isEmpty()); // should contain some delimiters - } - - @Test - public void testParameterToPairsWhenValueIsNotCollection() throws Exception { - String name = "param-a"; - Integer value = 1; - - List pairs = apiClient.parameterToPairs("csv", name, value); - - assertEquals(1, pairs.size()); - assertEquals(value, Integer.valueOf(pairs.get(0).getValue())); - } - - @Test - public void testParameterToPairsWhenValueIsCollection() throws Exception { - Map collectionFormatMap = new HashMap(); - collectionFormatMap.put("csv", ","); - collectionFormatMap.put("tsv", "\t"); - collectionFormatMap.put("ssv", " "); - collectionFormatMap.put("pipes", "\\|"); - collectionFormatMap.put("", ","); // no format, must default to csv - collectionFormatMap.put("unknown", ","); // all other formats, must default to csv - - String name = "param-a"; - - List values = new ArrayList(); - values.add("value-a"); - values.add(123); - values.add(new Date()); - - // check for multi separately - List multiPairs = apiClient.parameterToPairs("multi", name, values); - assertEquals(values.size(), multiPairs.size()); - - // all other formats - for (String collectionFormat : collectionFormatMap.keySet()) { - List pairs = apiClient.parameterToPairs(collectionFormat, name, values); - - assertEquals(1, pairs.size()); - - String delimiter = collectionFormatMap.get(collectionFormat); - String[] pairValueSplit = pairs.get(0).getValue().split(delimiter); - - // must equal input values - assertEquals(values.size(), pairValueSplit.length); - } - } -} diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/ConfigurationTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/ConfigurationTest.java deleted file mode 100644 index b95eb74605e..00000000000 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/client/ConfigurationTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package io.swagger.client; - -import org.junit.*; -import static org.junit.Assert.*; - - -public class ConfigurationTest { - @Test - public void testDefaultApiClient() { - ApiClient apiClient = Configuration.getDefaultApiClient(); - assertNotNull(apiClient); - assertEquals("http://petstore.swagger.io/v2", apiClient.getBasePath()); - assertFalse(apiClient.isDebugging()); - } -} diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/StringUtilTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/StringUtilTest.java deleted file mode 100644 index 4b03c7a9812..00000000000 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/client/StringUtilTest.java +++ /dev/null @@ -1,33 +0,0 @@ -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"}, ",")); - } -} diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/FakeApiTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/FakeApiTest.java deleted file mode 100644 index c564001ad70..00000000000 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/FakeApiTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package io.swagger.client.api; - -import io.swagger.client.ApiException; -import java.math.BigDecimal; -import java.util.Date; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * API tests for FakeApi - */ -public class FakeApiTest { - - private final FakeApi api = new FakeApi(); - - - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void testEndpointParametersTest() throws ApiException { - BigDecimal number = null; - Double _double = null; - String string = null; - byte[] _byte = null; - Integer integer = null; - Integer int32 = null; - Long int64 = null; - Float _float = null; - byte[] binary = null; - Date date = null; - Date dateTime = null; - String password = null; - // api.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); - - // TODO: test validations - } - -} diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/PetApiTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/PetApiTest.java deleted file mode 100644 index e75a9c7e7da..00000000000 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/PetApiTest.java +++ /dev/null @@ -1,306 +0,0 @@ -package io.swagger.client.api; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.*; -import com.fasterxml.jackson.datatype.joda.*; - -import io.swagger.TestUtils; - -import io.swagger.client.*; -import io.swagger.client.api.*; -import io.swagger.client.auth.*; -import io.swagger.client.model.*; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -import org.junit.*; -import static org.junit.Assert.*; - -public class PetApiTest { - private PetApi api; - private ObjectMapper mapper; - - @Before - public void setup() { - api = new PetApi(); - // setup authentication - ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); - apiKeyAuth.setApiKey("special-key"); - } - - @Test - public void testApiClient() { - // the default api client is used - assertEquals(Configuration.getDefaultApiClient(), api.getApiClient()); - assertNotNull(api.getApiClient()); - assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath()); - assertFalse(api.getApiClient().isDebugging()); - - ApiClient oldClient = api.getApiClient(); - - ApiClient newClient = new ApiClient(); - newClient.setBasePath("http://example.com"); - newClient.setDebugging(true); - - // set api client via constructor - api = new PetApi(newClient); - assertNotNull(api.getApiClient()); - assertEquals("http://example.com", api.getApiClient().getBasePath()); - assertTrue(api.getApiClient().isDebugging()); - - // set api client via setter method - api.setApiClient(oldClient); - assertNotNull(api.getApiClient()); - assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath()); - assertFalse(api.getApiClient().isDebugging()); - } - - @Test - public void testCreateAndGetPet() throws Exception { - Pet pet = createRandomPet(); - api.addPet(pet); - - Pet fetched = api.getPetById(pet.getId()); - assertNotNull(fetched); - assertEquals(pet.getId(), fetched.getId()); - assertNotNull(fetched.getCategory()); - assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); - } - - /* - @Test - public void testCreateAndGetPetWithByteArray() throws Exception { - Pet pet = createRandomPet(); - byte[] bytes = serializeJson(pet).getBytes(); - api.addPetUsingByteArray(bytes); - - byte[] fetchedBytes = api.petPetIdtestingByteArraytrueGet(pet.getId()); - Pet fetched = deserializeJson(new String(fetchedBytes), Pet.class); - assertNotNull(fetched); - assertEquals(pet.getId(), fetched.getId()); - assertNotNull(fetched.getCategory()); - assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); - } - - @Test - public void testGetPetByIdInObject() throws Exception { - Pet pet = new Pet(); - pet.setId(TestUtils.nextId()); - pet.setName("pet " + pet.getId()); - - Category category = new Category(); - category.setId(TestUtils.nextId()); - category.setName("category " + category.getId()); - pet.setCategory(category); - - pet.setStatus(Pet.StatusEnum.PENDING); - List photos = Arrays.asList(new String[]{"http://foo.bar.com/1"}); - pet.setPhotoUrls(photos); - - api.addPet(pet); - - InlineResponse200 fetched = api.getPetByIdInObject(pet.getId()); - assertEquals(pet.getId(), fetched.getId()); - assertEquals(pet.getName(), fetched.getName()); - - Object categoryObj = fetched.getCategory(); - assertNotNull(categoryObj); - assertTrue(categoryObj instanceof Map); - - Map categoryMap = (Map) categoryObj; - Object categoryIdObj = categoryMap.get("id"); - assertTrue(categoryIdObj instanceof Integer); - Integer categoryIdInt = (Integer) categoryIdObj; - assertEquals(category.getId(), Long.valueOf(categoryIdInt)); - assertEquals(category.getName(), categoryMap.get("name")); - } - */ - - @Test - public void testUpdatePet() throws Exception { - Pet pet = createRandomPet(); - pet.setName("programmer"); - - api.updatePet(pet); - - Pet fetched = api.getPetById(pet.getId()); - assertNotNull(fetched); - assertEquals(pet.getId(), fetched.getId()); - assertNotNull(fetched.getCategory()); - assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); - } - - @Test - public void testFindPetsByStatus() throws Exception { - Pet pet = createRandomPet(); - pet.setName("programmer"); - pet.setStatus(Pet.StatusEnum.AVAILABLE); - - api.updatePet(pet); - - List pets = api.findPetsByStatus(Arrays.asList(new String[]{"available"})); - assertNotNull(pets); - - boolean found = false; - for (Pet fetched : pets) { - if (fetched.getId().equals(pet.getId())) { - found = true; - break; - } - } - - assertTrue(found); - } - - @Test - public void testFindPetsByTags() throws Exception { - Pet pet = createRandomPet(); - pet.setName("monster"); - pet.setStatus(Pet.StatusEnum.AVAILABLE); - - List tags = new ArrayList(); - Tag tag1 = new Tag(); - tag1.setName("friendly"); - tags.add(tag1); - pet.setTags(tags); - - api.updatePet(pet); - - List pets = api.findPetsByTags(Arrays.asList(new String[]{"friendly"})); - assertNotNull(pets); - - boolean found = false; - for (Pet fetched : pets) { - if (fetched.getId().equals(pet.getId())) { - found = true; - break; - } - } - assertTrue(found); - } - - @Test - public void testUpdatePetWithForm() throws Exception { - Pet pet = createRandomPet(); - pet.setName("frank"); - api.addPet(pet); - - Pet fetched = api.getPetById(pet.getId()); - - api.updatePetWithForm(fetched.getId(), "furt", null); - Pet updated = api.getPetById(fetched.getId()); - - assertEquals(updated.getName(), "furt"); - } - - @Test - public void testDeletePet() throws Exception { - Pet pet = createRandomPet(); - api.addPet(pet); - - Pet fetched = api.getPetById(pet.getId()); - api.deletePet(fetched.getId(), null); - - try { - fetched = api.getPetById(fetched.getId()); - fail("expected an error"); - } catch (ApiException e) { - assertEquals(404, e.getCode()); - } - } - - @Test - public void testUploadFile() throws Exception { - Pet pet = createRandomPet(); - api.addPet(pet); - - File file = new File("hello.txt"); - BufferedWriter writer = new BufferedWriter(new FileWriter(file)); - writer.write("Hello world!"); - writer.close(); - - api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath())); - } - - @Test - public void testEqualsAndHashCode() { - Pet pet1 = new Pet(); - Pet pet2 = new Pet(); - assertTrue(pet1.equals(pet2)); - assertTrue(pet2.equals(pet1)); - assertTrue(pet1.hashCode() == pet2.hashCode()); - assertTrue(pet1.equals(pet1)); - assertTrue(pet1.hashCode() == pet1.hashCode()); - - pet2.setName("really-happy"); - pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); - assertFalse(pet1.equals(pet2)); - assertFalse(pet2.equals(pet1)); - assertFalse(pet1.hashCode() == (pet2.hashCode())); - assertTrue(pet2.equals(pet2)); - assertTrue(pet2.hashCode() == pet2.hashCode()); - - pet1.setName("really-happy"); - pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); - assertTrue(pet1.equals(pet2)); - assertTrue(pet2.equals(pet1)); - assertTrue(pet1.hashCode() == pet2.hashCode()); - assertTrue(pet1.equals(pet1)); - assertTrue(pet1.hashCode() == pet1.hashCode()); - } - - private Pet createRandomPet() { - Pet pet = new Pet(); - pet.setId(TestUtils.nextId()); - pet.setName("gorilla"); - - Category category = new Category(); - category.setName("really-happy"); - - pet.setCategory(category); - pet.setStatus(Pet.StatusEnum.AVAILABLE); - List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); - pet.setPhotoUrls(photos); - - return pet; - } - - private String serializeJson(Object o) { - if (mapper == null) { - mapper = createObjectMapper(); - } - try { - return mapper.writeValueAsString(o); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - private T deserializeJson(String json, Class klass) { - if (mapper == null) { - mapper = createObjectMapper(); - } - try { - return mapper.readValue(json, klass); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - private ObjectMapper createObjectMapper() { - ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); - mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); - mapper.registerModule(new JodaModule()); - return mapper; - } -} diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/StoreApiTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/StoreApiTest.java deleted file mode 100644 index 51779f265f0..00000000000 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/StoreApiTest.java +++ /dev/null @@ -1,103 +0,0 @@ -package io.swagger.client.api; - -import io.swagger.TestUtils; - -import io.swagger.client.ApiException; - -import io.swagger.client.*; -import io.swagger.client.api.*; -import io.swagger.client.auth.*; -import io.swagger.client.model.*; - -import java.lang.reflect.Field; -import java.util.Map; -import java.text.SimpleDateFormat; - -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; -import org.junit.*; -import static org.junit.Assert.*; - -public class StoreApiTest { - StoreApi api = null; - - @Before - public void setup() { - api = new StoreApi(); - // setup authentication - ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); - apiKeyAuth.setApiKey("special-key"); - // set custom date format that is used by the petstore server - api.getApiClient().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")); - } - - @Test - public void testGetInventory() throws Exception { - Map inventory = api.getInventory(); - assertTrue(inventory.keySet().size() > 0); - } - - /* - @Test - public void testGetInventoryInObject() throws Exception { - Object inventoryObj = api.getInventoryInObject(); - assertTrue(inventoryObj instanceof Map); - - Map inventoryMap = (Map) inventoryObj; - assertTrue(inventoryMap.keySet().size() > 0); - - Map.Entry firstEntry = (Map.Entry) inventoryMap.entrySet().iterator().next(); - assertTrue(firstEntry.getKey() instanceof String); - assertTrue(firstEntry.getValue() instanceof Integer); - } - */ - - @Test - public void testPlaceOrder() throws Exception { - Order order = createOrder(); - api.placeOrder(order); - - Order fetched = api.getOrderById(order.getId()); - assertEquals(order.getId(), fetched.getId()); - assertEquals(order.getPetId(), fetched.getPetId()); - assertEquals(order.getQuantity(), fetched.getQuantity()); - assertEquals(order.getShipDate().withZone(DateTimeZone.UTC), fetched.getShipDate().withZone(DateTimeZone.UTC)); - } - - @Test - public void testDeleteOrder() throws Exception { - Order order = createOrder(); - api.placeOrder(order); - - Order fetched = api.getOrderById(order.getId()); - assertEquals(fetched.getId(), order.getId()); - - api.deleteOrder(String.valueOf(order.getId())); - - try { - api.getOrderById(order.getId()); - // fail("expected an error"); - } catch (ApiException e) { - // ok - } - } - - private Order createOrder() { - Order order = new Order(); - order.setPetId(new Long(200)); - order.setQuantity(new Integer(13)); - order.setShipDate(DateTime.now()); - order.setStatus(Order.StatusEnum.PLACED); - order.setComplete(true); - - try { - Field idField = Order.class.getDeclaredField("id"); - idField.setAccessible(true); - idField.set(order, TestUtils.nextId()); - } catch (Exception e) { - throw new RuntimeException(e); - } - - return order; - } -} diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/UserApiTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/UserApiTest.java deleted file mode 100644 index c7fb92d2552..00000000000 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/UserApiTest.java +++ /dev/null @@ -1,88 +0,0 @@ -package io.swagger.client.api; - -import io.swagger.TestUtils; - -import io.swagger.client.api.*; -import io.swagger.client.auth.*; -import io.swagger.client.model.*; - -import java.util.Arrays; - -import org.junit.*; -import static org.junit.Assert.*; - -public class UserApiTest { - UserApi api = null; - - @Before - public void setup() { - api = new UserApi(); - // setup authentication - ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); - apiKeyAuth.setApiKey("special-key"); - } - - @Test - public void testCreateUser() throws Exception { - User user = createUser(); - - api.createUser(user); - - User fetched = api.getUserByName(user.getUsername()); - assertEquals(user.getId(), fetched.getId()); - } - - @Test - public void testCreateUsersWithArray() throws Exception { - User user1 = createUser(); - user1.setUsername("user" + user1.getId()); - User user2 = createUser(); - user2.setUsername("user" + user2.getId()); - - api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); - - User fetched = api.getUserByName(user1.getUsername()); - assertEquals(user1.getId(), fetched.getId()); - } - - @Test - public void testCreateUsersWithList() throws Exception { - User user1 = createUser(); - user1.setUsername("user" + user1.getId()); - User user2 = createUser(); - user2.setUsername("user" + user2.getId()); - - api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); - - User fetched = api.getUserByName(user1.getUsername()); - assertEquals(user1.getId(), fetched.getId()); - } - - @Test - public void testLoginUser() throws Exception { - User user = createUser(); - api.createUser(user); - - String token = api.loginUser(user.getUsername(), user.getPassword()); - assertTrue(token.startsWith("logged in user session:")); - } - - @Test - public void logoutUser() throws Exception { - api.logoutUser(); - } - - private User createUser() { - User user = new User(); - user.setId(TestUtils.nextId()); - user.setUsername("fred" + user.getId()); - user.setFirstName("Fred"); - user.setLastName("Meyer"); - user.setEmail("fred@fredmeyer.com"); - user.setPassword("xxXXxx"); - user.setPhone("408-867-5309"); - user.setUserStatus(123); - - return user; - } -} diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java deleted file mode 100644 index 5bdb4fb78fb..00000000000 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java +++ /dev/null @@ -1,47 +0,0 @@ -package io.swagger.client.auth; - -import java.util.HashMap; -import java.util.ArrayList; -import java.util.Map; -import java.util.List; - -import io.swagger.client.Pair; -import org.junit.*; -import static org.junit.Assert.*; - - -public class ApiKeyAuthTest { - @Test - public void testApplyToParamsInQuery() { - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - - ApiKeyAuth auth = new ApiKeyAuth("query", "api_key"); - auth.setApiKey("my-api-key"); - auth.applyToParams(queryParams, headerParams); - - assertEquals(1, queryParams.size()); - for (Pair queryParam : queryParams) { - assertEquals("my-api-key", queryParam.getValue()); - } - - // no changes to header parameters - assertEquals(0, headerParams.size()); - } - - @Test - public void testApplyToParamsInHeaderWithPrefix() { - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - - ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN"); - auth.setApiKey("my-api-token"); - auth.setApiKeyPrefix("Token"); - auth.applyToParams(queryParams, headerParams); - - // no changes to query parameters - assertEquals(0, queryParams.size()); - assertEquals(1, headerParams.size()); - assertEquals("Token my-api-token", headerParams.get("X-API-TOKEN")); - } -} diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java deleted file mode 100644 index 52c5497ba83..00000000000 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java +++ /dev/null @@ -1,52 +0,0 @@ -package io.swagger.client.auth; - -import java.util.HashMap; -import java.util.ArrayList; -import java.util.Map; -import java.util.List; - -import io.swagger.client.Pair; -import org.junit.*; -import static org.junit.Assert.*; - - -public class HttpBasicAuthTest { - HttpBasicAuth auth = null; - - @Before - public void setup() { - auth = new HttpBasicAuth(); - } - - @Test - public void testApplyToParams() { - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - - auth.setUsername("my-username"); - auth.setPassword("my-password"); - auth.applyToParams(queryParams, headerParams); - - // no changes to query parameters - assertEquals(0, queryParams.size()); - assertEquals(1, headerParams.size()); - // the string below is base64-encoded result of "my-username:my-password" with the "Basic " prefix - String expected = "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ="; - assertEquals(expected, headerParams.get("Authorization")); - - // null username should be treated as empty string - auth.setUsername(null); - auth.applyToParams(queryParams, headerParams); - // the string below is base64-encoded result of ":my-password" with the "Basic " prefix - expected = "Basic Om15LXBhc3N3b3Jk"; - assertEquals(expected, headerParams.get("Authorization")); - - // null password should be treated as empty string - auth.setUsername("my-username"); - auth.setPassword(null); - auth.applyToParams(queryParams, headerParams); - // the string below is base64-encoded result of "my-username:" with the "Basic " prefix - expected = "Basic bXktdXNlcm5hbWU6"; - assertEquals(expected, headerParams.get("Authorization")); - } -} diff --git a/samples/client/petstore/java/default/.gitignore b/samples/client/petstore/java/jersey1/.gitignore similarity index 100% rename from samples/client/petstore/java/default/.gitignore rename to samples/client/petstore/java/jersey1/.gitignore diff --git a/samples/client/petstore/java/default/.swagger-codegen-ignore b/samples/client/petstore/java/jersey1/.swagger-codegen-ignore similarity index 100% rename from samples/client/petstore/java/default/.swagger-codegen-ignore rename to samples/client/petstore/java/jersey1/.swagger-codegen-ignore diff --git a/samples/client/petstore/java/default/.travis.yml b/samples/client/petstore/java/jersey1/.travis.yml similarity index 100% rename from samples/client/petstore/java/default/.travis.yml rename to samples/client/petstore/java/jersey1/.travis.yml diff --git a/samples/client/petstore/java/default/LICENSE b/samples/client/petstore/java/jersey1/LICENSE similarity index 100% rename from samples/client/petstore/java/default/LICENSE rename to samples/client/petstore/java/jersey1/LICENSE diff --git a/samples/client/petstore/java/default/README.md b/samples/client/petstore/java/jersey1/README.md similarity index 69% rename from samples/client/petstore/java/default/README.md rename to samples/client/petstore/java/jersey1/README.md index 562d76a8db4..c824c828980 100644 --- a/samples/client/petstore/java/default/README.md +++ b/samples/client/petstore/java/jersey1/README.md @@ -61,30 +61,32 @@ Please follow the [installation](#installation) instruction and execute the foll import io.swagger.client.*; import io.swagger.client.auth.*; import io.swagger.client.model.*; -import io.swagger.client.api.PetApi; +import io.swagger.client.api.FakeApi; import java.io.File; import java.util.*; -public class PetApiExample { +public class FakeApiExample { public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - - // Configure OAuth2 access token for authorization: petstore_auth - OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); - petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); - - - - PetApi apiInstance = new PetApi(); - - Pet body = new Pet(); // Pet | Pet object that needs to be added to the store + FakeApi apiInstance = new FakeApi(); + BigDecimal number = new BigDecimal(); // BigDecimal | None + Double _double = 3.4D; // Double | None + String string = "string_example"; // String | None + byte[] _byte = B; // byte[] | None + Integer integer = 56; // Integer | None + Integer int32 = 56; // Integer | None + Long int64 = 789L; // Long | None + Float _float = 3.4F; // Float | None + byte[] binary = B; // byte[] | None + LocalDate date = new LocalDate(); // LocalDate | None + DateTime dateTime = new DateTime(); // DateTime | None + String password = "password_example"; // String | None try { - apiInstance.addPet(body); + apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); } catch (ApiException e) { - System.err.println("Exception when calling PetApi#addPet"); + System.err.println("Exception when calling FakeApi#testEndpointParameters"); e.printStackTrace(); } } @@ -98,21 +100,18 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- +*FakeApi* | [**testEndpointParameters**](docs/FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeApi* | [**testEnumQueryParameters**](docs/FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters *PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store -*PetApi* | [**addPetUsingByteArray**](docs/PetApi.md#addPetUsingByteArray) | **POST** /pet?testing_byte_array=true | Fake endpoint to test byte array in body parameter for adding a new pet to the store *PetApi* | [**deletePet**](docs/PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet *PetApi* | [**findPetsByStatus**](docs/PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status *PetApi* | [**findPetsByTags**](docs/PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags *PetApi* | [**getPetById**](docs/PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID -*PetApi* | [**getPetByIdInObject**](docs/PetApi.md#getPetByIdInObject) | **GET** /pet/{petId}?response=inline_arbitrary_object | Fake endpoint to test inline arbitrary object return by 'Find pet by ID' -*PetApi* | [**petPetIdtestingByteArraytrueGet**](docs/PetApi.md#petPetIdtestingByteArraytrueGet) | **GET** /pet/{petId}?testing_byte_array=true | Fake endpoint to test byte array return by 'Find pet by ID' *PetApi* | [**updatePet**](docs/PetApi.md#updatePet) | **PUT** /pet | Update an existing pet *PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data *PetApi* | [**uploadFile**](docs/PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image *StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID -*StoreApi* | [**findOrdersByStatus**](docs/StoreApi.md#findOrdersByStatus) | **GET** /store/findByStatus | Finds orders by status *StoreApi* | [**getInventory**](docs/StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status -*StoreApi* | [**getInventoryInObject**](docs/StoreApi.md#getInventoryInObject) | **GET** /store/inventory?response=arbitrary_object | Fake endpoint to test arbitrary object return by 'Get inventory' *StoreApi* | [**getOrderById**](docs/StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID *StoreApi* | [**placeOrder**](docs/StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet *UserApi* | [**createUser**](docs/UserApi.md#createUser) | **POST** /user | Create user @@ -127,16 +126,29 @@ Class | Method | HTTP request | Description ## Documentation for Models + - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) - [Animal](docs/Animal.md) + - [AnimalFarm](docs/AnimalFarm.md) + - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) + - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) + - [ArrayTest](docs/ArrayTest.md) - [Cat](docs/Cat.md) - [Category](docs/Category.md) - [Dog](docs/Dog.md) - - [InlineResponse200](docs/InlineResponse200.md) + - [EnumClass](docs/EnumClass.md) + - [EnumTest](docs/EnumTest.md) + - [FormatTest](docs/FormatTest.md) + - [HasOnlyReadOnly](docs/HasOnlyReadOnly.md) + - [MapTest](docs/MapTest.md) + - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - [Model200Response](docs/Model200Response.md) + - [ModelApiResponse](docs/ModelApiResponse.md) - [ModelReturn](docs/ModelReturn.md) - [Name](docs/Name.md) + - [NumberOnly](docs/NumberOnly.md) - [Order](docs/Order.md) - [Pet](docs/Pet.md) + - [ReadOnlyFirst](docs/ReadOnlyFirst.md) - [SpecialModelName](docs/SpecialModelName.md) - [Tag](docs/Tag.md) - [User](docs/User.md) @@ -145,6 +157,12 @@ Class | Method | HTTP request | Description ## Documentation for Authorization Authentication schemes defined for the API: +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + ### petstore_auth - **Type**: OAuth @@ -154,40 +172,6 @@ Authentication schemes defined for the API: - write:pets: modify pets in your account - read:pets: read your pets -### test_api_client_id - -- **Type**: API key -- **API key parameter name**: x-test_api_client_id -- **Location**: HTTP header - -### test_api_client_secret - -- **Type**: API key -- **API key parameter name**: x-test_api_client_secret -- **Location**: HTTP header - -### api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - -### test_http_basic - -- **Type**: HTTP basic authentication - -### test_api_key_query - -- **Type**: API key -- **API key parameter name**: test_api_key_query -- **Location**: URL query string - -### test_api_key_header - -- **Type**: API key -- **API key parameter name**: test_api_key_header -- **Location**: HTTP header - ## Recommendation diff --git a/samples/client/petstore/java/default/build.gradle b/samples/client/petstore/java/jersey1/build.gradle similarity index 72% rename from samples/client/petstore/java/default/build.gradle rename to samples/client/petstore/java/jersey1/build.gradle index 1e4969e26fd..0ec352a14c8 100644 --- a/samples/client/petstore/java/default/build.gradle +++ b/samples/client/petstore/java/jersey1/build.gradle @@ -23,7 +23,7 @@ if(hasProperty('target') && target == 'android') { apply plugin: 'com.android.library' apply plugin: 'com.github.dcendents.android-maven' - + android { compileSdkVersion 23 buildToolsVersion '23.0.2' @@ -35,7 +35,7 @@ if(hasProperty('target') && target == 'android') { sourceCompatibility JavaVersion.VERSION_1_7 targetCompatibility JavaVersion.VERSION_1_7 } - + // Rename the aar correctly libraryVariants.all { variant -> variant.outputs.each { output -> @@ -51,7 +51,7 @@ if(hasProperty('target') && target == 'android') { provided 'javax.annotation:jsr250-api:1.0' } } - + afterEvaluate { android.libraryVariants.all { variant -> def task = project.tasks.create "jar${variant.name.capitalize()}", Jar @@ -63,12 +63,12 @@ if(hasProperty('target') && target == 'android') { artifacts.add('archives', task); } } - + task sourcesJar(type: Jar) { from android.sourceSets.main.java.srcDirs classifier = 'sources' } - + artifacts { archives sourcesJar } @@ -80,37 +80,24 @@ if(hasProperty('target') && target == 'android') { sourceCompatibility = JavaVersion.VERSION_1_7 targetCompatibility = JavaVersion.VERSION_1_7 - + install { repositories.mavenInstaller { pom.artifactId = 'swagger-java-client' } } - + task execute(type:JavaExec) { main = System.getProperty('mainClass') classpath = sourceSets.main.runtimeClasspath } } -ext { - swagger_annotations_version = "1.5.8" - jackson_version = "2.7.5" - jersey_version = "1.19.1" - jodatime_version = "2.9.4" - junit_version = "4.12" -} - dependencies { - compile "io.swagger:swagger-annotations:$swagger_annotations_version" - compile "com.sun.jersey:jersey-client:$jersey_version" - compile "com.sun.jersey.contribs:jersey-multipart:$jersey_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.jaxrs:jackson-jaxrs-json-provider:$jackson_version" - compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version" - compile "joda-time:joda-time:$jodatime_version" - compile "com.brsanthu:migbase64:2.2" - testCompile "junit:junit:$junit_version" + compile 'io.swagger:swagger-annotations:1.5.8' + compile 'com.squareup.okhttp:okhttp:2.7.5' + compile 'com.squareup.okhttp:logging-interceptor:2.7.5' + compile 'com.google.code.gson:gson:2.6.2' + compile 'joda-time:joda-time:2.9.3' + testCompile 'junit:junit:4.12' } diff --git a/samples/client/petstore/java/jersey1/build.sbt b/samples/client/petstore/java/jersey1/build.sbt new file mode 100644 index 00000000000..59bf09eb5a7 --- /dev/null +++ b/samples/client/petstore/java/jersey1/build.sbt @@ -0,0 +1,20 @@ +lazy val root = (project in file(".")). + settings( + organization := "io.swagger", + name := "swagger-java-client", + version := "1.0.0", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "io.swagger" % "swagger-annotations" % "1.5.8", + "com.squareup.okhttp" % "okhttp" % "2.7.5", + "com.squareup.okhttp" % "logging-interceptor" % "2.7.5", + "com.google.code.gson" % "gson" % "2.6.2", + "joda-time" % "joda-time" % "2.9.3" % "compile", + "junit" % "junit" % "4.12" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/samples/client/petstore/java/default/docs/AdditionalPropertiesClass.md b/samples/client/petstore/java/jersey1/docs/AdditionalPropertiesClass.md similarity index 100% rename from samples/client/petstore/java/default/docs/AdditionalPropertiesClass.md rename to samples/client/petstore/java/jersey1/docs/AdditionalPropertiesClass.md diff --git a/samples/client/petstore/java/default/docs/Animal.md b/samples/client/petstore/java/jersey1/docs/Animal.md similarity index 100% rename from samples/client/petstore/java/default/docs/Animal.md rename to samples/client/petstore/java/jersey1/docs/Animal.md diff --git a/samples/client/petstore/java/default/docs/AnimalFarm.md b/samples/client/petstore/java/jersey1/docs/AnimalFarm.md similarity index 100% rename from samples/client/petstore/java/default/docs/AnimalFarm.md rename to samples/client/petstore/java/jersey1/docs/AnimalFarm.md diff --git a/samples/client/petstore/java/default/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/java/jersey1/docs/ArrayOfArrayOfNumberOnly.md similarity index 100% rename from samples/client/petstore/java/default/docs/ArrayOfArrayOfNumberOnly.md rename to samples/client/petstore/java/jersey1/docs/ArrayOfArrayOfNumberOnly.md diff --git a/samples/client/petstore/java/default/docs/ArrayOfNumberOnly.md b/samples/client/petstore/java/jersey1/docs/ArrayOfNumberOnly.md similarity index 100% rename from samples/client/petstore/java/default/docs/ArrayOfNumberOnly.md rename to samples/client/petstore/java/jersey1/docs/ArrayOfNumberOnly.md diff --git a/samples/client/petstore/java/default/docs/ArrayTest.md b/samples/client/petstore/java/jersey1/docs/ArrayTest.md similarity index 100% rename from samples/client/petstore/java/default/docs/ArrayTest.md rename to samples/client/petstore/java/jersey1/docs/ArrayTest.md diff --git a/samples/client/petstore/java/default/docs/Cat.md b/samples/client/petstore/java/jersey1/docs/Cat.md similarity index 100% rename from samples/client/petstore/java/default/docs/Cat.md rename to samples/client/petstore/java/jersey1/docs/Cat.md diff --git a/samples/client/petstore/java/default/docs/Category.md b/samples/client/petstore/java/jersey1/docs/Category.md similarity index 100% rename from samples/client/petstore/java/default/docs/Category.md rename to samples/client/petstore/java/jersey1/docs/Category.md diff --git a/samples/client/petstore/java/default/docs/Dog.md b/samples/client/petstore/java/jersey1/docs/Dog.md similarity index 100% rename from samples/client/petstore/java/default/docs/Dog.md rename to samples/client/petstore/java/jersey1/docs/Dog.md diff --git a/samples/client/petstore/java/default/docs/EnumClass.md b/samples/client/petstore/java/jersey1/docs/EnumClass.md similarity index 100% rename from samples/client/petstore/java/default/docs/EnumClass.md rename to samples/client/petstore/java/jersey1/docs/EnumClass.md diff --git a/samples/client/petstore/java/default/docs/EnumTest.md b/samples/client/petstore/java/jersey1/docs/EnumTest.md similarity index 100% rename from samples/client/petstore/java/default/docs/EnumTest.md rename to samples/client/petstore/java/jersey1/docs/EnumTest.md diff --git a/samples/client/petstore/java/default/docs/FakeApi.md b/samples/client/petstore/java/jersey1/docs/FakeApi.md similarity index 100% rename from samples/client/petstore/java/default/docs/FakeApi.md rename to samples/client/petstore/java/jersey1/docs/FakeApi.md diff --git a/samples/client/petstore/java/default/docs/FormatTest.md b/samples/client/petstore/java/jersey1/docs/FormatTest.md similarity index 100% rename from samples/client/petstore/java/default/docs/FormatTest.md rename to samples/client/petstore/java/jersey1/docs/FormatTest.md diff --git a/samples/client/petstore/java/default/docs/HasOnlyReadOnly.md b/samples/client/petstore/java/jersey1/docs/HasOnlyReadOnly.md similarity index 100% rename from samples/client/petstore/java/default/docs/HasOnlyReadOnly.md rename to samples/client/petstore/java/jersey1/docs/HasOnlyReadOnly.md diff --git a/samples/client/petstore/java/default/docs/MapTest.md b/samples/client/petstore/java/jersey1/docs/MapTest.md similarity index 100% rename from samples/client/petstore/java/default/docs/MapTest.md rename to samples/client/petstore/java/jersey1/docs/MapTest.md diff --git a/samples/client/petstore/java/default/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/java/jersey1/docs/MixedPropertiesAndAdditionalPropertiesClass.md similarity index 100% rename from samples/client/petstore/java/default/docs/MixedPropertiesAndAdditionalPropertiesClass.md rename to samples/client/petstore/java/jersey1/docs/MixedPropertiesAndAdditionalPropertiesClass.md diff --git a/samples/client/petstore/java/default/docs/Model200Response.md b/samples/client/petstore/java/jersey1/docs/Model200Response.md similarity index 100% rename from samples/client/petstore/java/default/docs/Model200Response.md rename to samples/client/petstore/java/jersey1/docs/Model200Response.md diff --git a/samples/client/petstore/java/default/docs/ModelApiResponse.md b/samples/client/petstore/java/jersey1/docs/ModelApiResponse.md similarity index 100% rename from samples/client/petstore/java/default/docs/ModelApiResponse.md rename to samples/client/petstore/java/jersey1/docs/ModelApiResponse.md diff --git a/samples/client/petstore/java/default/docs/ModelReturn.md b/samples/client/petstore/java/jersey1/docs/ModelReturn.md similarity index 100% rename from samples/client/petstore/java/default/docs/ModelReturn.md rename to samples/client/petstore/java/jersey1/docs/ModelReturn.md diff --git a/samples/client/petstore/java/default/docs/Name.md b/samples/client/petstore/java/jersey1/docs/Name.md similarity index 100% rename from samples/client/petstore/java/default/docs/Name.md rename to samples/client/petstore/java/jersey1/docs/Name.md diff --git a/samples/client/petstore/java/default/docs/NumberOnly.md b/samples/client/petstore/java/jersey1/docs/NumberOnly.md similarity index 100% rename from samples/client/petstore/java/default/docs/NumberOnly.md rename to samples/client/petstore/java/jersey1/docs/NumberOnly.md diff --git a/samples/client/petstore/java/default/docs/Order.md b/samples/client/petstore/java/jersey1/docs/Order.md similarity index 100% rename from samples/client/petstore/java/default/docs/Order.md rename to samples/client/petstore/java/jersey1/docs/Order.md diff --git a/samples/client/petstore/java/default/docs/Pet.md b/samples/client/petstore/java/jersey1/docs/Pet.md similarity index 100% rename from samples/client/petstore/java/default/docs/Pet.md rename to samples/client/petstore/java/jersey1/docs/Pet.md diff --git a/samples/client/petstore/java/default/docs/PetApi.md b/samples/client/petstore/java/jersey1/docs/PetApi.md similarity index 100% rename from samples/client/petstore/java/default/docs/PetApi.md rename to samples/client/petstore/java/jersey1/docs/PetApi.md diff --git a/samples/client/petstore/java/default/docs/ReadOnlyFirst.md b/samples/client/petstore/java/jersey1/docs/ReadOnlyFirst.md similarity index 100% rename from samples/client/petstore/java/default/docs/ReadOnlyFirst.md rename to samples/client/petstore/java/jersey1/docs/ReadOnlyFirst.md diff --git a/samples/client/petstore/java/default/docs/SpecialModelName.md b/samples/client/petstore/java/jersey1/docs/SpecialModelName.md similarity index 100% rename from samples/client/petstore/java/default/docs/SpecialModelName.md rename to samples/client/petstore/java/jersey1/docs/SpecialModelName.md diff --git a/samples/client/petstore/java/default/docs/StoreApi.md b/samples/client/petstore/java/jersey1/docs/StoreApi.md similarity index 100% rename from samples/client/petstore/java/default/docs/StoreApi.md rename to samples/client/petstore/java/jersey1/docs/StoreApi.md diff --git a/samples/client/petstore/java/default/docs/Tag.md b/samples/client/petstore/java/jersey1/docs/Tag.md similarity index 100% rename from samples/client/petstore/java/default/docs/Tag.md rename to samples/client/petstore/java/jersey1/docs/Tag.md diff --git a/samples/client/petstore/java/default/docs/User.md b/samples/client/petstore/java/jersey1/docs/User.md similarity index 100% rename from samples/client/petstore/java/default/docs/User.md rename to samples/client/petstore/java/jersey1/docs/User.md diff --git a/samples/client/petstore/java/default/docs/UserApi.md b/samples/client/petstore/java/jersey1/docs/UserApi.md similarity index 100% rename from samples/client/petstore/java/default/docs/UserApi.md rename to samples/client/petstore/java/jersey1/docs/UserApi.md diff --git a/samples/client/petstore/java/default/git_push.sh b/samples/client/petstore/java/jersey1/git_push.sh similarity index 100% rename from samples/client/petstore/java/default/git_push.sh rename to samples/client/petstore/java/jersey1/git_push.sh diff --git a/samples/client/petstore/java/default/gradle.properties b/samples/client/petstore/java/jersey1/gradle.properties similarity index 100% rename from samples/client/petstore/java/default/gradle.properties rename to samples/client/petstore/java/jersey1/gradle.properties diff --git a/samples/client/petstore/java/default/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/java/jersey1/gradle/wrapper/gradle-wrapper.jar similarity index 100% rename from samples/client/petstore/java/default/gradle/wrapper/gradle-wrapper.jar rename to samples/client/petstore/java/jersey1/gradle/wrapper/gradle-wrapper.jar diff --git a/samples/client/petstore/java/default/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/java/jersey1/gradle/wrapper/gradle-wrapper.properties similarity index 100% rename from samples/client/petstore/java/default/gradle/wrapper/gradle-wrapper.properties rename to samples/client/petstore/java/jersey1/gradle/wrapper/gradle-wrapper.properties diff --git a/samples/client/petstore/java/default/gradlew b/samples/client/petstore/java/jersey1/gradlew similarity index 100% rename from samples/client/petstore/java/default/gradlew rename to samples/client/petstore/java/jersey1/gradlew diff --git a/samples/client/petstore/java/default/gradlew.bat b/samples/client/petstore/java/jersey1/gradlew.bat similarity index 100% rename from samples/client/petstore/java/default/gradlew.bat rename to samples/client/petstore/java/jersey1/gradlew.bat diff --git a/samples/client/petstore/java/default/pom.xml b/samples/client/petstore/java/jersey1/pom.xml similarity index 65% rename from samples/client/petstore/java/default/pom.xml rename to samples/client/petstore/java/jersey1/pom.xml index c4cb68e99f4..638d5395d46 100644 --- a/samples/client/petstore/java/default/pom.xml +++ b/samples/client/petstore/java/jersey1/pom.xml @@ -6,7 +6,11 @@ jar swagger-java-client 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 @@ -92,61 +96,28 @@ - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.2 - - 1.7 - 1.7 - - io.swagger swagger-annotations - ${swagger-annotations-version} + ${swagger-core-version} - - - com.sun.jersey - jersey-client - ${jersey-version} + com.squareup.okhttp + okhttp + ${okhttp-version} - com.sun.jersey.contribs - jersey-multipart - ${jersey-version} + com.squareup.okhttp + logging-interceptor + ${okhttp-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.jaxrs - jackson-jaxrs-json-provider - ${jackson-version} - - - com.fasterxml.jackson.datatype - jackson-datatype-joda - ${jackson-version} + com.google.code.gson + gson + ${gson-version} joda-time @@ -154,13 +125,6 @@ ${jodatime-version} - - - com.brsanthu - migbase64 - 2.2 - - junit @@ -170,12 +134,15 @@ - UTF-8 - 1.5.8 - 1.19.1 - 2.7.5 - 2.9.4 + 1.7 + ${java.version} + ${java.version} + 1.5.9 + 2.7.5 + 2.6.2 + 2.9.3 1.0.0 4.12 + UTF-8 diff --git a/samples/client/petstore/java/default/settings.gradle b/samples/client/petstore/java/jersey1/settings.gradle similarity index 100% rename from samples/client/petstore/java/default/settings.gradle rename to samples/client/petstore/java/jersey1/settings.gradle diff --git a/samples/client/petstore/java/default/src/main/AndroidManifest.xml b/samples/client/petstore/java/jersey1/src/main/AndroidManifest.xml similarity index 100% rename from samples/client/petstore/java/default/src/main/AndroidManifest.xml rename to samples/client/petstore/java/jersey1/src/main/AndroidManifest.xml diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiCallback.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiCallback.java new file mode 100644 index 00000000000..3ca33cf8017 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiCallback.java @@ -0,0 +1,74 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import java.io.IOException; + +import java.util.Map; +import java.util.List; + +/** + * Callback for asynchronous API call. + * + * @param The return type + */ +public interface ApiCallback { + /** + * This is called when the API call fails. + * + * @param e The exception causing the failure + * @param statusCode Status code of the response if available, otherwise it would be 0 + * @param responseHeaders Headers of the response if available, otherwise it would be null + */ + void onFailure(ApiException e, int statusCode, Map> responseHeaders); + + /** + * This is called when the API call succeeded. + * + * @param result The result deserialized from response + * @param statusCode Status code of the response + * @param responseHeaders Headers of the response + */ + void onSuccess(T result, int statusCode, Map> responseHeaders); + + /** + * This is called when the API upload processing. + * + * @param bytesWritten bytes Written + * @param contentLength content length of request body + * @param done write end + */ + void onUploadProgress(long bytesWritten, long contentLength, boolean done); + + /** + * This is called when the API downlond processing. + * + * @param bytesRead bytes Read + * @param contentLength content lenngth of the response + * @param done Read end + */ + void onDownloadProgress(long bytesRead, long contentLength, boolean done); +} diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java new file mode 100644 index 00000000000..0204c5c96aa --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java @@ -0,0 +1,1324 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import com.squareup.okhttp.Call; +import com.squareup.okhttp.Callback; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Response; +import com.squareup.okhttp.RequestBody; +import com.squareup.okhttp.FormEncodingBuilder; +import com.squareup.okhttp.MultipartBuilder; +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.Headers; +import com.squareup.okhttp.internal.http.HttpMethod; +import com.squareup.okhttp.logging.HttpLoggingInterceptor; +import com.squareup.okhttp.logging.HttpLoggingInterceptor.Level; + +import java.lang.reflect.Type; + +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.Map.Entry; +import java.util.HashMap; +import java.util.List; +import java.util.ArrayList; +import java.util.Date; +import java.util.TimeZone; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import java.net.URLEncoder; +import java.net.URLConnection; + +import java.io.File; +import java.io.InputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; + +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.security.SecureRandom; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.text.ParseException; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.KeyManager; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509TrustManager; + +import okio.BufferedSink; +import okio.Okio; + +import io.swagger.client.auth.Authentication; +import io.swagger.client.auth.HttpBasicAuth; +import io.swagger.client.auth.ApiKeyAuth; +import io.swagger.client.auth.OAuth; + +public class ApiClient { + public static final double JAVA_VERSION; + public static final boolean IS_ANDROID; + public static final int ANDROID_SDK_VERSION; + + static { + JAVA_VERSION = Double.parseDouble(System.getProperty("java.specification.version")); + boolean isAndroid; + try { + Class.forName("android.app.Activity"); + isAndroid = true; + } catch (ClassNotFoundException e) { + isAndroid = false; + } + IS_ANDROID = isAndroid; + int sdkVersion = 0; + if (IS_ANDROID) { + try { + sdkVersion = Class.forName("android.os.Build$VERSION").getField("SDK_INT").getInt(null); + } catch (Exception e) { + try { + sdkVersion = Integer.parseInt((String) Class.forName("android.os.Build$VERSION").getField("SDK").get(null)); + } catch (Exception e2) { } + } + } + ANDROID_SDK_VERSION = sdkVersion; + } + + /** + * The datetime format to be used when lenientDatetimeFormat is enabled. + */ + public static final String LENIENT_DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; + + private String basePath = "http://petstore.swagger.io/v2"; + private boolean lenientOnJson = false; + private boolean debugging = false; + private Map defaultHeaderMap = new HashMap(); + private String tempFolderPath = null; + + private Map authentications; + + private DateFormat dateFormat; + private DateFormat datetimeFormat; + private boolean lenientDatetimeFormat; + private int dateLength; + + private InputStream sslCaCert; + private boolean verifyingSsl; + + private OkHttpClient httpClient; + private JSON json; + + private HttpLoggingInterceptor loggingInterceptor; + + /* + * Constructor for ApiClient + */ + public ApiClient() { + httpClient = new OkHttpClient(); + + verifyingSsl = true; + + json = new JSON(this); + + /* + * Use RFC3339 format for date and datetime. + * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + */ + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + // Always use UTC as the default time zone when dealing with date (without time). + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + initDatetimeFormat(); + + // Be lenient on datetime formats when parsing datetime from string. + // See parseDatetime. + this.lenientDatetimeFormat = true; + + // Set default User-Agent. + setUserAgent("Swagger-Codegen/1.0.0/java"); + + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap(); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("petstore_auth", new OAuth()); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + /** + * Get base path + * + * @return Baes path + */ + public String getBasePath() { + return basePath; + } + + /** + * Set base path + * + * @param basePath Base path of the URL (e.g http://petstore.swagger.io/v2 + * @return An instance of OkHttpClient + */ + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + /** + * Get HTTP client + * + * @return An instance of OkHttpClient + */ + public OkHttpClient getHttpClient() { + return httpClient; + } + + /** + * Set HTTP client + * + * @param httpClient An instance of OkHttpClient + * @return Api Client + */ + public ApiClient setHttpClient(OkHttpClient httpClient) { + this.httpClient = httpClient; + return this; + } + + /** + * Get JSON + * + * @return JSON object + */ + public JSON getJSON() { + return json; + } + + /** + * Set JSON + * + * @param json JSON object + * @return Api client + */ + public ApiClient setJSON(JSON json) { + this.json = json; + return this; + } + + /** + * True if isVerifyingSsl flag is on + * + * @return True if isVerifySsl flag is on + */ + public boolean isVerifyingSsl() { + return verifyingSsl; + } + + /** + * Configure whether to verify certificate and hostname when making https requests. + * Default to true. + * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. + * + * @param verifyingSsl True to verify TLS/SSL connection + * @return ApiClient + */ + public ApiClient setVerifyingSsl(boolean verifyingSsl) { + this.verifyingSsl = verifyingSsl; + applySslSettings(); + return this; + } + + /** + * Get SSL CA cert. + * + * @return Input stream to the SSL CA cert + */ + public InputStream getSslCaCert() { + return sslCaCert; + } + + /** + * Configure the CA certificate to be trusted when making https requests. + * Use null to reset to default. + * + * @param sslCaCert input stream for SSL CA cert + * @return ApiClient + */ + public ApiClient setSslCaCert(InputStream sslCaCert) { + this.sslCaCert = sslCaCert; + applySslSettings(); + return this; + } + + public DateFormat getDateFormat() { + return dateFormat; + } + + public ApiClient setDateFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + this.dateLength = this.dateFormat.format(new Date()).length(); + return this; + } + + public DateFormat getDatetimeFormat() { + return datetimeFormat; + } + + public ApiClient setDatetimeFormat(DateFormat datetimeFormat) { + this.datetimeFormat = datetimeFormat; + return this; + } + + /** + * Whether to allow various ISO 8601 datetime formats when parsing a datetime string. + * @see #parseDatetime(String) + * @return True if lenientDatetimeFormat flag is set to true + */ + public boolean isLenientDatetimeFormat() { + return lenientDatetimeFormat; + } + + public ApiClient setLenientDatetimeFormat(boolean lenientDatetimeFormat) { + this.lenientDatetimeFormat = lenientDatetimeFormat; + return this; + } + + /** + * Parse the given date string into Date object. + * The default dateFormat supports these ISO 8601 date formats: + * 2015-08-16 + * 2015-8-16 + * @param str String to be parsed + * @return Date + */ + public Date parseDate(String str) { + if (str == null) + return null; + try { + return dateFormat.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Parse the given datetime string into Date object. + * When lenientDatetimeFormat is enabled, the following ISO 8601 datetime formats are supported: + * 2015-08-16T08:20:05Z + * 2015-8-16T8:20:05Z + * 2015-08-16T08:20:05+00:00 + * 2015-08-16T08:20:05+0000 + * 2015-08-16T08:20:05.376Z + * 2015-08-16T08:20:05.376+00:00 + * 2015-08-16T08:20:05.376+00 + * Note: The 3-digit milli-seconds is optional. Time zone is required and can be in one of + * these formats: + * Z (same with +0000) + * +08:00 (same with +0800) + * -02 (same with -0200) + * -0200 + * @see ISO 8601 + * @param str Date time string to be parsed + * @return Date representation of the string + */ + public Date parseDatetime(String str) { + if (str == null) + return null; + + DateFormat format; + if (lenientDatetimeFormat) { + /* + * When lenientDatetimeFormat is enabled, normalize the date string + * into LENIENT_DATETIME_FORMAT to support various formats + * defined by ISO 8601. + */ + // normalize time zone + // trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000 + str = str.replaceAll("[zZ]\\z", "+0000"); + // remove colon in time zone: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000 + str = str.replaceAll("([+-]\\d{2}):(\\d{2})\\z", "$1$2"); + // expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000 + str = str.replaceAll("([+-]\\d{2})\\z", "$100"); + // add milliseconds when missing + // 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000 + str = str.replaceAll("(:\\d{1,2})([+-]\\d{4})\\z", "$1.000$2"); + format = new SimpleDateFormat(LENIENT_DATETIME_FORMAT); + } else { + format = this.datetimeFormat; + } + + try { + return format.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /* + * Parse date or date time in string format into Date object. + * + * @param str Date time string to be parsed + * @return Date representation of the string + */ + public Date parseDateOrDatetime(String str) { + if (str == null) + return null; + else if (str.length() <= dateLength) + return parseDate(str); + else + return parseDatetime(str); + } + + /** + * Format the given Date object into string (Date format). + * + * @param date Date object + * @return Formatted date in string representation + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } + + /** + * Format the given Date object into string (Datetime format). + * + * @param date Date object + * @return Formatted datetime in string representation + */ + public String formatDatetime(Date date) { + return datetimeFormat.format(date); + } + + /** + * Get authentications (key: authentication name, value: authentication). + * + * @return Map of authentication objects + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + * + * @param username Username + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + * + * @param password Password + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + * + * @param apiKey API key + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + * + * @param apiKeyPrefix API key prefix + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set access token for the first OAuth2 authentication. + * + * @param accessToken Access token + */ + public void setAccessToken(String accessToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); + return; + } + } + throw new RuntimeException("No OAuth2 authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + * + * @param userAgent HTTP request's user agent + * @return ApiClient + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + * @return ApiClient + */ + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + /** + * @see setLenient + * + * @return True if lenientOnJson is enabled, false otherwise. + */ + public boolean isLenientOnJson() { + return lenientOnJson; + } + + /** + * Set LenientOnJson + * + * @param lenient True to enable lenientOnJson + * @return ApiClient + */ + public ApiClient setLenientOnJson(boolean lenient) { + this.lenientOnJson = lenient; + return this; + } + + /** + * Check that whether debugging is enabled for this API client. + * + * @return True if debugging is enabled, false otherwise. + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + * @return ApiClient + */ + public ApiClient setDebugging(boolean debugging) { + if (debugging != this.debugging) { + if (debugging) { + loggingInterceptor = new HttpLoggingInterceptor(); + loggingInterceptor.setLevel(Level.BODY); + httpClient.interceptors().add(loggingInterceptor); + } else { + httpClient.interceptors().remove(loggingInterceptor); + loggingInterceptor = null; + } + } + this.debugging = debugging; + return this; + } + + /** + * The path of temporary folder used to store downloaded files from endpoints + * with file response. The default value is null, i.e. using + * the system's default tempopary folder. + * + * @see createTempFile + * @return Temporary folder path + */ + public String getTempFolderPath() { + return tempFolderPath; + } + + /** + * Set the tempoaray folder path (for downloading files) + * + * @param tempFolderPath Temporary folder path + * @return ApiClient + */ + public ApiClient setTempFolderPath(String tempFolderPath) { + this.tempFolderPath = tempFolderPath; + return this; + } + + /** + * Get connection timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getConnectTimeout() { + return httpClient.getConnectTimeout(); + } + + /** + * Sets the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * + * @param connectionTimeout connection timeout in milliseconds + * @return Api client + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + httpClient.setConnectTimeout(connectionTimeout, TimeUnit.MILLISECONDS); + return this; + } + + /** + * Format the given parameter object into string. + * + * @param param Parameter + * @return String representation of the parameter + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDatetime((Date) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for (Object o : (Collection)param) { + if (b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /** + * Format to {@code Pair} objects. + * + * @param collectionFormat collection format (e.g. csv, tsv) + * @param name Name + * @param value Value + * @return A list of Pair objects + */ + public List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + + // create the params based on the collection format + if (collectionFormat.equals("multi")) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); + } + + return params; + } + + String delimiter = ","; + + if (collectionFormat.equals("csv")) { + delimiter = ","; + } else if (collectionFormat.equals("ssv")) { + delimiter = " "; + } else if (collectionFormat.equals("tsv")) { + delimiter = "\t"; + } else if (collectionFormat.equals("pipes")) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + + return params; + } + + /** + * Sanitize filename by removing path. + * e.g. ../../sun.gif becomes sun.gif + * + * @param filename The filename to be sanitized + * @return The sanitized filename + */ + public String sanitizeFilename(String filename) { + return filename.replaceAll(".*[/\\\\]", ""); + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * + * @param mime MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public boolean isJsonMime(String mime) { + return mime != null && mime.matches("(?i)application\\/json(;.*)?"); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } + return contentTypes[0]; + } + + /** + * Escape the given string to be used as URL query value. + * + * @param str String to be escaped + * @return Escaped string + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Deserialize response body to Java object, according to the return type and + * the Content-Type response header. + * + * @param Type + * @param response HTTP response + * @param returnType The type of the Java object + * @return The deserialized Java object + * @throws ApiException If fail to deserialize response body, i.e. cannot read response body + * or the Content-Type of the response is not supported. + */ + public T deserialize(Response response, Type returnType) throws ApiException { + if (response == null || returnType == null) { + return null; + } + + if ("byte[]".equals(returnType.toString())) { + // Handle binary response (byte array). + try { + return (T) response.body().bytes(); + } catch (IOException e) { + throw new ApiException(e); + } + } else if (returnType.equals(File.class)) { + // Handle file downloading. + return (T) downloadFileFromResponse(response); + } + + String respBody; + try { + if (response.body() != null) + respBody = response.body().string(); + else + respBody = null; + } catch (IOException e) { + throw new ApiException(e); + } + + if (respBody == null || "".equals(respBody)) { + return null; + } + + String contentType = response.headers().get("Content-Type"); + if (contentType == null) { + // ensuring a default content type + contentType = "application/json"; + } + if (isJsonMime(contentType)) { + return json.deserialize(respBody, returnType); + } else if (returnType.equals(String.class)) { + // Expecting string, return the raw response body. + return (T) respBody; + } else { + throw new ApiException( + "Content type \"" + contentType + "\" is not supported for type: " + returnType, + response.code(), + response.headers().toMultimap(), + respBody); + } + } + + /** + * Serialize the given Java object into request body according to the object's + * class and the request Content-Type. + * + * @param obj The Java object + * @param contentType The request Content-Type + * @return The serialized request body + * @throws ApiException If fail to serialize the given object + */ + public RequestBody serialize(Object obj, String contentType) throws ApiException { + if (obj instanceof byte[]) { + // Binary (byte array) body parameter support. + return RequestBody.create(MediaType.parse(contentType), (byte[]) obj); + } else if (obj instanceof File) { + // File body parameter support. + return RequestBody.create(MediaType.parse(contentType), (File) obj); + } else if (isJsonMime(contentType)) { + String content; + if (obj != null) { + content = json.serialize(obj); + } else { + content = null; + } + return RequestBody.create(MediaType.parse(contentType), content); + } else { + throw new ApiException("Content type \"" + contentType + "\" is not supported"); + } + } + + /** + * Download file from the given response. + * + * @param response An instance of the Response object + * @throws ApiException If fail to read file content from response and write to disk + * @return Downloaded file + */ + public File downloadFileFromResponse(Response response) throws ApiException { + try { + File file = prepareDownloadFile(response); + BufferedSink sink = Okio.buffer(Okio.sink(file)); + sink.writeAll(response.body().source()); + sink.close(); + return file; + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * Prepare file for download + * + * @param response An instance of the Response object + * @throws IOException If fail to prepare file for download + * @return Prepared file for the download + */ + public File prepareDownloadFile(Response response) throws IOException { + String filename = null; + String contentDisposition = response.header("Content-Disposition"); + if (contentDisposition != null && !"".equals(contentDisposition)) { + // Get filename from the Content-Disposition header. + Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); + Matcher matcher = pattern.matcher(contentDisposition); + if (matcher.find()) { + filename = sanitizeFilename(matcher.group(1)); + } + } + + String prefix = null; + String suffix = null; + if (filename == null) { + prefix = "download-"; + suffix = ""; + } else { + int pos = filename.lastIndexOf("."); + if (pos == -1) { + prefix = filename + "-"; + } else { + prefix = filename.substring(0, pos) + "-"; + suffix = filename.substring(pos); + } + // File.createTempFile requires the prefix to be at least three characters long + if (prefix.length() < 3) + prefix = "download-"; + } + + if (tempFolderPath == null) + return File.createTempFile(prefix, suffix); + else + return File.createTempFile(prefix, suffix, new File(tempFolderPath)); + } + + /** + * {@link #execute(Call, Type)} + * + * @param Type + * @param call An instance of the Call object + * @throws ApiException If fail to execute the call + * @return ApiResponse<T> + */ + public ApiResponse execute(Call call) throws ApiException { + return execute(call, null); + } + + /** + * Execute HTTP call and deserialize the HTTP response body into the given return type. + * + * @param returnType The return type used to deserialize HTTP response body + * @param The return type corresponding to (same with) returnType + * @param call Call + * @return ApiResponse object containing response status, headers and + * data, which is a Java object deserialized from response body and would be null + * when returnType is null. + * @throws ApiException If fail to execute the call + */ + public ApiResponse execute(Call call, Type returnType) throws ApiException { + try { + Response response = call.execute(); + T data = handleResponse(response, returnType); + return new ApiResponse(response.code(), response.headers().toMultimap(), data); + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * {@link #executeAsync(Call, Type, ApiCallback)} + * + * @param Type + * @param call An instance of the Call object + * @param callback ApiCallback<T> + */ + public void executeAsync(Call call, ApiCallback callback) { + executeAsync(call, null, callback); + } + + /** + * Execute HTTP call asynchronously. + * + * @see #execute(Call, Type) + * @param Type + * @param call The callback to be executed when the API call finishes + * @param returnType Return type + * @param callback ApiCallback + */ + public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { + call.enqueue(new Callback() { + @Override + public void onFailure(Request request, IOException e) { + callback.onFailure(new ApiException(e), 0, null); + } + + @Override + public void onResponse(Response response) throws IOException { + T result; + try { + result = (T) handleResponse(response, returnType); + } catch (ApiException e) { + callback.onFailure(e, response.code(), response.headers().toMultimap()); + return; + } + callback.onSuccess(result, response.code(), response.headers().toMultimap()); + } + }); + } + + /** + * Handle the given response, return the deserialized object when the response is successful. + * + * @param Type + * @param response Response + * @param returnType Return type + * @throws ApiException If the response has a unsuccessful status code or + * fail to deserialize the response body + * @return Type + */ + public T handleResponse(Response response, Type returnType) throws ApiException { + if (response.isSuccessful()) { + if (returnType == null || response.code() == 204) { + // returning null if the returnType is not defined, + // or the status code is 204 (No Content) + return null; + } else { + return deserialize(response, returnType); + } + } else { + String respBody = null; + if (response.body() != null) { + try { + respBody = response.body().string(); + } catch (IOException e) { + throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); + } + } + throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); + } + } + + /** + * Build HTTP call with the given options. + * + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param formParams The form parameters + * @param authNames The authentications to apply + * @param progressRequestListener Progress request listener + * @return The HTTP call + * @throws ApiException If fail to serialize the request body object + */ + public Call buildCall(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + updateParamsForAuth(authNames, queryParams, headerParams); + + final String url = buildUrl(path, queryParams); + final Request.Builder reqBuilder = new Request.Builder().url(url); + processHeaderParams(headerParams, reqBuilder); + + String contentType = (String) headerParams.get("Content-Type"); + // ensuring a default content type + if (contentType == null) { + contentType = "application/json"; + } + + RequestBody reqBody; + if (!HttpMethod.permitsRequestBody(method)) { + reqBody = null; + } else if ("application/x-www-form-urlencoded".equals(contentType)) { + reqBody = buildRequestBodyFormEncoding(formParams); + } else if ("multipart/form-data".equals(contentType)) { + reqBody = buildRequestBodyMultipart(formParams); + } else if (body == null) { + if ("DELETE".equals(method)) { + // allow calling DELETE without sending a request body + reqBody = null; + } else { + // use an empty request body (for POST, PUT and PATCH) + reqBody = RequestBody.create(MediaType.parse(contentType), ""); + } + } else { + reqBody = serialize(body, contentType); + } + + Request request = null; + + if(progressRequestListener != null && reqBody != null) { + ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener); + request = reqBuilder.method(method, progressRequestBody).build(); + } else { + request = reqBuilder.method(method, reqBody).build(); + } + + return httpClient.newCall(request); + } + + /** + * Build full URL by concatenating base path, the given sub path and query parameters. + * + * @param path The sub path + * @param queryParams The query parameters + * @return The full URL + */ + public String buildUrl(String path, List queryParams) { + final StringBuilder url = new StringBuilder(); + url.append(basePath).append(path); + + if (queryParams != null && !queryParams.isEmpty()) { + // support (constant) query string in `path`, e.g. "/posts?draft=1" + String prefix = path.contains("?") ? "&" : "?"; + for (Pair param : queryParams) { + if (param.getValue() != null) { + if (prefix != null) { + url.append(prefix); + prefix = null; + } else { + url.append("&"); + } + String value = parameterToString(param.getValue()); + url.append(escapeString(param.getName())).append("=").append(escapeString(value)); + } + } + } + + return url.toString(); + } + + /** + * Set header parameters to the request builder, including default headers. + * + * @param headerParams Header parameters in the ofrm of Map + * @param reqBuilder Reqeust.Builder + */ + public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { + for (Entry param : headerParams.entrySet()) { + reqBuilder.header(param.getKey(), parameterToString(param.getValue())); + } + for (Entry header : defaultHeaderMap.entrySet()) { + if (!headerParams.containsKey(header.getKey())) { + reqBuilder.header(header.getKey(), parameterToString(header.getValue())); + } + } + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + */ + public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); + auth.applyToParams(queryParams, headerParams); + } + } + + /** + * Build a form-encoding request body with the given form parameters. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyFormEncoding(Map formParams) { + FormEncodingBuilder formBuilder = new FormEncodingBuilder(); + for (Entry param : formParams.entrySet()) { + formBuilder.add(param.getKey(), parameterToString(param.getValue())); + } + return formBuilder.build(); + } + + /** + * Build a multipart (file uploading) request body with the given form parameters, + * which could contain text fields and file fields. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyMultipart(Map formParams) { + MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); + for (Entry param : formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\""); + MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); + mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file)); + } else { + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\""); + mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue()))); + } + } + return mpBuilder.build(); + } + + /** + * Guess Content-Type header from the given file (defaults to "application/octet-stream"). + * + * @param file The given file + * @return The guessed Content-Type + */ + public String guessContentTypeFromFile(File file) { + String contentType = URLConnection.guessContentTypeFromName(file.getName()); + if (contentType == null) { + return "application/octet-stream"; + } else { + return contentType; + } + } + + /** + * Initialize datetime format according to the current environment, e.g. Java 1.7 and Android. + */ + private void initDatetimeFormat() { + String formatWithTimeZone = null; + if (IS_ANDROID) { + if (ANDROID_SDK_VERSION >= 18) { + // The time zone format "ZZZZZ" is available since Android 4.3 (SDK version 18) + formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"; + } + } else if (JAVA_VERSION >= 1.7) { + // The time zone format "XXX" is available since Java 1.7 + formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; + } + if (formatWithTimeZone != null) { + this.datetimeFormat = new SimpleDateFormat(formatWithTimeZone); + // NOTE: Use the system's default time zone (mainly for datetime formatting). + } else { + // Use a common format that works across all systems. + this.datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + // Always use the UTC time zone as we are using a constant trailing "Z" here. + this.datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + } + } + + /** + * Apply SSL related settings to httpClient according to the current values of + * verifyingSsl and sslCaCert. + */ + private void applySslSettings() { + try { + KeyManager[] keyManagers = null; + TrustManager[] trustManagers = null; + HostnameVerifier hostnameVerifier = null; + if (!verifyingSsl) { + TrustManager trustAll = new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} + @Override + public X509Certificate[] getAcceptedIssuers() { return null; } + }; + SSLContext sslContext = SSLContext.getInstance("TLS"); + trustManagers = new TrustManager[]{ trustAll }; + hostnameVerifier = new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { return true; } + }; + } else if (sslCaCert != null) { + char[] password = null; // Any password will work. + CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); + Collection certificates = certificateFactory.generateCertificates(sslCaCert); + if (certificates.isEmpty()) { + throw new IllegalArgumentException("expected non-empty set of trusted certificates"); + } + KeyStore caKeyStore = newEmptyKeyStore(password); + int index = 0; + for (Certificate certificate : certificates) { + String certificateAlias = "ca" + Integer.toString(index++); + caKeyStore.setCertificateEntry(certificateAlias, certificate); + } + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagerFactory.init(caKeyStore); + trustManagers = trustManagerFactory.getTrustManagers(); + } + + if (keyManagers != null || trustManagers != null) { + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(keyManagers, trustManagers, new SecureRandom()); + httpClient.setSslSocketFactory(sslContext.getSocketFactory()); + } else { + httpClient.setSslSocketFactory(null); + } + httpClient.setHostnameVerifier(hostnameVerifier); + } catch (GeneralSecurityException e) { + throw new RuntimeException(e); + } + } + + private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { + try { + KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + keyStore.load(null, password); + return keyStore; + } catch (IOException e) { + throw new AssertionError(e); + } + } +} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiException.java similarity index 100% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiException.java diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiResponse.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiResponse.java new file mode 100644 index 00000000000..d7dde1ee939 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiResponse.java @@ -0,0 +1,71 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import java.util.List; +import java.util.Map; + +/** + * API response returned by API call. + * + * @param T The type of data that is deserialized from response body + */ +public class ApiResponse { + final private int statusCode; + final private Map> headers; + final private T data; + + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + */ + public ApiResponse(int statusCode, Map> headers) { + this(statusCode, headers, null); + } + + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + * @param data The object deserialized from response bod + */ + public ApiResponse(int statusCode, Map> headers, T data) { + this.statusCode = statusCode; + this.headers = headers; + this.data = data; + } + + public int getStatusCode() { + return statusCode; + } + + public Map> getHeaders() { + return headers; + } + + public T getData() { + return data; + } +} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/Configuration.java similarity index 100% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/Configuration.java diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/JSON.java new file mode 100644 index 00000000000..a0b9c9c1cf0 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/JSON.java @@ -0,0 +1,236 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonNull; +import com.google.gson.JsonParseException; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +import java.io.IOException; +import java.io.StringReader; +import java.lang.reflect.Type; +import java.util.Date; + +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; + +public class JSON { + private ApiClient apiClient; + private Gson gson; + + /** + * JSON constructor. + * + * @param apiClient An instance of ApiClient + */ + public JSON(ApiClient apiClient) { + this.apiClient = apiClient; + gson = new GsonBuilder() + .registerTypeAdapter(Date.class, new DateAdapter(apiClient)) + .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) + .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) + .create(); + } + + /** + * Get Gson. + * + * @return Gson + */ + public Gson getGson() { + return gson; + } + + /** + * Set Gson. + * + * @param gson Gson + */ + public void setGson(Gson gson) { + this.gson = gson; + } + + /** + * Serialize the given Java object into JSON string. + * + * @param obj Object + * @return String representation of the JSON + */ + public String serialize(Object obj) { + return gson.toJson(obj); + } + + /** + * Deserialize the given JSON string to Java object. + * + * @param Type + * @param body The JSON string + * @param returnType The type to deserialize inot + * @return The deserialized Java object + */ + public T deserialize(String body, Type returnType) { + try { + if (apiClient.isLenientOnJson()) { + JsonReader jsonReader = new JsonReader(new StringReader(body)); + // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) + jsonReader.setLenient(true); + return gson.fromJson(jsonReader, returnType); + } else { + return gson.fromJson(body, returnType); + } + } catch (JsonParseException e) { + // Fallback processing when failed to parse JSON form response body: + // return the response body string directly for the String return type; + // parse response body into date or datetime for the Date return type. + if (returnType.equals(String.class)) + return (T) body; + else if (returnType.equals(Date.class)) + return (T) apiClient.parseDateOrDatetime(body); + else throw(e); + } + } +} + +class DateAdapter implements JsonSerializer, JsonDeserializer { + private final ApiClient apiClient; + + /** + * Constructor for DateAdapter + * + * @param apiClient Api client + */ + public DateAdapter(ApiClient apiClient) { + super(); + this.apiClient = apiClient; + } + + /** + * Serialize + * + * @param src Date + * @param typeOfSrc Type + * @param context Json Serialization Context + * @return Json Element + */ + @Override + public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { + if (src == null) { + return JsonNull.INSTANCE; + } else { + return new JsonPrimitive(apiClient.formatDatetime(src)); + } + } + + /** + * Deserialize + * + * @param json Json element + * @param date Type + * @param typeOfSrc Type + * @param context Json Serialization Context + * @return Date + * @throw JsonParseException if fail to parse + */ + @Override + public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException { + String str = json.getAsJsonPrimitive().getAsString(); + try { + return apiClient.parseDateOrDatetime(str); + } catch (RuntimeException e) { + throw new JsonParseException(e); + } + } +} + +/** + * Gson TypeAdapter for Joda DateTime type + */ +class DateTimeTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + + @Override + public void write(JsonWriter out, DateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public DateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseDateTime(date); + } + } +} + +/** + * Gson TypeAdapter for Joda LocalDate type + */ +class LocalDateTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.date(); + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseLocalDate(date); + } + } +} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/Pair.java similarity index 100% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/Pair.java diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ProgressRequestBody.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ProgressRequestBody.java new file mode 100644 index 00000000000..d9ca742ecd2 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ProgressRequestBody.java @@ -0,0 +1,95 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.RequestBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSink; +import okio.ForwardingSink; +import okio.Okio; +import okio.Sink; + +public class ProgressRequestBody extends RequestBody { + + public interface ProgressRequestListener { + void onRequestProgress(long bytesWritten, long contentLength, boolean done); + } + + private final RequestBody requestBody; + + private final ProgressRequestListener progressListener; + + private BufferedSink bufferedSink; + + public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) { + this.requestBody = requestBody; + this.progressListener = progressListener; + } + + @Override + public MediaType contentType() { + return requestBody.contentType(); + } + + @Override + public long contentLength() throws IOException { + return requestBody.contentLength(); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + if (bufferedSink == null) { + bufferedSink = Okio.buffer(sink(sink)); + } + + requestBody.writeTo(bufferedSink); + bufferedSink.flush(); + + } + + private Sink sink(Sink sink) { + return new ForwardingSink(sink) { + + long bytesWritten = 0L; + long contentLength = 0L; + + @Override + public void write(Buffer source, long byteCount) throws IOException { + super.write(source, byteCount); + if (contentLength == 0) { + contentLength = contentLength(); + } + + bytesWritten += byteCount; + progressListener.onRequestProgress(bytesWritten, contentLength, bytesWritten == contentLength); + } + }; + } +} diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ProgressResponseBody.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ProgressResponseBody.java new file mode 100644 index 00000000000..f8af685999d --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ProgressResponseBody.java @@ -0,0 +1,88 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.ResponseBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSource; +import okio.ForwardingSource; +import okio.Okio; +import okio.Source; + +public class ProgressResponseBody extends ResponseBody { + + public interface ProgressListener { + void update(long bytesRead, long contentLength, boolean done); + } + + private final ResponseBody responseBody; + private final ProgressListener progressListener; + private BufferedSource bufferedSource; + + public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) { + this.responseBody = responseBody; + this.progressListener = progressListener; + } + + @Override + public MediaType contentType() { + return responseBody.contentType(); + } + + @Override + public long contentLength() throws IOException { + return responseBody.contentLength(); + } + + @Override + public BufferedSource source() throws IOException { + if (bufferedSource == null) { + bufferedSource = Okio.buffer(source(responseBody.source())); + } + return bufferedSource; + } + + private Source source(Source source) { + return new ForwardingSource(source) { + long totalBytesRead = 0L; + + @Override + public long read(Buffer sink, long byteCount) throws IOException { + long bytesRead = super.read(sink, byteCount); + // read() returns the number of bytes read, or -1 if this source is exhausted. + totalBytesRead += bytesRead != -1 ? bytesRead : 0; + progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1); + return bytesRead; + } + }; + } +} + + diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/StringUtil.java similarity index 100% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/StringUtil.java diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java new file mode 100644 index 00000000000..52dce361e2a --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java @@ -0,0 +1,353 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + +import org.joda.time.LocalDate; +import org.joda.time.DateTime; +import java.math.BigDecimal; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class FakeApi { + private ApiClient apiClient; + + public FakeApi() { + this(Configuration.getDefaultApiClient()); + } + + public FakeApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for testEndpointParameters */ + private com.squareup.okhttp.Call testEndpointParametersCall(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'number' is set + if (number == null) { + throw new ApiException("Missing the required parameter 'number' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter '_double' is set + if (_double == null) { + throw new ApiException("Missing the required parameter '_double' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter 'string' is set + if (string == null) { + throw new ApiException("Missing the required parameter 'string' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter '_byte' is set + if (_byte == null) { + throw new ApiException("Missing the required parameter '_byte' when calling testEndpointParameters(Async)"); + } + + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (integer != null) + localVarFormParams.put("integer", integer); + if (int32 != null) + localVarFormParams.put("int32", int32); + if (int64 != null) + localVarFormParams.put("int64", int64); + if (number != null) + localVarFormParams.put("number", number); + if (_float != null) + localVarFormParams.put("float", _float); + if (_double != null) + localVarFormParams.put("double", _double); + if (string != null) + localVarFormParams.put("string", string); + if (_byte != null) + localVarFormParams.put("byte", _byte); + if (binary != null) + localVarFormParams.put("binary", binary); + if (date != null) + localVarFormParams.put("date", date); + if (dateTime != null) + localVarFormParams.put("dateTime", dateTime); + if (password != null) + localVarFormParams.put("password", password); + + final String[] localVarAccepts = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param string None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { + testEndpointParametersWithHttpInfo(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param string None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { + com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password, null, null); + return apiClient.execute(call); + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 (asynchronously) + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param string None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call testEndpointParametersAsync(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for testEnumQueryParameters */ + private com.squareup.okhttp.Call testEnumQueryParametersCall(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (enumQueryInteger != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_integer", enumQueryInteger)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (enumQueryString != null) + localVarFormParams.put("enum_query_string", enumQueryString); + if (enumQueryDouble != null) + localVarFormParams.put("enum_query_double", enumQueryDouble); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * To test enum query parameters + * + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void testEnumQueryParameters(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { + testEnumQueryParametersWithHttpInfo(enumQueryString, enumQueryInteger, enumQueryDouble); + } + + /** + * To test enum query parameters + * + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse testEnumQueryParametersWithHttpInfo(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { + com.squareup.okhttp.Call call = testEnumQueryParametersCall(enumQueryString, enumQueryInteger, enumQueryDouble, null, null); + return apiClient.execute(call); + } + + /** + * To test enum query parameters (asynchronously) + * + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call testEnumQueryParametersAsync(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = testEnumQueryParametersCall(enumQueryString, enumQueryInteger, enumQueryDouble, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } +} diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java new file mode 100644 index 00000000000..2039a8842c1 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java @@ -0,0 +1,935 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + +import io.swagger.client.model.Pet; +import java.io.File; +import io.swagger.client.model.ModelApiResponse; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class PetApi { + private ApiClient apiClient; + + public PetApi() { + this(Configuration.getDefaultApiClient()); + } + + public PetApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for addPet */ + private com.squareup.okhttp.Call addPetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling addPet(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void addPet(Pet body) throws ApiException { + addPetWithHttpInfo(body); + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse addPetWithHttpInfo(Pet body) throws ApiException { + com.squareup.okhttp.Call call = addPetCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Add a new pet to the store (asynchronously) + * + * @param body Pet object that needs to be added to the store (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call addPetAsync(Pet body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = addPetCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for deletePet */ + private com.squareup.okhttp.Call deletePetCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling deletePet(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + if (apiKey != null) + localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deletePet(Long petId, String apiKey) throws ApiException { + deletePetWithHttpInfo(petId, apiKey); + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deletePetWithHttpInfo(Long petId, String apiKey) throws ApiException { + com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, null, null); + return apiClient.execute(call); + } + + /** + * Deletes a pet (asynchronously) + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deletePetAsync(Long petId, String apiKey, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for findPetsByStatus */ + private com.squareup.okhttp.Call findPetsByStatusCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'status' is set + if (status == null) { + throw new ApiException("Missing the required parameter 'status' when calling findPetsByStatus(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/findByStatus".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (status != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "status", status)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return List<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public List findPetsByStatus(List status) throws ApiException { + ApiResponse> resp = findPetsByStatusWithHttpInfo(status); + return resp.getData(); + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return ApiResponse<List<Pet>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> findPetsByStatusWithHttpInfo(List status) throws ApiException { + com.squareup.okhttp.Call call = findPetsByStatusCall(status, null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Finds Pets by status (asynchronously) + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call findPetsByStatusAsync(List status, final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = findPetsByStatusCall(status, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for findPetsByTags */ + private com.squareup.okhttp.Call findPetsByTagsCall(List tags, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'tags' is set + if (tags == null) { + throw new ApiException("Missing the required parameter 'tags' when calling findPetsByTags(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/findByTags".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (tags != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "tags", tags)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return List<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public List findPetsByTags(List tags) throws ApiException { + ApiResponse> resp = findPetsByTagsWithHttpInfo(tags); + return resp.getData(); + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return ApiResponse<List<Pet>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> findPetsByTagsWithHttpInfo(List tags) throws ApiException { + com.squareup.okhttp.Call call = findPetsByTagsCall(tags, null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Finds Pets by tags (asynchronously) + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call findPetsByTagsAsync(List tags, final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = findPetsByTagsCall(tags, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for getPetById */ + private com.squareup.okhttp.Call getPetByIdCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling getPetById(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "api_key" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return Pet + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Pet getPetById(Long petId) throws ApiException { + ApiResponse resp = getPetByIdWithHttpInfo(petId); + return resp.getData(); + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return ApiResponse<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getPetByIdWithHttpInfo(Long petId) throws ApiException { + com.squareup.okhttp.Call call = getPetByIdCall(petId, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Find pet by ID (asynchronously) + * Returns a single pet + * @param petId ID of pet to return (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getPetByIdAsync(Long petId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getPetByIdCall(petId, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for updatePet */ + private com.squareup.okhttp.Call updatePetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling updatePet(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updatePet(Pet body) throws ApiException { + updatePetWithHttpInfo(body); + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updatePetWithHttpInfo(Pet body) throws ApiException { + com.squareup.okhttp.Call call = updatePetCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Update an existing pet (asynchronously) + * + * @param body Pet object that needs to be added to the store (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updatePetAsync(Pet body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updatePetCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for updatePetWithForm */ + private com.squareup.okhttp.Call updatePetWithFormCall(Long petId, String name, String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling updatePetWithForm(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (name != null) + localVarFormParams.put("name", name); + if (status != null) + localVarFormParams.put("status", status); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/x-www-form-urlencoded" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updatePetWithForm(Long petId, String name, String status) throws ApiException { + updatePetWithFormWithHttpInfo(petId, name, status); + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updatePetWithFormWithHttpInfo(Long petId, String name, String status) throws ApiException { + com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, null, null); + return apiClient.execute(call); + } + + /** + * Updates a pet in the store with form data (asynchronously) + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updatePetWithFormAsync(Long petId, String name, String status, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for uploadFile */ + private com.squareup.okhttp.Call uploadFileCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling uploadFile(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (additionalMetadata != null) + localVarFormParams.put("additionalMetadata", additionalMetadata); + if (file != null) + localVarFormParams.put("file", file); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ModelApiResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { + ApiResponse resp = uploadFileWithHttpInfo(petId, additionalMetadata, file); + return resp.getData(); + } + + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ApiResponse<ModelApiResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file) throws ApiException { + com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * uploads an image (asynchronously) + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call uploadFileAsync(Long petId, String additionalMetadata, File file, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } +} diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/StoreApi.java new file mode 100644 index 00000000000..0768744c263 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/StoreApi.java @@ -0,0 +1,482 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + +import io.swagger.client.model.Order; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class StoreApi { + private ApiClient apiClient; + + public StoreApi() { + this(Configuration.getDefaultApiClient()); + } + + public StoreApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for deleteOrder */ + private com.squareup.okhttp.Call deleteOrderCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling deleteOrder(Async)"); + } + + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deleteOrder(String orderId) throws ApiException { + deleteOrderWithHttpInfo(orderId); + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deleteOrderWithHttpInfo(String orderId) throws ApiException { + com.squareup.okhttp.Call call = deleteOrderCall(orderId, null, null); + return apiClient.execute(call); + } + + /** + * Delete purchase order by ID (asynchronously) + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deleteOrderAsync(String orderId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = deleteOrderCall(orderId, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for getInventory */ + private com.squareup.okhttp.Call getInventoryCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + + // create path and map variables + String localVarPath = "/store/inventory".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "api_key" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return Map<String, Integer> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Map getInventory() throws ApiException { + ApiResponse> resp = getInventoryWithHttpInfo(); + return resp.getData(); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return ApiResponse<Map<String, Integer>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> getInventoryWithHttpInfo() throws ApiException { + com.squareup.okhttp.Call call = getInventoryCall(null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Returns pet inventories by status (asynchronously) + * Returns a map of status codes to quantities + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getInventoryAsync(final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getInventoryCall(progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for getOrderById */ + private com.squareup.okhttp.Call getOrderByIdCall(Long orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling getOrderById(Async)"); + } + + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @return Order + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Order getOrderById(Long orderId) throws ApiException { + ApiResponse resp = getOrderByIdWithHttpInfo(orderId); + return resp.getData(); + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @return ApiResponse<Order> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getOrderByIdWithHttpInfo(Long orderId) throws ApiException { + com.squareup.okhttp.Call call = getOrderByIdCall(orderId, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Find purchase order by ID (asynchronously) + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getOrderByIdAsync(Long orderId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getOrderByIdCall(orderId, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for placeOrder */ + private com.squareup.okhttp.Call placeOrderCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling placeOrder(Async)"); + } + + + // create path and map variables + String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet (required) + * @return Order + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Order placeOrder(Order body) throws ApiException { + ApiResponse resp = placeOrderWithHttpInfo(body); + return resp.getData(); + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet (required) + * @return ApiResponse<Order> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse placeOrderWithHttpInfo(Order body) throws ApiException { + com.squareup.okhttp.Call call = placeOrderCall(body, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Place an order for a pet (asynchronously) + * + * @param body order placed for purchasing the pet (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call placeOrderAsync(Order body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = placeOrderCall(body, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } +} diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/UserApi.java new file mode 100644 index 00000000000..1c4fc3101a1 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/UserApi.java @@ -0,0 +1,907 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + +import io.swagger.client.model.User; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class UserApi { + private ApiClient apiClient; + + public UserApi() { + this(Configuration.getDefaultApiClient()); + } + + public UserApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for createUser */ + private com.squareup.okhttp.Call createUserCall(User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUser(User body) throws ApiException { + createUserWithHttpInfo(body); + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUserWithHttpInfo(User body) throws ApiException { + com.squareup.okhttp.Call call = createUserCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Create user (asynchronously) + * This can only be done by the logged in user. + * @param body Created user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUserAsync(User body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = createUserCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for createUsersWithArrayInput */ + private com.squareup.okhttp.Call createUsersWithArrayInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUsersWithArrayInput(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/createWithArray".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUsersWithArrayInput(List body) throws ApiException { + createUsersWithArrayInputWithHttpInfo(body); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUsersWithArrayInputWithHttpInfo(List body) throws ApiException { + com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Creates list of users with given input array (asynchronously) + * + * @param body List of user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUsersWithArrayInputAsync(List body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for createUsersWithListInput */ + private com.squareup.okhttp.Call createUsersWithListInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUsersWithListInput(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUsersWithListInput(List body) throws ApiException { + createUsersWithListInputWithHttpInfo(body); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUsersWithListInputWithHttpInfo(List body) throws ApiException { + com.squareup.okhttp.Call call = createUsersWithListInputCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Creates list of users with given input array (asynchronously) + * + * @param body List of user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUsersWithListInputAsync(List body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = createUsersWithListInputCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for deleteUser */ + private com.squareup.okhttp.Call deleteUserCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling deleteUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deleteUser(String username) throws ApiException { + deleteUserWithHttpInfo(username); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deleteUserWithHttpInfo(String username) throws ApiException { + com.squareup.okhttp.Call call = deleteUserCall(username, null, null); + return apiClient.execute(call); + } + + /** + * Delete user (asynchronously) + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deleteUserAsync(String username, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = deleteUserCall(username, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for getUserByName */ + private com.squareup.okhttp.Call getUserByNameCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling getUserByName(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return User + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public User getUserByName(String username) throws ApiException { + ApiResponse resp = getUserByNameWithHttpInfo(username); + return resp.getData(); + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return ApiResponse<User> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getUserByNameWithHttpInfo(String username) throws ApiException { + com.squareup.okhttp.Call call = getUserByNameCall(username, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Get user by user name (asynchronously) + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getUserByNameAsync(String username, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getUserByNameCall(username, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for loginUser */ + private com.squareup.okhttp.Call loginUserCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling loginUser(Async)"); + } + + // verify the required parameter 'password' is set + if (password == null) { + throw new ApiException("Missing the required parameter 'password' when calling loginUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/login".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (username != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "username", username)); + if (password != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "password", password)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return String + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public String loginUser(String username, String password) throws ApiException { + ApiResponse resp = loginUserWithHttpInfo(username, password); + return resp.getData(); + } + + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return ApiResponse<String> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse loginUserWithHttpInfo(String username, String password) throws ApiException { + com.squareup.okhttp.Call call = loginUserCall(username, password, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Logs user into the system (asynchronously) + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call loginUserAsync(String username, String password, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = loginUserCall(username, password, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for logoutUser */ + private com.squareup.okhttp.Call logoutUserCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + + // create path and map variables + String localVarPath = "/user/logout".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Logs out current logged in user session + * + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void logoutUser() throws ApiException { + logoutUserWithHttpInfo(); + } + + /** + * Logs out current logged in user session + * + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse logoutUserWithHttpInfo() throws ApiException { + com.squareup.okhttp.Call call = logoutUserCall(null, null); + return apiClient.execute(call); + } + + /** + * Logs out current logged in user session (asynchronously) + * + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call logoutUserAsync(final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = logoutUserCall(progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for updateUser */ + private com.squareup.okhttp.Call updateUserCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling updateUser(Async)"); + } + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling updateUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updateUser(String username, User body) throws ApiException { + updateUserWithHttpInfo(username, body); + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updateUserWithHttpInfo(String username, User body) throws ApiException { + com.squareup.okhttp.Call call = updateUserCall(username, body, null, null); + return apiClient.execute(call); + } + + /** + * Updated user (asynchronously) + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updateUserAsync(String username, User body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updateUserCall(username, body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } +} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/ApiKeyAuth.java similarity index 100% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/ApiKeyAuth.java diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/Authentication.java similarity index 100% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/Authentication.java diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/HttpBasicAuth.java similarity index 59% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 592648b2bba..4eb2300b69d 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -27,44 +27,40 @@ import io.swagger.client.Pair; -import com.migcomponents.migbase64.Base64; +import com.squareup.okhttp.Credentials; import java.util.Map; import java.util.List; import java.io.UnsupportedEncodingException; - public class HttpBasicAuth implements Authentication { - private String username; - private String password; - - public String getUsername() { - return username; - } + private String username; + private String password; - public void setUsername(String username) { - this.username = username; - } + public String getUsername() { + return username; + } - public String getPassword() { - return password; - } + public void setUsername(String username) { + this.username = username; + } - public void setPassword(String password) { - this.password = password; - } + public String getPassword() { + return password; + } - @Override - public void applyToParams(List queryParams, Map headerParams) { - if (username == null && password == null) { - return; + public void setPassword(String password) { + this.password = password; } - String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); - try { - headerParams.put("Authorization", "Basic " + Base64.encodeToString(str.getBytes("UTF-8"), false)); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); + + @Override + public void applyToParams(List queryParams, Map headerParams) { + if (username == null && password == null) { + return; + } + headerParams.put("Authorization", Credentials.basic( + username == null ? "" : username, + password == null ? "" : password)); } - } } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/OAuth.java similarity index 100% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/OAuth.java diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/OAuthFlow.java similarity index 100% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuthFlow.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/OAuthFlow.java diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 1e2d40891a2..1943e013fa1 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; @@ -39,10 +39,10 @@ */ public class AdditionalPropertiesClass { - @JsonProperty("map_property") + @SerializedName("map_property") private Map mapProperty = new HashMap(); - @JsonProperty("map_of_map_property") + @SerializedName("map_of_map_property") private Map> mapOfMapProperty = new HashMap>(); public AdditionalPropertiesClass mapProperty(Map mapProperty) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Animal.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Animal.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Animal.java index 3ed2c6d9660..ba3806dc875 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Animal.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,10 +36,10 @@ */ public class Animal { - @JsonProperty("className") + @SerializedName("className") private String className = null; - @JsonProperty("color") + @SerializedName("color") private String color = "red"; public Animal className(String className) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AnimalFarm.java similarity index 100% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/AnimalFarm.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AnimalFarm.java diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 4d0dc41ee70..5446c2c439b 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; @@ -39,7 +39,7 @@ */ public class ArrayOfArrayOfNumberOnly { - @JsonProperty("ArrayArrayNumber") + @SerializedName("ArrayArrayNumber") private List> arrayArrayNumber = new ArrayList>(); public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index bd3f05a2ad4..c9257a5d3ee 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; @@ -39,7 +39,7 @@ */ public class ArrayOfNumberOnly { - @JsonProperty("ArrayNumber") + @SerializedName("ArrayNumber") private List arrayNumber = new ArrayList(); public ArrayOfNumberOnly arrayNumber(List arrayNumber) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayTest.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayTest.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayTest.java index 900b8375eb0..8d58870bcdc 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayTest.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.ReadOnlyFirst; @@ -39,13 +39,13 @@ */ public class ArrayTest { - @JsonProperty("array_of_string") + @SerializedName("array_of_string") private List arrayOfString = new ArrayList(); - @JsonProperty("array_array_of_integer") + @SerializedName("array_array_of_integer") private List> arrayArrayOfInteger = new ArrayList>(); - @JsonProperty("array_array_of_model") + @SerializedName("array_array_of_model") private List> arrayArrayOfModel = new ArrayList>(); public ArrayTest arrayOfString(List arrayOfString) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Cat.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Cat.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Cat.java index f39b159f0b4..21ed0f4c26b 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Cat.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -37,13 +37,13 @@ */ public class Cat extends Animal { - @JsonProperty("className") + @SerializedName("className") private String className = null; - @JsonProperty("color") + @SerializedName("color") private String color = "red"; - @JsonProperty("declawed") + @SerializedName("declawed") private Boolean declawed = null; public Cat className(String className) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Category.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Category.java index c9bbbf525c5..2178a866f62 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Category.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,10 +36,10 @@ */ public class Category { - @JsonProperty("id") + @SerializedName("id") private Long id = null; - @JsonProperty("name") + @SerializedName("name") private String name = null; public Category id(Long id) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Dog.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Dog.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Dog.java index dbcd1a7207b..4ba5804553f 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Dog.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -37,13 +37,13 @@ */ public class Dog extends Animal { - @JsonProperty("className") + @SerializedName("className") private String className = null; - @JsonProperty("color") + @SerializedName("color") private String color = "red"; - @JsonProperty("breed") + @SerializedName("breed") private String breed = null; public Dog className(String className) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumClass.java similarity index 91% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumClass.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumClass.java index 4433dca5f48..73484907229 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumClass.java @@ -26,6 +26,7 @@ package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; /** @@ -33,10 +34,13 @@ */ public enum EnumClass { + @SerializedName("_abc") _ABC("_abc"), + @SerializedName("-efg") _EFG("-efg"), + @SerializedName("(xyz)") _XYZ_("(xyz)"); private String value; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumTest.java similarity index 93% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumTest.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumTest.java index de36ef40ed4..9aad1223215 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumTest.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -40,8 +40,10 @@ public class EnumTest { * Gets or Sets enumString */ public enum EnumStringEnum { + @SerializedName("UPPER") UPPER("UPPER"), + @SerializedName("lower") LOWER("lower"); private String value; @@ -56,15 +58,17 @@ public String toString() { } } - @JsonProperty("enum_string") + @SerializedName("enum_string") private EnumStringEnum enumString = null; /** * Gets or Sets enumInteger */ public enum EnumIntegerEnum { + @SerializedName("1") NUMBER_1(1), + @SerializedName("-1") NUMBER_MINUS_1(-1); private Integer value; @@ -79,15 +83,17 @@ public String toString() { } } - @JsonProperty("enum_integer") + @SerializedName("enum_integer") private EnumIntegerEnum enumInteger = null; /** * Gets or Sets enumNumber */ public enum EnumNumberEnum { + @SerializedName("1.1") NUMBER_1_DOT_1(1.1), + @SerializedName("-1.2") NUMBER_MINUS_1_DOT_2(-1.2); private Double value; @@ -102,7 +108,7 @@ public String toString() { } } - @JsonProperty("enum_number") + @SerializedName("enum_number") private EnumNumberEnum enumNumber = null; public EnumTest enumString(EnumStringEnum enumString) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/FormatTest.java similarity index 95% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/FormatTest.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/FormatTest.java index 9e17949ebc8..91109681509 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/FormatTest.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; @@ -39,43 +39,43 @@ */ public class FormatTest { - @JsonProperty("integer") + @SerializedName("integer") private Integer integer = null; - @JsonProperty("int32") + @SerializedName("int32") private Integer int32 = null; - @JsonProperty("int64") + @SerializedName("int64") private Long int64 = null; - @JsonProperty("number") + @SerializedName("number") private BigDecimal number = null; - @JsonProperty("float") + @SerializedName("float") private Float _float = null; - @JsonProperty("double") + @SerializedName("double") private Double _double = null; - @JsonProperty("string") + @SerializedName("string") private String string = null; - @JsonProperty("byte") + @SerializedName("byte") private byte[] _byte = null; - @JsonProperty("binary") + @SerializedName("binary") private byte[] binary = null; - @JsonProperty("date") + @SerializedName("date") private LocalDate date = null; - @JsonProperty("dateTime") + @SerializedName("dateTime") private DateTime dateTime = null; - @JsonProperty("uuid") + @SerializedName("uuid") private String uuid = null; - @JsonProperty("password") + @SerializedName("password") private String password = null; public FormatTest integer(Integer integer) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java index a3d01218197..d77fc7ac36b 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,10 +36,10 @@ */ public class HasOnlyReadOnly { - @JsonProperty("bar") + @SerializedName("bar") private String bar = null; - @JsonProperty("foo") + @SerializedName("foo") private String foo = null; /** diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MapTest.java similarity index 95% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/MapTest.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MapTest.java index 6c0fc91ac41..61bdb6b2c65 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MapTest.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; @@ -39,15 +39,17 @@ */ public class MapTest { - @JsonProperty("map_map_of_string") + @SerializedName("map_map_of_string") private Map> mapMapOfString = new HashMap>(); /** * Gets or Sets inner */ public enum InnerEnum { + @SerializedName("UPPER") UPPER("UPPER"), + @SerializedName("lower") LOWER("lower"); private String value; @@ -62,7 +64,7 @@ public String toString() { } } - @JsonProperty("map_of_enum_string") + @SerializedName("map_of_enum_string") private Map mapOfEnumString = new HashMap(); public MapTest mapMapOfString(Map> mapMapOfString) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index c37d141f972..6e587b1bf97 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -41,13 +41,13 @@ */ public class MixedPropertiesAndAdditionalPropertiesClass { - @JsonProperty("uuid") + @SerializedName("uuid") private String uuid = null; - @JsonProperty("dateTime") + @SerializedName("dateTime") private DateTime dateTime = null; - @JsonProperty("map") + @SerializedName("map") private Map map = new HashMap(); public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Model200Response.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Model200Response.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Model200Response.java index 3f4edf12daa..d8da58aca9c 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Model200Response.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -37,10 +37,10 @@ @ApiModel(description = "Model for testing model name starting with number") public class Model200Response { - @JsonProperty("name") + @SerializedName("name") private Integer name = null; - @JsonProperty("class") + @SerializedName("class") private String PropertyClass = null; public Model200Response name(Integer name) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelApiResponse.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelApiResponse.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelApiResponse.java index 7b86d07a148..2a823298323 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,13 +36,13 @@ */ public class ModelApiResponse { - @JsonProperty("code") + @SerializedName("code") private Integer code = null; - @JsonProperty("type") + @SerializedName("type") private String type = null; - @JsonProperty("message") + @SerializedName("message") private String message = null; public ModelApiResponse code(Integer code) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelReturn.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelReturn.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelReturn.java index e8762f850db..024a9c0df1c 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelReturn.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -37,7 +37,7 @@ @ApiModel(description = "Model for testing reserved words") public class ModelReturn { - @JsonProperty("return") + @SerializedName("return") private Integer _return = null; public ModelReturn _return(Integer _return) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Name.java similarity index 95% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Name.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Name.java index de446cdf30d..318a2ddd50e 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Name.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -37,16 +37,16 @@ @ApiModel(description = "Model for testing model name same as property name") public class Name { - @JsonProperty("name") + @SerializedName("name") private Integer name = null; - @JsonProperty("snake_case") + @SerializedName("snake_case") private Integer snakeCase = null; - @JsonProperty("property") + @SerializedName("property") private String property = null; - @JsonProperty("123Number") + @SerializedName("123Number") private Integer _123Number = null; public Name name(Integer name) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/NumberOnly.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/NumberOnly.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/NumberOnly.java index 88c33f00f02..9b9ca048dfb 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/NumberOnly.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/NumberOnly.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; @@ -37,7 +37,7 @@ */ public class NumberOnly { - @JsonProperty("JustNumber") + @SerializedName("JustNumber") private BigDecimal justNumber = null; public NumberOnly justNumber(BigDecimal justNumber) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Order.java similarity index 94% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Order.java index ddebd7f8e48..90cfd2f3892 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Order.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.joda.time.DateTime; @@ -37,26 +37,29 @@ */ public class Order { - @JsonProperty("id") + @SerializedName("id") private Long id = null; - @JsonProperty("petId") + @SerializedName("petId") private Long petId = null; - @JsonProperty("quantity") + @SerializedName("quantity") private Integer quantity = null; - @JsonProperty("shipDate") + @SerializedName("shipDate") private DateTime shipDate = null; /** * Order Status */ public enum StatusEnum { + @SerializedName("placed") PLACED("placed"), + @SerializedName("approved") APPROVED("approved"), + @SerializedName("delivered") DELIVERED("delivered"); private String value; @@ -71,10 +74,10 @@ public String toString() { } } - @JsonProperty("status") + @SerializedName("status") private StatusEnum status = null; - @JsonProperty("complete") + @SerializedName("complete") private Boolean complete = false; public Order id(Long id) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Pet.java similarity index 94% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Pet.java index b468ebf1237..b80fdeaf923 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Pet.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Category; @@ -40,29 +40,32 @@ */ public class Pet { - @JsonProperty("id") + @SerializedName("id") private Long id = null; - @JsonProperty("category") + @SerializedName("category") private Category category = null; - @JsonProperty("name") + @SerializedName("name") private String name = null; - @JsonProperty("photoUrls") + @SerializedName("photoUrls") private List photoUrls = new ArrayList(); - @JsonProperty("tags") + @SerializedName("tags") private List tags = new ArrayList(); /** * pet status in the store */ public enum StatusEnum { + @SerializedName("available") AVAILABLE("available"), + @SerializedName("pending") PENDING("pending"), + @SerializedName("sold") SOLD("sold"); private String value; @@ -77,7 +80,7 @@ public String toString() { } } - @JsonProperty("status") + @SerializedName("status") private StatusEnum status = null; public Pet id(Long id) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ReadOnlyFirst.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ReadOnlyFirst.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index 7f56ef2ff35..13b729bb94d 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,10 +36,10 @@ */ public class ReadOnlyFirst { - @JsonProperty("bar") + @SerializedName("bar") private String bar = null; - @JsonProperty("baz") + @SerializedName("baz") private String baz = null; /** diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/SpecialModelName.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/SpecialModelName.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/SpecialModelName.java index bc4863f101a..b46b8367a01 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,7 +36,7 @@ */ public class SpecialModelName { - @JsonProperty("$special[property.name]") + @SerializedName("$special[property.name]") private Long specialPropertyName = null; public SpecialModelName specialPropertyName(Long specialPropertyName) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Tag.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Tag.java index f27e45ea2aa..e56eb535d1e 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Tag.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,10 +36,10 @@ */ public class Tag { - @JsonProperty("id") + @SerializedName("id") private Long id = null; - @JsonProperty("name") + @SerializedName("name") private String name = null; public Tag id(Long id) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/User.java similarity index 95% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/User.java index 7c0421fa09e..6c1ed6ceacc 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/User.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,28 +36,28 @@ */ public class User { - @JsonProperty("id") + @SerializedName("id") private Long id = null; - @JsonProperty("username") + @SerializedName("username") private String username = null; - @JsonProperty("firstName") + @SerializedName("firstName") private String firstName = null; - @JsonProperty("lastName") + @SerializedName("lastName") private String lastName = null; - @JsonProperty("email") + @SerializedName("email") private String email = null; - @JsonProperty("password") + @SerializedName("password") private String password = null; - @JsonProperty("phone") + @SerializedName("phone") private String phone = null; - @JsonProperty("userStatus") + @SerializedName("userStatus") private Integer userStatus = null; public User id(Long id) { diff --git a/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/FakeApiTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/FakeApiTest.java new file mode 100644 index 00000000000..5a7d2e5aa80 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/FakeApiTest.java @@ -0,0 +1,92 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import org.joda.time.LocalDate; +import org.joda.time.DateTime; +import java.math.BigDecimal; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for FakeApi + */ +public class FakeApiTest { + + private final FakeApi api = new FakeApi(); + + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testEndpointParametersTest() throws ApiException { + BigDecimal number = null; + Double _double = null; + String string = null; + byte[] _byte = null; + Integer integer = null; + Integer int32 = null; + Long int64 = null; + Float _float = null; + byte[] binary = null; + LocalDate date = null; + DateTime dateTime = null; + String password = null; + // api.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + + // TODO: test validations + } + + /** + * To test enum query parameters + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testEnumQueryParametersTest() throws ApiException { + String enumQueryString = null; + BigDecimal enumQueryInteger = null; + Double enumQueryDouble = null; + // api.testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/PetApiTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/PetApiTest.java new file mode 100644 index 00000000000..373f7d287ad --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/PetApiTest.java @@ -0,0 +1,180 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.model.Pet; +import java.io.File; +import io.swagger.client.model.ModelApiResponse; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for PetApi + */ +public class PetApiTest { + + private final PetApi api = new PetApi(); + + + /** + * Add a new pet to the store + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void addPetTest() throws ApiException { + Pet body = null; + // api.addPet(body); + + // TODO: test validations + } + + /** + * Deletes a pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deletePetTest() throws ApiException { + Long petId = null; + String apiKey = null; + // api.deletePet(petId, apiKey); + + // TODO: test validations + } + + /** + * Finds Pets by status + * + * Multiple status values can be provided with comma separated strings + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void findPetsByStatusTest() throws ApiException { + List status = null; + // List response = api.findPetsByStatus(status); + + // TODO: test validations + } + + /** + * Finds Pets by tags + * + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void findPetsByTagsTest() throws ApiException { + List tags = null; + // List response = api.findPetsByTags(tags); + + // TODO: test validations + } + + /** + * Find pet by ID + * + * Returns a single pet + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getPetByIdTest() throws ApiException { + Long petId = null; + // Pet response = api.getPetById(petId); + + // TODO: test validations + } + + /** + * Update an existing pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updatePetTest() throws ApiException { + Pet body = null; + // api.updatePet(body); + + // TODO: test validations + } + + /** + * Updates a pet in the store with form data + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updatePetWithFormTest() throws ApiException { + Long petId = null; + String name = null; + String status = null; + // api.updatePetWithForm(petId, name, status); + + // TODO: test validations + } + + /** + * uploads an image + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void uploadFileTest() throws ApiException { + Long petId = null; + String additionalMetadata = null; + File file = null; + // ModelApiResponse response = api.uploadFile(petId, additionalMetadata, file); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/StoreApiTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/StoreApiTest.java new file mode 100644 index 00000000000..4bcdcbf8338 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/StoreApiTest.java @@ -0,0 +1,108 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.model.Order; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for StoreApi + */ +public class StoreApiTest { + + private final StoreApi api = new StoreApi(); + + + /** + * Delete purchase order by ID + * + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deleteOrderTest() throws ApiException { + String orderId = null; + // api.deleteOrder(orderId); + + // TODO: test validations + } + + /** + * Returns pet inventories by status + * + * Returns a map of status codes to quantities + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getInventoryTest() throws ApiException { + // Map response = api.getInventory(); + + // TODO: test validations + } + + /** + * Find purchase order by ID + * + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getOrderByIdTest() throws ApiException { + Long orderId = null; + // Order response = api.getOrderById(orderId); + + // TODO: test validations + } + + /** + * Place an order for a pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void placeOrderTest() throws ApiException { + Order body = null; + // Order response = api.placeOrder(body); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/UserApiTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/UserApiTest.java new file mode 100644 index 00000000000..832748dbb45 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/UserApiTest.java @@ -0,0 +1,174 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.model.User; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for UserApi + */ +public class UserApiTest { + + private final UserApi api = new UserApi(); + + + /** + * Create user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUserTest() throws ApiException { + User body = null; + // api.createUser(body); + + // TODO: test validations + } + + /** + * Creates list of users with given input array + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUsersWithArrayInputTest() throws ApiException { + List body = null; + // api.createUsersWithArrayInput(body); + + // TODO: test validations + } + + /** + * Creates list of users with given input array + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUsersWithListInputTest() throws ApiException { + List body = null; + // api.createUsersWithListInput(body); + + // TODO: test validations + } + + /** + * Delete user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deleteUserTest() throws ApiException { + String username = null; + // api.deleteUser(username); + + // TODO: test validations + } + + /** + * Get user by user name + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getUserByNameTest() throws ApiException { + String username = null; + // User response = api.getUserByName(username); + + // TODO: test validations + } + + /** + * Logs user into the system + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void loginUserTest() throws ApiException { + String username = null; + String password = null; + // String response = api.loginUser(username, password); + + // TODO: test validations + } + + /** + * Logs out current logged in user session + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void logoutUserTest() throws ApiException { + // api.logoutUser(); + + // TODO: test validations + } + + /** + * Updated user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updateUserTest() throws ApiException { + String username = null; + User body = null; + // api.updateUser(username, body); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/okhttp-gson/docs/ArrayTest.md b/samples/client/petstore/java/okhttp-gson/docs/ArrayTest.md index 2cd4b9d33f9..9feee16427f 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/ArrayTest.md +++ b/samples/client/petstore/java/okhttp-gson/docs/ArrayTest.md @@ -7,13 +7,6 @@ Name | Type | Description | Notes **arrayOfString** | **List<String>** | | [optional] **arrayArrayOfInteger** | [**List<List<Long>>**](List.md) | | [optional] **arrayArrayOfModel** | [**List<List<ReadOnlyFirst>>**](List.md) | | [optional] -**arrayOfEnum** | [**List<ArrayOfEnumEnum>**](#List<ArrayOfEnumEnum>) | | [optional] - - - -## Enum: List<ArrayOfEnumEnum> -Name | Value ----- | ----- diff --git a/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md b/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md index bb52256e6be..21a4db7c377 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md +++ b/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md @@ -4,53 +4,10 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**testCodeInjectEnd**](FakeApi.md#testCodeInjectEnd) | **PUT** /fake | To test code injection =end [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters - -# **testCodeInjectEnd** -> testCodeInjectEnd(testCodeInjectEnd) - -To test code injection =end - -### Example -```java -// Import classes: -//import io.swagger.client.ApiException; -//import io.swagger.client.api.FakeApi; - - -FakeApi apiInstance = new FakeApi(); -String testCodeInjectEnd = "testCodeInjectEnd_example"; // String | To test code injection =end -try { - apiInstance.testCodeInjectEnd(testCodeInjectEnd); -} catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testCodeInjectEnd"); - e.printStackTrace(); -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **testCodeInjectEnd** | **String**| To test code injection =end | [optional] - -### Return type - -null (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json, */ =end'));(phpinfo(' - - **Accept**: application/json, */ end - # **testEndpointParameters** > testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) 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 0204c5c96aa..b7b04e3e4c5 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 @@ -812,6 +812,7 @@ public String escapeString(String str) { * @throws ApiException If fail to deserialize response body, i.e. cannot read response body * or the Content-Type of the response is not supported. */ + @SuppressWarnings("unchecked") public T deserialize(Response response, Type returnType) throws ApiException { if (response == null || returnType == null) { return null; @@ -1006,6 +1007,7 @@ public void executeAsync(Call call, ApiCallback callback) { * @param returnType Return type * @param callback ApiCallback */ + @SuppressWarnings("unchecked") public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { call.enqueue(new Callback() { @Override diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java index a0b9c9c1cf0..540611eab9d 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java @@ -103,6 +103,7 @@ public String serialize(Object obj) { * @param returnType The type to deserialize inot * @return The deserialized Java object */ + @SuppressWarnings("unchecked") public T deserialize(String body, Type returnType) { try { if (apiClient.isLenientOnJson()) { diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java index 6d956441b6f..52dce361e2a 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java @@ -67,105 +67,6 @@ public void setApiClient(ApiClient apiClient) { this.apiClient = apiClient; } - /* Build call for testCodeInjectEnd */ - private com.squareup.okhttp.Call testCodeInjectEndCall(String testCodeInjectEnd, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - - // create path and map variables - String localVarPath = "/fake".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (testCodeInjectEnd != null) - localVarFormParams.put("test code inject */ =end", testCodeInjectEnd); - - final String[] localVarAccepts = { - "application/json", "*/ end" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/json", "*/ =end'));(phpinfo('" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * To test code injection =end - * - * @param testCodeInjectEnd To test code injection =end (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void testCodeInjectEnd(String testCodeInjectEnd) throws ApiException { - testCodeInjectEndWithHttpInfo(testCodeInjectEnd); - } - - /** - * To test code injection =end - * - * @param testCodeInjectEnd To test code injection =end (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse testCodeInjectEndWithHttpInfo(String testCodeInjectEnd) throws ApiException { - com.squareup.okhttp.Call call = testCodeInjectEndCall(testCodeInjectEnd, null, null); - return apiClient.execute(call); - } - - /** - * To test code injection =end (asynchronously) - * - * @param testCodeInjectEnd To test code injection =end (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call testCodeInjectEndAsync(String testCodeInjectEnd, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = testCodeInjectEndCall(testCodeInjectEnd, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } /* Build call for testEndpointParameters */ private com.squareup.okhttp.Call testEndpointParametersCall(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java index b853a0b035a..8d58870bcdc 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java @@ -48,31 +48,6 @@ public class ArrayTest { @SerializedName("array_array_of_model") private List> arrayArrayOfModel = new ArrayList>(); - /** - * Gets or Sets arrayOfEnum - */ - public enum ArrayOfEnumEnum { - @SerializedName("UPPER") - UPPER("UPPER"), - - @SerializedName("lower") - LOWER("lower"); - - private String value; - - ArrayOfEnumEnum(String value) { - this.value = value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - } - - @SerializedName("array_of_enum") - private List arrayOfEnum = new ArrayList(); - public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; return this; @@ -127,24 +102,6 @@ public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } - public ArrayTest arrayOfEnum(List arrayOfEnum) { - this.arrayOfEnum = arrayOfEnum; - return this; - } - - /** - * Get arrayOfEnum - * @return arrayOfEnum - **/ - @ApiModelProperty(example = "null", value = "") - public List getArrayOfEnum() { - return arrayOfEnum; - } - - public void setArrayOfEnum(List arrayOfEnum) { - this.arrayOfEnum = arrayOfEnum; - } - @Override public boolean equals(java.lang.Object o) { @@ -157,13 +114,12 @@ public boolean equals(java.lang.Object o) { ArrayTest arrayTest = (ArrayTest) o; return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && - Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel) && - Objects.equals(this.arrayOfEnum, arrayTest.arrayOfEnum); + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); } @Override public int hashCode() { - return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel, arrayOfEnum); + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); } @Override @@ -174,7 +130,6 @@ public String toString() { sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); - sb.append(" arrayOfEnum: ").append(toIndentedString(arrayOfEnum)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/typescript-node/npm/api.d.ts b/samples/client/petstore/typescript-node/npm/api.d.ts index 8d1bd4acbb5..2399bc3a4f5 100644 --- a/samples/client/petstore/typescript-node/npm/api.d.ts +++ b/samples/client/petstore/typescript-node/npm/api.d.ts @@ -82,8 +82,8 @@ export declare class PetApi { protected _useQuerystring: boolean; protected authentications: { 'default': Authentication; - 'petstore_auth': OAuth; 'api_key': ApiKeyAuth; + 'petstore_auth': OAuth; }; constructor(basePath?: string); useQuerystring: boolean; @@ -132,8 +132,8 @@ export declare class StoreApi { protected _useQuerystring: boolean; protected authentications: { 'default': Authentication; - 'petstore_auth': OAuth; 'api_key': ApiKeyAuth; + 'petstore_auth': OAuth; }; constructor(basePath?: string); useQuerystring: boolean; @@ -168,8 +168,8 @@ export declare class UserApi { protected _useQuerystring: boolean; protected authentications: { 'default': Authentication; - 'petstore_auth': OAuth; 'api_key': ApiKeyAuth; + 'petstore_auth': OAuth; }; constructor(basePath?: string); useQuerystring: boolean; From ed7344d452c3d71092a7936adce1cda9775e1991 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 6 Jul 2016 22:19:54 +0800 Subject: [PATCH 068/470] minor fix to pom.xml --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 2be7b856d8f..f31a7c230d9 100644 --- a/pom.xml +++ b/pom.xml @@ -615,7 +615,7 @@ samples/client/petstore/typescript-node/npm samples/client/petstore/android/volley samples/client/petstore/clojure - samples/client/petstore/java/default + samples/client/petstore/java/jersey1 samples/client/petstore/java/feign samples/client/petstore/java/jersey2 samples/client/petstore/java/okhttp-gson From d4f9eefa94ca995bb1c4d28bd8eded04dfabd003 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 6 Jul 2016 22:24:33 +0800 Subject: [PATCH 069/470] update java-petstore-all.sh and regenerate all java petstore sample --- bin/java-petstore-all.sh | 2 +- bin/java8-petstore-jersey2.sh | 0 .../client/petstore/java/feign/.travis.yml | 29 + .../feign/docs/AdditionalPropertiesClass.md | 11 + .../client/petstore/java/feign/docs/Animal.md | 11 + .../petstore/java/feign/docs/AnimalFarm.md | 9 + .../feign/docs/ArrayOfArrayOfNumberOnly.md | 10 + .../java/feign/docs/ArrayOfNumberOnly.md | 10 + .../petstore/java/feign/docs/ArrayTest.md | 12 + .../client/petstore/java/feign/docs/Cat.md | 12 + .../petstore/java/feign/docs/Category.md | 11 + .../client/petstore/java/feign/docs/Dog.md | 12 + .../petstore/java/feign/docs/EnumClass.md | 14 + .../petstore/java/feign/docs/EnumTest.md | 36 + .../petstore/java/feign/docs/FakeApi.md | 122 + .../petstore/java/feign/docs/FormatTest.md | 22 + .../java/feign/docs/HasOnlyReadOnly.md | 11 + .../petstore/java/feign/docs/MapTest.md | 17 + ...dPropertiesAndAdditionalPropertiesClass.md | 12 + .../java/feign/docs/Model200Response.md | 11 + .../java/feign/docs/ModelApiResponse.md | 12 + .../petstore/java/feign/docs/ModelReturn.md | 10 + .../client/petstore/java/feign/docs/Name.md | 13 + .../petstore/java/feign/docs/NumberOnly.md | 10 + .../client/petstore/java/feign/docs/Order.md | 24 + .../client/petstore/java/feign/docs/Pet.md | 24 + .../client/petstore/java/feign/docs/PetApi.md | 448 ++++ .../petstore/java/feign/docs/ReadOnlyFirst.md | 11 + .../java/feign/docs/SpecialModelName.md | 10 + .../petstore/java/feign/docs/StoreApi.md | 197 ++ .../client/petstore/java/feign/docs/Tag.md | 11 + .../client/petstore/java/feign/docs/User.md | 17 + .../petstore/java/feign/docs/UserApi.md | 370 ++++ samples/client/petstore/java/feign/gradlew | 0 samples/client/petstore/java/feign/hello.txt | 1 - .../java/io/swagger/client/ApiCallback.java | 74 + .../java/io/swagger/client/ApiClient.java | 6 +- .../java/io/swagger/client/ApiException.java | 103 + .../java/io/swagger/client/ApiResponse.java | 71 + .../java/io/swagger/client/Configuration.java | 51 + .../io/swagger/client/FormAwareEncoder.java | 197 -- .../src/main/java/io/swagger/client/JSON.java | 237 ++ .../src/main/java/io/swagger/client/Pair.java | 64 + .../swagger/client/ProgressRequestBody.java | 95 + .../swagger/client/ProgressResponseBody.java | 88 + .../java/io/swagger/client/StringUtil.java | 2 +- .../java/io/swagger/client/api/FakeApi.java | 17 +- .../java/io/swagger/client/api/PetApi.java | 2 +- .../swagger/client/auth/Authentication.java | 41 + .../io/swagger/client/auth/OAuthFlow.java | 2 +- .../model/AdditionalPropertiesClass.java | 54 +- .../java/io/swagger/client/model/Animal.java | 54 +- .../io/swagger/client/model/AnimalFarm.java | 28 +- .../model/ArrayOfArrayOfNumberOnly.java | 102 + .../client/model/ArrayOfNumberOnly.java | 102 + .../io/swagger/client/model/ArrayTest.java | 68 +- .../java/io/swagger/client/model/Cat.java | 67 +- .../io/swagger/client/model/Category.java | 54 +- .../java/io/swagger/client/model/Dog.java | 67 +- .../io/swagger/client/model/EnumClass.java | 35 +- .../io/swagger/client/model/EnumTest.java | 79 +- .../io/swagger/client/model/FormatTest.java | 217 +- .../swagger/client/model/HasOnlyReadOnly.java | 104 + .../java/io/swagger/client/model/MapTest.java | 147 ++ ...ropertiesAndAdditionalPropertiesClass.java | 67 +- .../client/model/Model200Response.java | 54 +- .../client/model/ModelApiResponse.java | 67 +- .../io/swagger/client/model/ModelReturn.java | 41 +- .../java/io/swagger/client/model/Name.java | 70 +- .../io/swagger/client/model/NumberOnly.java | 100 + .../java/io/swagger/client/model/Order.java | 113 +- .../java/io/swagger/client/model/Pet.java | 113 +- .../swagger/client/model/ReadOnlyFirst.java | 49 +- .../client/model/SpecialModelName.java | 41 +- .../java/io/swagger/client/model/Tag.java | 54 +- .../java/io/swagger/client/model/User.java | 133 +- .../java/io/swagger/client/ApiClient.java | 2 + .../src/main/java/io/swagger/client/JSON.java | 1 + .../petstore/java/jersey2-java8/build.gradle | 27 +- .../petstore/java/jersey2-java8/build.sbt | 11 +- .../docs/ArrayOfArrayOfNumberOnly.md | 10 + .../jersey2-java8/docs/ArrayOfNumberOnly.md | 10 + .../java/jersey2-java8/docs/FakeApi.md | 47 + .../jersey2-java8/docs/HasOnlyReadOnly.md | 11 + .../java/jersey2-java8/docs/MapTest.md | 17 + .../jersey2-java8/docs/Model200Response.md | 1 + .../java/jersey2-java8/docs/NumberOnly.md | 10 + .../petstore/java/jersey2-java8/gradlew.bat | 180 +- .../petstore/java/jersey2-java8/pom.xml | 72 +- .../java/io/swagger/client/ApiCallback.java | 74 + .../java/io/swagger/client/ApiClient.java | 1964 +++++++++++------ .../java/io/swagger/client/ApiException.java | 2 +- .../java/io/swagger/client/ApiResponse.java | 71 + .../java/io/swagger/client/Configuration.java | 2 +- .../src/main/java/io/swagger/client/JSON.java | 256 ++- .../src/main/java/io/swagger/client/Pair.java | 2 +- .../swagger/client/ProgressRequestBody.java | 95 + .../swagger/client/ProgressResponseBody.java | 88 + .../java/io/swagger/client/StringUtil.java | 2 +- .../java/io/swagger/client/api/FakeApi.java | 440 +++- .../java/io/swagger/client/api/PetApi.java | 1285 ++++++++--- .../java/io/swagger/client/api/StoreApi.java | 646 ++++-- .../java/io/swagger/client/api/UserApi.java | 1245 ++++++++--- .../io/swagger/client/auth/ApiKeyAuth.java | 2 +- .../swagger/client/auth/Authentication.java | 2 +- .../io/swagger/client/auth/HttpBasicAuth.java | 52 +- .../java/io/swagger/client/auth/OAuth.java | 2 +- .../io/swagger/client/auth/OAuthFlow.java | 2 +- .../model/AdditionalPropertiesClass.java | 54 +- .../java/io/swagger/client/model/Animal.java | 54 +- .../io/swagger/client/model/AnimalFarm.java | 28 +- .../model/ArrayOfArrayOfNumberOnly.java | 102 + .../client/model/ArrayOfNumberOnly.java | 102 + .../io/swagger/client/model/ArrayTest.java | 68 +- .../java/io/swagger/client/model/Cat.java | 67 +- .../io/swagger/client/model/Category.java | 54 +- .../java/io/swagger/client/model/Dog.java | 67 +- .../io/swagger/client/model/EnumClass.java | 35 +- .../io/swagger/client/model/EnumTest.java | 79 +- .../io/swagger/client/model/FormatTest.java | 217 +- .../swagger/client/model/HasOnlyReadOnly.java | 104 + .../java/io/swagger/client/model/MapTest.java | 147 ++ ...ropertiesAndAdditionalPropertiesClass.java | 67 +- .../client/model/Model200Response.java | 68 +- .../client/model/ModelApiResponse.java | 67 +- .../io/swagger/client/model/ModelReturn.java | 41 +- .../java/io/swagger/client/model/Name.java | 70 +- .../io/swagger/client/model/NumberOnly.java | 100 + .../java/io/swagger/client/model/Order.java | 113 +- .../java/io/swagger/client/model/Pet.java | 113 +- .../swagger/client/model/ReadOnlyFirst.java | 49 +- .../client/model/SpecialModelName.java | 41 +- .../java/io/swagger/client/model/Tag.java | 54 +- .../java/io/swagger/client/model/User.java | 133 +- .../client/petstore/java/jersey2/build.gradle | 26 +- .../client/petstore/java/jersey2/build.sbt | 13 +- .../jersey2/docs/ArrayOfArrayOfNumberOnly.md | 10 + .../java/jersey2/docs/ArrayOfNumberOnly.md | 10 + .../petstore/java/jersey2/docs/FakeApi.md | 47 + .../java/jersey2/docs/HasOnlyReadOnly.md | 11 + .../petstore/java/jersey2/docs/MapTest.md | 17 + .../petstore/java/jersey2/docs/NumberOnly.md | 10 + .../client/petstore/java/jersey2/hello.txt | 1 - samples/client/petstore/java/jersey2/pom.xml | 73 +- .../java/io/swagger/client/ApiCallback.java | 74 + .../java/io/swagger/client/ApiClient.java | 1964 +++++++++++------ .../java/io/swagger/client/ApiException.java | 2 +- .../java/io/swagger/client/ApiResponse.java | 71 + .../java/io/swagger/client/Configuration.java | 2 +- .../src/main/java/io/swagger/client/JSON.java | 253 ++- .../src/main/java/io/swagger/client/Pair.java | 2 +- .../swagger/client/ProgressRequestBody.java | 95 + .../swagger/client/ProgressResponseBody.java | 88 + .../java/io/swagger/client/StringUtil.java | 2 +- .../java/io/swagger/client/api/FakeApi.java | 440 +++- .../java/io/swagger/client/api/PetApi.java | 1285 ++++++++--- .../java/io/swagger/client/api/StoreApi.java | 646 ++++-- .../java/io/swagger/client/api/UserApi.java | 1245 ++++++++--- .../io/swagger/client/auth/ApiKeyAuth.java | 2 +- .../swagger/client/auth/Authentication.java | 2 +- .../io/swagger/client/auth/HttpBasicAuth.java | 52 +- .../java/io/swagger/client/auth/OAuth.java | 2 +- .../io/swagger/client/auth/OAuthFlow.java | 2 +- .../model/AdditionalPropertiesClass.java | 54 +- .../java/io/swagger/client/model/Animal.java | 54 +- .../io/swagger/client/model/AnimalFarm.java | 28 +- .../model/ArrayOfArrayOfNumberOnly.java | 102 + .../client/model/ArrayOfNumberOnly.java | 102 + .../io/swagger/client/model/ArrayTest.java | 68 +- .../java/io/swagger/client/model/Cat.java | 67 +- .../io/swagger/client/model/Category.java | 54 +- .../java/io/swagger/client/model/Dog.java | 67 +- .../io/swagger/client/model/EnumClass.java | 35 +- .../io/swagger/client/model/EnumTest.java | 79 +- .../io/swagger/client/model/FormatTest.java | 217 +- .../swagger/client/model/HasOnlyReadOnly.java | 104 + .../java/io/swagger/client/model/MapTest.java | 147 ++ ...ropertiesAndAdditionalPropertiesClass.java | 67 +- .../client/model/Model200Response.java | 54 +- .../client/model/ModelApiResponse.java | 67 +- .../io/swagger/client/model/ModelReturn.java | 41 +- .../java/io/swagger/client/model/Name.java | 70 +- .../io/swagger/client/model/NumberOnly.java | 100 + .../java/io/swagger/client/model/Order.java | 113 +- .../java/io/swagger/client/model/Pet.java | 113 +- .../swagger/client/model/ReadOnlyFirst.java | 49 +- .../client/model/SpecialModelName.java | 41 +- .../java/io/swagger/client/model/Tag.java | 54 +- .../java/io/swagger/client/model/User.java | 133 +- .../client/petstore/java/retrofit/.travis.yml | 29 + .../petstore/java/retrofit/build.gradle | 37 +- .../client/petstore/java/retrofit/build.sbt | 8 +- .../docs/AdditionalPropertiesClass.md | 11 + .../petstore/java/retrofit/docs/Animal.md | 11 + .../petstore/java/retrofit/docs/AnimalFarm.md | 9 + .../retrofit/docs/ArrayOfArrayOfNumberOnly.md | 10 + .../java/retrofit/docs/ArrayOfNumberOnly.md | 10 + .../petstore/java/retrofit/docs/ArrayTest.md | 12 + .../client/petstore/java/retrofit/docs/Cat.md | 12 + .../petstore/java/retrofit/docs/Category.md | 11 + .../client/petstore/java/retrofit/docs/Dog.md | 12 + .../petstore/java/retrofit/docs/EnumClass.md | 14 + .../petstore/java/retrofit/docs/EnumTest.md | 36 + .../petstore/java/retrofit/docs/FakeApi.md | 122 + .../petstore/java/retrofit/docs/FormatTest.md | 22 + .../java/retrofit/docs/HasOnlyReadOnly.md | 11 + .../petstore/java/retrofit/docs/MapTest.md | 17 + ...dPropertiesAndAdditionalPropertiesClass.md | 12 + .../java/retrofit/docs/Model200Response.md | 11 + .../java/retrofit/docs/ModelApiResponse.md | 12 + .../java/retrofit/docs/ModelReturn.md | 10 + .../petstore/java/retrofit/docs/Name.md | 13 + .../petstore/java/retrofit/docs/NumberOnly.md | 10 + .../petstore/java/retrofit/docs/Order.md | 24 + .../client/petstore/java/retrofit/docs/Pet.md | 24 + .../petstore/java/retrofit/docs/PetApi.md | 448 ++++ .../java/retrofit/docs/ReadOnlyFirst.md | 11 + .../java/retrofit/docs/SpecialModelName.md | 10 + .../petstore/java/retrofit/docs/StoreApi.md | 197 ++ .../client/petstore/java/retrofit/docs/Tag.md | 11 + .../petstore/java/retrofit/docs/User.md | 17 + .../petstore/java/retrofit/docs/UserApi.md | 370 ++++ samples/client/petstore/java/retrofit/pom.xml | 39 +- .../java/io/swagger/client/ApiCallback.java | 74 + .../java/io/swagger/client/ApiClient.java | 1465 +++++++++--- .../java/io/swagger/client/ApiException.java | 103 + .../java/io/swagger/client/ApiResponse.java | 71 + .../io/swagger/client/CollectionFormats.java | 95 - .../java/io/swagger/client/Configuration.java | 51 + .../src/main/java/io/swagger/client/JSON.java | 237 ++ .../src/main/java/io/swagger/client/Pair.java | 64 + .../swagger/client/ProgressRequestBody.java | 95 + .../swagger/client/ProgressResponseBody.java | 88 + .../java/io/swagger/client/StringUtil.java | 2 +- .../java/io/swagger/client/api/FakeApi.java | 393 +++- .../java/io/swagger/client/api/PetApi.java | 1140 ++++++++-- .../java/io/swagger/client/api/StoreApi.java | 572 ++++- .../java/io/swagger/client/api/UserApi.java | 1101 +++++++-- .../io/swagger/client/auth/ApiKeyAuth.java | 125 +- .../swagger/client/auth/Authentication.java | 41 + .../io/swagger/client/auth/HttpBasicAuth.java | 59 +- .../java/io/swagger/client/auth/OAuth.java | 205 +- .../io/swagger/client/auth/OAuthFlow.java | 2 +- .../client/auth/OAuthOkHttpClient.java | 69 - .../model/AdditionalPropertiesClass.java | 71 +- .../java/io/swagger/client/model/Animal.java | 71 +- .../io/swagger/client/model/AnimalFarm.java | 41 +- .../model/ArrayOfArrayOfNumberOnly.java | 102 + .../client/model/ArrayOfNumberOnly.java | 102 + .../io/swagger/client/model/ArrayTest.java | 88 +- .../java/io/swagger/client/model/Cat.java | 90 +- .../io/swagger/client/model/Category.java | 71 +- .../java/io/swagger/client/model/Dog.java | 90 +- .../io/swagger/client/model/EnumClass.java | 77 +- .../io/swagger/client/model/EnumTest.java | 96 +- .../io/swagger/client/model/FormatTest.java | 247 ++- .../swagger/client/model/HasOnlyReadOnly.java | 104 + .../java/io/swagger/client/model/MapTest.java | 147 ++ ...ropertiesAndAdditionalPropertiesClass.java | 87 +- .../client/model/Model200Response.java | 71 +- .../client/model/ModelApiResponse.java | 87 +- .../io/swagger/client/model/ModelReturn.java | 55 +- .../java/io/swagger/client/model/Name.java | 91 +- .../io/swagger/client/model/NumberOnly.java | 100 + .../java/io/swagger/client/model/Order.java | 139 +- .../java/io/swagger/client/model/Pet.java | 139 +- .../swagger/client/model/ReadOnlyFirst.java | 65 +- .../client/model/SpecialModelName.java | 55 +- .../java/io/swagger/client/model/Tag.java | 71 +- .../java/io/swagger/client/model/User.java | 166 +- .../petstore/java/retrofit2/docs/FakeApi.md | 18 +- .../petstore/java/retrofit2/docs/PetApi.md | 44 +- .../petstore/java/retrofit2/docs/StoreApi.md | 15 +- .../petstore/java/retrofit2/docs/UserApi.md | 58 +- .../java/io/swagger/client/ApiCallback.java | 74 + .../java/io/swagger/client/ApiException.java | 103 + .../java/io/swagger/client/ApiResponse.java | 71 + .../io/swagger/client/CollectionFormats.java | 95 - .../java/io/swagger/client/Configuration.java | 51 + .../src/main/java/io/swagger/client/JSON.java | 237 ++ .../src/main/java/io/swagger/client/Pair.java | 64 + .../swagger/client/ProgressRequestBody.java | 95 + .../swagger/client/ProgressResponseBody.java | 88 + .../java/io/swagger/client/api/FakeApi.java | 12 +- .../java/io/swagger/client/api/PetApi.java | 36 +- .../java/io/swagger/client/api/StoreApi.java | 12 +- .../java/io/swagger/client/api/UserApi.java | 40 +- .../swagger/client/auth/Authentication.java | 41 + .../client/auth/OAuthOkHttpClient.java | 72 - .../java/retrofit2rx/docs/ArrayTest.md | 7 - .../petstore/java/retrofit2rx/docs/FakeApi.md | 62 +- .../petstore/java/retrofit2rx/docs/PetApi.md | 44 +- .../java/retrofit2rx/docs/StoreApi.md | 15 +- .../petstore/java/retrofit2rx/docs/UserApi.md | 58 +- .../client/petstore/java/retrofit2rx/pom.xml | 2 + .../java/io/swagger/client/ApiCallback.java | 74 + .../java/io/swagger/client/ApiClient.java | 54 +- .../java/io/swagger/client/ApiException.java | 103 + .../java/io/swagger/client/ApiResponse.java | 71 + .../io/swagger/client/CollectionFormats.java | 95 - .../java/io/swagger/client/Configuration.java | 51 + .../src/main/java/io/swagger/client/JSON.java | 237 ++ .../src/main/java/io/swagger/client/Pair.java | 64 + .../swagger/client/ProgressRequestBody.java | 95 + .../swagger/client/ProgressResponseBody.java | 88 + .../java/io/swagger/client/api/FakeApi.java | 27 +- .../java/io/swagger/client/api/PetApi.java | 46 +- .../java/io/swagger/client/api/StoreApi.java | 18 +- .../java/io/swagger/client/api/UserApi.java | 44 +- .../swagger/client/auth/Authentication.java | 41 + .../client/auth/OAuthOkHttpClient.java | 72 - .../io/swagger/client/model/ArrayTest.java | 49 +- 312 files changed, 27039 insertions(+), 7706 deletions(-) mode change 100644 => 100755 bin/java8-petstore-jersey2.sh create mode 100644 samples/client/petstore/java/feign/.travis.yml create mode 100644 samples/client/petstore/java/feign/docs/AdditionalPropertiesClass.md create mode 100644 samples/client/petstore/java/feign/docs/Animal.md create mode 100644 samples/client/petstore/java/feign/docs/AnimalFarm.md create mode 100644 samples/client/petstore/java/feign/docs/ArrayOfArrayOfNumberOnly.md create mode 100644 samples/client/petstore/java/feign/docs/ArrayOfNumberOnly.md create mode 100644 samples/client/petstore/java/feign/docs/ArrayTest.md create mode 100644 samples/client/petstore/java/feign/docs/Cat.md create mode 100644 samples/client/petstore/java/feign/docs/Category.md create mode 100644 samples/client/petstore/java/feign/docs/Dog.md create mode 100644 samples/client/petstore/java/feign/docs/EnumClass.md create mode 100644 samples/client/petstore/java/feign/docs/EnumTest.md create mode 100644 samples/client/petstore/java/feign/docs/FakeApi.md create mode 100644 samples/client/petstore/java/feign/docs/FormatTest.md create mode 100644 samples/client/petstore/java/feign/docs/HasOnlyReadOnly.md create mode 100644 samples/client/petstore/java/feign/docs/MapTest.md create mode 100644 samples/client/petstore/java/feign/docs/MixedPropertiesAndAdditionalPropertiesClass.md create mode 100644 samples/client/petstore/java/feign/docs/Model200Response.md create mode 100644 samples/client/petstore/java/feign/docs/ModelApiResponse.md create mode 100644 samples/client/petstore/java/feign/docs/ModelReturn.md create mode 100644 samples/client/petstore/java/feign/docs/Name.md create mode 100644 samples/client/petstore/java/feign/docs/NumberOnly.md create mode 100644 samples/client/petstore/java/feign/docs/Order.md create mode 100644 samples/client/petstore/java/feign/docs/Pet.md create mode 100644 samples/client/petstore/java/feign/docs/PetApi.md create mode 100644 samples/client/petstore/java/feign/docs/ReadOnlyFirst.md create mode 100644 samples/client/petstore/java/feign/docs/SpecialModelName.md create mode 100644 samples/client/petstore/java/feign/docs/StoreApi.md create mode 100644 samples/client/petstore/java/feign/docs/Tag.md create mode 100644 samples/client/petstore/java/feign/docs/User.md create mode 100644 samples/client/petstore/java/feign/docs/UserApi.md mode change 100755 => 100644 samples/client/petstore/java/feign/gradlew delete mode 100644 samples/client/petstore/java/feign/hello.txt create mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiCallback.java create mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiException.java create mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiResponse.java create mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/Configuration.java delete mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java create mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/JSON.java create mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/Pair.java create mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/ProgressRequestBody.java create mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/ProgressResponseBody.java create mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/Authentication.java create mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java create mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java create mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java create mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MapTest.java create mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/NumberOnly.java create mode 100644 samples/client/petstore/java/jersey2-java8/docs/ArrayOfArrayOfNumberOnly.md create mode 100644 samples/client/petstore/java/jersey2-java8/docs/ArrayOfNumberOnly.md create mode 100644 samples/client/petstore/java/jersey2-java8/docs/HasOnlyReadOnly.md create mode 100644 samples/client/petstore/java/jersey2-java8/docs/MapTest.md create mode 100644 samples/client/petstore/java/jersey2-java8/docs/NumberOnly.md create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiCallback.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiResponse.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ProgressRequestBody.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ProgressResponseBody.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MapTest.java create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/NumberOnly.java create mode 100644 samples/client/petstore/java/jersey2/docs/ArrayOfArrayOfNumberOnly.md create mode 100644 samples/client/petstore/java/jersey2/docs/ArrayOfNumberOnly.md create mode 100644 samples/client/petstore/java/jersey2/docs/HasOnlyReadOnly.md create mode 100644 samples/client/petstore/java/jersey2/docs/MapTest.md create mode 100644 samples/client/petstore/java/jersey2/docs/NumberOnly.md delete mode 100644 samples/client/petstore/java/jersey2/hello.txt create mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiCallback.java create mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiResponse.java create mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ProgressRequestBody.java create mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ProgressResponseBody.java create mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java create mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java create mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java create mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MapTest.java create mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/NumberOnly.java create mode 100644 samples/client/petstore/java/retrofit/.travis.yml create mode 100644 samples/client/petstore/java/retrofit/docs/AdditionalPropertiesClass.md create mode 100644 samples/client/petstore/java/retrofit/docs/Animal.md create mode 100644 samples/client/petstore/java/retrofit/docs/AnimalFarm.md create mode 100644 samples/client/petstore/java/retrofit/docs/ArrayOfArrayOfNumberOnly.md create mode 100644 samples/client/petstore/java/retrofit/docs/ArrayOfNumberOnly.md create mode 100644 samples/client/petstore/java/retrofit/docs/ArrayTest.md create mode 100644 samples/client/petstore/java/retrofit/docs/Cat.md create mode 100644 samples/client/petstore/java/retrofit/docs/Category.md create mode 100644 samples/client/petstore/java/retrofit/docs/Dog.md create mode 100644 samples/client/petstore/java/retrofit/docs/EnumClass.md create mode 100644 samples/client/petstore/java/retrofit/docs/EnumTest.md create mode 100644 samples/client/petstore/java/retrofit/docs/FakeApi.md create mode 100644 samples/client/petstore/java/retrofit/docs/FormatTest.md create mode 100644 samples/client/petstore/java/retrofit/docs/HasOnlyReadOnly.md create mode 100644 samples/client/petstore/java/retrofit/docs/MapTest.md create mode 100644 samples/client/petstore/java/retrofit/docs/MixedPropertiesAndAdditionalPropertiesClass.md create mode 100644 samples/client/petstore/java/retrofit/docs/Model200Response.md create mode 100644 samples/client/petstore/java/retrofit/docs/ModelApiResponse.md create mode 100644 samples/client/petstore/java/retrofit/docs/ModelReturn.md create mode 100644 samples/client/petstore/java/retrofit/docs/Name.md create mode 100644 samples/client/petstore/java/retrofit/docs/NumberOnly.md create mode 100644 samples/client/petstore/java/retrofit/docs/Order.md create mode 100644 samples/client/petstore/java/retrofit/docs/Pet.md create mode 100644 samples/client/petstore/java/retrofit/docs/PetApi.md create mode 100644 samples/client/petstore/java/retrofit/docs/ReadOnlyFirst.md create mode 100644 samples/client/petstore/java/retrofit/docs/SpecialModelName.md create mode 100644 samples/client/petstore/java/retrofit/docs/StoreApi.md create mode 100644 samples/client/petstore/java/retrofit/docs/Tag.md create mode 100644 samples/client/petstore/java/retrofit/docs/User.md create mode 100644 samples/client/petstore/java/retrofit/docs/UserApi.md create mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiCallback.java create mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiException.java create mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiResponse.java delete mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/CollectionFormats.java create mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/Configuration.java create mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/JSON.java create mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/Pair.java create mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ProgressRequestBody.java create mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ProgressResponseBody.java create mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/Authentication.java delete mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java create mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java create mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java create mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java create mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MapTest.java create mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/NumberOnly.java create mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiCallback.java create mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiException.java create mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiResponse.java delete mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/CollectionFormats.java create mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/Configuration.java create mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/JSON.java create mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/Pair.java create mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ProgressRequestBody.java create mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ProgressResponseBody.java create mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/Authentication.java delete mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java create mode 100644 samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiCallback.java create mode 100644 samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiException.java create mode 100644 samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiResponse.java delete mode 100644 samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/CollectionFormats.java create mode 100644 samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/Configuration.java create mode 100644 samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/JSON.java create mode 100644 samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/Pair.java create mode 100644 samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ProgressRequestBody.java create mode 100644 samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ProgressResponseBody.java create mode 100644 samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/Authentication.java delete mode 100644 samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java diff --git a/bin/java-petstore-all.sh b/bin/java-petstore-all.sh index b108cc06a4d..d3e98a74894 100755 --- a/bin/java-petstore-all.sh +++ b/bin/java-petstore-all.sh @@ -1,7 +1,7 @@ #!/bin/sh # update java petstore for all supported http libraries -./bin/java-petstore.sh +./bin/java-petstore-jersey1.sh ./bin/java-petstore-jersey2.sh ./bin/java-petstore-feign.sh ./bin/java-petstore-okhttp-gson.sh diff --git a/bin/java8-petstore-jersey2.sh b/bin/java8-petstore-jersey2.sh old mode 100644 new mode 100755 diff --git a/samples/client/petstore/java/feign/.travis.yml b/samples/client/petstore/java/feign/.travis.yml new file mode 100644 index 00000000000..33e79472abd --- /dev/null +++ b/samples/client/petstore/java/feign/.travis.yml @@ -0,0 +1,29 @@ +# +# Generated by: https://github.com/swagger-api/swagger-codegen.git +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +language: java +jdk: + - oraclejdk8 + - oraclejdk7 +before_install: + # ensure gradlew has proper permission + - chmod a+x ./gradlew +script: + # test using maven + - mvn test + # uncomment below to test using gradle + # - gradle test + # uncomment below to test using sbt + # - sbt test diff --git a/samples/client/petstore/java/feign/docs/AdditionalPropertiesClass.md b/samples/client/petstore/java/feign/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..0437c4dd8cc --- /dev/null +++ b/samples/client/petstore/java/feign/docs/AdditionalPropertiesClass.md @@ -0,0 +1,11 @@ + +# AdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapProperty** | **Map<String, String>** | | [optional] +**mapOfMapProperty** | [**Map<String, Map<String, String>>**](Map.md) | | [optional] + + + diff --git a/samples/client/petstore/java/feign/docs/Animal.md b/samples/client/petstore/java/feign/docs/Animal.md new file mode 100644 index 00000000000..b3f325c3524 --- /dev/null +++ b/samples/client/petstore/java/feign/docs/Animal.md @@ -0,0 +1,11 @@ + +# Animal + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/feign/docs/AnimalFarm.md b/samples/client/petstore/java/feign/docs/AnimalFarm.md new file mode 100644 index 00000000000..c7c7f1ddcce --- /dev/null +++ b/samples/client/petstore/java/feign/docs/AnimalFarm.md @@ -0,0 +1,9 @@ + +# AnimalFarm + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + + diff --git a/samples/client/petstore/java/feign/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/java/feign/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 00000000000..77292549927 --- /dev/null +++ b/samples/client/petstore/java/feign/docs/ArrayOfArrayOfNumberOnly.md @@ -0,0 +1,10 @@ + +# ArrayOfArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayArrayNumber** | [**List<List<BigDecimal>>**](List.md) | | [optional] + + + diff --git a/samples/client/petstore/java/feign/docs/ArrayOfNumberOnly.md b/samples/client/petstore/java/feign/docs/ArrayOfNumberOnly.md new file mode 100644 index 00000000000..e8cc4cd36dc --- /dev/null +++ b/samples/client/petstore/java/feign/docs/ArrayOfNumberOnly.md @@ -0,0 +1,10 @@ + +# ArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayNumber** | [**List<BigDecimal>**](BigDecimal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/feign/docs/ArrayTest.md b/samples/client/petstore/java/feign/docs/ArrayTest.md new file mode 100644 index 00000000000..9feee16427f --- /dev/null +++ b/samples/client/petstore/java/feign/docs/ArrayTest.md @@ -0,0 +1,12 @@ + +# ArrayTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayOfString** | **List<String>** | | [optional] +**arrayArrayOfInteger** | [**List<List<Long>>**](List.md) | | [optional] +**arrayArrayOfModel** | [**List<List<ReadOnlyFirst>>**](List.md) | | [optional] + + + diff --git a/samples/client/petstore/java/feign/docs/Cat.md b/samples/client/petstore/java/feign/docs/Cat.md new file mode 100644 index 00000000000..be6e56fa8ce --- /dev/null +++ b/samples/client/petstore/java/feign/docs/Cat.md @@ -0,0 +1,12 @@ + +# Cat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | [optional] +**declawed** | **Boolean** | | [optional] + + + diff --git a/samples/client/petstore/java/feign/docs/Category.md b/samples/client/petstore/java/feign/docs/Category.md new file mode 100644 index 00000000000..e2df0803278 --- /dev/null +++ b/samples/client/petstore/java/feign/docs/Category.md @@ -0,0 +1,11 @@ + +# Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**name** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/feign/docs/Dog.md b/samples/client/petstore/java/feign/docs/Dog.md new file mode 100644 index 00000000000..71a7dbe809e --- /dev/null +++ b/samples/client/petstore/java/feign/docs/Dog.md @@ -0,0 +1,12 @@ + +# Dog + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | [optional] +**breed** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/feign/docs/EnumClass.md b/samples/client/petstore/java/feign/docs/EnumClass.md new file mode 100644 index 00000000000..c746edc3cb1 --- /dev/null +++ b/samples/client/petstore/java/feign/docs/EnumClass.md @@ -0,0 +1,14 @@ + +# EnumClass + +## Enum + + +* `_ABC` (value: `"_abc"`) + +* `_EFG` (value: `"-efg"`) + +* `_XYZ_` (value: `"(xyz)"`) + + + diff --git a/samples/client/petstore/java/feign/docs/EnumTest.md b/samples/client/petstore/java/feign/docs/EnumTest.md new file mode 100644 index 00000000000..deb1951c552 --- /dev/null +++ b/samples/client/petstore/java/feign/docs/EnumTest.md @@ -0,0 +1,36 @@ + +# EnumTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enumString** | [**EnumStringEnum**](#EnumStringEnum) | | [optional] +**enumInteger** | [**EnumIntegerEnum**](#EnumIntegerEnum) | | [optional] +**enumNumber** | [**EnumNumberEnum**](#EnumNumberEnum) | | [optional] + + + +## Enum: EnumStringEnum +Name | Value +---- | ----- +UPPER | "UPPER" +LOWER | "lower" + + + +## Enum: EnumIntegerEnum +Name | Value +---- | ----- +NUMBER_1 | 1 +NUMBER_MINUS_1 | -1 + + + +## Enum: EnumNumberEnum +Name | Value +---- | ----- +NUMBER_1_DOT_1 | 1.1 +NUMBER_MINUS_1_DOT_2 | -1.2 + + + diff --git a/samples/client/petstore/java/feign/docs/FakeApi.md b/samples/client/petstore/java/feign/docs/FakeApi.md new file mode 100644 index 00000000000..21a4db7c377 --- /dev/null +++ b/samples/client/petstore/java/feign/docs/FakeApi.md @@ -0,0 +1,122 @@ +# FakeApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters + + + +# **testEndpointParameters** +> testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +BigDecimal number = new BigDecimal(); // BigDecimal | None +Double _double = 3.4D; // Double | None +String string = "string_example"; // String | None +byte[] _byte = B; // byte[] | None +Integer integer = 56; // Integer | None +Integer int32 = 56; // Integer | None +Long int64 = 789L; // Long | None +Float _float = 3.4F; // Float | None +byte[] binary = B; // byte[] | None +LocalDate date = new LocalDate(); // LocalDate | None +DateTime dateTime = new DateTime(); // DateTime | None +String password = "password_example"; // String | None +try { + apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEndpointParameters"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **number** | **BigDecimal**| None | + **_double** | **Double**| None | + **string** | **String**| None | + **_byte** | **byte[]**| None | + **integer** | **Integer**| None | [optional] + **int32** | **Integer**| None | [optional] + **int64** | **Long**| None | [optional] + **_float** | **Float**| None | [optional] + **binary** | **byte[]**| None | [optional] + **date** | **LocalDate**| None | [optional] + **dateTime** | **DateTime**| None | [optional] + **password** | **String**| None | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/xml; charset=utf-8, application/json; charset=utf-8 + - **Accept**: application/xml; charset=utf-8, application/json; charset=utf-8 + + +# **testEnumQueryParameters** +> testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble) + +To test enum query parameters + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +String enumQueryString = "-efg"; // String | Query parameter enum test (string) +BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | Query parameter enum test (double) +Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) +try { + apiInstance.testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEnumQueryParameters"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + **enumQueryInteger** | **BigDecimal**| Query parameter enum test (double) | [optional] + **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + diff --git a/samples/client/petstore/java/feign/docs/FormatTest.md b/samples/client/petstore/java/feign/docs/FormatTest.md new file mode 100644 index 00000000000..44de7d9511a --- /dev/null +++ b/samples/client/petstore/java/feign/docs/FormatTest.md @@ -0,0 +1,22 @@ + +# FormatTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**integer** | **Integer** | | [optional] +**int32** | **Integer** | | [optional] +**int64** | **Long** | | [optional] +**number** | [**BigDecimal**](BigDecimal.md) | | +**_float** | **Float** | | [optional] +**_double** | **Double** | | [optional] +**string** | **String** | | [optional] +**_byte** | **byte[]** | | +**binary** | **byte[]** | | [optional] +**date** | [**LocalDate**](LocalDate.md) | | +**dateTime** | [**DateTime**](DateTime.md) | | [optional] +**uuid** | **String** | | [optional] +**password** | **String** | | + + + diff --git a/samples/client/petstore/java/feign/docs/HasOnlyReadOnly.md b/samples/client/petstore/java/feign/docs/HasOnlyReadOnly.md new file mode 100644 index 00000000000..c1d0aac5672 --- /dev/null +++ b/samples/client/petstore/java/feign/docs/HasOnlyReadOnly.md @@ -0,0 +1,11 @@ + +# HasOnlyReadOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] +**foo** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/feign/docs/MapTest.md b/samples/client/petstore/java/feign/docs/MapTest.md new file mode 100644 index 00000000000..c671e97ffbc --- /dev/null +++ b/samples/client/petstore/java/feign/docs/MapTest.md @@ -0,0 +1,17 @@ + +# MapTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapMapOfString** | [**Map<String, Map<String, String>>**](Map.md) | | [optional] +**mapOfEnumString** | [**Map<String, InnerEnum>**](#Map<String, InnerEnum>) | | [optional] + + + +## Enum: Map<String, InnerEnum> +Name | Value +---- | ----- + + + diff --git a/samples/client/petstore/java/feign/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/java/feign/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..e3487bcc501 --- /dev/null +++ b/samples/client/petstore/java/feign/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,12 @@ + +# MixedPropertiesAndAdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | **String** | | [optional] +**dateTime** | [**DateTime**](DateTime.md) | | [optional] +**map** | [**Map<String, Animal>**](Animal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/feign/docs/Model200Response.md b/samples/client/petstore/java/feign/docs/Model200Response.md new file mode 100644 index 00000000000..b47618b28cc --- /dev/null +++ b/samples/client/petstore/java/feign/docs/Model200Response.md @@ -0,0 +1,11 @@ + +# Model200Response + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Integer** | | [optional] +**PropertyClass** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/feign/docs/ModelApiResponse.md b/samples/client/petstore/java/feign/docs/ModelApiResponse.md new file mode 100644 index 00000000000..3eec8686cc9 --- /dev/null +++ b/samples/client/petstore/java/feign/docs/ModelApiResponse.md @@ -0,0 +1,12 @@ + +# ModelApiResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **Integer** | | [optional] +**type** | **String** | | [optional] +**message** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/feign/docs/ModelReturn.md b/samples/client/petstore/java/feign/docs/ModelReturn.md new file mode 100644 index 00000000000..a679b04953e --- /dev/null +++ b/samples/client/petstore/java/feign/docs/ModelReturn.md @@ -0,0 +1,10 @@ + +# ModelReturn + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_return** | **Integer** | | [optional] + + + diff --git a/samples/client/petstore/java/feign/docs/Name.md b/samples/client/petstore/java/feign/docs/Name.md new file mode 100644 index 00000000000..ce2fb4dee50 --- /dev/null +++ b/samples/client/petstore/java/feign/docs/Name.md @@ -0,0 +1,13 @@ + +# Name + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Integer** | | +**snakeCase** | **Integer** | | [optional] +**property** | **String** | | [optional] +**_123Number** | **Integer** | | [optional] + + + diff --git a/samples/client/petstore/java/feign/docs/NumberOnly.md b/samples/client/petstore/java/feign/docs/NumberOnly.md new file mode 100644 index 00000000000..a3feac7fadc --- /dev/null +++ b/samples/client/petstore/java/feign/docs/NumberOnly.md @@ -0,0 +1,10 @@ + +# NumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**justNumber** | [**BigDecimal**](BigDecimal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/feign/docs/Order.md b/samples/client/petstore/java/feign/docs/Order.md new file mode 100644 index 00000000000..a1089f5384e --- /dev/null +++ b/samples/client/petstore/java/feign/docs/Order.md @@ -0,0 +1,24 @@ + +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**petId** | **Long** | | [optional] +**quantity** | **Integer** | | [optional] +**shipDate** | [**DateTime**](DateTime.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] +**complete** | **Boolean** | | [optional] + + + +## Enum: StatusEnum +Name | Value +---- | ----- +PLACED | "placed" +APPROVED | "approved" +DELIVERED | "delivered" + + + diff --git a/samples/client/petstore/java/feign/docs/Pet.md b/samples/client/petstore/java/feign/docs/Pet.md new file mode 100644 index 00000000000..5b63109ef92 --- /dev/null +++ b/samples/client/petstore/java/feign/docs/Pet.md @@ -0,0 +1,24 @@ + +# Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**name** | **String** | | +**photoUrls** | **List<String>** | | +**tags** | [**List<Tag>**](Tag.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] + + + +## Enum: StatusEnum +Name | Value +---- | ----- +AVAILABLE | "available" +PENDING | "pending" +SOLD | "sold" + + + diff --git a/samples/client/petstore/java/feign/docs/PetApi.md b/samples/client/petstore/java/feign/docs/PetApi.md new file mode 100644 index 00000000000..e0314e20e51 --- /dev/null +++ b/samples/client/petstore/java/feign/docs/PetApi.md @@ -0,0 +1,448 @@ +# PetApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image + + + +# **addPet** +> addPet(body) + +Add a new pet to the store + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Pet body = new Pet(); // Pet | Pet object that needs to be added to the store +try { + apiInstance.addPet(body); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#addPet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/xml, application/json + + +# **deletePet** +> deletePet(petId, apiKey) + +Deletes a pet + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | Pet id to delete +String apiKey = "apiKey_example"; // String | +try { + apiInstance.deletePet(petId, apiKey); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#deletePet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| Pet id to delete | + **apiKey** | **String**| | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **findPetsByStatus** +> List<Pet> findPetsByStatus(status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +List status = Arrays.asList("status_example"); // List | Status values that need to be considered for filter +try { + List result = apiInstance.findPetsByStatus(status); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByStatus"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **findPetsByTags** +> List<Pet> findPetsByTags(tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +List tags = Arrays.asList("tags_example"); // List | Tags to filter by +try { + List result = apiInstance.findPetsByTags(tags); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByTags"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**List<String>**](String.md)| Tags to filter by | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **getPetById** +> Pet getPetById(petId) + +Find pet by ID + +Returns a single pet + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure API key authorization: api_key +ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); +api_key.setApiKey("YOUR API KEY"); +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//api_key.setApiKeyPrefix("Token"); + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | ID of pet to return +try { + Pet result = apiInstance.getPetById(petId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#getPetById"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **updatePet** +> updatePet(body) + +Update an existing pet + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Pet body = new Pet(); // Pet | Pet object that needs to be added to the store +try { + apiInstance.updatePet(body); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/xml, application/json + + +# **updatePetWithForm** +> updatePetWithForm(petId, name, status) + +Updates a pet in the store with form data + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | ID of pet that needs to be updated +String name = "name_example"; // String | Updated name of the pet +String status = "status_example"; // String | Updated status of the pet +try { + apiInstance.updatePetWithForm(petId, name, status); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePetWithForm"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet that needs to be updated | + **name** | **String**| Updated name of the pet | [optional] + **status** | **String**| Updated status of the pet | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: application/xml, application/json + + +# **uploadFile** +> ModelApiResponse uploadFile(petId, additionalMetadata, file) + +uploads an image + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | ID of pet to update +String additionalMetadata = "additionalMetadata_example"; // String | Additional data to pass to server +File file = new File("/path/to/file.txt"); // File | file to upload +try { + ModelApiResponse result = apiInstance.uploadFile(petId, additionalMetadata, file); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#uploadFile"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to update | + **additionalMetadata** | **String**| Additional data to pass to server | [optional] + **file** | **File**| file to upload | [optional] + +### Return type + +[**ModelApiResponse**](ModelApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + diff --git a/samples/client/petstore/java/feign/docs/ReadOnlyFirst.md b/samples/client/petstore/java/feign/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..426b7cde95a --- /dev/null +++ b/samples/client/petstore/java/feign/docs/ReadOnlyFirst.md @@ -0,0 +1,11 @@ + +# ReadOnlyFirst + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] +**baz** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/feign/docs/SpecialModelName.md b/samples/client/petstore/java/feign/docs/SpecialModelName.md new file mode 100644 index 00000000000..c2c6117c552 --- /dev/null +++ b/samples/client/petstore/java/feign/docs/SpecialModelName.md @@ -0,0 +1,10 @@ + +# SpecialModelName + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**specialPropertyName** | **Long** | | [optional] + + + diff --git a/samples/client/petstore/java/feign/docs/StoreApi.md b/samples/client/petstore/java/feign/docs/StoreApi.md new file mode 100644 index 00000000000..0b30791725a --- /dev/null +++ b/samples/client/petstore/java/feign/docs/StoreApi.md @@ -0,0 +1,197 @@ +# StoreApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet + + + +# **deleteOrder** +> deleteOrder(orderId) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +String orderId = "orderId_example"; // String | ID of the order that needs to be deleted +try { + apiInstance.deleteOrder(orderId); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#deleteOrder"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **String**| ID of the order that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **getInventory** +> Map<String, Integer> getInventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.StoreApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure API key authorization: api_key +ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); +api_key.setApiKey("YOUR API KEY"); +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//api_key.setApiKeyPrefix("Token"); + +StoreApi apiInstance = new StoreApi(); +try { + Map result = apiInstance.getInventory(); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getInventory"); + e.printStackTrace(); +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**Map<String, Integer>**](Map.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +# **getOrderById** +> Order getOrderById(orderId) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +Long orderId = 789L; // Long | ID of pet that needs to be fetched +try { + Order result = apiInstance.getOrderById(orderId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getOrderById"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **Long**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **placeOrder** +> Order placeOrder(body) + +Place an order for a pet + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +Order body = new Order(); // Order | order placed for purchasing the pet +try { + Order result = apiInstance.placeOrder(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#placeOrder"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + diff --git a/samples/client/petstore/java/feign/docs/Tag.md b/samples/client/petstore/java/feign/docs/Tag.md new file mode 100644 index 00000000000..de6814b55d5 --- /dev/null +++ b/samples/client/petstore/java/feign/docs/Tag.md @@ -0,0 +1,11 @@ + +# Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**name** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/feign/docs/User.md b/samples/client/petstore/java/feign/docs/User.md new file mode 100644 index 00000000000..8b6753dd284 --- /dev/null +++ b/samples/client/petstore/java/feign/docs/User.md @@ -0,0 +1,17 @@ + +# User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**username** | **String** | | [optional] +**firstName** | **String** | | [optional] +**lastName** | **String** | | [optional] +**email** | **String** | | [optional] +**password** | **String** | | [optional] +**phone** | **String** | | [optional] +**userStatus** | **Integer** | User Status | [optional] + + + diff --git a/samples/client/petstore/java/feign/docs/UserApi.md b/samples/client/petstore/java/feign/docs/UserApi.md new file mode 100644 index 00000000000..8cdc15992ee --- /dev/null +++ b/samples/client/petstore/java/feign/docs/UserApi.md @@ -0,0 +1,370 @@ +# UserApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createUser**](UserApi.md#createUser) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + + +# **createUser** +> createUser(body) + +Create user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +User body = new User(); // User | Created user object +try { + apiInstance.createUser(body); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md)| Created user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **createUsersWithArrayInput** +> createUsersWithArrayInput(body) + +Creates list of users with given input array + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +List body = Arrays.asList(new User()); // List | List of user object +try { + apiInstance.createUsersWithArrayInput(body); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithArrayInput"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List<User>**](User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **createUsersWithListInput** +> createUsersWithListInput(body) + +Creates list of users with given input array + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +List body = Arrays.asList(new User()); // List | List of user object +try { + apiInstance.createUsersWithListInput(body); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithListInput"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List<User>**](User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **deleteUser** +> deleteUser(username) + +Delete user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The name that needs to be deleted +try { + apiInstance.deleteUser(username); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#deleteUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **getUserByName** +> User getUserByName(username) + +Get user by user name + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The name that needs to be fetched. Use user1 for testing. +try { + User result = apiInstance.getUserByName(username); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#getUserByName"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **loginUser** +> String loginUser(username, password) + +Logs user into the system + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The user name for login +String password = "password_example"; // String | The password for login in clear text +try { + String result = apiInstance.loginUser(username, password); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#loginUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The user name for login | + **password** | **String**| The password for login in clear text | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **logoutUser** +> logoutUser() + +Logs out current logged in user session + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +try { + apiInstance.logoutUser(); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#logoutUser"); + e.printStackTrace(); +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **updateUser** +> updateUser(username, body) + +Updated user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | name that need to be deleted +User body = new User(); // User | Updated user object +try { + apiInstance.updateUser(username, body); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#updateUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| name that need to be deleted | + **body** | [**User**](User.md)| Updated user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + diff --git a/samples/client/petstore/java/feign/gradlew b/samples/client/petstore/java/feign/gradlew old mode 100755 new mode 100644 diff --git a/samples/client/petstore/java/feign/hello.txt b/samples/client/petstore/java/feign/hello.txt deleted file mode 100644 index 6769dd60bdf..00000000000 --- a/samples/client/petstore/java/feign/hello.txt +++ /dev/null @@ -1 +0,0 @@ -Hello world! \ No newline at end of file diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiCallback.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiCallback.java new file mode 100644 index 00000000000..3ca33cf8017 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiCallback.java @@ -0,0 +1,74 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import java.io.IOException; + +import java.util.Map; +import java.util.List; + +/** + * Callback for asynchronous API call. + * + * @param The return type + */ +public interface ApiCallback { + /** + * This is called when the API call fails. + * + * @param e The exception causing the failure + * @param statusCode Status code of the response if available, otherwise it would be 0 + * @param responseHeaders Headers of the response if available, otherwise it would be null + */ + void onFailure(ApiException e, int statusCode, Map> responseHeaders); + + /** + * This is called when the API call succeeded. + * + * @param result The result deserialized from response + * @param statusCode Status code of the response + * @param responseHeaders Headers of the response + */ + void onSuccess(T result, int statusCode, Map> responseHeaders); + + /** + * This is called when the API upload processing. + * + * @param bytesWritten bytes Written + * @param contentLength content length of request body + * @param done write end + */ + void onUploadProgress(long bytesWritten, long contentLength, boolean done); + + /** + * This is called when the API downlond processing. + * + * @param bytesRead bytes Read + * @param contentLength content lenngth of the response + * @param done Read end + */ + void onDownloadProgress(long bytesRead, long contentLength, boolean done); +} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java index 75b3a96f2c7..e21bded5212 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java @@ -41,10 +41,10 @@ public ApiClient(String[] authNames) { this(); for(String authName : authNames) { RequestInterceptor auth; - if (authName == "petstore_auth") { - auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); - } else if (authName == "api_key") { + if (authName == "api_key") { auth = new ApiKeyAuth("header", "api_key"); + } else if (authName == "petstore_auth") { + auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); } else { throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiException.java new file mode 100644 index 00000000000..3bed001f002 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiException.java @@ -0,0 +1,103 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import java.util.Map; +import java.util.List; + + +public class ApiException extends Exception { + private int code = 0; + private Map> responseHeaders = null; + private String responseBody = null; + + public ApiException() {} + + public ApiException(Throwable throwable) { + super(throwable); + } + + public ApiException(String message) { + super(message); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } + + public ApiException(int code, Map> responseHeaders, String responseBody) { + this((String) null, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(int code, String message) { + super(message); + this.code = code; + } + + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this(code, message); + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + /** + * Get the HTTP status code. + * + * @return HTTP status code + */ + public int getCode() { + return code; + } + + /** + * Get the HTTP response headers. + * + * @return A map of list of string + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + + /** + * Get the HTTP response body. + * + * @return Response body in the form of string + */ + public String getResponseBody() { + return responseBody; + } +} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiResponse.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiResponse.java new file mode 100644 index 00000000000..d7dde1ee939 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiResponse.java @@ -0,0 +1,71 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import java.util.List; +import java.util.Map; + +/** + * API response returned by API call. + * + * @param T The type of data that is deserialized from response body + */ +public class ApiResponse { + final private int statusCode; + final private Map> headers; + final private T data; + + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + */ + public ApiResponse(int statusCode, Map> headers) { + this(statusCode, headers, null); + } + + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + * @param data The object deserialized from response bod + */ + public ApiResponse(int statusCode, Map> headers, T data) { + this.statusCode = statusCode; + this.headers = headers; + this.data = data; + } + + public int getStatusCode() { + return statusCode; + } + + public Map> getHeaders() { + return headers; + } + + public T getData() { + return data; + } +} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/Configuration.java new file mode 100644 index 00000000000..5191b9b73c6 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/Configuration.java @@ -0,0 +1,51 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + + +public class Configuration { + private static ApiClient defaultApiClient = new ApiClient(); + + /** + * Get the default API client, which would be used when creating API + * instances without providing an API client. + * + * @return Default API client + */ + public static ApiClient getDefaultApiClient() { + return defaultApiClient; + } + + /** + * Set the default API client, which would be used when creating API + * instances without providing an API client. + * + * @param apiClient API client + */ + public static void setDefaultApiClient(ApiClient apiClient) { + defaultApiClient = apiClient; + } +} 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 deleted file mode 100644 index 179a2834da9..00000000000 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java +++ /dev/null @@ -1,197 +0,0 @@ -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; - - -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/JSON.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/JSON.java new file mode 100644 index 00000000000..540611eab9d --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/JSON.java @@ -0,0 +1,237 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonNull; +import com.google.gson.JsonParseException; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +import java.io.IOException; +import java.io.StringReader; +import java.lang.reflect.Type; +import java.util.Date; + +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; + +public class JSON { + private ApiClient apiClient; + private Gson gson; + + /** + * JSON constructor. + * + * @param apiClient An instance of ApiClient + */ + public JSON(ApiClient apiClient) { + this.apiClient = apiClient; + gson = new GsonBuilder() + .registerTypeAdapter(Date.class, new DateAdapter(apiClient)) + .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) + .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) + .create(); + } + + /** + * Get Gson. + * + * @return Gson + */ + public Gson getGson() { + return gson; + } + + /** + * Set Gson. + * + * @param gson Gson + */ + public void setGson(Gson gson) { + this.gson = gson; + } + + /** + * Serialize the given Java object into JSON string. + * + * @param obj Object + * @return String representation of the JSON + */ + public String serialize(Object obj) { + return gson.toJson(obj); + } + + /** + * Deserialize the given JSON string to Java object. + * + * @param Type + * @param body The JSON string + * @param returnType The type to deserialize inot + * @return The deserialized Java object + */ + @SuppressWarnings("unchecked") + public T deserialize(String body, Type returnType) { + try { + if (apiClient.isLenientOnJson()) { + JsonReader jsonReader = new JsonReader(new StringReader(body)); + // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) + jsonReader.setLenient(true); + return gson.fromJson(jsonReader, returnType); + } else { + return gson.fromJson(body, returnType); + } + } catch (JsonParseException e) { + // Fallback processing when failed to parse JSON form response body: + // return the response body string directly for the String return type; + // parse response body into date or datetime for the Date return type. + if (returnType.equals(String.class)) + return (T) body; + else if (returnType.equals(Date.class)) + return (T) apiClient.parseDateOrDatetime(body); + else throw(e); + } + } +} + +class DateAdapter implements JsonSerializer, JsonDeserializer { + private final ApiClient apiClient; + + /** + * Constructor for DateAdapter + * + * @param apiClient Api client + */ + public DateAdapter(ApiClient apiClient) { + super(); + this.apiClient = apiClient; + } + + /** + * Serialize + * + * @param src Date + * @param typeOfSrc Type + * @param context Json Serialization Context + * @return Json Element + */ + @Override + public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { + if (src == null) { + return JsonNull.INSTANCE; + } else { + return new JsonPrimitive(apiClient.formatDatetime(src)); + } + } + + /** + * Deserialize + * + * @param json Json element + * @param date Type + * @param typeOfSrc Type + * @param context Json Serialization Context + * @return Date + * @throw JsonParseException if fail to parse + */ + @Override + public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException { + String str = json.getAsJsonPrimitive().getAsString(); + try { + return apiClient.parseDateOrDatetime(str); + } catch (RuntimeException e) { + throw new JsonParseException(e); + } + } +} + +/** + * Gson TypeAdapter for Joda DateTime type + */ +class DateTimeTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + + @Override + public void write(JsonWriter out, DateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public DateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseDateTime(date); + } + } +} + +/** + * Gson TypeAdapter for Joda LocalDate type + */ +class LocalDateTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.date(); + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseLocalDate(date); + } + } +} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/Pair.java new file mode 100644 index 00000000000..15b247eea93 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/Pair.java @@ -0,0 +1,64 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + + +public class Pair { + private String name = ""; + private String value = ""; + + public Pair (String name, String value) { + setName(name); + setValue(value); + } + + private void setName(String name) { + if (!isValidString(name)) return; + + this.name = name; + } + + private void setValue(String value) { + if (!isValidString(value)) return; + + this.value = value; + } + + public String getName() { + return this.name; + } + + public String getValue() { + return this.value; + } + + private boolean isValidString(String arg) { + if (arg == null) return false; + if (arg.trim().isEmpty()) return false; + + return true; + } +} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ProgressRequestBody.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ProgressRequestBody.java new file mode 100644 index 00000000000..d9ca742ecd2 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ProgressRequestBody.java @@ -0,0 +1,95 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.RequestBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSink; +import okio.ForwardingSink; +import okio.Okio; +import okio.Sink; + +public class ProgressRequestBody extends RequestBody { + + public interface ProgressRequestListener { + void onRequestProgress(long bytesWritten, long contentLength, boolean done); + } + + private final RequestBody requestBody; + + private final ProgressRequestListener progressListener; + + private BufferedSink bufferedSink; + + public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) { + this.requestBody = requestBody; + this.progressListener = progressListener; + } + + @Override + public MediaType contentType() { + return requestBody.contentType(); + } + + @Override + public long contentLength() throws IOException { + return requestBody.contentLength(); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + if (bufferedSink == null) { + bufferedSink = Okio.buffer(sink(sink)); + } + + requestBody.writeTo(bufferedSink); + bufferedSink.flush(); + + } + + private Sink sink(Sink sink) { + return new ForwardingSink(sink) { + + long bytesWritten = 0L; + long contentLength = 0L; + + @Override + public void write(Buffer source, long byteCount) throws IOException { + super.write(source, byteCount); + if (contentLength == 0) { + contentLength = contentLength(); + } + + bytesWritten += byteCount; + progressListener.onRequestProgress(bytesWritten, contentLength, bytesWritten == contentLength); + } + }; + } +} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ProgressResponseBody.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ProgressResponseBody.java new file mode 100644 index 00000000000..f8af685999d --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ProgressResponseBody.java @@ -0,0 +1,88 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.ResponseBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSource; +import okio.ForwardingSource; +import okio.Okio; +import okio.Source; + +public class ProgressResponseBody extends ResponseBody { + + public interface ProgressListener { + void update(long bytesRead, long contentLength, boolean done); + } + + private final ResponseBody responseBody; + private final ProgressListener progressListener; + private BufferedSource bufferedSource; + + public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) { + this.responseBody = responseBody; + this.progressListener = progressListener; + } + + @Override + public MediaType contentType() { + return responseBody.contentType(); + } + + @Override + public long contentLength() throws IOException { + return responseBody.contentLength(); + } + + @Override + public BufferedSource source() throws IOException { + if (bufferedSource == null) { + bufferedSource = Okio.buffer(source(responseBody.source())); + } + return bufferedSource; + } + + private Source source(Source source) { + return new ForwardingSource(source) { + long totalBytesRead = 0L; + + @Override + public long read(Buffer sink, long byteCount) throws IOException { + long bytesRead = super.read(sink, byteCount); + // read() returns the number of bytes read, or -1 if this source is exhausted. + totalBytesRead += bytesRead != -1 ? bytesRead : 0; + progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1); + return bytesRead; + } + }; + } +} + + diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java index 03c6c81e434..fdcef6b1010 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ /** * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java index dbabdc64995..fd559f5e624 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java @@ -3,8 +3,8 @@ import io.swagger.client.ApiClient; import org.joda.time.LocalDate; -import java.math.BigDecimal; import org.joda.time.DateTime; +import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; @@ -39,4 +39,19 @@ public interface FakeApi extends ApiClient.Api { "Accept: application/xml; charset=utf-8,application/json; charset=utf-8", }) void testEndpointParameters(@Param("number") BigDecimal number, @Param("_double") Double _double, @Param("string") String string, @Param("_byte") byte[] _byte, @Param("integer") Integer integer, @Param("int32") Integer int32, @Param("int64") Long int64, @Param("_float") Float _float, @Param("binary") byte[] binary, @Param("date") LocalDate date, @Param("dateTime") DateTime dateTime, @Param("password") String password); + + /** + * To test enum query parameters + * + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @return void + */ + @RequestLine("GET /fake?enum_query_integer={enumQueryInteger}") + @Headers({ + "Content-type: application/json", + "Accept: application/json", + }) + void testEnumQueryParameters(@Param("enumQueryString") String enumQueryString, @Param("enumQueryInteger") BigDecimal enumQueryInteger, @Param("enumQueryDouble") Double enumQueryDouble); } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java index e486495c5a9..4d4cc14f625 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java @@ -3,8 +3,8 @@ import io.swagger.client.ApiClient; import io.swagger.client.model.Pet; -import io.swagger.client.model.ModelApiResponse; import java.io.File; +import io.swagger.client.model.ModelApiResponse; import java.util.ArrayList; import java.util.HashMap; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/Authentication.java new file mode 100644 index 00000000000..221a7d9dd1f --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/Authentication.java @@ -0,0 +1,41 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + +public interface Authentication { + /** + * Apply authentication settings to header and query params. + * + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + */ + void applyToParams(List queryParams, Map headerParams); +} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuthFlow.java index ec1f942b0f2..50d5260cfd9 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,6 +1,6 @@ /** * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index ccaba7709c4..1943e013fa1 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; @@ -15,40 +39,44 @@ */ public class AdditionalPropertiesClass { - + @SerializedName("map_property") private Map mapProperty = new HashMap(); + + @SerializedName("map_of_map_property") private Map> mapOfMapProperty = new HashMap>(); - - /** - **/ public AdditionalPropertiesClass mapProperty(Map mapProperty) { this.mapProperty = mapProperty; return this; } - + + /** + * Get mapProperty + * @return mapProperty + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("map_property") public Map getMapProperty() { return mapProperty; } + public void setMapProperty(Map mapProperty) { this.mapProperty = mapProperty; } - - /** - **/ public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { this.mapOfMapProperty = mapOfMapProperty; return this; } - + + /** + * Get mapOfMapProperty + * @return mapOfMapProperty + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("map_of_map_property") public Map> getMapOfMapProperty() { return mapOfMapProperty; } + public void setMapOfMapProperty(Map> mapOfMapProperty) { this.mapOfMapProperty = mapOfMapProperty; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java index 25c7d3e421c..ba3806dc875 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,40 +36,44 @@ */ public class Animal { - + @SerializedName("className") private String className = null; + + @SerializedName("color") private String color = "red"; - - /** - **/ public Animal className(String className) { this.className = className; return this; } - + + /** + * Get className + * @return className + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("className") public String getClassName() { return className; } + public void setClassName(String className) { this.className = className; } - - /** - **/ public Animal color(String color) { this.color = color; return this; } - + + /** + * Get color + * @return color + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("color") public String getColor() { return color; } + public void setColor(String color) { this.color = color; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java index 647e3a893e1..b54adb09d7b 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -1,6 +1,30 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import io.swagger.client.model.Animal; import java.util.ArrayList; @@ -12,9 +36,7 @@ */ public class AnimalFarm extends ArrayList { - - @Override public boolean equals(java.lang.Object o) { if (this == o) { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 00000000000..5446c2c439b --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,102 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + + +/** + * ArrayOfArrayOfNumberOnly + */ + +public class ArrayOfArrayOfNumberOnly { + @SerializedName("ArrayArrayNumber") + private List> arrayArrayNumber = new ArrayList>(); + + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + /** + * Get arrayArrayNumber + * @return arrayArrayNumber + **/ + @ApiModelProperty(example = "null", value = "") + public List> getArrayArrayNumber() { + return arrayArrayNumber; + } + + public void setArrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly = (ArrayOfArrayOfNumberOnly) o; + return Objects.equals(this.arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayArrayNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfArrayOfNumberOnly {\n"); + + sb.append(" arrayArrayNumber: ").append(toIndentedString(arrayArrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java new file mode 100644 index 00000000000..c9257a5d3ee --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -0,0 +1,102 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + + +/** + * ArrayOfNumberOnly + */ + +public class ArrayOfNumberOnly { + @SerializedName("ArrayNumber") + private List arrayNumber = new ArrayList(); + + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + /** + * Get arrayNumber + * @return arrayNumber + **/ + @ApiModelProperty(example = "null", value = "") + public List getArrayNumber() { + return arrayNumber; + } + + public void setArrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfNumberOnly arrayOfNumberOnly = (ArrayOfNumberOnly) o; + return Objects.equals(this.arrayNumber, arrayOfNumberOnly.arrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfNumberOnly {\n"); + + sb.append(" arrayNumber: ").append(toIndentedString(arrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayTest.java index 6c1eb23d8d0..8d58870bcdc 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayTest.java @@ -1,10 +1,35 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.ReadOnlyFirst; import java.util.ArrayList; import java.util.List; @@ -14,58 +39,65 @@ */ public class ArrayTest { - + @SerializedName("array_of_string") private List arrayOfString = new ArrayList(); + + @SerializedName("array_array_of_integer") private List> arrayArrayOfInteger = new ArrayList>(); + + @SerializedName("array_array_of_model") private List> arrayArrayOfModel = new ArrayList>(); - - /** - **/ public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; return this; } - + + /** + * Get arrayOfString + * @return arrayOfString + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("array_of_string") public List getArrayOfString() { return arrayOfString; } + public void setArrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; } - - /** - **/ public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; return this; } - + + /** + * Get arrayArrayOfInteger + * @return arrayArrayOfInteger + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("array_array_of_integer") public List> getArrayArrayOfInteger() { return arrayArrayOfInteger; } + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - - /** - **/ public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } - + + /** + * Get arrayArrayOfModel + * @return arrayArrayOfModel + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("array_array_of_model") public List> getArrayArrayOfModel() { return arrayArrayOfModel; } + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java index 5ef9e23bd96..21ed0f4c26b 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -13,58 +37,65 @@ */ public class Cat extends Animal { - + @SerializedName("className") private String className = null; + + @SerializedName("color") private String color = "red"; + + @SerializedName("declawed") private Boolean declawed = null; - - /** - **/ public Cat className(String className) { this.className = className; return this; } - + + /** + * Get className + * @return className + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("className") public String getClassName() { return className; } + public void setClassName(String className) { this.className = className; } - - /** - **/ public Cat color(String color) { this.color = color; return this; } - + + /** + * Get color + * @return color + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("color") public String getColor() { return color; } + public void setColor(String color) { this.color = color; } - - /** - **/ public Cat declawed(Boolean declawed) { this.declawed = declawed; return this; } - + + /** + * Get declawed + * @return declawed + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("declawed") public Boolean getDeclawed() { return declawed; } + public void setDeclawed(Boolean declawed) { this.declawed = declawed; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java index c6cb703a89e..2178a866f62 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,40 +36,44 @@ */ public class Category { - + @SerializedName("id") private Long id = null; + + @SerializedName("name") private String name = null; - - /** - **/ public Category id(Long id) { this.id = id; return this; } - + + /** + * Get id + * @return id + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - - /** - **/ public Category name(String name) { this.name = name; return this; } - + + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java index 4b3cc947cc5..4ba5804553f 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -13,58 +37,65 @@ */ public class Dog extends Animal { - + @SerializedName("className") private String className = null; + + @SerializedName("color") private String color = "red"; + + @SerializedName("breed") private String breed = null; - - /** - **/ public Dog className(String className) { this.className = className; return this; } - + + /** + * Get className + * @return className + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("className") public String getClassName() { return className; } + public void setClassName(String className) { this.className = className; } - - /** - **/ public Dog color(String color) { this.color = color; return this; } - + + /** + * Get color + * @return color + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("color") public String getColor() { return color; } + public void setColor(String color) { this.color = color; } - - /** - **/ public Dog breed(String breed) { this.breed = breed; return this; } - + + /** + * Get breed + * @return breed + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("breed") public String getBreed() { return breed; } + public void setBreed(String breed) { this.breed = breed; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumClass.java index 42434e297ff..73484907229 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumClass.java @@ -1,16 +1,46 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonValue; +import com.google.gson.annotations.SerializedName; /** * Gets or Sets EnumClass */ public enum EnumClass { + + @SerializedName("_abc") _ABC("_abc"), + + @SerializedName("-efg") _EFG("-efg"), + + @SerializedName("(xyz)") _XYZ_("(xyz)"); private String value; @@ -20,7 +50,6 @@ public enum EnumClass { } @Override - @JsonValue public String toString() { return String.valueOf(value); } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java index 1c8657fd3ec..9aad1223215 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java @@ -1,9 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonValue; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -13,13 +36,14 @@ */ public class EnumTest { - - /** * Gets or Sets enumString */ public enum EnumStringEnum { + @SerializedName("UPPER") UPPER("UPPER"), + + @SerializedName("lower") LOWER("lower"); private String value; @@ -29,19 +53,22 @@ public enum EnumStringEnum { } @Override - @JsonValue public String toString() { return String.valueOf(value); } } + @SerializedName("enum_string") private EnumStringEnum enumString = null; /** * Gets or Sets enumInteger */ public enum EnumIntegerEnum { + @SerializedName("1") NUMBER_1(1), + + @SerializedName("-1") NUMBER_MINUS_1(-1); private Integer value; @@ -51,19 +78,22 @@ public enum EnumIntegerEnum { } @Override - @JsonValue public String toString() { return String.valueOf(value); } } + @SerializedName("enum_integer") private EnumIntegerEnum enumInteger = null; /** * Gets or Sets enumNumber */ public enum EnumNumberEnum { + @SerializedName("1.1") NUMBER_1_DOT_1(1.1), + + @SerializedName("-1.2") NUMBER_MINUS_1_DOT_2(-1.2); private Double value; @@ -73,61 +103,64 @@ public enum EnumNumberEnum { } @Override - @JsonValue public String toString() { return String.valueOf(value); } } + @SerializedName("enum_number") private EnumNumberEnum enumNumber = null; - - /** - **/ public EnumTest enumString(EnumStringEnum enumString) { this.enumString = enumString; return this; } - + + /** + * Get enumString + * @return enumString + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("enum_string") public EnumStringEnum getEnumString() { return enumString; } + public void setEnumString(EnumStringEnum enumString) { this.enumString = enumString; } - - /** - **/ public EnumTest enumInteger(EnumIntegerEnum enumInteger) { this.enumInteger = enumInteger; return this; } - + + /** + * Get enumInteger + * @return enumInteger + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("enum_integer") public EnumIntegerEnum getEnumInteger() { return enumInteger; } + public void setEnumInteger(EnumIntegerEnum enumInteger) { this.enumInteger = enumInteger; } - - /** - **/ public EnumTest enumNumber(EnumNumberEnum enumNumber) { this.enumNumber = enumNumber; return this; } - + + /** + * Get enumNumber + * @return enumNumber + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("enum_number") public EnumNumberEnum getEnumNumber() { return enumNumber; } + public void setEnumNumber(EnumNumberEnum enumNumber) { this.enumNumber = enumNumber; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java index 79376150017..91109681509 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; @@ -15,248 +39,285 @@ */ public class FormatTest { - + @SerializedName("integer") private Integer integer = null; + + @SerializedName("int32") private Integer int32 = null; + + @SerializedName("int64") private Long int64 = null; + + @SerializedName("number") private BigDecimal number = null; + + @SerializedName("float") private Float _float = null; + + @SerializedName("double") private Double _double = null; + + @SerializedName("string") private String string = null; + + @SerializedName("byte") private byte[] _byte = null; + + @SerializedName("binary") private byte[] binary = null; + + @SerializedName("date") private LocalDate date = null; + + @SerializedName("dateTime") private DateTime dateTime = null; + + @SerializedName("uuid") private String uuid = null; + + @SerializedName("password") private String password = null; - - /** - * minimum: 10.0 - * maximum: 100.0 - **/ public FormatTest integer(Integer integer) { this.integer = integer; return this; } - + + /** + * Get integer + * minimum: 10.0 + * maximum: 100.0 + * @return integer + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("integer") public Integer getInteger() { return integer; } + public void setInteger(Integer integer) { this.integer = integer; } - - /** - * minimum: 20.0 - * maximum: 200.0 - **/ public FormatTest int32(Integer int32) { this.int32 = int32; return this; } - + + /** + * Get int32 + * minimum: 20.0 + * maximum: 200.0 + * @return int32 + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("int32") public Integer getInt32() { return int32; } + public void setInt32(Integer int32) { this.int32 = int32; } - - /** - **/ public FormatTest int64(Long int64) { this.int64 = int64; return this; } - + + /** + * Get int64 + * @return int64 + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("int64") public Long getInt64() { return int64; } + public void setInt64(Long int64) { this.int64 = int64; } - - /** - * minimum: 32.1 - * maximum: 543.2 - **/ public FormatTest number(BigDecimal number) { this.number = number; return this; } - + + /** + * Get number + * minimum: 32.1 + * maximum: 543.2 + * @return number + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("number") public BigDecimal getNumber() { return number; } + public void setNumber(BigDecimal number) { this.number = number; } - - /** - * minimum: 54.3 - * maximum: 987.6 - **/ public FormatTest _float(Float _float) { this._float = _float; return this; } - + + /** + * Get _float + * minimum: 54.3 + * maximum: 987.6 + * @return _float + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("float") public Float getFloat() { return _float; } + public void setFloat(Float _float) { this._float = _float; } - - /** - * minimum: 67.8 - * maximum: 123.4 - **/ public FormatTest _double(Double _double) { this._double = _double; return this; } - + + /** + * Get _double + * minimum: 67.8 + * maximum: 123.4 + * @return _double + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("double") public Double getDouble() { return _double; } + public void setDouble(Double _double) { this._double = _double; } - - /** - **/ public FormatTest string(String string) { this.string = string; return this; } - + + /** + * Get string + * @return string + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("string") public String getString() { return string; } + public void setString(String string) { this.string = string; } - - /** - **/ public FormatTest _byte(byte[] _byte) { this._byte = _byte; return this; } - + + /** + * Get _byte + * @return _byte + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("byte") public byte[] getByte() { return _byte; } + public void setByte(byte[] _byte) { this._byte = _byte; } - - /** - **/ public FormatTest binary(byte[] binary) { this.binary = binary; return this; } - + + /** + * Get binary + * @return binary + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("binary") public byte[] getBinary() { return binary; } + public void setBinary(byte[] binary) { this.binary = binary; } - - /** - **/ public FormatTest date(LocalDate date) { this.date = date; return this; } - + + /** + * Get date + * @return date + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("date") public LocalDate getDate() { return date; } + public void setDate(LocalDate date) { this.date = date; } - - /** - **/ public FormatTest dateTime(DateTime dateTime) { this.dateTime = dateTime; return this; } - + + /** + * Get dateTime + * @return dateTime + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("dateTime") public DateTime getDateTime() { return dateTime; } + public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } - - /** - **/ public FormatTest uuid(String uuid) { this.uuid = uuid; return this; } - + + /** + * Get uuid + * @return uuid + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("uuid") public String getUuid() { return uuid; } + public void setUuid(String uuid) { this.uuid = uuid; } - - /** - **/ public FormatTest password(String password) { this.password = password; return this; } - + + /** + * Get password + * @return password + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("password") public String getPassword() { return password; } + public void setPassword(String password) { this.password = password; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java new file mode 100644 index 00000000000..d77fc7ac36b --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -0,0 +1,104 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +/** + * HasOnlyReadOnly + */ + +public class HasOnlyReadOnly { + @SerializedName("bar") + private String bar = null; + + @SerializedName("foo") + private String foo = null; + + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(example = "null", value = "") + public String getBar() { + return bar; + } + + /** + * Get foo + * @return foo + **/ + @ApiModelProperty(example = "null", value = "") + public String getFoo() { + return foo; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HasOnlyReadOnly hasOnlyReadOnly = (HasOnlyReadOnly) o; + return Objects.equals(this.bar, hasOnlyReadOnly.bar) && + Objects.equals(this.foo, hasOnlyReadOnly.foo); + } + + @Override + public int hashCode() { + return Objects.hash(bar, foo); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HasOnlyReadOnly {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" foo: ").append(toIndentedString(foo)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MapTest.java new file mode 100644 index 00000000000..61bdb6b2c65 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MapTest.java @@ -0,0 +1,147 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +/** + * MapTest + */ + +public class MapTest { + @SerializedName("map_map_of_string") + private Map> mapMapOfString = new HashMap>(); + + /** + * Gets or Sets inner + */ + public enum InnerEnum { + @SerializedName("UPPER") + UPPER("UPPER"), + + @SerializedName("lower") + LOWER("lower"); + + private String value; + + InnerEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + @SerializedName("map_of_enum_string") + private Map mapOfEnumString = new HashMap(); + + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + /** + * Get mapMapOfString + * @return mapMapOfString + **/ + @ApiModelProperty(example = "null", value = "") + public Map> getMapMapOfString() { + return mapMapOfString; + } + + public void setMapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + } + + public MapTest mapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + return this; + } + + /** + * Get mapOfEnumString + * @return mapOfEnumString + **/ + @ApiModelProperty(example = "null", value = "") + public Map getMapOfEnumString() { + return mapOfEnumString; + } + + public void setMapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MapTest mapTest = (MapTest) o; + return Objects.equals(this.mapMapOfString, mapTest.mapMapOfString) && + Objects.equals(this.mapOfEnumString, mapTest.mapOfEnumString); + } + + @Override + public int hashCode() { + return Objects.hash(mapMapOfString, mapOfEnumString); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MapTest {\n"); + + sb.append(" mapMapOfString: ").append(toIndentedString(mapMapOfString)).append("\n"); + sb.append(" mapOfEnumString: ").append(toIndentedString(mapOfEnumString)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 2f0972bf41e..6e587b1bf97 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -17,58 +41,65 @@ */ public class MixedPropertiesAndAdditionalPropertiesClass { - + @SerializedName("uuid") private String uuid = null; + + @SerializedName("dateTime") private DateTime dateTime = null; + + @SerializedName("map") private Map map = new HashMap(); - - /** - **/ public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { this.uuid = uuid; return this; } - + + /** + * Get uuid + * @return uuid + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("uuid") public String getUuid() { return uuid; } + public void setUuid(String uuid) { this.uuid = uuid; } - - /** - **/ public MixedPropertiesAndAdditionalPropertiesClass dateTime(DateTime dateTime) { this.dateTime = dateTime; return this; } - + + /** + * Get dateTime + * @return dateTime + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("dateTime") public DateTime getDateTime() { return dateTime; } + public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } - - /** - **/ public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { this.map = map; return this; } - + + /** + * Get map + * @return map + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("map") public Map getMap() { return map; } + public void setMap(Map map) { this.map = map; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java index eed3902b922..d8da58aca9c 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -13,40 +37,44 @@ @ApiModel(description = "Model for testing model name starting with number") public class Model200Response { - + @SerializedName("name") private Integer name = null; + + @SerializedName("class") private String PropertyClass = null; - - /** - **/ public Model200Response name(Integer name) { this.name = name; return this; } - + + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("name") public Integer getName() { return name; } + public void setName(Integer name) { this.name = name; } - - /** - **/ public Model200Response PropertyClass(String PropertyClass) { this.PropertyClass = PropertyClass; return this; } - + + /** + * Get PropertyClass + * @return PropertyClass + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("class") public String getPropertyClass() { return PropertyClass; } + public void setPropertyClass(String PropertyClass) { this.PropertyClass = PropertyClass; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java index 32fb86dd323..2a823298323 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,58 +36,65 @@ */ public class ModelApiResponse { - + @SerializedName("code") private Integer code = null; + + @SerializedName("type") private String type = null; + + @SerializedName("message") private String message = null; - - /** - **/ public ModelApiResponse code(Integer code) { this.code = code; return this; } - + + /** + * Get code + * @return code + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("code") public Integer getCode() { return code; } + public void setCode(Integer code) { this.code = code; } - - /** - **/ public ModelApiResponse type(String type) { this.type = type; return this; } - + + /** + * Get type + * @return type + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("type") public String getType() { return type; } + public void setType(String type) { this.type = type; } - - /** - **/ public ModelApiResponse message(String message) { this.message = message; return this; } - + + /** + * Get message + * @return message + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("message") public String getMessage() { return message; } + public void setMessage(String message) { this.message = message; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java index a076d16f964..024a9c0df1c 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -13,22 +37,23 @@ @ApiModel(description = "Model for testing reserved words") public class ModelReturn { - + @SerializedName("return") private Integer _return = null; - - /** - **/ public ModelReturn _return(Integer _return) { this._return = _return; return this; } - + + /** + * Get _return + * @return _return + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("return") public Integer getReturn() { return _return; } + public void setReturn(Integer _return) { this._return = _return; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java index 1ba2cc5e4a3..318a2ddd50e 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -13,56 +37,68 @@ @ApiModel(description = "Model for testing model name same as property name") public class Name { - + @SerializedName("name") private Integer name = null; + + @SerializedName("snake_case") private Integer snakeCase = null; + + @SerializedName("property") private String property = null; + + @SerializedName("123Number") private Integer _123Number = null; - - /** - **/ public Name name(Integer name) { this.name = name; return this; } - + + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("name") public Integer getName() { return name; } + public void setName(Integer name) { this.name = name; } - + /** + * Get snakeCase + * @return snakeCase + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("snake_case") public Integer getSnakeCase() { return snakeCase; } - - /** - **/ public Name property(String property) { this.property = property; return this; } - + + /** + * Get property + * @return property + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("property") public String getProperty() { return property; } + public void setProperty(String property) { this.property = property; } - + /** + * Get _123Number + * @return _123Number + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("123Number") public Integer get123Number() { return _123Number; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/NumberOnly.java new file mode 100644 index 00000000000..9b9ca048dfb --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/NumberOnly.java @@ -0,0 +1,100 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; + + +/** + * NumberOnly + */ + +public class NumberOnly { + @SerializedName("JustNumber") + private BigDecimal justNumber = null; + + public NumberOnly justNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + return this; + } + + /** + * Get justNumber + * @return justNumber + **/ + @ApiModelProperty(example = "null", value = "") + public BigDecimal getJustNumber() { + return justNumber; + } + + public void setJustNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NumberOnly numberOnly = (NumberOnly) o; + return Objects.equals(this.justNumber, numberOnly.justNumber); + } + + @Override + public int hashCode() { + return Objects.hash(justNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NumberOnly {\n"); + + sb.append(" justNumber: ").append(toIndentedString(justNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java index cec651e73a6..90cfd2f3892 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java @@ -1,9 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonValue; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.joda.time.DateTime; @@ -14,18 +37,29 @@ */ public class Order { - + @SerializedName("id") private Long id = null; + + @SerializedName("petId") private Long petId = null; + + @SerializedName("quantity") private Integer quantity = null; + + @SerializedName("shipDate") private DateTime shipDate = null; /** * Order Status */ public enum StatusEnum { + @SerializedName("placed") PLACED("placed"), + + @SerializedName("approved") APPROVED("approved"), + + @SerializedName("delivered") DELIVERED("delivered"); private String value; @@ -35,114 +69,121 @@ public enum StatusEnum { } @Override - @JsonValue public String toString() { return String.valueOf(value); } } + @SerializedName("status") private StatusEnum status = null; + + @SerializedName("complete") private Boolean complete = false; - - /** - **/ public Order id(Long id) { this.id = id; return this; } - + + /** + * Get id + * @return id + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - - /** - **/ public Order petId(Long petId) { this.petId = petId; return this; } - + + /** + * Get petId + * @return petId + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("petId") public Long getPetId() { return petId; } + public void setPetId(Long petId) { this.petId = petId; } - - /** - **/ public Order quantity(Integer quantity) { this.quantity = quantity; return this; } - + + /** + * Get quantity + * @return quantity + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("quantity") public Integer getQuantity() { return quantity; } + public void setQuantity(Integer quantity) { this.quantity = quantity; } - - /** - **/ public Order shipDate(DateTime shipDate) { this.shipDate = shipDate; return this; } - + + /** + * Get shipDate + * @return shipDate + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("shipDate") public DateTime getShipDate() { return shipDate; } + public void setShipDate(DateTime shipDate) { this.shipDate = shipDate; } - - /** - * Order Status - **/ public Order status(StatusEnum status) { this.status = status; return this; } - + + /** + * Order Status + * @return status + **/ @ApiModelProperty(example = "null", value = "Order Status") - @JsonProperty("status") public StatusEnum getStatus() { return status; } + public void setStatus(StatusEnum status) { this.status = status; } - - /** - **/ public Order complete(Boolean complete) { this.complete = complete; return this; } - + + /** + * Get complete + * @return complete + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("complete") public Boolean getComplete() { return complete; } + public void setComplete(Boolean complete) { this.complete = complete; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java index da8b76ad024..b80fdeaf923 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java @@ -1,9 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonValue; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Category; @@ -17,19 +40,32 @@ */ public class Pet { - + @SerializedName("id") private Long id = null; + + @SerializedName("category") private Category category = null; + + @SerializedName("name") private String name = null; + + @SerializedName("photoUrls") private List photoUrls = new ArrayList(); + + @SerializedName("tags") private List tags = new ArrayList(); /** * pet status in the store */ public enum StatusEnum { + @SerializedName("available") AVAILABLE("available"), + + @SerializedName("pending") PENDING("pending"), + + @SerializedName("sold") SOLD("sold"); private String value; @@ -39,113 +75,118 @@ public enum StatusEnum { } @Override - @JsonValue public String toString() { return String.valueOf(value); } } + @SerializedName("status") private StatusEnum status = null; - - /** - **/ public Pet id(Long id) { this.id = id; return this; } - + + /** + * Get id + * @return id + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - - /** - **/ public Pet category(Category category) { this.category = category; return this; } - + + /** + * Get category + * @return category + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("category") public Category getCategory() { return category; } + public void setCategory(Category category) { this.category = category; } - - /** - **/ public Pet name(String name) { this.name = name; return this; } - + + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "doggie", required = true, value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } - - /** - **/ public Pet photoUrls(List photoUrls) { this.photoUrls = photoUrls; return this; } - + + /** + * Get photoUrls + * @return photoUrls + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("photoUrls") public List getPhotoUrls() { return photoUrls; } + public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } - - /** - **/ public Pet tags(List tags) { this.tags = tags; return this; } - + + /** + * Get tags + * @return tags + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("tags") public List getTags() { return tags; } + public void setTags(List tags) { this.tags = tags; } - - /** - * pet status in the store - **/ public Pet status(StatusEnum status) { this.status = status; return this; } - + + /** + * pet status in the store + * @return status + **/ @ApiModelProperty(example = "null", value = "pet status in the store") - @JsonProperty("status") public StatusEnum getStatus() { return status; } + public void setStatus(StatusEnum status) { this.status = status; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index fdc3587df0e..13b729bb94d 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,30 +36,35 @@ */ public class ReadOnlyFirst { - + @SerializedName("bar") private String bar = null; + + @SerializedName("baz") private String baz = null; - + /** + * Get bar + * @return bar + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("bar") public String getBar() { return bar; } - - /** - **/ public ReadOnlyFirst baz(String baz) { this.baz = baz; return this; } - + + /** + * Get baz + * @return baz + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("baz") public String getBaz() { return baz; } + public void setBaz(String baz) { this.baz = baz; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java index 24e57756cb2..b46b8367a01 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,22 +36,23 @@ */ public class SpecialModelName { - + @SerializedName("$special[property.name]") private Long specialPropertyName = null; - - /** - **/ public SpecialModelName specialPropertyName(Long specialPropertyName) { this.specialPropertyName = specialPropertyName; return this; } - + + /** + * Get specialPropertyName + * @return specialPropertyName + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("$special[property.name]") public Long getSpecialPropertyName() { return specialPropertyName; } + public void setSpecialPropertyName(Long specialPropertyName) { this.specialPropertyName = specialPropertyName; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java index 9d3bdd8cb9e..e56eb535d1e 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,40 +36,44 @@ */ public class Tag { - + @SerializedName("id") private Long id = null; + + @SerializedName("name") private String name = null; - - /** - **/ public Tag id(Long id) { this.id = id; return this; } - + + /** + * Get id + * @return id + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - - /** - **/ public Tag name(String name) { this.name = name; return this; } - + + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java index f23553660de..6c1ed6ceacc 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,149 +36,170 @@ */ public class User { - + @SerializedName("id") private Long id = null; + + @SerializedName("username") private String username = null; + + @SerializedName("firstName") private String firstName = null; + + @SerializedName("lastName") private String lastName = null; + + @SerializedName("email") private String email = null; + + @SerializedName("password") private String password = null; + + @SerializedName("phone") private String phone = null; + + @SerializedName("userStatus") private Integer userStatus = null; - - /** - **/ public User id(Long id) { this.id = id; return this; } - + + /** + * Get id + * @return id + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - - /** - **/ public User username(String username) { this.username = username; return this; } - + + /** + * Get username + * @return username + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("username") public String getUsername() { return username; } + public void setUsername(String username) { this.username = username; } - - /** - **/ public User firstName(String firstName) { this.firstName = firstName; return this; } - + + /** + * Get firstName + * @return firstName + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("firstName") public String getFirstName() { return firstName; } + public void setFirstName(String firstName) { this.firstName = firstName; } - - /** - **/ public User lastName(String lastName) { this.lastName = lastName; return this; } - + + /** + * Get lastName + * @return lastName + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("lastName") public String getLastName() { return lastName; } + public void setLastName(String lastName) { this.lastName = lastName; } - - /** - **/ public User email(String email) { this.email = email; return this; } - + + /** + * Get email + * @return email + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("email") public String getEmail() { return email; } + public void setEmail(String email) { this.email = email; } - - /** - **/ public User password(String password) { this.password = password; return this; } - + + /** + * Get password + * @return password + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("password") public String getPassword() { return password; } + public void setPassword(String password) { this.password = password; } - - /** - **/ public User phone(String phone) { this.phone = phone; return this; } - + + /** + * Get phone + * @return phone + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("phone") public String getPhone() { return phone; } + public void setPhone(String phone) { this.phone = phone; } - - /** - * User Status - **/ public User userStatus(Integer userStatus) { this.userStatus = userStatus; return this; } - + + /** + * User Status + * @return userStatus + **/ @ApiModelProperty(example = "null", value = "User Status") - @JsonProperty("userStatus") public Integer getUserStatus() { return userStatus; } + public void setUserStatus(Integer userStatus) { this.userStatus = userStatus; } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java index 0204c5c96aa..b7b04e3e4c5 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java @@ -812,6 +812,7 @@ public String escapeString(String str) { * @throws ApiException If fail to deserialize response body, i.e. cannot read response body * or the Content-Type of the response is not supported. */ + @SuppressWarnings("unchecked") public T deserialize(Response response, Type returnType) throws ApiException { if (response == null || returnType == null) { return null; @@ -1006,6 +1007,7 @@ public void executeAsync(Call call, ApiCallback callback) { * @param returnType Return type * @param callback ApiCallback */ + @SuppressWarnings("unchecked") public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { call.enqueue(new Callback() { @Override diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/JSON.java index a0b9c9c1cf0..540611eab9d 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/JSON.java @@ -103,6 +103,7 @@ public String serialize(Object obj) { * @param returnType The type to deserialize inot * @return The deserialized Java object */ + @SuppressWarnings("unchecked") public T deserialize(String body, Type returnType) { try { if (apiClient.isLenientOnJson()) { diff --git a/samples/client/petstore/java/jersey2-java8/build.gradle b/samples/client/petstore/java/jersey2-java8/build.gradle index ece2fa55d57..45cca63a19d 100644 --- a/samples/client/petstore/java/jersey2-java8/build.gradle +++ b/samples/client/petstore/java/jersey2-java8/build.gradle @@ -32,8 +32,8 @@ if(hasProperty('target') && target == 'android') { targetSdkVersion 23 } compileOptions { - sourceCompatibility JavaVersion.VERSION_1_8 - targetCompatibility JavaVersion.VERSION_1_8 + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 } // Rename the aar correctly @@ -77,6 +77,7 @@ if(hasProperty('target') && target == 'android') { apply plugin: 'java' apply plugin: 'maven' + sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 @@ -92,22 +93,10 @@ if(hasProperty('target') && target == 'android') { } } -ext { - swagger_annotations_version = "1.5.8" - jackson_version = "2.7.5" - jersey_version = "2.22.2" - junit_version = "4.12" -} - dependencies { - compile "io.swagger:swagger-annotations:$swagger_annotations_version" - compile "org.glassfish.jersey.core:jersey-client:$jersey_version" - compile "org.glassfish.jersey.media:jersey-media-multipart:$jersey_version" - compile "org.glassfish.jersey.media:jersey-media-json-jackson:$jersey_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-jsr310:$jackson_version" - compile "com.brsanthu:migbase64:2.2" - testCompile "junit:junit:$junit_version" + compile 'io.swagger:swagger-annotations:1.5.8' + compile 'com.squareup.okhttp:okhttp:2.7.5' + compile 'com.squareup.okhttp:logging-interceptor:2.7.5' + compile 'com.google.code.gson:gson:2.6.2' + testCompile 'junit:junit:4.12' } diff --git a/samples/client/petstore/java/jersey2-java8/build.sbt b/samples/client/petstore/java/jersey2-java8/build.sbt index b187fb67ae2..45814b8a5cc 100644 --- a/samples/client/petstore/java/jersey2-java8/build.sbt +++ b/samples/client/petstore/java/jersey2-java8/build.sbt @@ -10,14 +10,9 @@ lazy val root = (project in file(".")). resolvers += Resolver.mavenLocal, libraryDependencies ++= Seq( "io.swagger" % "swagger-annotations" % "1.5.8", - "org.glassfish.jersey.core" % "jersey-client" % "2.22.2", - "org.glassfish.jersey.media" % "jersey-media-multipart" % "2.22.2", - "org.glassfish.jersey.media" % "jersey-media-json-jackson" % "2.22.2", - "com.fasterxml.jackson.core" % "jackson-core" % "2.7.5", - "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.5", - "com.fasterxml.jackson.core" % "jackson-databind" % "2.7.5", - "com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % "2.7.5", - "com.brsanthu" % "migbase64" % "2.2", + "com.squareup.okhttp" % "okhttp" % "2.7.5", + "com.squareup.okhttp" % "logging-interceptor" % "2.7.5", + "com.google.code.gson" % "gson" % "2.6.2", "junit" % "junit" % "4.12" % "test", "com.novocode" % "junit-interface" % "0.10" % "test" ) diff --git a/samples/client/petstore/java/jersey2-java8/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/java/jersey2-java8/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 00000000000..77292549927 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/ArrayOfArrayOfNumberOnly.md @@ -0,0 +1,10 @@ + +# ArrayOfArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayArrayNumber** | [**List<List<BigDecimal>>**](List.md) | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/ArrayOfNumberOnly.md b/samples/client/petstore/java/jersey2-java8/docs/ArrayOfNumberOnly.md new file mode 100644 index 00000000000..e8cc4cd36dc --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/ArrayOfNumberOnly.md @@ -0,0 +1,10 @@ + +# ArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayNumber** | [**List<BigDecimal>**](BigDecimal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/FakeApi.md b/samples/client/petstore/java/jersey2-java8/docs/FakeApi.md index 0e2b14922de..678a0f76a82 100644 --- a/samples/client/petstore/java/jersey2-java8/docs/FakeApi.md +++ b/samples/client/petstore/java/jersey2-java8/docs/FakeApi.md @@ -5,6 +5,7 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters @@ -73,3 +74,49 @@ No authorization required - **Content-Type**: application/xml; charset=utf-8, application/json; charset=utf-8 - **Accept**: application/xml; charset=utf-8, application/json; charset=utf-8 + +# **testEnumQueryParameters** +> testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble) + +To test enum query parameters + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +String enumQueryString = "-efg"; // String | Query parameter enum test (string) +BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | Query parameter enum test (double) +Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) +try { + apiInstance.testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEnumQueryParameters"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + **enumQueryInteger** | **BigDecimal**| Query parameter enum test (double) | [optional] + **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + diff --git a/samples/client/petstore/java/jersey2-java8/docs/HasOnlyReadOnly.md b/samples/client/petstore/java/jersey2-java8/docs/HasOnlyReadOnly.md new file mode 100644 index 00000000000..c1d0aac5672 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/HasOnlyReadOnly.md @@ -0,0 +1,11 @@ + +# HasOnlyReadOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] +**foo** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/MapTest.md b/samples/client/petstore/java/jersey2-java8/docs/MapTest.md new file mode 100644 index 00000000000..c671e97ffbc --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/MapTest.md @@ -0,0 +1,17 @@ + +# MapTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapMapOfString** | [**Map<String, Map<String, String>>**](Map.md) | | [optional] +**mapOfEnumString** | [**Map<String, InnerEnum>**](#Map<String, InnerEnum>) | | [optional] + + + +## Enum: Map<String, InnerEnum> +Name | Value +---- | ----- + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/Model200Response.md b/samples/client/petstore/java/jersey2-java8/docs/Model200Response.md index 0819b88c4f4..b47618b28cc 100644 --- a/samples/client/petstore/java/jersey2-java8/docs/Model200Response.md +++ b/samples/client/petstore/java/jersey2-java8/docs/Model200Response.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **Integer** | | [optional] +**PropertyClass** | **String** | | [optional] diff --git a/samples/client/petstore/java/jersey2-java8/docs/NumberOnly.md b/samples/client/petstore/java/jersey2-java8/docs/NumberOnly.md new file mode 100644 index 00000000000..a3feac7fadc --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/NumberOnly.md @@ -0,0 +1,10 @@ + +# NumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**justNumber** | [**BigDecimal**](BigDecimal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2-java8/gradlew.bat b/samples/client/petstore/java/jersey2-java8/gradlew.bat index 5f192121eb4..72d362dafd8 100644 --- a/samples/client/petstore/java/jersey2-java8/gradlew.bat +++ b/samples/client/petstore/java/jersey2-java8/gradlew.bat @@ -1,90 +1,90 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -set CMD_LINE_ARGS=%$ - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/java/jersey2-java8/pom.xml b/samples/client/petstore/java/jersey2-java8/pom.xml index d3327ef4b98..9bf4ed63d67 100644 --- a/samples/client/petstore/java/jersey2-java8/pom.xml +++ b/samples/client/petstore/java/jersey2-java8/pom.xml @@ -52,7 +52,7 @@ org.apache.maven.plugins maven-jar-plugin - 2.6 + 2.2 @@ -68,6 +68,7 @@ org.codehaus.mojo build-helper-maven-plugin + 1.10 add_sources @@ -95,15 +96,6 @@ - - org.apache.maven.plugins - maven-compiler-plugin - 2.5.1 - - 1.8 - 1.8 - - @@ -112,51 +104,20 @@ swagger-annotations ${swagger-core-version} - - - - org.glassfish.jersey.core - jersey-client - ${jersey-version} - - - org.glassfish.jersey.media - jersey-media-multipart - ${jersey-version} - - org.glassfish.jersey.media - jersey-media-json-jackson - ${jersey-version} + com.squareup.okhttp + okhttp + ${okhttp-version} - - - com.fasterxml.jackson.core - jackson-core - ${jackson-version} + com.squareup.okhttp + logging-interceptor + ${okhttp-version} - com.fasterxml.jackson.core - jackson-annotations - ${jackson-version} - - - com.fasterxml.jackson.core - jackson-databind - ${jackson-version} - - - com.fasterxml.jackson.datatype - jackson-datatype-jsr310 - ${jackson-version} - - - - - com.brsanthu - migbase64 - 2.2 + com.google.code.gson + gson + ${gson-version} @@ -168,10 +129,15 @@ - 1.5.8 - 2.22.2 - 2.7.5 + 1.8 + ${java.version} + ${java.version} + 1.5.9 + 2.7.5 + 2.6.2 + 2.9.3 1.0.0 4.12 + UTF-8 diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiCallback.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiCallback.java new file mode 100644 index 00000000000..3ca33cf8017 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiCallback.java @@ -0,0 +1,74 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import java.io.IOException; + +import java.util.Map; +import java.util.List; + +/** + * Callback for asynchronous API call. + * + * @param The return type + */ +public interface ApiCallback { + /** + * This is called when the API call fails. + * + * @param e The exception causing the failure + * @param statusCode Status code of the response if available, otherwise it would be 0 + * @param responseHeaders Headers of the response if available, otherwise it would be null + */ + void onFailure(ApiException e, int statusCode, Map> responseHeaders); + + /** + * This is called when the API call succeeded. + * + * @param result The result deserialized from response + * @param statusCode Status code of the response + * @param responseHeaders Headers of the response + */ + void onSuccess(T result, int statusCode, Map> responseHeaders); + + /** + * This is called when the API upload processing. + * + * @param bytesWritten bytes Written + * @param contentLength content length of request body + * @param done write end + */ + void onUploadProgress(long bytesWritten, long contentLength, boolean done); + + /** + * This is called when the API downlond processing. + * + * @param bytesRead bytes Read + * @param contentLength content lenngth of the response + * @param done Read end + */ + void onDownloadProgress(long bytesRead, long contentLength, boolean done); +} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiClient.java index 06f6d4d899a..b7b04e3e4c5 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiClient.java @@ -1,28 +1,46 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -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; - -import org.glassfish.jersey.client.ClientConfig; -import org.glassfish.jersey.client.ClientProperties; -import org.glassfish.jersey.filter.LoggingFilter; -import org.glassfish.jersey.jackson.JacksonFeature; -import org.glassfish.jersey.media.multipart.FormDataBodyPart; -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; -import org.glassfish.jersey.media.multipart.MultiPart; -import org.glassfish.jersey.media.multipart.MultiPartFeature; +import com.squareup.okhttp.Call; +import com.squareup.okhttp.Callback; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Response; +import com.squareup.okhttp.RequestBody; +import com.squareup.okhttp.FormEncodingBuilder; +import com.squareup.okhttp.MultipartBuilder; +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.Headers; +import com.squareup.okhttp.internal.http.HttpMethod; +import com.squareup.okhttp.logging.HttpLoggingInterceptor; +import com.squareup.okhttp.logging.HttpLoggingInterceptor.Level; + +import java.lang.reflect.Type; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Files; import java.util.Collection; import java.util.Collections; import java.util.Map; @@ -32,667 +50,1277 @@ import java.util.ArrayList; import java.util.Date; import java.util.TimeZone; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import java.net.URLEncoder; +import java.net.URLConnection; import java.io.File; +import java.io.InputStream; +import java.io.IOException; import java.io.UnsupportedEncodingException; +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.security.SecureRandom; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; + import java.text.DateFormat; import java.text.SimpleDateFormat; -import java.util.regex.Matcher; -import java.util.regex.Pattern; +import java.text.ParseException; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.KeyManager; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509TrustManager; + +import okio.BufferedSink; +import okio.Okio; import io.swagger.client.auth.Authentication; import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; - public class ApiClient { - private Map defaultHeaderMap = new HashMap(); - private String basePath = "http://petstore.swagger.io/v2"; - private boolean debugging = false; - private int connectionTimeout = 0; - - private Client httpClient; - private JSON json; - private String tempFolderPath = null; - - private Map authentications; - - private int statusCode; - private Map> responseHeaders; - - private DateFormat dateFormat; - - public ApiClient() { - json = new JSON(); - httpClient = buildHttpClient(debugging); - - // Use RFC3339 format for date and datetime. - // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 - this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); - - // Use UTC as the default time zone. - this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - - this.json.setDateFormat((DateFormat) dateFormat.clone()); - - // Set default User-Agent. - setUserAgent("Swagger-Codegen/1.0.0/java"); - - // Setup authentications (key: authentication name, value: authentication). - authentications = new HashMap(); - authentications.put("petstore_auth", new OAuth()); - authentications.put("api_key", new ApiKeyAuth("header", "api_key")); - // Prevent the authentications from being modified. - authentications = Collections.unmodifiableMap(authentications); - } - - /** - * Gets the JSON instance to do JSON serialization and deserialization. - */ - public JSON getJSON() { - return json; - } - - public Client getHttpClient() { - return httpClient; - } - - public ApiClient setHttpClient(Client httpClient) { - this.httpClient = httpClient; - return this; - } - - public String getBasePath() { - return basePath; - } - - public ApiClient setBasePath(String basePath) { - this.basePath = basePath; - return this; - } - - /** - * Gets the status code of the previous request - */ - public int getStatusCode() { - return statusCode; - } - - /** - * Gets the response headers of the previous request - */ - public Map> getResponseHeaders() { - return responseHeaders; - } - - /** - * Get authentications (key: authentication name, value: authentication). - */ - public Map getAuthentications() { - return authentications; - } - - /** - * Get authentication for the given name. - * - * @param authName The authentication name - * @return The authentication, null if not found - */ - public Authentication getAuthentication(String authName) { - return authentications.get(authName); - } - - /** - * Helper method to set username for the first HTTP basic authentication. - */ - public void setUsername(String username) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setUsername(username); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set password for the first HTTP basic authentication. - */ - public void setPassword(String password) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setPassword(password); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set API key value for the first API key authentication. - */ - public void setApiKey(String apiKey) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKey(apiKey); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set API key prefix for the first API key authentication. - */ - public void setApiKeyPrefix(String apiKeyPrefix) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set access token for the first OAuth2 authentication. - */ - public void setAccessToken(String accessToken) { - for (Authentication auth : authentications.values()) { - if (auth instanceof OAuth) { - ((OAuth) auth).setAccessToken(accessToken); - return; - } - } - throw new RuntimeException("No OAuth2 authentication configured!"); - } - - /** - * Set the User-Agent header's value (by adding to the default header map). - */ - public ApiClient setUserAgent(String userAgent) { - addDefaultHeader("User-Agent", userAgent); - return this; - } - - /** - * Add a default header. - * - * @param key The header's key - * @param value The header's value - */ - public ApiClient addDefaultHeader(String key, String value) { - defaultHeaderMap.put(key, value); - return this; - } - - /** - * Check that whether debugging is enabled for this API client. - */ - public boolean isDebugging() { - return debugging; - } - - /** - * Enable/disable debugging for this API client. - * - * @param debugging To enable (true) or disable (false) debugging - */ - public ApiClient setDebugging(boolean debugging) { - this.debugging = debugging; - // Rebuild HTTP Client according to the new "debugging" value. - this.httpClient = buildHttpClient(debugging); - return this; - } - - /** - * The path of temporary folder used to store downloaded files from endpoints - * with file response. The default value is null, i.e. using - * the system's default tempopary folder. - * - * @see https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createTempFile(java.lang.String,%20java.lang.String,%20java.io.File) - */ - public String getTempFolderPath() { - return tempFolderPath; - } - - public ApiClient setTempFolderPath(String tempFolderPath) { - this.tempFolderPath = tempFolderPath; - return this; - } - - /** - * Connect timeout (in milliseconds). - */ - public int getConnectTimeout() { - return connectionTimeout; - } - - /** - * Set the connect timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * {@link Integer#MAX_VALUE}. - */ - public ApiClient setConnectTimeout(int connectionTimeout) { - this.connectionTimeout = connectionTimeout; - httpClient.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout); - return this; - } - - /** - * Get the date format used to parse/format date parameters. - */ - public DateFormat getDateFormat() { - return dateFormat; - } - - /** - * Set the date format used to parse/format date parameters. - */ - 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()); - return this; - } - - /** - * Parse the given string into Date object. - */ - public Date parseDate(String str) { - try { - return dateFormat.parse(str); - } catch (java.text.ParseException e) { - throw new RuntimeException(e); - } - } - - /** - * Format the given Date object into string. - */ - public String formatDate(Date date) { - return dateFormat.format(date); - } - - /** - * 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 to {@code Pair} objects. - */ - public List parameterToPairs(String collectionFormat, String name, Object value){ - List params = new ArrayList(); - - // preconditions - if (name == null || name.isEmpty() || value == null) return params; - - Collection valueCollection = null; - if (value instanceof Collection) { - valueCollection = (Collection) value; - } else { - params.add(new Pair(name, parameterToString(value))); - return params; - } - - if (valueCollection.isEmpty()){ - return params; - } - - // get the collection format - collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv - - // create the params based on the collection format - if (collectionFormat.equals("multi")) { - for (Object item : valueCollection) { - params.add(new Pair(name, parameterToString(item))); - } - - return params; - } - - String delimiter = ","; - - if (collectionFormat.equals("csv")) { - delimiter = ","; - } else if (collectionFormat.equals("ssv")) { - delimiter = " "; - } else if (collectionFormat.equals("tsv")) { - delimiter = "\t"; - } else if (collectionFormat.equals("pipes")) { - delimiter = "|"; - } - - StringBuilder sb = new StringBuilder() ; - for (Object item : valueCollection) { - sb.append(delimiter); - sb.append(parameterToString(item)); - } - - params.add(new Pair(name, sb.substring(1))); - - return params; - } - - /** - * Check if the given MIME is a JSON MIME. - * JSON MIME examples: - * application/json - * application/json; charset=UTF8 - * APPLICATION/JSON - */ - public boolean isJsonMime(String mime) { - return mime != null && mime.matches("(?i)application\\/json(;.*)?"); - } - - /** - * Select the Accept header's value from the given accepts array: - * if JSON exists in the given array, use it; - * otherwise use all of them (joining into a string) - * - * @param accepts The accepts array to select from - * @return The Accept header to use. If the given array is empty, - * null will be returned (not to set the Accept header explicitly). - */ - public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) { - return null; - } - for (String accept : accepts) { - if (isJsonMime(accept)) { - return accept; - } - } - return StringUtil.join(accepts, ","); - } - - /** - * Select the Content-Type header's value from the given array: - * if JSON exists in the given array, use it; - * otherwise use the first one of the array. - * - * @param contentTypes The Content-Type array to select from - * @return The Content-Type header to use. If the given array is empty, - * JSON will be used. - */ - public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) { - return "application/json"; - } - for (String contentType : contentTypes) { - if (isJsonMime(contentType)) { - return contentType; - } - } - return contentTypes[0]; - } - - /** - * Escape the given string to be used as URL query value. - */ - public String escapeString(String str) { - try { - return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); - } catch (UnsupportedEncodingException e) { - return str; - } - } - - /** - * Serialize the given Java object into string entity according the given - * Content-Type (only JSON is supported for now). - */ - 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)); + public static final double JAVA_VERSION; + public static final boolean IS_ANDROID; + public static final int ANDROID_SDK_VERSION; + + static { + JAVA_VERSION = Double.parseDouble(System.getProperty("java.specification.version")); + boolean isAndroid; + try { + Class.forName("android.app.Activity"); + isAndroid = true; + } catch (ClassNotFoundException e) { + isAndroid = false; + } + IS_ANDROID = isAndroid; + int sdkVersion = 0; + if (IS_ANDROID) { + try { + sdkVersion = Class.forName("android.os.Build$VERSION").getField("SDK_INT").getInt(null); + } catch (Exception e) { + try { + sdkVersion = Integer.parseInt((String) Class.forName("android.os.Build$VERSION").getField("SDK").get(null)); + } catch (Exception e2) { } + } + } + ANDROID_SDK_VERSION = sdkVersion; + } + + /** + * The datetime format to be used when lenientDatetimeFormat is enabled. + */ + public static final String LENIENT_DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; + + private String basePath = "http://petstore.swagger.io/v2"; + private boolean lenientOnJson = false; + private boolean debugging = false; + private Map defaultHeaderMap = new HashMap(); + private String tempFolderPath = null; + + private Map authentications; + + private DateFormat dateFormat; + private DateFormat datetimeFormat; + private boolean lenientDatetimeFormat; + private int dateLength; + + private InputStream sslCaCert; + private boolean verifyingSsl; + + private OkHttpClient httpClient; + private JSON json; + + private HttpLoggingInterceptor loggingInterceptor; + + /* + * Constructor for ApiClient + */ + public ApiClient() { + httpClient = new OkHttpClient(); + + verifyingSsl = true; + + json = new JSON(this); + + /* + * Use RFC3339 format for date and datetime. + * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + */ + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + // Always use UTC as the default time zone when dealing with date (without time). + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + initDatetimeFormat(); + + // Be lenient on datetime formats when parsing datetime from string. + // See parseDatetime. + this.lenientDatetimeFormat = true; + + // Set default User-Agent. + setUserAgent("Swagger-Codegen/1.0.0/java"); + + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap(); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("petstore_auth", new OAuth()); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + /** + * Get base path + * + * @return Baes path + */ + public String getBasePath() { + return basePath; + } + + /** + * Set base path + * + * @param basePath Base path of the URL (e.g http://petstore.swagger.io/v2 + * @return An instance of OkHttpClient + */ + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + /** + * Get HTTP client + * + * @return An instance of OkHttpClient + */ + public OkHttpClient getHttpClient() { + return httpClient; + } + + /** + * Set HTTP client + * + * @param httpClient An instance of OkHttpClient + * @return Api Client + */ + public ApiClient setHttpClient(OkHttpClient httpClient) { + this.httpClient = httpClient; + return this; + } + + /** + * Get JSON + * + * @return JSON object + */ + public JSON getJSON() { + return json; + } + + /** + * Set JSON + * + * @param json JSON object + * @return Api client + */ + public ApiClient setJSON(JSON json) { + this.json = json; + return this; + } + + /** + * True if isVerifyingSsl flag is on + * + * @return True if isVerifySsl flag is on + */ + public boolean isVerifyingSsl() { + return verifyingSsl; + } + + /** + * Configure whether to verify certificate and hostname when making https requests. + * Default to true. + * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. + * + * @param verifyingSsl True to verify TLS/SSL connection + * @return ApiClient + */ + public ApiClient setVerifyingSsl(boolean verifyingSsl) { + this.verifyingSsl = verifyingSsl; + applySslSettings(); + return this; + } + + /** + * Get SSL CA cert. + * + * @return Input stream to the SSL CA cert + */ + public InputStream getSslCaCert() { + return sslCaCert; + } + + /** + * Configure the CA certificate to be trusted when making https requests. + * Use null to reset to default. + * + * @param sslCaCert input stream for SSL CA cert + * @return ApiClient + */ + public ApiClient setSslCaCert(InputStream sslCaCert) { + this.sslCaCert = sslCaCert; + applySslSettings(); + return this; + } + + public DateFormat getDateFormat() { + return dateFormat; + } + + public ApiClient setDateFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + this.dateLength = this.dateFormat.format(new Date()).length(); + return this; + } + + public DateFormat getDatetimeFormat() { + return datetimeFormat; + } + + public ApiClient setDatetimeFormat(DateFormat datetimeFormat) { + this.datetimeFormat = datetimeFormat; + return this; + } + + /** + * Whether to allow various ISO 8601 datetime formats when parsing a datetime string. + * @see #parseDatetime(String) + * @return True if lenientDatetimeFormat flag is set to true + */ + public boolean isLenientDatetimeFormat() { + return lenientDatetimeFormat; + } + + public ApiClient setLenientDatetimeFormat(boolean lenientDatetimeFormat) { + this.lenientDatetimeFormat = lenientDatetimeFormat; + return this; + } + + /** + * Parse the given date string into Date object. + * The default dateFormat supports these ISO 8601 date formats: + * 2015-08-16 + * 2015-8-16 + * @param str String to be parsed + * @return Date + */ + public Date parseDate(String str) { + if (str == null) + return null; + try { + return dateFormat.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Parse the given datetime string into Date object. + * When lenientDatetimeFormat is enabled, the following ISO 8601 datetime formats are supported: + * 2015-08-16T08:20:05Z + * 2015-8-16T8:20:05Z + * 2015-08-16T08:20:05+00:00 + * 2015-08-16T08:20:05+0000 + * 2015-08-16T08:20:05.376Z + * 2015-08-16T08:20:05.376+00:00 + * 2015-08-16T08:20:05.376+00 + * Note: The 3-digit milli-seconds is optional. Time zone is required and can be in one of + * these formats: + * Z (same with +0000) + * +08:00 (same with +0800) + * -02 (same with -0200) + * -0200 + * @see ISO 8601 + * @param str Date time string to be parsed + * @return Date representation of the string + */ + public Date parseDatetime(String str) { + if (str == null) + return null; + + DateFormat format; + if (lenientDatetimeFormat) { + /* + * When lenientDatetimeFormat is enabled, normalize the date string + * into LENIENT_DATETIME_FORMAT to support various formats + * defined by ISO 8601. + */ + // normalize time zone + // trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000 + str = str.replaceAll("[zZ]\\z", "+0000"); + // remove colon in time zone: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000 + str = str.replaceAll("([+-]\\d{2}):(\\d{2})\\z", "$1$2"); + // expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000 + str = str.replaceAll("([+-]\\d{2})\\z", "$100"); + // add milliseconds when missing + // 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000 + str = str.replaceAll("(:\\d{1,2})([+-]\\d{4})\\z", "$1.000$2"); + format = new SimpleDateFormat(LENIENT_DATETIME_FORMAT); + } else { + format = this.datetimeFormat; + } + + try { + return format.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /* + * Parse date or date time in string format into Date object. + * + * @param str Date time string to be parsed + * @return Date representation of the string + */ + public Date parseDateOrDatetime(String str) { + if (str == null) + return null; + else if (str.length() <= dateLength) + return parseDate(str); + else + return parseDatetime(str); + } + + /** + * Format the given Date object into string (Date format). + * + * @param date Date object + * @return Formatted date in string representation + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } + + /** + * Format the given Date object into string (Datetime format). + * + * @param date Date object + * @return Formatted datetime in string representation + */ + public String formatDatetime(Date date) { + return datetimeFormat.format(date); + } + + /** + * Get authentications (key: authentication name, value: authentication). + * + * @return Map of authentication objects + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + * + * @param username Username + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + * + * @param password Password + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + * + * @param apiKey API key + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + * + * @param apiKeyPrefix API key prefix + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set access token for the first OAuth2 authentication. + * + * @param accessToken Access token + */ + public void setAccessToken(String accessToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); + return; + } + } + throw new RuntimeException("No OAuth2 authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + * + * @param userAgent HTTP request's user agent + * @return ApiClient + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + * @return ApiClient + */ + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + /** + * @see setLenient + * + * @return True if lenientOnJson is enabled, false otherwise. + */ + public boolean isLenientOnJson() { + return lenientOnJson; + } + + /** + * Set LenientOnJson + * + * @param lenient True to enable lenientOnJson + * @return ApiClient + */ + public ApiClient setLenientOnJson(boolean lenient) { + this.lenientOnJson = lenient; + return this; + } + + /** + * Check that whether debugging is enabled for this API client. + * + * @return True if debugging is enabled, false otherwise. + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + * @return ApiClient + */ + public ApiClient setDebugging(boolean debugging) { + if (debugging != this.debugging) { + if (debugging) { + loggingInterceptor = new HttpLoggingInterceptor(); + loggingInterceptor.setLevel(Level.BODY); + httpClient.interceptors().add(loggingInterceptor); + } else { + httpClient.interceptors().remove(loggingInterceptor); + loggingInterceptor = null; + } + } + this.debugging = debugging; + return this; + } + + /** + * The path of temporary folder used to store downloaded files from endpoints + * with file response. The default value is null, i.e. using + * the system's default tempopary folder. + * + * @see createTempFile + * @return Temporary folder path + */ + public String getTempFolderPath() { + return tempFolderPath; + } + + /** + * Set the tempoaray folder path (for downloading files) + * + * @param tempFolderPath Temporary folder path + * @return ApiClient + */ + public ApiClient setTempFolderPath(String tempFolderPath) { + this.tempFolderPath = tempFolderPath; + return this; + } + + /** + * Get connection timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getConnectTimeout() { + return httpClient.getConnectTimeout(); + } + + /** + * Sets the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * + * @param connectionTimeout connection timeout in milliseconds + * @return Api client + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + httpClient.setConnectTimeout(connectionTimeout, TimeUnit.MILLISECONDS); + return this; + } + + /** + * Format the given parameter object into string. + * + * @param param Parameter + * @return String representation of the parameter + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDatetime((Date) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for (Object o : (Collection)param) { + if (b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /** + * Format to {@code Pair} objects. + * + * @param collectionFormat collection format (e.g. csv, tsv) + * @param name Name + * @param value Value + * @return A list of Pair objects + */ + public List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + + // create the params based on the collection format + if (collectionFormat.equals("multi")) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); + } + + return params; + } + + String delimiter = ","; + + if (collectionFormat.equals("csv")) { + delimiter = ","; + } else if (collectionFormat.equals("ssv")) { + delimiter = " "; + } else if (collectionFormat.equals("tsv")) { + delimiter = "\t"; + } else if (collectionFormat.equals("pipes")) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + + return params; + } + + /** + * Sanitize filename by removing path. + * e.g. ../../sun.gif becomes sun.gif + * + * @param filename The filename to be sanitized + * @return The sanitized filename + */ + public String sanitizeFilename(String filename) { + return filename.replaceAll(".*[/\\\\]", ""); + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * + * @param mime MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public boolean isJsonMime(String mime) { + return mime != null && mime.matches("(?i)application\\/json(;.*)?"); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } + return contentTypes[0]; + } + + /** + * Escape the given string to be used as URL query value. + * + * @param str String to be escaped + * @return Escaped string + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Deserialize response body to Java object, according to the return type and + * the Content-Type response header. + * + * @param Type + * @param response HTTP response + * @param returnType The type of the Java object + * @return The deserialized Java object + * @throws ApiException If fail to deserialize response body, i.e. cannot read response body + * or the Content-Type of the response is not supported. + */ + @SuppressWarnings("unchecked") + public T deserialize(Response response, Type returnType) throws ApiException { + if (response == null || returnType == null) { + return null; + } + + if ("byte[]".equals(returnType.toString())) { + // Handle binary response (byte array). + try { + return (T) response.body().bytes(); + } catch (IOException e) { + throw new ApiException(e); + } + } else if (returnType.equals(File.class)) { + // Handle file downloading. + return (T) downloadFileFromResponse(response); + } + + String respBody; + try { + if (response.body() != null) + respBody = response.body().string(); + else + respBody = null; + } catch (IOException e) { + throw new ApiException(e); + } + + if (respBody == null || "".equals(respBody)) { + return null; + } + + String contentType = response.headers().get("Content-Type"); + if (contentType == null) { + // ensuring a default content type + contentType = "application/json"; + } + if (isJsonMime(contentType)) { + return json.deserialize(respBody, returnType); + } else if (returnType.equals(String.class)) { + // Expecting string, return the raw response body. + return (T) respBody; + } else { + throw new ApiException( + "Content type \"" + contentType + "\" is not supported for type: " + returnType, + response.code(), + response.headers().toMultimap(), + respBody); + } + } + + /** + * Serialize the given Java object into request body according to the object's + * class and the request Content-Type. + * + * @param obj The Java object + * @param contentType The request Content-Type + * @return The serialized request body + * @throws ApiException If fail to serialize the given object + */ + public RequestBody serialize(Object obj, String contentType) throws ApiException { + if (obj instanceof byte[]) { + // Binary (byte array) body parameter support. + return RequestBody.create(MediaType.parse(contentType), (byte[]) obj); + } else if (obj instanceof File) { + // File body parameter support. + return RequestBody.create(MediaType.parse(contentType), (File) obj); + } else if (isJsonMime(contentType)) { + String content; + if (obj != null) { + content = json.serialize(obj); + } else { + content = null; + } + return RequestBody.create(MediaType.parse(contentType), content); } else { - 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 { - // 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, GenericType returnType) throws ApiException { - // Handle file downloading. - if (returnType.equals(File.class)) { - @SuppressWarnings("unchecked") - T file = (T) downloadFileFromResponse(response); - return file; - } - - String contentType = null; - List contentTypes = response.getHeaders().get("Content-Type"); - if (contentTypes != null && !contentTypes.isEmpty()) - contentType = String.valueOf(contentTypes.get(0)); - if (contentType == null) - throw new ApiException(500, "missing Content-Type in response"); - - return response.readEntity(returnType); - } - - /** - * Download file from the given response. - * @throws ApiException If fail to read file content from response and write to disk - */ - public File downloadFileFromResponse(Response response) throws ApiException { - try { - File file = prepareDownloadFile(response); - Files.copy(response.readEntity(InputStream.class), file.toPath()); - return file; - } catch (IOException e) { - throw new ApiException(e); - } - } - - public File prepareDownloadFile(Response response) throws IOException { - String filename = null; - String contentDisposition = (String) response.getHeaders().getFirst("Content-Disposition"); - if (contentDisposition != null && !"".equals(contentDisposition)) { - // Get filename from the Content-Disposition header. - Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); - Matcher matcher = pattern.matcher(contentDisposition); - if (matcher.find()) - filename = matcher.group(1); - } - - String prefix = null; - String suffix = null; - if (filename == null) { - prefix = "download-"; - suffix = ""; - } else { - int pos = filename.lastIndexOf("."); - if (pos == -1) { - prefix = filename + "-"; - } else { - prefix = filename.substring(0, pos) + "-"; - suffix = filename.substring(pos); - } - // File.createTempFile requires the prefix to be at least three characters long - if (prefix.length() < 3) - prefix = "download-"; - } - - if (tempFolderPath == null) - return File.createTempFile(prefix, suffix); - else - return File.createTempFile(prefix, suffix, new File(tempFolderPath)); - } - - /** - * Invoke API by sending HTTP request with the given options. - * - * @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 - * @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 - * @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, GenericType returnType) throws ApiException { - updateParamsForAuth(authNames, queryParams, headerParams); - - // Not using `.target(this.basePath).path(path)` below, - // to support (constant) query string in `path`, e.g. "/posts?draft=1" - WebTarget target = httpClient.target(this.basePath + path); - - if (queryParams != null) { - for (Pair queryParam : queryParams) { - if (queryParam.getValue() != null) { - target = target.queryParam(queryParam.getName(), queryParam.getValue()); - } - } - } - - Invocation.Builder invocationBuilder = target.request().accept(accept); - - for (String key : headerParams.keySet()) { - String value = headerParams.get(key); - if (value != null) { - invocationBuilder = invocationBuilder.header(key, value); - } - } - - for (String key : defaultHeaderMap.keySet()) { - if (!headerParams.containsKey(key)) { - String value = defaultHeaderMap.get(key); - if (value != null) { - invocationBuilder = invocationBuilder.header(key, value); - } - } - } - - Entity entity = serialize(body, formParams, contentType); - - Response response = null; - - if ("GET".equals(method)) { - response = invocationBuilder.get(); - } else if ("POST".equals(method)) { - response = invocationBuilder.post(entity); - } else if ("PUT".equals(method)) { - response = invocationBuilder.put(entity); - } else if ("DELETE".equals(method)) { - response = invocationBuilder.delete(); - } else { - throw new ApiException(500, "unknown method type " + method); - } - - statusCode = response.getStatusInfo().getStatusCode(); - responseHeaders = buildResponseHeaders(response); - - if (response.getStatus() == Status.NO_CONTENT.getStatusCode()) { - return null; - } else if (response.getStatusInfo().getFamily().equals(Status.Family.SUCCESSFUL)) { - if (returnType == null) - return null; - else - return deserialize(response, returnType); - } else { - String message = "error"; - String respBody = null; - if (response.hasEntity()) { + throw new ApiException("Content type \"" + contentType + "\" is not supported"); + } + } + + /** + * Download file from the given response. + * + * @param response An instance of the Response object + * @throws ApiException If fail to read file content from response and write to disk + * @return Downloaded file + */ + public File downloadFileFromResponse(Response response) throws ApiException { try { - respBody = String.valueOf(response.readEntity(String.class)); - message = respBody; - } catch (RuntimeException e) { - // e.printStackTrace(); - } - } - throw new ApiException( - response.getStatus(), - message, - buildResponseHeaders(response), - respBody); - } - } - - /** - * Build the Client used to make HTTP requests. - */ - private Client buildHttpClient(boolean debugging) { - final ClientConfig clientConfig = new ClientConfig(); - clientConfig.register(MultiPartFeature.class); - clientConfig.register(json); - clientConfig.register(JacksonFeature.class); - if (debugging) { - clientConfig.register(LoggingFilter.class); - } - return ClientBuilder.newClient(clientConfig); - } - - private Map> buildResponseHeaders(Response response) { - Map> responseHeaders = new HashMap>(); - for (Entry> entry: response.getHeaders().entrySet()) { - List values = entry.getValue(); - List headers = new ArrayList(); - for (Object o : values) { - headers.add(String.valueOf(o)); - } - responseHeaders.put(entry.getKey(), headers); - } - return responseHeaders; - } - - /** - * Update query and header parameters based on authentication settings. - * - * @param authNames The authentications to apply - */ - private void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { - for (String authName : authNames) { - Authentication auth = authentications.get(authName); - if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); - auth.applyToParams(queryParams, headerParams); - } - } + File file = prepareDownloadFile(response); + BufferedSink sink = Okio.buffer(Okio.sink(file)); + sink.writeAll(response.body().source()); + sink.close(); + return file; + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * Prepare file for download + * + * @param response An instance of the Response object + * @throws IOException If fail to prepare file for download + * @return Prepared file for the download + */ + public File prepareDownloadFile(Response response) throws IOException { + String filename = null; + String contentDisposition = response.header("Content-Disposition"); + if (contentDisposition != null && !"".equals(contentDisposition)) { + // Get filename from the Content-Disposition header. + Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); + Matcher matcher = pattern.matcher(contentDisposition); + if (matcher.find()) { + filename = sanitizeFilename(matcher.group(1)); + } + } + + String prefix = null; + String suffix = null; + if (filename == null) { + prefix = "download-"; + suffix = ""; + } else { + int pos = filename.lastIndexOf("."); + if (pos == -1) { + prefix = filename + "-"; + } else { + prefix = filename.substring(0, pos) + "-"; + suffix = filename.substring(pos); + } + // File.createTempFile requires the prefix to be at least three characters long + if (prefix.length() < 3) + prefix = "download-"; + } + + if (tempFolderPath == null) + return File.createTempFile(prefix, suffix); + else + return File.createTempFile(prefix, suffix, new File(tempFolderPath)); + } + + /** + * {@link #execute(Call, Type)} + * + * @param Type + * @param call An instance of the Call object + * @throws ApiException If fail to execute the call + * @return ApiResponse<T> + */ + public ApiResponse execute(Call call) throws ApiException { + return execute(call, null); + } + + /** + * Execute HTTP call and deserialize the HTTP response body into the given return type. + * + * @param returnType The return type used to deserialize HTTP response body + * @param The return type corresponding to (same with) returnType + * @param call Call + * @return ApiResponse object containing response status, headers and + * data, which is a Java object deserialized from response body and would be null + * when returnType is null. + * @throws ApiException If fail to execute the call + */ + public ApiResponse execute(Call call, Type returnType) throws ApiException { + try { + Response response = call.execute(); + T data = handleResponse(response, returnType); + return new ApiResponse(response.code(), response.headers().toMultimap(), data); + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * {@link #executeAsync(Call, Type, ApiCallback)} + * + * @param Type + * @param call An instance of the Call object + * @param callback ApiCallback<T> + */ + public void executeAsync(Call call, ApiCallback callback) { + executeAsync(call, null, callback); + } + + /** + * Execute HTTP call asynchronously. + * + * @see #execute(Call, Type) + * @param Type + * @param call The callback to be executed when the API call finishes + * @param returnType Return type + * @param callback ApiCallback + */ + @SuppressWarnings("unchecked") + public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { + call.enqueue(new Callback() { + @Override + public void onFailure(Request request, IOException e) { + callback.onFailure(new ApiException(e), 0, null); + } + + @Override + public void onResponse(Response response) throws IOException { + T result; + try { + result = (T) handleResponse(response, returnType); + } catch (ApiException e) { + callback.onFailure(e, response.code(), response.headers().toMultimap()); + return; + } + callback.onSuccess(result, response.code(), response.headers().toMultimap()); + } + }); + } + + /** + * Handle the given response, return the deserialized object when the response is successful. + * + * @param Type + * @param response Response + * @param returnType Return type + * @throws ApiException If the response has a unsuccessful status code or + * fail to deserialize the response body + * @return Type + */ + public T handleResponse(Response response, Type returnType) throws ApiException { + if (response.isSuccessful()) { + if (returnType == null || response.code() == 204) { + // returning null if the returnType is not defined, + // or the status code is 204 (No Content) + return null; + } else { + return deserialize(response, returnType); + } + } else { + String respBody = null; + if (response.body() != null) { + try { + respBody = response.body().string(); + } catch (IOException e) { + throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); + } + } + throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); + } + } + + /** + * Build HTTP call with the given options. + * + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param formParams The form parameters + * @param authNames The authentications to apply + * @param progressRequestListener Progress request listener + * @return The HTTP call + * @throws ApiException If fail to serialize the request body object + */ + public Call buildCall(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + updateParamsForAuth(authNames, queryParams, headerParams); + + final String url = buildUrl(path, queryParams); + final Request.Builder reqBuilder = new Request.Builder().url(url); + processHeaderParams(headerParams, reqBuilder); + + String contentType = (String) headerParams.get("Content-Type"); + // ensuring a default content type + if (contentType == null) { + contentType = "application/json"; + } + + RequestBody reqBody; + if (!HttpMethod.permitsRequestBody(method)) { + reqBody = null; + } else if ("application/x-www-form-urlencoded".equals(contentType)) { + reqBody = buildRequestBodyFormEncoding(formParams); + } else if ("multipart/form-data".equals(contentType)) { + reqBody = buildRequestBodyMultipart(formParams); + } else if (body == null) { + if ("DELETE".equals(method)) { + // allow calling DELETE without sending a request body + reqBody = null; + } else { + // use an empty request body (for POST, PUT and PATCH) + reqBody = RequestBody.create(MediaType.parse(contentType), ""); + } + } else { + reqBody = serialize(body, contentType); + } + + Request request = null; + + if(progressRequestListener != null && reqBody != null) { + ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener); + request = reqBuilder.method(method, progressRequestBody).build(); + } else { + request = reqBuilder.method(method, reqBody).build(); + } + + return httpClient.newCall(request); + } + + /** + * Build full URL by concatenating base path, the given sub path and query parameters. + * + * @param path The sub path + * @param queryParams The query parameters + * @return The full URL + */ + public String buildUrl(String path, List queryParams) { + final StringBuilder url = new StringBuilder(); + url.append(basePath).append(path); + + if (queryParams != null && !queryParams.isEmpty()) { + // support (constant) query string in `path`, e.g. "/posts?draft=1" + String prefix = path.contains("?") ? "&" : "?"; + for (Pair param : queryParams) { + if (param.getValue() != null) { + if (prefix != null) { + url.append(prefix); + prefix = null; + } else { + url.append("&"); + } + String value = parameterToString(param.getValue()); + url.append(escapeString(param.getName())).append("=").append(escapeString(value)); + } + } + } + + return url.toString(); + } + + /** + * Set header parameters to the request builder, including default headers. + * + * @param headerParams Header parameters in the ofrm of Map + * @param reqBuilder Reqeust.Builder + */ + public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { + for (Entry param : headerParams.entrySet()) { + reqBuilder.header(param.getKey(), parameterToString(param.getValue())); + } + for (Entry header : defaultHeaderMap.entrySet()) { + if (!headerParams.containsKey(header.getKey())) { + reqBuilder.header(header.getKey(), parameterToString(header.getValue())); + } + } + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + */ + public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); + auth.applyToParams(queryParams, headerParams); + } + } + + /** + * Build a form-encoding request body with the given form parameters. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyFormEncoding(Map formParams) { + FormEncodingBuilder formBuilder = new FormEncodingBuilder(); + for (Entry param : formParams.entrySet()) { + formBuilder.add(param.getKey(), parameterToString(param.getValue())); + } + return formBuilder.build(); + } + + /** + * Build a multipart (file uploading) request body with the given form parameters, + * which could contain text fields and file fields. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyMultipart(Map formParams) { + MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); + for (Entry param : formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\""); + MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); + mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file)); + } else { + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\""); + mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue()))); + } + } + return mpBuilder.build(); + } + + /** + * Guess Content-Type header from the given file (defaults to "application/octet-stream"). + * + * @param file The given file + * @return The guessed Content-Type + */ + public String guessContentTypeFromFile(File file) { + String contentType = URLConnection.guessContentTypeFromName(file.getName()); + if (contentType == null) { + return "application/octet-stream"; + } else { + return contentType; + } + } + + /** + * Initialize datetime format according to the current environment, e.g. Java 1.7 and Android. + */ + private void initDatetimeFormat() { + String formatWithTimeZone = null; + if (IS_ANDROID) { + if (ANDROID_SDK_VERSION >= 18) { + // The time zone format "ZZZZZ" is available since Android 4.3 (SDK version 18) + formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"; + } + } else if (JAVA_VERSION >= 1.7) { + // The time zone format "XXX" is available since Java 1.7 + formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; + } + if (formatWithTimeZone != null) { + this.datetimeFormat = new SimpleDateFormat(formatWithTimeZone); + // NOTE: Use the system's default time zone (mainly for datetime formatting). + } else { + // Use a common format that works across all systems. + this.datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + // Always use the UTC time zone as we are using a constant trailing "Z" here. + this.datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + } + } + + /** + * Apply SSL related settings to httpClient according to the current values of + * verifyingSsl and sslCaCert. + */ + private void applySslSettings() { + try { + KeyManager[] keyManagers = null; + TrustManager[] trustManagers = null; + HostnameVerifier hostnameVerifier = null; + if (!verifyingSsl) { + TrustManager trustAll = new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} + @Override + public X509Certificate[] getAcceptedIssuers() { return null; } + }; + SSLContext sslContext = SSLContext.getInstance("TLS"); + trustManagers = new TrustManager[]{ trustAll }; + hostnameVerifier = new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { return true; } + }; + } else if (sslCaCert != null) { + char[] password = null; // Any password will work. + CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); + Collection certificates = certificateFactory.generateCertificates(sslCaCert); + if (certificates.isEmpty()) { + throw new IllegalArgumentException("expected non-empty set of trusted certificates"); + } + KeyStore caKeyStore = newEmptyKeyStore(password); + int index = 0; + for (Certificate certificate : certificates) { + String certificateAlias = "ca" + Integer.toString(index++); + caKeyStore.setCertificateEntry(certificateAlias, certificate); + } + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagerFactory.init(caKeyStore); + trustManagers = trustManagerFactory.getTrustManagers(); + } + + if (keyManagers != null || trustManagers != null) { + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(keyManagers, trustManagers, new SecureRandom()); + httpClient.setSslSocketFactory(sslContext.getSocketFactory()); + } else { + httpClient.setSslSocketFactory(null); + } + httpClient.setHostnameVerifier(hostnameVerifier); + } catch (GeneralSecurityException e) { + throw new RuntimeException(e); + } + } + + private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { + try { + KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + keyStore.load(null, password); + return keyStore; + } catch (IOException e) { + throw new AssertionError(e); + } + } } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiException.java index 600bb507f09..3bed001f002 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiException.java @@ -1,6 +1,6 @@ /** * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiResponse.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiResponse.java new file mode 100644 index 00000000000..d7dde1ee939 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiResponse.java @@ -0,0 +1,71 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import java.util.List; +import java.util.Map; + +/** + * API response returned by API call. + * + * @param T The type of data that is deserialized from response body + */ +public class ApiResponse { + final private int statusCode; + final private Map> headers; + final private T data; + + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + */ + public ApiResponse(int statusCode, Map> headers) { + this(statusCode, headers, null); + } + + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + * @param data The object deserialized from response bod + */ + public ApiResponse(int statusCode, Map> headers, T data) { + this.statusCode = statusCode; + this.headers = headers; + this.data = data; + } + + public int getStatusCode() { + return statusCode; + } + + public Map> getHeaders() { + return headers; + } + + public T getData() { + return data; + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/Configuration.java index cbdadd6262d..5191b9b73c6 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/Configuration.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/Configuration.java @@ -1,6 +1,6 @@ /** * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/JSON.java index d0feb432d99..11bdce59abf 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/JSON.java @@ -1,36 +1,240 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.*; -import com.fasterxml.jackson.datatype.jsr310.*; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonNull; +import com.google.gson.JsonParseException; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +import java.io.IOException; +import java.io.StringReader; +import java.lang.reflect.Type; +import java.util.Date; + +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +public class JSON { + private ApiClient apiClient; + private Gson gson; -import java.text.DateFormat; + /** + * JSON constructor. + * + * @param apiClient An instance of ApiClient + */ + public JSON(ApiClient apiClient) { + this.apiClient = apiClient; + gson = new GsonBuilder() + .registerTypeAdapter(Date.class, new DateAdapter(apiClient)) + .registerTypeAdapter(OffsetDateTime.class, new OffsetDateTimeTypeAdapter()) + .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) + .create(); + } + + /** + * Get Gson. + * + * @return Gson + */ + public Gson getGson() { + return gson; + } + + /** + * Set Gson. + * + * @param gson Gson + */ + public void setGson(Gson gson) { + this.gson = gson; + } + + /** + * Serialize the given Java object into JSON string. + * + * @param obj Object + * @return String representation of the JSON + */ + public String serialize(Object obj) { + return gson.toJson(obj); + } + + /** + * Deserialize the given JSON string to Java object. + * + * @param Type + * @param body The JSON string + * @param returnType The type to deserialize inot + * @return The deserialized Java object + */ + @SuppressWarnings("unchecked") + public T deserialize(String body, Type returnType) { + try { + if (apiClient.isLenientOnJson()) { + JsonReader jsonReader = new JsonReader(new StringReader(body)); + // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) + jsonReader.setLenient(true); + return gson.fromJson(jsonReader, returnType); + } else { + return gson.fromJson(body, returnType); + } + } catch (JsonParseException e) { + // Fallback processing when failed to parse JSON form response body: + // return the response body string directly for the String return type; + // parse response body into date or datetime for the Date return type. + if (returnType.equals(String.class)) + return (T) body; + else if (returnType.equals(Date.class)) + return (T) apiClient.parseDateOrDatetime(body); + else throw(e); + } + } +} -import javax.ws.rs.ext.ContextResolver; +class DateAdapter implements JsonSerializer, JsonDeserializer { + private final ApiClient apiClient; + /** + * Constructor for DateAdapter + * + * @param apiClient Api client + */ + public DateAdapter(ApiClient apiClient) { + super(); + this.apiClient = apiClient; + } + + /** + * Serialize + * + * @param src Date + * @param typeOfSrc Type + * @param context Json Serialization Context + * @return Json Element + */ + @Override + public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { + if (src == null) { + return JsonNull.INSTANCE; + } else { + return new JsonPrimitive(apiClient.formatDatetime(src)); + } + } + + /** + * Deserialize + * + * @param json Json element + * @param date Type + * @param typeOfSrc Type + * @param context Json Serialization Context + * @return Date + * @throw JsonParseException if fail to parse + */ + @Override + public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException { + String str = json.getAsJsonPrimitive().getAsString(); + try { + return apiClient.parseDateOrDatetime(str); + } catch (RuntimeException e) { + throw new JsonParseException(e); + } + } +} + +/** + * Gson TypeAdapter for jsr310 OffsetDateTime type + */ +class OffsetDateTimeTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME; + + @Override + public void write(JsonWriter out, OffsetDateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.format(date)); + } + } + + @Override + public OffsetDateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + if (date.endsWith("+0000")) { + date = date.substring(0, date.length()-5) + "Z"; + } + + return OffsetDateTime.parse(date, formatter); + } + } +} -public class JSON implements ContextResolver { - private ObjectMapper mapper; +/** + * Gson TypeAdapter for jsr310 LocalDate type + */ +class LocalDateTypeAdapter extends TypeAdapter { - 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 JavaTimeModule()); - } + private final DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE; - /** - * Set the date format for JSON (de)serialization with Date properties. - */ - public void setDateFormat(DateFormat dateFormat) { - mapper.setDateFormat(dateFormat); - } + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.format(date)); + } + } - @Override - public ObjectMapper getContext(Class type) { - return mapper; - } + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return LocalDate.parse(date, formatter); + } + } } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/Pair.java index 4b44c415812..15b247eea93 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/Pair.java @@ -1,6 +1,6 @@ /** * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ProgressRequestBody.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ProgressRequestBody.java new file mode 100644 index 00000000000..d9ca742ecd2 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ProgressRequestBody.java @@ -0,0 +1,95 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.RequestBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSink; +import okio.ForwardingSink; +import okio.Okio; +import okio.Sink; + +public class ProgressRequestBody extends RequestBody { + + public interface ProgressRequestListener { + void onRequestProgress(long bytesWritten, long contentLength, boolean done); + } + + private final RequestBody requestBody; + + private final ProgressRequestListener progressListener; + + private BufferedSink bufferedSink; + + public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) { + this.requestBody = requestBody; + this.progressListener = progressListener; + } + + @Override + public MediaType contentType() { + return requestBody.contentType(); + } + + @Override + public long contentLength() throws IOException { + return requestBody.contentLength(); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + if (bufferedSink == null) { + bufferedSink = Okio.buffer(sink(sink)); + } + + requestBody.writeTo(bufferedSink); + bufferedSink.flush(); + + } + + private Sink sink(Sink sink) { + return new ForwardingSink(sink) { + + long bytesWritten = 0L; + long contentLength = 0L; + + @Override + public void write(Buffer source, long byteCount) throws IOException { + super.write(source, byteCount); + if (contentLength == 0) { + contentLength = contentLength(); + } + + bytesWritten += byteCount; + progressListener.onRequestProgress(bytesWritten, contentLength, bytesWritten == contentLength); + } + }; + } +} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ProgressResponseBody.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ProgressResponseBody.java new file mode 100644 index 00000000000..f8af685999d --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ProgressResponseBody.java @@ -0,0 +1,88 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.ResponseBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSource; +import okio.ForwardingSource; +import okio.Okio; +import okio.Source; + +public class ProgressResponseBody extends ResponseBody { + + public interface ProgressListener { + void update(long bytesRead, long contentLength, boolean done); + } + + private final ResponseBody responseBody; + private final ProgressListener progressListener; + private BufferedSource bufferedSource; + + public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) { + this.responseBody = responseBody; + this.progressListener = progressListener; + } + + @Override + public MediaType contentType() { + return responseBody.contentType(); + } + + @Override + public long contentLength() throws IOException { + return responseBody.contentLength(); + } + + @Override + public BufferedSource source() throws IOException { + if (bufferedSource == null) { + bufferedSource = Okio.buffer(source(responseBody.source())); + } + return bufferedSource; + } + + private Source source(Source source) { + return new ForwardingSource(source) { + long totalBytesRead = 0L; + + @Override + public long read(Buffer sink, long byteCount) throws IOException { + long bytesRead = super.read(sink, byteCount); + // read() returns the number of bytes read, or -1 if this source is exhausted. + totalBytesRead += bytesRead != -1 ? bytesRead : 0; + progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1); + return bytesRead; + } + }; + } +} + + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/StringUtil.java index 03c6c81e434..fdcef6b1010 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ /** * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/FakeApi.java index 7738d3ac259..5935c42e1c3 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/FakeApi.java @@ -1,129 +1,353 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.api; -import io.swagger.client.ApiException; +import io.swagger.client.ApiCallback; import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; import io.swagger.client.Configuration; import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; -import javax.ws.rs.core.GenericType; +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; -import java.time.OffsetDateTime; import java.time.LocalDate; +import java.time.OffsetDateTime; import java.math.BigDecimal; +import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - public class FakeApi { - private ApiClient apiClient; - - public FakeApi() { - this(Configuration.getDefaultApiClient()); - } - - public FakeApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * @param number None (required) - * @param _double None (required) - * @param string None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @throws ApiException if fails to make API call - */ - public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'number' is set - if (number == null) { - throw new ApiException(400, "Missing the required parameter 'number' when calling testEndpointParameters"); + private ApiClient apiClient; + + public FakeApi() { + this(Configuration.getDefaultApiClient()); + } + + public FakeApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; } - - // verify the required parameter '_double' is set - if (_double == null) { - throw new ApiException(400, "Missing the required parameter '_double' when calling testEndpointParameters"); + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; } - - // verify the required parameter 'string' is set - if (string == null) { - throw new ApiException(400, "Missing the required parameter 'string' when calling testEndpointParameters"); + + /* Build call for testEndpointParameters */ + private com.squareup.okhttp.Call testEndpointParametersCall(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'number' is set + if (number == null) { + throw new ApiException("Missing the required parameter 'number' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter '_double' is set + if (_double == null) { + throw new ApiException("Missing the required parameter '_double' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter 'string' is set + if (string == null) { + throw new ApiException("Missing the required parameter 'string' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter '_byte' is set + if (_byte == null) { + throw new ApiException("Missing the required parameter '_byte' when calling testEndpointParameters(Async)"); + } + + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (integer != null) + localVarFormParams.put("integer", integer); + if (int32 != null) + localVarFormParams.put("int32", int32); + if (int64 != null) + localVarFormParams.put("int64", int64); + if (number != null) + localVarFormParams.put("number", number); + if (_float != null) + localVarFormParams.put("float", _float); + if (_double != null) + localVarFormParams.put("double", _double); + if (string != null) + localVarFormParams.put("string", string); + if (_byte != null) + localVarFormParams.put("byte", _byte); + if (binary != null) + localVarFormParams.put("binary", binary); + if (date != null) + localVarFormParams.put("date", date); + if (dateTime != null) + localVarFormParams.put("dateTime", dateTime); + if (password != null) + localVarFormParams.put("password", password); + + final String[] localVarAccepts = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - - // verify the required parameter '_byte' is set - if (_byte == null) { - throw new ApiException(400, "Missing the required parameter '_byte' when calling testEndpointParameters"); + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param string None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password) throws ApiException { + testEndpointParametersWithHttpInfo(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param string None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password) throws ApiException { + com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password, null, null); + return apiClient.execute(call); + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 (asynchronously) + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param string None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call testEndpointParametersAsync(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for testEnumQueryParameters */ + private com.squareup.okhttp.Call testEnumQueryParametersCall(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (enumQueryInteger != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_integer", enumQueryInteger)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (enumQueryString != null) + localVarFormParams.put("enum_query_string", enumQueryString); + if (enumQueryDouble != null) + localVarFormParams.put("enum_query_double", enumQueryDouble); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * To test enum query parameters + * + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void testEnumQueryParameters(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { + testEnumQueryParametersWithHttpInfo(enumQueryString, enumQueryInteger, enumQueryDouble); + } + + /** + * To test enum query parameters + * + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse testEnumQueryParametersWithHttpInfo(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { + com.squareup.okhttp.Call call = testEnumQueryParametersCall(enumQueryString, enumQueryInteger, enumQueryDouble, null, null); + return apiClient.execute(call); + } + + /** + * To test enum query parameters (asynchronously) + * + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call testEnumQueryParametersAsync(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = testEnumQueryParametersCall(enumQueryString, enumQueryInteger, enumQueryDouble, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; } - - // create path and map variables - String localVarPath = "/fake".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - if (integer != null) - localVarFormParams.put("integer", integer); -if (int32 != null) - localVarFormParams.put("int32", int32); -if (int64 != null) - localVarFormParams.put("int64", int64); -if (number != null) - localVarFormParams.put("number", number); -if (_float != null) - localVarFormParams.put("float", _float); -if (_double != null) - localVarFormParams.put("double", _double); -if (string != null) - localVarFormParams.put("string", string); -if (_byte != null) - localVarFormParams.put("byte", _byte); -if (binary != null) - localVarFormParams.put("binary", binary); -if (date != null) - localVarFormParams.put("date", date); -if (dateTime != null) - localVarFormParams.put("dateTime", dateTime); -if (password != null) - localVarFormParams.put("password", password); - - final String[] localVarAccepts = { - "application/xml; charset=utf-8", "application/json; charset=utf-8" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - "application/xml; charset=utf-8", "application/json; charset=utf-8" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/PetApi.java index ad66598406d..2039a8842c1 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/PetApi.java @@ -1,384 +1,935 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.api; -import io.swagger.client.ApiException; +import io.swagger.client.ApiCallback; import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; import io.swagger.client.Configuration; import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; -import javax.ws.rs.core.GenericType; +import java.io.IOException; import io.swagger.client.model.Pet; -import io.swagger.client.model.ModelApiResponse; import java.io.File; +import io.swagger.client.model.ModelApiResponse; +import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - public class PetApi { - private ApiClient apiClient; - - public PetApi() { - this(Configuration.getDefaultApiClient()); - } - - public PetApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store (required) - * @throws ApiException if fails to make API call - */ - public void addPet(Pet body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling addPet"); - } - - // create path and map variables - String localVarPath = "/pet".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - "application/json", "application/xml" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - - apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Deletes a pet - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @throws ApiException if fails to make API call - */ - public void deletePet(Long petId, String apiKey) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling deletePet"); - } - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - if (apiKey != null) - localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - - apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Finds Pets by status - * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for filter (required) - * @return List - * @throws ApiException if fails to make API call - */ - public List findPetsByStatus(List status) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'status' is set - if (status == null) { - throw new ApiException(400, "Missing the required parameter 'status' when calling findPetsByStatus"); - } - - // create path and map variables - String localVarPath = "/pet/findByStatus".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "status", status)); - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - GenericType> localVarReturnType = new GenericType>() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Finds Pets by tags - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by (required) - * @return List - * @throws ApiException if fails to make API call - */ - public List findPetsByTags(List tags) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'tags' is set - if (tags == null) { - throw new ApiException(400, "Missing the required parameter 'tags' when calling findPetsByTags"); - } - - // create path and map variables - String localVarPath = "/pet/findByTags".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "tags", tags)); - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - GenericType> localVarReturnType = new GenericType>() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Find pet by ID - * Returns a single pet - * @param petId ID of pet to return (required) - * @return Pet - * @throws ApiException if fails to make API call - */ - public Pet getPetById(Long petId) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling getPetById"); - } - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "api_key" }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store (required) - * @throws ApiException if fails to make API call - */ - public void updatePet(Pet body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling updatePet"); - } - - // create path and map variables - String localVarPath = "/pet".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - "application/json", "application/xml" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - - apiClient.invokeAPI(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @throws ApiException if fails to make API call - */ - public void updatePetWithForm(Long petId, String name, String status) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling updatePetWithForm"); - } - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - if (name != null) - localVarFormParams.put("name", name); -if (status != null) - localVarFormParams.put("status", status); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - "application/x-www-form-urlencoded" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - - apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * uploads an image - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @return ModelApiResponse - * @throws ApiException if fails to make API call - */ - public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling uploadFile"); - } - - // create path and map variables - String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - if (additionalMetadata != null) - localVarFormParams.put("additionalMetadata", additionalMetadata); -if (file != null) - localVarFormParams.put("file", file); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - "multipart/form-data" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } + private ApiClient apiClient; + + public PetApi() { + this(Configuration.getDefaultApiClient()); + } + + public PetApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for addPet */ + private com.squareup.okhttp.Call addPetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling addPet(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void addPet(Pet body) throws ApiException { + addPetWithHttpInfo(body); + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse addPetWithHttpInfo(Pet body) throws ApiException { + com.squareup.okhttp.Call call = addPetCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Add a new pet to the store (asynchronously) + * + * @param body Pet object that needs to be added to the store (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call addPetAsync(Pet body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = addPetCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for deletePet */ + private com.squareup.okhttp.Call deletePetCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling deletePet(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + if (apiKey != null) + localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deletePet(Long petId, String apiKey) throws ApiException { + deletePetWithHttpInfo(petId, apiKey); + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deletePetWithHttpInfo(Long petId, String apiKey) throws ApiException { + com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, null, null); + return apiClient.execute(call); + } + + /** + * Deletes a pet (asynchronously) + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deletePetAsync(Long petId, String apiKey, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for findPetsByStatus */ + private com.squareup.okhttp.Call findPetsByStatusCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'status' is set + if (status == null) { + throw new ApiException("Missing the required parameter 'status' when calling findPetsByStatus(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/findByStatus".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (status != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "status", status)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return List<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public List findPetsByStatus(List status) throws ApiException { + ApiResponse> resp = findPetsByStatusWithHttpInfo(status); + return resp.getData(); + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return ApiResponse<List<Pet>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> findPetsByStatusWithHttpInfo(List status) throws ApiException { + com.squareup.okhttp.Call call = findPetsByStatusCall(status, null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Finds Pets by status (asynchronously) + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call findPetsByStatusAsync(List status, final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = findPetsByStatusCall(status, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for findPetsByTags */ + private com.squareup.okhttp.Call findPetsByTagsCall(List tags, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'tags' is set + if (tags == null) { + throw new ApiException("Missing the required parameter 'tags' when calling findPetsByTags(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/findByTags".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (tags != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "tags", tags)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return List<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public List findPetsByTags(List tags) throws ApiException { + ApiResponse> resp = findPetsByTagsWithHttpInfo(tags); + return resp.getData(); + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return ApiResponse<List<Pet>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> findPetsByTagsWithHttpInfo(List tags) throws ApiException { + com.squareup.okhttp.Call call = findPetsByTagsCall(tags, null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Finds Pets by tags (asynchronously) + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call findPetsByTagsAsync(List tags, final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = findPetsByTagsCall(tags, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for getPetById */ + private com.squareup.okhttp.Call getPetByIdCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling getPetById(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "api_key" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return Pet + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Pet getPetById(Long petId) throws ApiException { + ApiResponse resp = getPetByIdWithHttpInfo(petId); + return resp.getData(); + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return ApiResponse<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getPetByIdWithHttpInfo(Long petId) throws ApiException { + com.squareup.okhttp.Call call = getPetByIdCall(petId, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Find pet by ID (asynchronously) + * Returns a single pet + * @param petId ID of pet to return (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getPetByIdAsync(Long petId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getPetByIdCall(petId, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for updatePet */ + private com.squareup.okhttp.Call updatePetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling updatePet(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updatePet(Pet body) throws ApiException { + updatePetWithHttpInfo(body); + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updatePetWithHttpInfo(Pet body) throws ApiException { + com.squareup.okhttp.Call call = updatePetCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Update an existing pet (asynchronously) + * + * @param body Pet object that needs to be added to the store (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updatePetAsync(Pet body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updatePetCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for updatePetWithForm */ + private com.squareup.okhttp.Call updatePetWithFormCall(Long petId, String name, String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling updatePetWithForm(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (name != null) + localVarFormParams.put("name", name); + if (status != null) + localVarFormParams.put("status", status); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/x-www-form-urlencoded" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updatePetWithForm(Long petId, String name, String status) throws ApiException { + updatePetWithFormWithHttpInfo(petId, name, status); + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updatePetWithFormWithHttpInfo(Long petId, String name, String status) throws ApiException { + com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, null, null); + return apiClient.execute(call); + } + + /** + * Updates a pet in the store with form data (asynchronously) + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updatePetWithFormAsync(Long petId, String name, String status, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for uploadFile */ + private com.squareup.okhttp.Call uploadFileCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling uploadFile(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (additionalMetadata != null) + localVarFormParams.put("additionalMetadata", additionalMetadata); + if (file != null) + localVarFormParams.put("file", file); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ModelApiResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { + ApiResponse resp = uploadFileWithHttpInfo(petId, additionalMetadata, file); + return resp.getData(); + } + + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ApiResponse<ModelApiResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file) throws ApiException { + com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * uploads an image (asynchronously) + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call uploadFileAsync(Long petId, String additionalMetadata, File file, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/StoreApi.java index c0c9a166ad7..0768744c263 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/StoreApi.java @@ -1,196 +1,482 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.api; -import io.swagger.client.ApiException; +import io.swagger.client.ApiCallback; import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; import io.swagger.client.Configuration; import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; -import javax.ws.rs.core.GenericType; +import java.io.IOException; import io.swagger.client.model.Order; +import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - public class StoreApi { - private ApiClient apiClient; - - public StoreApi() { - this(Configuration.getDefaultApiClient()); - } - - public StoreApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted (required) - * @throws ApiException if fails to make API call - */ - public void deleteOrder(String orderId) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder"); - } - - // create path and map variables - String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - * @return Map - * @throws ApiException if fails to make API call - */ - public Map getInventory() throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/store/inventory".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "api_key" }; - - GenericType> localVarReturnType = new GenericType>() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched (required) - * @return Order - * @throws ApiException if fails to make API call - */ - public Order getOrderById(Long orderId) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById"); - } - - // create path and map variables - String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet (required) - * @return Order - * @throws ApiException if fails to make API call - */ - public Order placeOrder(Order body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling placeOrder"); - } - - // create path and map variables - String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } + private ApiClient apiClient; + + public StoreApi() { + this(Configuration.getDefaultApiClient()); + } + + public StoreApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for deleteOrder */ + private com.squareup.okhttp.Call deleteOrderCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling deleteOrder(Async)"); + } + + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deleteOrder(String orderId) throws ApiException { + deleteOrderWithHttpInfo(orderId); + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deleteOrderWithHttpInfo(String orderId) throws ApiException { + com.squareup.okhttp.Call call = deleteOrderCall(orderId, null, null); + return apiClient.execute(call); + } + + /** + * Delete purchase order by ID (asynchronously) + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deleteOrderAsync(String orderId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = deleteOrderCall(orderId, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for getInventory */ + private com.squareup.okhttp.Call getInventoryCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + + // create path and map variables + String localVarPath = "/store/inventory".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "api_key" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return Map<String, Integer> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Map getInventory() throws ApiException { + ApiResponse> resp = getInventoryWithHttpInfo(); + return resp.getData(); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return ApiResponse<Map<String, Integer>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> getInventoryWithHttpInfo() throws ApiException { + com.squareup.okhttp.Call call = getInventoryCall(null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Returns pet inventories by status (asynchronously) + * Returns a map of status codes to quantities + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getInventoryAsync(final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getInventoryCall(progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for getOrderById */ + private com.squareup.okhttp.Call getOrderByIdCall(Long orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling getOrderById(Async)"); + } + + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @return Order + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Order getOrderById(Long orderId) throws ApiException { + ApiResponse resp = getOrderByIdWithHttpInfo(orderId); + return resp.getData(); + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @return ApiResponse<Order> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getOrderByIdWithHttpInfo(Long orderId) throws ApiException { + com.squareup.okhttp.Call call = getOrderByIdCall(orderId, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Find purchase order by ID (asynchronously) + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getOrderByIdAsync(Long orderId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getOrderByIdCall(orderId, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for placeOrder */ + private com.squareup.okhttp.Call placeOrderCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling placeOrder(Async)"); + } + + + // create path and map variables + String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet (required) + * @return Order + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Order placeOrder(Order body) throws ApiException { + ApiResponse resp = placeOrderWithHttpInfo(body); + return resp.getData(); + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet (required) + * @return ApiResponse<Order> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse placeOrderWithHttpInfo(Order body) throws ApiException { + com.squareup.okhttp.Call call = placeOrderCall(body, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Place an order for a pet (asynchronously) + * + * @param body order placed for purchasing the pet (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call placeOrderAsync(Order body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = placeOrderCall(body, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/UserApi.java index 7602f4e2ba9..1c4fc3101a1 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/UserApi.java @@ -1,370 +1,907 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.api; -import io.swagger.client.ApiException; +import io.swagger.client.ApiCallback; import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; import io.swagger.client.Configuration; import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; -import javax.ws.rs.core.GenericType; +import java.io.IOException; import io.swagger.client.model.User; +import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - public class UserApi { - private ApiClient apiClient; - - public UserApi() { - this(Configuration.getDefaultApiClient()); - } - - public UserApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object (required) - * @throws ApiException if fails to make API call - */ - public void createUser(User body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling createUser"); - } - - // create path and map variables - String localVarPath = "/user".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @throws ApiException if fails to make API call - */ - public void createUsersWithArrayInput(List body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling createUsersWithArrayInput"); - } - - // create path and map variables - String localVarPath = "/user/createWithArray".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @throws ApiException if fails to make API call - */ - public void createUsersWithListInput(List body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling createUsersWithListInput"); - } - - // create path and map variables - String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @throws ApiException if fails to make API call - */ - public void deleteUser(String username) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling deleteUser"); - } - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return User - * @throws ApiException if fails to make API call - */ - public User getUserByName(String username) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling getUserByName"); - } - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Logs user into the system - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @return String - * @throws ApiException if fails to make API call - */ - public String loginUser(String username, String password) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling loginUser"); - } - - // verify the required parameter 'password' is set - if (password == null) { - throw new ApiException(400, "Missing the required parameter 'password' when calling loginUser"); - } - - // create path and map variables - String localVarPath = "/user/login".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - localVarQueryParams.addAll(apiClient.parameterToPairs("", "username", username)); - localVarQueryParams.addAll(apiClient.parameterToPairs("", "password", password)); - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Logs out current logged in user session - * - * @throws ApiException if fails to make API call - */ - public void logoutUser() throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/user/logout".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @throws ApiException if fails to make API call - */ - public void updateUser(String username, User body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser"); - } - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling updateUser"); - } - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } + private ApiClient apiClient; + + public UserApi() { + this(Configuration.getDefaultApiClient()); + } + + public UserApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for createUser */ + private com.squareup.okhttp.Call createUserCall(User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUser(User body) throws ApiException { + createUserWithHttpInfo(body); + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUserWithHttpInfo(User body) throws ApiException { + com.squareup.okhttp.Call call = createUserCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Create user (asynchronously) + * This can only be done by the logged in user. + * @param body Created user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUserAsync(User body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = createUserCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for createUsersWithArrayInput */ + private com.squareup.okhttp.Call createUsersWithArrayInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUsersWithArrayInput(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/createWithArray".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUsersWithArrayInput(List body) throws ApiException { + createUsersWithArrayInputWithHttpInfo(body); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUsersWithArrayInputWithHttpInfo(List body) throws ApiException { + com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Creates list of users with given input array (asynchronously) + * + * @param body List of user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUsersWithArrayInputAsync(List body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for createUsersWithListInput */ + private com.squareup.okhttp.Call createUsersWithListInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUsersWithListInput(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUsersWithListInput(List body) throws ApiException { + createUsersWithListInputWithHttpInfo(body); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUsersWithListInputWithHttpInfo(List body) throws ApiException { + com.squareup.okhttp.Call call = createUsersWithListInputCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Creates list of users with given input array (asynchronously) + * + * @param body List of user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUsersWithListInputAsync(List body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = createUsersWithListInputCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for deleteUser */ + private com.squareup.okhttp.Call deleteUserCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling deleteUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deleteUser(String username) throws ApiException { + deleteUserWithHttpInfo(username); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deleteUserWithHttpInfo(String username) throws ApiException { + com.squareup.okhttp.Call call = deleteUserCall(username, null, null); + return apiClient.execute(call); + } + + /** + * Delete user (asynchronously) + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deleteUserAsync(String username, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = deleteUserCall(username, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for getUserByName */ + private com.squareup.okhttp.Call getUserByNameCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling getUserByName(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return User + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public User getUserByName(String username) throws ApiException { + ApiResponse resp = getUserByNameWithHttpInfo(username); + return resp.getData(); + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return ApiResponse<User> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getUserByNameWithHttpInfo(String username) throws ApiException { + com.squareup.okhttp.Call call = getUserByNameCall(username, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Get user by user name (asynchronously) + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getUserByNameAsync(String username, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getUserByNameCall(username, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for loginUser */ + private com.squareup.okhttp.Call loginUserCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling loginUser(Async)"); + } + + // verify the required parameter 'password' is set + if (password == null) { + throw new ApiException("Missing the required parameter 'password' when calling loginUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/login".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (username != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "username", username)); + if (password != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "password", password)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return String + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public String loginUser(String username, String password) throws ApiException { + ApiResponse resp = loginUserWithHttpInfo(username, password); + return resp.getData(); + } + + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return ApiResponse<String> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse loginUserWithHttpInfo(String username, String password) throws ApiException { + com.squareup.okhttp.Call call = loginUserCall(username, password, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Logs user into the system (asynchronously) + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call loginUserAsync(String username, String password, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = loginUserCall(username, password, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for logoutUser */ + private com.squareup.okhttp.Call logoutUserCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + + // create path and map variables + String localVarPath = "/user/logout".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Logs out current logged in user session + * + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void logoutUser() throws ApiException { + logoutUserWithHttpInfo(); + } + + /** + * Logs out current logged in user session + * + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse logoutUserWithHttpInfo() throws ApiException { + com.squareup.okhttp.Call call = logoutUserCall(null, null); + return apiClient.execute(call); + } + + /** + * Logs out current logged in user session (asynchronously) + * + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call logoutUserAsync(final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = logoutUserCall(progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for updateUser */ + private com.squareup.okhttp.Call updateUserCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling updateUser(Async)"); + } + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling updateUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updateUser(String username, User body) throws ApiException { + updateUserWithHttpInfo(username, body); + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updateUserWithHttpInfo(String username, User body) throws ApiException { + com.squareup.okhttp.Call call = updateUserCall(username, body, null, null); + return apiClient.execute(call); + } + + /** + * Updated user (asynchronously) + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updateUserAsync(String username, User body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updateUserCall(username, body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index 6ba15566b60..a125fff5f24 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -1,6 +1,6 @@ /** * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/Authentication.java index a063a6998b5..221a7d9dd1f 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/Authentication.java @@ -1,6 +1,6 @@ /** * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 5895370e4d4..4eb2300b69d 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -1,6 +1,6 @@ /** * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io @@ -27,44 +27,40 @@ import io.swagger.client.Pair; -import com.migcomponents.migbase64.Base64; +import com.squareup.okhttp.Credentials; import java.util.Map; import java.util.List; import java.io.UnsupportedEncodingException; - public class HttpBasicAuth implements Authentication { - private String username; - private String password; - - public String getUsername() { - return username; - } + private String username; + private String password; - public void setUsername(String username) { - this.username = username; - } + public String getUsername() { + return username; + } - public String getPassword() { - return password; - } + public void setUsername(String username) { + this.username = username; + } - public void setPassword(String password) { - this.password = password; - } + public String getPassword() { + return password; + } - @Override - public void applyToParams(List queryParams, Map headerParams) { - if (username == null && password == null) { - return; + public void setPassword(String password) { + this.password = password; } - String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); - try { - headerParams.put("Authorization", "Basic " + Base64.encodeToString(str.getBytes("UTF-8"), false)); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); + + @Override + public void applyToParams(List queryParams, Map headerParams) { + if (username == null && password == null) { + return; + } + headerParams.put("Authorization", Credentials.basic( + username == null ? "" : username, + password == null ? "" : password)); } - } } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/OAuth.java index 8802ebc92c8..14521f6ed7e 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/OAuth.java @@ -1,6 +1,6 @@ /** * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/OAuthFlow.java index ec1f942b0f2..50d5260cfd9 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,6 +1,6 @@ /** * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index ccaba7709c4..1943e013fa1 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; @@ -15,40 +39,44 @@ */ public class AdditionalPropertiesClass { - + @SerializedName("map_property") private Map mapProperty = new HashMap(); + + @SerializedName("map_of_map_property") private Map> mapOfMapProperty = new HashMap>(); - - /** - **/ public AdditionalPropertiesClass mapProperty(Map mapProperty) { this.mapProperty = mapProperty; return this; } - + + /** + * Get mapProperty + * @return mapProperty + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("map_property") public Map getMapProperty() { return mapProperty; } + public void setMapProperty(Map mapProperty) { this.mapProperty = mapProperty; } - - /** - **/ public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { this.mapOfMapProperty = mapOfMapProperty; return this; } - + + /** + * Get mapOfMapProperty + * @return mapOfMapProperty + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("map_of_map_property") public Map> getMapOfMapProperty() { return mapOfMapProperty; } + public void setMapOfMapProperty(Map> mapOfMapProperty) { this.mapOfMapProperty = mapOfMapProperty; } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Animal.java index 25c7d3e421c..ba3806dc875 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Animal.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,40 +36,44 @@ */ public class Animal { - + @SerializedName("className") private String className = null; + + @SerializedName("color") private String color = "red"; - - /** - **/ public Animal className(String className) { this.className = className; return this; } - + + /** + * Get className + * @return className + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("className") public String getClassName() { return className; } + public void setClassName(String className) { this.className = className; } - - /** - **/ public Animal color(String color) { this.color = color; return this; } - + + /** + * Get color + * @return color + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("color") public String getColor() { return color; } + public void setColor(String color) { this.color = color; } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AnimalFarm.java index 647e3a893e1..b54adb09d7b 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -1,6 +1,30 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import io.swagger.client.model.Animal; import java.util.ArrayList; @@ -12,9 +36,7 @@ */ public class AnimalFarm extends ArrayList { - - @Override public boolean equals(java.lang.Object o) { if (this == o) { diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 00000000000..5446c2c439b --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,102 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + + +/** + * ArrayOfArrayOfNumberOnly + */ + +public class ArrayOfArrayOfNumberOnly { + @SerializedName("ArrayArrayNumber") + private List> arrayArrayNumber = new ArrayList>(); + + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + /** + * Get arrayArrayNumber + * @return arrayArrayNumber + **/ + @ApiModelProperty(example = "null", value = "") + public List> getArrayArrayNumber() { + return arrayArrayNumber; + } + + public void setArrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly = (ArrayOfArrayOfNumberOnly) o; + return Objects.equals(this.arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayArrayNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfArrayOfNumberOnly {\n"); + + sb.append(" arrayArrayNumber: ").append(toIndentedString(arrayArrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java new file mode 100644 index 00000000000..c9257a5d3ee --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -0,0 +1,102 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + + +/** + * ArrayOfNumberOnly + */ + +public class ArrayOfNumberOnly { + @SerializedName("ArrayNumber") + private List arrayNumber = new ArrayList(); + + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + /** + * Get arrayNumber + * @return arrayNumber + **/ + @ApiModelProperty(example = "null", value = "") + public List getArrayNumber() { + return arrayNumber; + } + + public void setArrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfNumberOnly arrayOfNumberOnly = (ArrayOfNumberOnly) o; + return Objects.equals(this.arrayNumber, arrayOfNumberOnly.arrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfNumberOnly {\n"); + + sb.append(" arrayNumber: ").append(toIndentedString(arrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayTest.java index 6c1eb23d8d0..8d58870bcdc 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayTest.java @@ -1,10 +1,35 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.ReadOnlyFirst; import java.util.ArrayList; import java.util.List; @@ -14,58 +39,65 @@ */ public class ArrayTest { - + @SerializedName("array_of_string") private List arrayOfString = new ArrayList(); + + @SerializedName("array_array_of_integer") private List> arrayArrayOfInteger = new ArrayList>(); + + @SerializedName("array_array_of_model") private List> arrayArrayOfModel = new ArrayList>(); - - /** - **/ public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; return this; } - + + /** + * Get arrayOfString + * @return arrayOfString + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("array_of_string") public List getArrayOfString() { return arrayOfString; } + public void setArrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; } - - /** - **/ public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; return this; } - + + /** + * Get arrayArrayOfInteger + * @return arrayArrayOfInteger + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("array_array_of_integer") public List> getArrayArrayOfInteger() { return arrayArrayOfInteger; } + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - - /** - **/ public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } - + + /** + * Get arrayArrayOfModel + * @return arrayArrayOfModel + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("array_array_of_model") public List> getArrayArrayOfModel() { return arrayArrayOfModel; } + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Cat.java index 5ef9e23bd96..21ed0f4c26b 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Cat.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -13,58 +37,65 @@ */ public class Cat extends Animal { - + @SerializedName("className") private String className = null; + + @SerializedName("color") private String color = "red"; + + @SerializedName("declawed") private Boolean declawed = null; - - /** - **/ public Cat className(String className) { this.className = className; return this; } - + + /** + * Get className + * @return className + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("className") public String getClassName() { return className; } + public void setClassName(String className) { this.className = className; } - - /** - **/ public Cat color(String color) { this.color = color; return this; } - + + /** + * Get color + * @return color + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("color") public String getColor() { return color; } + public void setColor(String color) { this.color = color; } - - /** - **/ public Cat declawed(Boolean declawed) { this.declawed = declawed; return this; } - + + /** + * Get declawed + * @return declawed + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("declawed") public Boolean getDeclawed() { return declawed; } + public void setDeclawed(Boolean declawed) { this.declawed = declawed; } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Category.java index c6cb703a89e..2178a866f62 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Category.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,40 +36,44 @@ */ public class Category { - + @SerializedName("id") private Long id = null; + + @SerializedName("name") private String name = null; - - /** - **/ public Category id(Long id) { this.id = id; return this; } - + + /** + * Get id + * @return id + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - - /** - **/ public Category name(String name) { this.name = name; return this; } - + + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Dog.java index 4b3cc947cc5..4ba5804553f 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Dog.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -13,58 +37,65 @@ */ public class Dog extends Animal { - + @SerializedName("className") private String className = null; + + @SerializedName("color") private String color = "red"; + + @SerializedName("breed") private String breed = null; - - /** - **/ public Dog className(String className) { this.className = className; return this; } - + + /** + * Get className + * @return className + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("className") public String getClassName() { return className; } + public void setClassName(String className) { this.className = className; } - - /** - **/ public Dog color(String color) { this.color = color; return this; } - + + /** + * Get color + * @return color + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("color") public String getColor() { return color; } + public void setColor(String color) { this.color = color; } - - /** - **/ public Dog breed(String breed) { this.breed = breed; return this; } - + + /** + * Get breed + * @return breed + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("breed") public String getBreed() { return breed; } + public void setBreed(String breed) { this.breed = breed; } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumClass.java index 42434e297ff..73484907229 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumClass.java @@ -1,16 +1,46 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonValue; +import com.google.gson.annotations.SerializedName; /** * Gets or Sets EnumClass */ public enum EnumClass { + + @SerializedName("_abc") _ABC("_abc"), + + @SerializedName("-efg") _EFG("-efg"), + + @SerializedName("(xyz)") _XYZ_("(xyz)"); private String value; @@ -20,7 +50,6 @@ public enum EnumClass { } @Override - @JsonValue public String toString() { return String.valueOf(value); } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumTest.java index 1c8657fd3ec..9aad1223215 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumTest.java @@ -1,9 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonValue; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -13,13 +36,14 @@ */ public class EnumTest { - - /** * Gets or Sets enumString */ public enum EnumStringEnum { + @SerializedName("UPPER") UPPER("UPPER"), + + @SerializedName("lower") LOWER("lower"); private String value; @@ -29,19 +53,22 @@ public enum EnumStringEnum { } @Override - @JsonValue public String toString() { return String.valueOf(value); } } + @SerializedName("enum_string") private EnumStringEnum enumString = null; /** * Gets or Sets enumInteger */ public enum EnumIntegerEnum { + @SerializedName("1") NUMBER_1(1), + + @SerializedName("-1") NUMBER_MINUS_1(-1); private Integer value; @@ -51,19 +78,22 @@ public enum EnumIntegerEnum { } @Override - @JsonValue public String toString() { return String.valueOf(value); } } + @SerializedName("enum_integer") private EnumIntegerEnum enumInteger = null; /** * Gets or Sets enumNumber */ public enum EnumNumberEnum { + @SerializedName("1.1") NUMBER_1_DOT_1(1.1), + + @SerializedName("-1.2") NUMBER_MINUS_1_DOT_2(-1.2); private Double value; @@ -73,61 +103,64 @@ public enum EnumNumberEnum { } @Override - @JsonValue public String toString() { return String.valueOf(value); } } + @SerializedName("enum_number") private EnumNumberEnum enumNumber = null; - - /** - **/ public EnumTest enumString(EnumStringEnum enumString) { this.enumString = enumString; return this; } - + + /** + * Get enumString + * @return enumString + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("enum_string") public EnumStringEnum getEnumString() { return enumString; } + public void setEnumString(EnumStringEnum enumString) { this.enumString = enumString; } - - /** - **/ public EnumTest enumInteger(EnumIntegerEnum enumInteger) { this.enumInteger = enumInteger; return this; } - + + /** + * Get enumInteger + * @return enumInteger + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("enum_integer") public EnumIntegerEnum getEnumInteger() { return enumInteger; } + public void setEnumInteger(EnumIntegerEnum enumInteger) { this.enumInteger = enumInteger; } - - /** - **/ public EnumTest enumNumber(EnumNumberEnum enumNumber) { this.enumNumber = enumNumber; return this; } - + + /** + * Get enumNumber + * @return enumNumber + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("enum_number") public EnumNumberEnum getEnumNumber() { return enumNumber; } + public void setEnumNumber(EnumNumberEnum enumNumber) { this.enumNumber = enumNumber; } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/FormatTest.java index fce146a9b6a..4f7b82a92a1 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/FormatTest.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; @@ -15,248 +39,285 @@ */ public class FormatTest { - + @SerializedName("integer") private Integer integer = null; + + @SerializedName("int32") private Integer int32 = null; + + @SerializedName("int64") private Long int64 = null; + + @SerializedName("number") private BigDecimal number = null; + + @SerializedName("float") private Float _float = null; + + @SerializedName("double") private Double _double = null; + + @SerializedName("string") private String string = null; + + @SerializedName("byte") private byte[] _byte = null; + + @SerializedName("binary") private byte[] binary = null; + + @SerializedName("date") private LocalDate date = null; + + @SerializedName("dateTime") private OffsetDateTime dateTime = null; + + @SerializedName("uuid") private String uuid = null; + + @SerializedName("password") private String password = null; - - /** - * minimum: 10.0 - * maximum: 100.0 - **/ public FormatTest integer(Integer integer) { this.integer = integer; return this; } - + + /** + * Get integer + * minimum: 10.0 + * maximum: 100.0 + * @return integer + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("integer") public Integer getInteger() { return integer; } + public void setInteger(Integer integer) { this.integer = integer; } - - /** - * minimum: 20.0 - * maximum: 200.0 - **/ public FormatTest int32(Integer int32) { this.int32 = int32; return this; } - + + /** + * Get int32 + * minimum: 20.0 + * maximum: 200.0 + * @return int32 + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("int32") public Integer getInt32() { return int32; } + public void setInt32(Integer int32) { this.int32 = int32; } - - /** - **/ public FormatTest int64(Long int64) { this.int64 = int64; return this; } - + + /** + * Get int64 + * @return int64 + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("int64") public Long getInt64() { return int64; } + public void setInt64(Long int64) { this.int64 = int64; } - - /** - * minimum: 32.1 - * maximum: 543.2 - **/ public FormatTest number(BigDecimal number) { this.number = number; return this; } - + + /** + * Get number + * minimum: 32.1 + * maximum: 543.2 + * @return number + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("number") public BigDecimal getNumber() { return number; } + public void setNumber(BigDecimal number) { this.number = number; } - - /** - * minimum: 54.3 - * maximum: 987.6 - **/ public FormatTest _float(Float _float) { this._float = _float; return this; } - + + /** + * Get _float + * minimum: 54.3 + * maximum: 987.6 + * @return _float + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("float") public Float getFloat() { return _float; } + public void setFloat(Float _float) { this._float = _float; } - - /** - * minimum: 67.8 - * maximum: 123.4 - **/ public FormatTest _double(Double _double) { this._double = _double; return this; } - + + /** + * Get _double + * minimum: 67.8 + * maximum: 123.4 + * @return _double + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("double") public Double getDouble() { return _double; } + public void setDouble(Double _double) { this._double = _double; } - - /** - **/ public FormatTest string(String string) { this.string = string; return this; } - + + /** + * Get string + * @return string + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("string") public String getString() { return string; } + public void setString(String string) { this.string = string; } - - /** - **/ public FormatTest _byte(byte[] _byte) { this._byte = _byte; return this; } - + + /** + * Get _byte + * @return _byte + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("byte") public byte[] getByte() { return _byte; } + public void setByte(byte[] _byte) { this._byte = _byte; } - - /** - **/ public FormatTest binary(byte[] binary) { this.binary = binary; return this; } - + + /** + * Get binary + * @return binary + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("binary") public byte[] getBinary() { return binary; } + public void setBinary(byte[] binary) { this.binary = binary; } - - /** - **/ public FormatTest date(LocalDate date) { this.date = date; return this; } - + + /** + * Get date + * @return date + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("date") public LocalDate getDate() { return date; } + public void setDate(LocalDate date) { this.date = date; } - - /** - **/ public FormatTest dateTime(OffsetDateTime dateTime) { this.dateTime = dateTime; return this; } - + + /** + * Get dateTime + * @return dateTime + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("dateTime") public OffsetDateTime getDateTime() { return dateTime; } + public void setDateTime(OffsetDateTime dateTime) { this.dateTime = dateTime; } - - /** - **/ public FormatTest uuid(String uuid) { this.uuid = uuid; return this; } - + + /** + * Get uuid + * @return uuid + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("uuid") public String getUuid() { return uuid; } + public void setUuid(String uuid) { this.uuid = uuid; } - - /** - **/ public FormatTest password(String password) { this.password = password; return this; } - + + /** + * Get password + * @return password + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("password") public String getPassword() { return password; } + public void setPassword(String password) { this.password = password; } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java new file mode 100644 index 00000000000..d77fc7ac36b --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -0,0 +1,104 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +/** + * HasOnlyReadOnly + */ + +public class HasOnlyReadOnly { + @SerializedName("bar") + private String bar = null; + + @SerializedName("foo") + private String foo = null; + + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(example = "null", value = "") + public String getBar() { + return bar; + } + + /** + * Get foo + * @return foo + **/ + @ApiModelProperty(example = "null", value = "") + public String getFoo() { + return foo; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HasOnlyReadOnly hasOnlyReadOnly = (HasOnlyReadOnly) o; + return Objects.equals(this.bar, hasOnlyReadOnly.bar) && + Objects.equals(this.foo, hasOnlyReadOnly.foo); + } + + @Override + public int hashCode() { + return Objects.hash(bar, foo); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HasOnlyReadOnly {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" foo: ").append(toIndentedString(foo)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MapTest.java new file mode 100644 index 00000000000..61bdb6b2c65 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MapTest.java @@ -0,0 +1,147 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +/** + * MapTest + */ + +public class MapTest { + @SerializedName("map_map_of_string") + private Map> mapMapOfString = new HashMap>(); + + /** + * Gets or Sets inner + */ + public enum InnerEnum { + @SerializedName("UPPER") + UPPER("UPPER"), + + @SerializedName("lower") + LOWER("lower"); + + private String value; + + InnerEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + @SerializedName("map_of_enum_string") + private Map mapOfEnumString = new HashMap(); + + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + /** + * Get mapMapOfString + * @return mapMapOfString + **/ + @ApiModelProperty(example = "null", value = "") + public Map> getMapMapOfString() { + return mapMapOfString; + } + + public void setMapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + } + + public MapTest mapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + return this; + } + + /** + * Get mapOfEnumString + * @return mapOfEnumString + **/ + @ApiModelProperty(example = "null", value = "") + public Map getMapOfEnumString() { + return mapOfEnumString; + } + + public void setMapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MapTest mapTest = (MapTest) o; + return Objects.equals(this.mapMapOfString, mapTest.mapMapOfString) && + Objects.equals(this.mapOfEnumString, mapTest.mapOfEnumString); + } + + @Override + public int hashCode() { + return Objects.hash(mapMapOfString, mapOfEnumString); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MapTest {\n"); + + sb.append(" mapMapOfString: ").append(toIndentedString(mapMapOfString)).append("\n"); + sb.append(" mapOfEnumString: ").append(toIndentedString(mapOfEnumString)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 5227df8a692..2eefddfc9a1 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -17,58 +41,65 @@ */ public class MixedPropertiesAndAdditionalPropertiesClass { - + @SerializedName("uuid") private String uuid = null; + + @SerializedName("dateTime") private OffsetDateTime dateTime = null; + + @SerializedName("map") private Map map = new HashMap(); - - /** - **/ public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { this.uuid = uuid; return this; } - + + /** + * Get uuid + * @return uuid + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("uuid") public String getUuid() { return uuid; } + public void setUuid(String uuid) { this.uuid = uuid; } - - /** - **/ public MixedPropertiesAndAdditionalPropertiesClass dateTime(OffsetDateTime dateTime) { this.dateTime = dateTime; return this; } - + + /** + * Get dateTime + * @return dateTime + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("dateTime") public OffsetDateTime getDateTime() { return dateTime; } + public void setDateTime(OffsetDateTime dateTime) { this.dateTime = dateTime; } - - /** - **/ public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { this.map = map; return this; } - + + /** + * Get map + * @return map + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("map") public Map getMap() { return map; } + public void setMap(Map map) { this.map = map; } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Model200Response.java index b2809525c7f..d8da58aca9c 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Model200Response.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -13,26 +37,48 @@ @ApiModel(description = "Model for testing model name starting with number") public class Model200Response { - + @SerializedName("name") private Integer name = null; - - /** - **/ + @SerializedName("class") + private String PropertyClass = null; + public Model200Response name(Integer name) { this.name = name; return this; } - + + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("name") public Integer getName() { return name; } + public void setName(Integer name) { this.name = name; } + public Model200Response PropertyClass(String PropertyClass) { + this.PropertyClass = PropertyClass; + return this; + } + + /** + * Get PropertyClass + * @return PropertyClass + **/ + @ApiModelProperty(example = "null", value = "") + public String getPropertyClass() { + return PropertyClass; + } + + public void setPropertyClass(String PropertyClass) { + this.PropertyClass = PropertyClass; + } + @Override public boolean equals(java.lang.Object o) { @@ -43,12 +89,13 @@ public boolean equals(java.lang.Object o) { return false; } Model200Response _200Response = (Model200Response) o; - return Objects.equals(this.name, _200Response.name); + return Objects.equals(this.name, _200Response.name) && + Objects.equals(this.PropertyClass, _200Response.PropertyClass); } @Override public int hashCode() { - return Objects.hash(name); + return Objects.hash(name, PropertyClass); } @Override @@ -57,6 +104,7 @@ public String toString() { sb.append("class Model200Response {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" PropertyClass: ").append(toIndentedString(PropertyClass)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelApiResponse.java index 32fb86dd323..2a823298323 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,58 +36,65 @@ */ public class ModelApiResponse { - + @SerializedName("code") private Integer code = null; + + @SerializedName("type") private String type = null; + + @SerializedName("message") private String message = null; - - /** - **/ public ModelApiResponse code(Integer code) { this.code = code; return this; } - + + /** + * Get code + * @return code + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("code") public Integer getCode() { return code; } + public void setCode(Integer code) { this.code = code; } - - /** - **/ public ModelApiResponse type(String type) { this.type = type; return this; } - + + /** + * Get type + * @return type + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("type") public String getType() { return type; } + public void setType(String type) { this.type = type; } - - /** - **/ public ModelApiResponse message(String message) { this.message = message; return this; } - + + /** + * Get message + * @return message + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("message") public String getMessage() { return message; } + public void setMessage(String message) { this.message = message; } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelReturn.java index a076d16f964..024a9c0df1c 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelReturn.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -13,22 +37,23 @@ @ApiModel(description = "Model for testing reserved words") public class ModelReturn { - + @SerializedName("return") private Integer _return = null; - - /** - **/ public ModelReturn _return(Integer _return) { this._return = _return; return this; } - + + /** + * Get _return + * @return _return + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("return") public Integer getReturn() { return _return; } + public void setReturn(Integer _return) { this._return = _return; } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Name.java index 1ba2cc5e4a3..318a2ddd50e 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Name.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -13,56 +37,68 @@ @ApiModel(description = "Model for testing model name same as property name") public class Name { - + @SerializedName("name") private Integer name = null; + + @SerializedName("snake_case") private Integer snakeCase = null; + + @SerializedName("property") private String property = null; + + @SerializedName("123Number") private Integer _123Number = null; - - /** - **/ public Name name(Integer name) { this.name = name; return this; } - + + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("name") public Integer getName() { return name; } + public void setName(Integer name) { this.name = name; } - + /** + * Get snakeCase + * @return snakeCase + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("snake_case") public Integer getSnakeCase() { return snakeCase; } - - /** - **/ public Name property(String property) { this.property = property; return this; } - + + /** + * Get property + * @return property + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("property") public String getProperty() { return property; } + public void setProperty(String property) { this.property = property; } - + /** + * Get _123Number + * @return _123Number + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("123Number") public Integer get123Number() { return _123Number; } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/NumberOnly.java new file mode 100644 index 00000000000..9b9ca048dfb --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/NumberOnly.java @@ -0,0 +1,100 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; + + +/** + * NumberOnly + */ + +public class NumberOnly { + @SerializedName("JustNumber") + private BigDecimal justNumber = null; + + public NumberOnly justNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + return this; + } + + /** + * Get justNumber + * @return justNumber + **/ + @ApiModelProperty(example = "null", value = "") + public BigDecimal getJustNumber() { + return justNumber; + } + + public void setJustNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NumberOnly numberOnly = (NumberOnly) o; + return Objects.equals(this.justNumber, numberOnly.justNumber); + } + + @Override + public int hashCode() { + return Objects.hash(justNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NumberOnly {\n"); + + sb.append(" justNumber: ").append(toIndentedString(justNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Order.java index 132e0494f17..eaf4397c4bf 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Order.java @@ -1,9 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonValue; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.time.OffsetDateTime; @@ -14,18 +37,29 @@ */ public class Order { - + @SerializedName("id") private Long id = null; + + @SerializedName("petId") private Long petId = null; + + @SerializedName("quantity") private Integer quantity = null; + + @SerializedName("shipDate") private OffsetDateTime shipDate = null; /** * Order Status */ public enum StatusEnum { + @SerializedName("placed") PLACED("placed"), + + @SerializedName("approved") APPROVED("approved"), + + @SerializedName("delivered") DELIVERED("delivered"); private String value; @@ -35,114 +69,121 @@ public enum StatusEnum { } @Override - @JsonValue public String toString() { return String.valueOf(value); } } + @SerializedName("status") private StatusEnum status = null; + + @SerializedName("complete") private Boolean complete = false; - - /** - **/ public Order id(Long id) { this.id = id; return this; } - + + /** + * Get id + * @return id + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - - /** - **/ public Order petId(Long petId) { this.petId = petId; return this; } - + + /** + * Get petId + * @return petId + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("petId") public Long getPetId() { return petId; } + public void setPetId(Long petId) { this.petId = petId; } - - /** - **/ public Order quantity(Integer quantity) { this.quantity = quantity; return this; } - + + /** + * Get quantity + * @return quantity + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("quantity") public Integer getQuantity() { return quantity; } + public void setQuantity(Integer quantity) { this.quantity = quantity; } - - /** - **/ public Order shipDate(OffsetDateTime shipDate) { this.shipDate = shipDate; return this; } - + + /** + * Get shipDate + * @return shipDate + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("shipDate") public OffsetDateTime getShipDate() { return shipDate; } + public void setShipDate(OffsetDateTime shipDate) { this.shipDate = shipDate; } - - /** - * Order Status - **/ public Order status(StatusEnum status) { this.status = status; return this; } - + + /** + * Order Status + * @return status + **/ @ApiModelProperty(example = "null", value = "Order Status") - @JsonProperty("status") public StatusEnum getStatus() { return status; } + public void setStatus(StatusEnum status) { this.status = status; } - - /** - **/ public Order complete(Boolean complete) { this.complete = complete; return this; } - + + /** + * Get complete + * @return complete + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("complete") public Boolean getComplete() { return complete; } + public void setComplete(Boolean complete) { this.complete = complete; } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Pet.java index da8b76ad024..b80fdeaf923 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Pet.java @@ -1,9 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonValue; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Category; @@ -17,19 +40,32 @@ */ public class Pet { - + @SerializedName("id") private Long id = null; + + @SerializedName("category") private Category category = null; + + @SerializedName("name") private String name = null; + + @SerializedName("photoUrls") private List photoUrls = new ArrayList(); + + @SerializedName("tags") private List tags = new ArrayList(); /** * pet status in the store */ public enum StatusEnum { + @SerializedName("available") AVAILABLE("available"), + + @SerializedName("pending") PENDING("pending"), + + @SerializedName("sold") SOLD("sold"); private String value; @@ -39,113 +75,118 @@ public enum StatusEnum { } @Override - @JsonValue public String toString() { return String.valueOf(value); } } + @SerializedName("status") private StatusEnum status = null; - - /** - **/ public Pet id(Long id) { this.id = id; return this; } - + + /** + * Get id + * @return id + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - - /** - **/ public Pet category(Category category) { this.category = category; return this; } - + + /** + * Get category + * @return category + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("category") public Category getCategory() { return category; } + public void setCategory(Category category) { this.category = category; } - - /** - **/ public Pet name(String name) { this.name = name; return this; } - + + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "doggie", required = true, value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } - - /** - **/ public Pet photoUrls(List photoUrls) { this.photoUrls = photoUrls; return this; } - + + /** + * Get photoUrls + * @return photoUrls + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("photoUrls") public List getPhotoUrls() { return photoUrls; } + public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } - - /** - **/ public Pet tags(List tags) { this.tags = tags; return this; } - + + /** + * Get tags + * @return tags + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("tags") public List getTags() { return tags; } + public void setTags(List tags) { this.tags = tags; } - - /** - * pet status in the store - **/ public Pet status(StatusEnum status) { this.status = status; return this; } - + + /** + * pet status in the store + * @return status + **/ @ApiModelProperty(example = "null", value = "pet status in the store") - @JsonProperty("status") public StatusEnum getStatus() { return status; } + public void setStatus(StatusEnum status) { this.status = status; } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index fdc3587df0e..13b729bb94d 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,30 +36,35 @@ */ public class ReadOnlyFirst { - + @SerializedName("bar") private String bar = null; + + @SerializedName("baz") private String baz = null; - + /** + * Get bar + * @return bar + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("bar") public String getBar() { return bar; } - - /** - **/ public ReadOnlyFirst baz(String baz) { this.baz = baz; return this; } - + + /** + * Get baz + * @return baz + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("baz") public String getBaz() { return baz; } + public void setBaz(String baz) { this.baz = baz; } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/SpecialModelName.java index 24e57756cb2..b46b8367a01 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,22 +36,23 @@ */ public class SpecialModelName { - + @SerializedName("$special[property.name]") private Long specialPropertyName = null; - - /** - **/ public SpecialModelName specialPropertyName(Long specialPropertyName) { this.specialPropertyName = specialPropertyName; return this; } - + + /** + * Get specialPropertyName + * @return specialPropertyName + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("$special[property.name]") public Long getSpecialPropertyName() { return specialPropertyName; } + public void setSpecialPropertyName(Long specialPropertyName) { this.specialPropertyName = specialPropertyName; } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Tag.java index 9d3bdd8cb9e..e56eb535d1e 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Tag.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,40 +36,44 @@ */ public class Tag { - + @SerializedName("id") private Long id = null; + + @SerializedName("name") private String name = null; - - /** - **/ public Tag id(Long id) { this.id = id; return this; } - + + /** + * Get id + * @return id + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - - /** - **/ public Tag name(String name) { this.name = name; return this; } - + + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/User.java index f23553660de..6c1ed6ceacc 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/User.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,149 +36,170 @@ */ public class User { - + @SerializedName("id") private Long id = null; + + @SerializedName("username") private String username = null; + + @SerializedName("firstName") private String firstName = null; + + @SerializedName("lastName") private String lastName = null; + + @SerializedName("email") private String email = null; + + @SerializedName("password") private String password = null; + + @SerializedName("phone") private String phone = null; + + @SerializedName("userStatus") private Integer userStatus = null; - - /** - **/ public User id(Long id) { this.id = id; return this; } - + + /** + * Get id + * @return id + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - - /** - **/ public User username(String username) { this.username = username; return this; } - + + /** + * Get username + * @return username + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("username") public String getUsername() { return username; } + public void setUsername(String username) { this.username = username; } - - /** - **/ public User firstName(String firstName) { this.firstName = firstName; return this; } - + + /** + * Get firstName + * @return firstName + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("firstName") public String getFirstName() { return firstName; } + public void setFirstName(String firstName) { this.firstName = firstName; } - - /** - **/ public User lastName(String lastName) { this.lastName = lastName; return this; } - + + /** + * Get lastName + * @return lastName + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("lastName") public String getLastName() { return lastName; } + public void setLastName(String lastName) { this.lastName = lastName; } - - /** - **/ public User email(String email) { this.email = email; return this; } - + + /** + * Get email + * @return email + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("email") public String getEmail() { return email; } + public void setEmail(String email) { this.email = email; } - - /** - **/ public User password(String password) { this.password = password; return this; } - + + /** + * Get password + * @return password + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("password") public String getPassword() { return password; } + public void setPassword(String password) { this.password = password; } - - /** - **/ public User phone(String phone) { this.phone = phone; return this; } - + + /** + * Get phone + * @return phone + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("phone") public String getPhone() { return phone; } + public void setPhone(String phone) { this.phone = phone; } - - /** - * User Status - **/ public User userStatus(Integer userStatus) { this.userStatus = userStatus; return this; } - + + /** + * User Status + * @return userStatus + **/ @ApiModelProperty(example = "null", value = "User Status") - @JsonProperty("userStatus") public Integer getUserStatus() { return userStatus; } + public void setUserStatus(Integer userStatus) { this.userStatus = userStatus; } diff --git a/samples/client/petstore/java/jersey2/build.gradle b/samples/client/petstore/java/jersey2/build.gradle index 067c81e1645..9dfa55f2f89 100644 --- a/samples/client/petstore/java/jersey2/build.gradle +++ b/samples/client/petstore/java/jersey2/build.gradle @@ -77,6 +77,7 @@ if(hasProperty('target') && target == 'android') { apply plugin: 'java' apply plugin: 'maven' + sourceCompatibility = JavaVersion.VERSION_1_7 targetCompatibility = JavaVersion.VERSION_1_7 @@ -92,24 +93,11 @@ if(hasProperty('target') && target == 'android') { } } -ext { - swagger_annotations_version = "1.5.8" - jackson_version = "2.7.5" - jersey_version = "2.22.2" - jodatime_version = "2.9.4" - junit_version = "4.12" -} - dependencies { - compile "io.swagger:swagger-annotations:$swagger_annotations_version" - compile "org.glassfish.jersey.core:jersey-client:$jersey_version" - compile "org.glassfish.jersey.media:jersey-media-multipart:$jersey_version" - compile "org.glassfish.jersey.media:jersey-media-json-jackson:$jersey_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:$jackson_version" - compile "joda-time:joda-time:$jodatime_version" - compile "com.brsanthu:migbase64:2.2" - testCompile "junit:junit:$junit_version" + compile 'io.swagger:swagger-annotations:1.5.8' + compile 'com.squareup.okhttp:okhttp:2.7.5' + compile 'com.squareup.okhttp:logging-interceptor:2.7.5' + compile 'com.google.code.gson:gson:2.6.2' + compile 'joda-time:joda-time:2.9.3' + testCompile 'junit:junit:4.12' } diff --git a/samples/client/petstore/java/jersey2/build.sbt b/samples/client/petstore/java/jersey2/build.sbt index 555b44f16db..c192efc1d42 100644 --- a/samples/client/petstore/java/jersey2/build.sbt +++ b/samples/client/petstore/java/jersey2/build.sbt @@ -10,15 +10,10 @@ lazy val root = (project in file(".")). resolvers += Resolver.mavenLocal, libraryDependencies ++= Seq( "io.swagger" % "swagger-annotations" % "1.5.8", - "org.glassfish.jersey.core" % "jersey-client" % "2.22.2", - "org.glassfish.jersey.media" % "jersey-media-multipart" % "2.22.2", - "org.glassfish.jersey.media" % "jersey-media-json-jackson" % "2.22.2", - "com.fasterxml.jackson.core" % "jackson-core" % "2.7.5", - "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.5", - "com.fasterxml.jackson.core" % "jackson-databind" % "2.7.5", - "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.7.5", - "joda-time" % "joda-time" % "2.9.4", - "com.brsanthu" % "migbase64" % "2.2", + "com.squareup.okhttp" % "okhttp" % "2.7.5", + "com.squareup.okhttp" % "logging-interceptor" % "2.7.5", + "com.google.code.gson" % "gson" % "2.6.2", + "joda-time" % "joda-time" % "2.9.3" % "compile", "junit" % "junit" % "4.12" % "test", "com.novocode" % "junit-interface" % "0.10" % "test" ) diff --git a/samples/client/petstore/java/jersey2/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/java/jersey2/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 00000000000..77292549927 --- /dev/null +++ b/samples/client/petstore/java/jersey2/docs/ArrayOfArrayOfNumberOnly.md @@ -0,0 +1,10 @@ + +# ArrayOfArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayArrayNumber** | [**List<List<BigDecimal>>**](List.md) | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2/docs/ArrayOfNumberOnly.md b/samples/client/petstore/java/jersey2/docs/ArrayOfNumberOnly.md new file mode 100644 index 00000000000..e8cc4cd36dc --- /dev/null +++ b/samples/client/petstore/java/jersey2/docs/ArrayOfNumberOnly.md @@ -0,0 +1,10 @@ + +# ArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayNumber** | [**List<BigDecimal>**](BigDecimal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2/docs/FakeApi.md b/samples/client/petstore/java/jersey2/docs/FakeApi.md index 0c1f55a0902..21a4db7c377 100644 --- a/samples/client/petstore/java/jersey2/docs/FakeApi.md +++ b/samples/client/petstore/java/jersey2/docs/FakeApi.md @@ -5,6 +5,7 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters @@ -73,3 +74,49 @@ No authorization required - **Content-Type**: application/xml; charset=utf-8, application/json; charset=utf-8 - **Accept**: application/xml; charset=utf-8, application/json; charset=utf-8 + +# **testEnumQueryParameters** +> testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble) + +To test enum query parameters + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +String enumQueryString = "-efg"; // String | Query parameter enum test (string) +BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | Query parameter enum test (double) +Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) +try { + apiInstance.testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEnumQueryParameters"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + **enumQueryInteger** | **BigDecimal**| Query parameter enum test (double) | [optional] + **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + diff --git a/samples/client/petstore/java/jersey2/docs/HasOnlyReadOnly.md b/samples/client/petstore/java/jersey2/docs/HasOnlyReadOnly.md new file mode 100644 index 00000000000..c1d0aac5672 --- /dev/null +++ b/samples/client/petstore/java/jersey2/docs/HasOnlyReadOnly.md @@ -0,0 +1,11 @@ + +# HasOnlyReadOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] +**foo** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2/docs/MapTest.md b/samples/client/petstore/java/jersey2/docs/MapTest.md new file mode 100644 index 00000000000..c671e97ffbc --- /dev/null +++ b/samples/client/petstore/java/jersey2/docs/MapTest.md @@ -0,0 +1,17 @@ + +# MapTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapMapOfString** | [**Map<String, Map<String, String>>**](Map.md) | | [optional] +**mapOfEnumString** | [**Map<String, InnerEnum>**](#Map<String, InnerEnum>) | | [optional] + + + +## Enum: Map<String, InnerEnum> +Name | Value +---- | ----- + + + diff --git a/samples/client/petstore/java/jersey2/docs/NumberOnly.md b/samples/client/petstore/java/jersey2/docs/NumberOnly.md new file mode 100644 index 00000000000..a3feac7fadc --- /dev/null +++ b/samples/client/petstore/java/jersey2/docs/NumberOnly.md @@ -0,0 +1,10 @@ + +# NumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**justNumber** | [**BigDecimal**](BigDecimal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2/hello.txt b/samples/client/petstore/java/jersey2/hello.txt deleted file mode 100644 index 6769dd60bdf..00000000000 --- a/samples/client/petstore/java/jersey2/hello.txt +++ /dev/null @@ -1 +0,0 @@ -Hello world! \ No newline at end of file diff --git a/samples/client/petstore/java/jersey2/pom.xml b/samples/client/petstore/java/jersey2/pom.xml index 0026cda2c47..43699a74d4e 100644 --- a/samples/client/petstore/java/jersey2/pom.xml +++ b/samples/client/petstore/java/jersey2/pom.xml @@ -52,7 +52,7 @@ org.apache.maven.plugins maven-jar-plugin - 2.6 + 2.2 @@ -68,6 +68,7 @@ org.codehaus.mojo build-helper-maven-plugin + 1.10 add_sources @@ -95,15 +96,6 @@ - - org.apache.maven.plugins - maven-compiler-plugin - 2.5.1 - - 1.7 - 1.7 - - @@ -112,44 +104,20 @@ swagger-annotations ${swagger-core-version} - - - - org.glassfish.jersey.core - jersey-client - ${jersey-version} - - - org.glassfish.jersey.media - jersey-media-multipart - ${jersey-version} - - org.glassfish.jersey.media - jersey-media-json-jackson - ${jersey-version} + com.squareup.okhttp + okhttp + ${okhttp-version} - - - com.fasterxml.jackson.core - jackson-core - ${jackson-version} + com.squareup.okhttp + logging-interceptor + ${okhttp-version} - com.fasterxml.jackson.core - jackson-annotations - ${jackson-version} - - - com.fasterxml.jackson.core - jackson-databind - ${jackson-version} - - - com.fasterxml.jackson.datatype - jackson-datatype-joda - ${jackson-version} + com.google.code.gson + gson + ${gson-version} joda-time @@ -157,13 +125,6 @@ ${jodatime-version} - - - com.brsanthu - migbase64 - 2.2 - - junit @@ -173,11 +134,15 @@ - 1.5.8 - 2.22.2 - 2.7.5 - 2.9.4 + 1.7 + ${java.version} + ${java.version} + 1.5.9 + 2.7.5 + 2.6.2 + 2.9.3 1.0.0 4.12 + UTF-8 diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiCallback.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiCallback.java new file mode 100644 index 00000000000..3ca33cf8017 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiCallback.java @@ -0,0 +1,74 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import java.io.IOException; + +import java.util.Map; +import java.util.List; + +/** + * Callback for asynchronous API call. + * + * @param The return type + */ +public interface ApiCallback { + /** + * This is called when the API call fails. + * + * @param e The exception causing the failure + * @param statusCode Status code of the response if available, otherwise it would be 0 + * @param responseHeaders Headers of the response if available, otherwise it would be null + */ + void onFailure(ApiException e, int statusCode, Map> responseHeaders); + + /** + * This is called when the API call succeeded. + * + * @param result The result deserialized from response + * @param statusCode Status code of the response + * @param responseHeaders Headers of the response + */ + void onSuccess(T result, int statusCode, Map> responseHeaders); + + /** + * This is called when the API upload processing. + * + * @param bytesWritten bytes Written + * @param contentLength content length of request body + * @param done write end + */ + void onUploadProgress(long bytesWritten, long contentLength, boolean done); + + /** + * This is called when the API downlond processing. + * + * @param bytesRead bytes Read + * @param contentLength content lenngth of the response + * @param done Read end + */ + void onDownloadProgress(long bytesRead, long contentLength, boolean done); +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java index 06f6d4d899a..b7b04e3e4c5 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 @@ -1,28 +1,46 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -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; - -import org.glassfish.jersey.client.ClientConfig; -import org.glassfish.jersey.client.ClientProperties; -import org.glassfish.jersey.filter.LoggingFilter; -import org.glassfish.jersey.jackson.JacksonFeature; -import org.glassfish.jersey.media.multipart.FormDataBodyPart; -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; -import org.glassfish.jersey.media.multipart.MultiPart; -import org.glassfish.jersey.media.multipart.MultiPartFeature; +import com.squareup.okhttp.Call; +import com.squareup.okhttp.Callback; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Response; +import com.squareup.okhttp.RequestBody; +import com.squareup.okhttp.FormEncodingBuilder; +import com.squareup.okhttp.MultipartBuilder; +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.Headers; +import com.squareup.okhttp.internal.http.HttpMethod; +import com.squareup.okhttp.logging.HttpLoggingInterceptor; +import com.squareup.okhttp.logging.HttpLoggingInterceptor.Level; + +import java.lang.reflect.Type; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Files; import java.util.Collection; import java.util.Collections; import java.util.Map; @@ -32,667 +50,1277 @@ import java.util.ArrayList; import java.util.Date; import java.util.TimeZone; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import java.net.URLEncoder; +import java.net.URLConnection; import java.io.File; +import java.io.InputStream; +import java.io.IOException; import java.io.UnsupportedEncodingException; +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.security.SecureRandom; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; + import java.text.DateFormat; import java.text.SimpleDateFormat; -import java.util.regex.Matcher; -import java.util.regex.Pattern; +import java.text.ParseException; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.KeyManager; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509TrustManager; + +import okio.BufferedSink; +import okio.Okio; import io.swagger.client.auth.Authentication; import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; - public class ApiClient { - private Map defaultHeaderMap = new HashMap(); - private String basePath = "http://petstore.swagger.io/v2"; - private boolean debugging = false; - private int connectionTimeout = 0; - - private Client httpClient; - private JSON json; - private String tempFolderPath = null; - - private Map authentications; - - private int statusCode; - private Map> responseHeaders; - - private DateFormat dateFormat; - - public ApiClient() { - json = new JSON(); - httpClient = buildHttpClient(debugging); - - // Use RFC3339 format for date and datetime. - // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 - this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); - - // Use UTC as the default time zone. - this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - - this.json.setDateFormat((DateFormat) dateFormat.clone()); - - // Set default User-Agent. - setUserAgent("Swagger-Codegen/1.0.0/java"); - - // Setup authentications (key: authentication name, value: authentication). - authentications = new HashMap(); - authentications.put("petstore_auth", new OAuth()); - authentications.put("api_key", new ApiKeyAuth("header", "api_key")); - // Prevent the authentications from being modified. - authentications = Collections.unmodifiableMap(authentications); - } - - /** - * Gets the JSON instance to do JSON serialization and deserialization. - */ - public JSON getJSON() { - return json; - } - - public Client getHttpClient() { - return httpClient; - } - - public ApiClient setHttpClient(Client httpClient) { - this.httpClient = httpClient; - return this; - } - - public String getBasePath() { - return basePath; - } - - public ApiClient setBasePath(String basePath) { - this.basePath = basePath; - return this; - } - - /** - * Gets the status code of the previous request - */ - public int getStatusCode() { - return statusCode; - } - - /** - * Gets the response headers of the previous request - */ - public Map> getResponseHeaders() { - return responseHeaders; - } - - /** - * Get authentications (key: authentication name, value: authentication). - */ - public Map getAuthentications() { - return authentications; - } - - /** - * Get authentication for the given name. - * - * @param authName The authentication name - * @return The authentication, null if not found - */ - public Authentication getAuthentication(String authName) { - return authentications.get(authName); - } - - /** - * Helper method to set username for the first HTTP basic authentication. - */ - public void setUsername(String username) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setUsername(username); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set password for the first HTTP basic authentication. - */ - public void setPassword(String password) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setPassword(password); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set API key value for the first API key authentication. - */ - public void setApiKey(String apiKey) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKey(apiKey); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set API key prefix for the first API key authentication. - */ - public void setApiKeyPrefix(String apiKeyPrefix) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set access token for the first OAuth2 authentication. - */ - public void setAccessToken(String accessToken) { - for (Authentication auth : authentications.values()) { - if (auth instanceof OAuth) { - ((OAuth) auth).setAccessToken(accessToken); - return; - } - } - throw new RuntimeException("No OAuth2 authentication configured!"); - } - - /** - * Set the User-Agent header's value (by adding to the default header map). - */ - public ApiClient setUserAgent(String userAgent) { - addDefaultHeader("User-Agent", userAgent); - return this; - } - - /** - * Add a default header. - * - * @param key The header's key - * @param value The header's value - */ - public ApiClient addDefaultHeader(String key, String value) { - defaultHeaderMap.put(key, value); - return this; - } - - /** - * Check that whether debugging is enabled for this API client. - */ - public boolean isDebugging() { - return debugging; - } - - /** - * Enable/disable debugging for this API client. - * - * @param debugging To enable (true) or disable (false) debugging - */ - public ApiClient setDebugging(boolean debugging) { - this.debugging = debugging; - // Rebuild HTTP Client according to the new "debugging" value. - this.httpClient = buildHttpClient(debugging); - return this; - } - - /** - * The path of temporary folder used to store downloaded files from endpoints - * with file response. The default value is null, i.e. using - * the system's default tempopary folder. - * - * @see https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createTempFile(java.lang.String,%20java.lang.String,%20java.io.File) - */ - public String getTempFolderPath() { - return tempFolderPath; - } - - public ApiClient setTempFolderPath(String tempFolderPath) { - this.tempFolderPath = tempFolderPath; - return this; - } - - /** - * Connect timeout (in milliseconds). - */ - public int getConnectTimeout() { - return connectionTimeout; - } - - /** - * Set the connect timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * {@link Integer#MAX_VALUE}. - */ - public ApiClient setConnectTimeout(int connectionTimeout) { - this.connectionTimeout = connectionTimeout; - httpClient.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout); - return this; - } - - /** - * Get the date format used to parse/format date parameters. - */ - public DateFormat getDateFormat() { - return dateFormat; - } - - /** - * Set the date format used to parse/format date parameters. - */ - 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()); - return this; - } - - /** - * Parse the given string into Date object. - */ - public Date parseDate(String str) { - try { - return dateFormat.parse(str); - } catch (java.text.ParseException e) { - throw new RuntimeException(e); - } - } - - /** - * Format the given Date object into string. - */ - public String formatDate(Date date) { - return dateFormat.format(date); - } - - /** - * 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 to {@code Pair} objects. - */ - public List parameterToPairs(String collectionFormat, String name, Object value){ - List params = new ArrayList(); - - // preconditions - if (name == null || name.isEmpty() || value == null) return params; - - Collection valueCollection = null; - if (value instanceof Collection) { - valueCollection = (Collection) value; - } else { - params.add(new Pair(name, parameterToString(value))); - return params; - } - - if (valueCollection.isEmpty()){ - return params; - } - - // get the collection format - collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv - - // create the params based on the collection format - if (collectionFormat.equals("multi")) { - for (Object item : valueCollection) { - params.add(new Pair(name, parameterToString(item))); - } - - return params; - } - - String delimiter = ","; - - if (collectionFormat.equals("csv")) { - delimiter = ","; - } else if (collectionFormat.equals("ssv")) { - delimiter = " "; - } else if (collectionFormat.equals("tsv")) { - delimiter = "\t"; - } else if (collectionFormat.equals("pipes")) { - delimiter = "|"; - } - - StringBuilder sb = new StringBuilder() ; - for (Object item : valueCollection) { - sb.append(delimiter); - sb.append(parameterToString(item)); - } - - params.add(new Pair(name, sb.substring(1))); - - return params; - } - - /** - * Check if the given MIME is a JSON MIME. - * JSON MIME examples: - * application/json - * application/json; charset=UTF8 - * APPLICATION/JSON - */ - public boolean isJsonMime(String mime) { - return mime != null && mime.matches("(?i)application\\/json(;.*)?"); - } - - /** - * Select the Accept header's value from the given accepts array: - * if JSON exists in the given array, use it; - * otherwise use all of them (joining into a string) - * - * @param accepts The accepts array to select from - * @return The Accept header to use. If the given array is empty, - * null will be returned (not to set the Accept header explicitly). - */ - public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) { - return null; - } - for (String accept : accepts) { - if (isJsonMime(accept)) { - return accept; - } - } - return StringUtil.join(accepts, ","); - } - - /** - * Select the Content-Type header's value from the given array: - * if JSON exists in the given array, use it; - * otherwise use the first one of the array. - * - * @param contentTypes The Content-Type array to select from - * @return The Content-Type header to use. If the given array is empty, - * JSON will be used. - */ - public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) { - return "application/json"; - } - for (String contentType : contentTypes) { - if (isJsonMime(contentType)) { - return contentType; - } - } - return contentTypes[0]; - } - - /** - * Escape the given string to be used as URL query value. - */ - public String escapeString(String str) { - try { - return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); - } catch (UnsupportedEncodingException e) { - return str; - } - } - - /** - * Serialize the given Java object into string entity according the given - * Content-Type (only JSON is supported for now). - */ - 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)); + public static final double JAVA_VERSION; + public static final boolean IS_ANDROID; + public static final int ANDROID_SDK_VERSION; + + static { + JAVA_VERSION = Double.parseDouble(System.getProperty("java.specification.version")); + boolean isAndroid; + try { + Class.forName("android.app.Activity"); + isAndroid = true; + } catch (ClassNotFoundException e) { + isAndroid = false; + } + IS_ANDROID = isAndroid; + int sdkVersion = 0; + if (IS_ANDROID) { + try { + sdkVersion = Class.forName("android.os.Build$VERSION").getField("SDK_INT").getInt(null); + } catch (Exception e) { + try { + sdkVersion = Integer.parseInt((String) Class.forName("android.os.Build$VERSION").getField("SDK").get(null)); + } catch (Exception e2) { } + } + } + ANDROID_SDK_VERSION = sdkVersion; + } + + /** + * The datetime format to be used when lenientDatetimeFormat is enabled. + */ + public static final String LENIENT_DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; + + private String basePath = "http://petstore.swagger.io/v2"; + private boolean lenientOnJson = false; + private boolean debugging = false; + private Map defaultHeaderMap = new HashMap(); + private String tempFolderPath = null; + + private Map authentications; + + private DateFormat dateFormat; + private DateFormat datetimeFormat; + private boolean lenientDatetimeFormat; + private int dateLength; + + private InputStream sslCaCert; + private boolean verifyingSsl; + + private OkHttpClient httpClient; + private JSON json; + + private HttpLoggingInterceptor loggingInterceptor; + + /* + * Constructor for ApiClient + */ + public ApiClient() { + httpClient = new OkHttpClient(); + + verifyingSsl = true; + + json = new JSON(this); + + /* + * Use RFC3339 format for date and datetime. + * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + */ + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + // Always use UTC as the default time zone when dealing with date (without time). + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + initDatetimeFormat(); + + // Be lenient on datetime formats when parsing datetime from string. + // See parseDatetime. + this.lenientDatetimeFormat = true; + + // Set default User-Agent. + setUserAgent("Swagger-Codegen/1.0.0/java"); + + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap(); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("petstore_auth", new OAuth()); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + /** + * Get base path + * + * @return Baes path + */ + public String getBasePath() { + return basePath; + } + + /** + * Set base path + * + * @param basePath Base path of the URL (e.g http://petstore.swagger.io/v2 + * @return An instance of OkHttpClient + */ + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + /** + * Get HTTP client + * + * @return An instance of OkHttpClient + */ + public OkHttpClient getHttpClient() { + return httpClient; + } + + /** + * Set HTTP client + * + * @param httpClient An instance of OkHttpClient + * @return Api Client + */ + public ApiClient setHttpClient(OkHttpClient httpClient) { + this.httpClient = httpClient; + return this; + } + + /** + * Get JSON + * + * @return JSON object + */ + public JSON getJSON() { + return json; + } + + /** + * Set JSON + * + * @param json JSON object + * @return Api client + */ + public ApiClient setJSON(JSON json) { + this.json = json; + return this; + } + + /** + * True if isVerifyingSsl flag is on + * + * @return True if isVerifySsl flag is on + */ + public boolean isVerifyingSsl() { + return verifyingSsl; + } + + /** + * Configure whether to verify certificate and hostname when making https requests. + * Default to true. + * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. + * + * @param verifyingSsl True to verify TLS/SSL connection + * @return ApiClient + */ + public ApiClient setVerifyingSsl(boolean verifyingSsl) { + this.verifyingSsl = verifyingSsl; + applySslSettings(); + return this; + } + + /** + * Get SSL CA cert. + * + * @return Input stream to the SSL CA cert + */ + public InputStream getSslCaCert() { + return sslCaCert; + } + + /** + * Configure the CA certificate to be trusted when making https requests. + * Use null to reset to default. + * + * @param sslCaCert input stream for SSL CA cert + * @return ApiClient + */ + public ApiClient setSslCaCert(InputStream sslCaCert) { + this.sslCaCert = sslCaCert; + applySslSettings(); + return this; + } + + public DateFormat getDateFormat() { + return dateFormat; + } + + public ApiClient setDateFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + this.dateLength = this.dateFormat.format(new Date()).length(); + return this; + } + + public DateFormat getDatetimeFormat() { + return datetimeFormat; + } + + public ApiClient setDatetimeFormat(DateFormat datetimeFormat) { + this.datetimeFormat = datetimeFormat; + return this; + } + + /** + * Whether to allow various ISO 8601 datetime formats when parsing a datetime string. + * @see #parseDatetime(String) + * @return True if lenientDatetimeFormat flag is set to true + */ + public boolean isLenientDatetimeFormat() { + return lenientDatetimeFormat; + } + + public ApiClient setLenientDatetimeFormat(boolean lenientDatetimeFormat) { + this.lenientDatetimeFormat = lenientDatetimeFormat; + return this; + } + + /** + * Parse the given date string into Date object. + * The default dateFormat supports these ISO 8601 date formats: + * 2015-08-16 + * 2015-8-16 + * @param str String to be parsed + * @return Date + */ + public Date parseDate(String str) { + if (str == null) + return null; + try { + return dateFormat.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Parse the given datetime string into Date object. + * When lenientDatetimeFormat is enabled, the following ISO 8601 datetime formats are supported: + * 2015-08-16T08:20:05Z + * 2015-8-16T8:20:05Z + * 2015-08-16T08:20:05+00:00 + * 2015-08-16T08:20:05+0000 + * 2015-08-16T08:20:05.376Z + * 2015-08-16T08:20:05.376+00:00 + * 2015-08-16T08:20:05.376+00 + * Note: The 3-digit milli-seconds is optional. Time zone is required and can be in one of + * these formats: + * Z (same with +0000) + * +08:00 (same with +0800) + * -02 (same with -0200) + * -0200 + * @see ISO 8601 + * @param str Date time string to be parsed + * @return Date representation of the string + */ + public Date parseDatetime(String str) { + if (str == null) + return null; + + DateFormat format; + if (lenientDatetimeFormat) { + /* + * When lenientDatetimeFormat is enabled, normalize the date string + * into LENIENT_DATETIME_FORMAT to support various formats + * defined by ISO 8601. + */ + // normalize time zone + // trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000 + str = str.replaceAll("[zZ]\\z", "+0000"); + // remove colon in time zone: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000 + str = str.replaceAll("([+-]\\d{2}):(\\d{2})\\z", "$1$2"); + // expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000 + str = str.replaceAll("([+-]\\d{2})\\z", "$100"); + // add milliseconds when missing + // 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000 + str = str.replaceAll("(:\\d{1,2})([+-]\\d{4})\\z", "$1.000$2"); + format = new SimpleDateFormat(LENIENT_DATETIME_FORMAT); + } else { + format = this.datetimeFormat; + } + + try { + return format.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /* + * Parse date or date time in string format into Date object. + * + * @param str Date time string to be parsed + * @return Date representation of the string + */ + public Date parseDateOrDatetime(String str) { + if (str == null) + return null; + else if (str.length() <= dateLength) + return parseDate(str); + else + return parseDatetime(str); + } + + /** + * Format the given Date object into string (Date format). + * + * @param date Date object + * @return Formatted date in string representation + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } + + /** + * Format the given Date object into string (Datetime format). + * + * @param date Date object + * @return Formatted datetime in string representation + */ + public String formatDatetime(Date date) { + return datetimeFormat.format(date); + } + + /** + * Get authentications (key: authentication name, value: authentication). + * + * @return Map of authentication objects + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + * + * @param username Username + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + * + * @param password Password + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + * + * @param apiKey API key + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + * + * @param apiKeyPrefix API key prefix + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set access token for the first OAuth2 authentication. + * + * @param accessToken Access token + */ + public void setAccessToken(String accessToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); + return; + } + } + throw new RuntimeException("No OAuth2 authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + * + * @param userAgent HTTP request's user agent + * @return ApiClient + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + * @return ApiClient + */ + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + /** + * @see setLenient + * + * @return True if lenientOnJson is enabled, false otherwise. + */ + public boolean isLenientOnJson() { + return lenientOnJson; + } + + /** + * Set LenientOnJson + * + * @param lenient True to enable lenientOnJson + * @return ApiClient + */ + public ApiClient setLenientOnJson(boolean lenient) { + this.lenientOnJson = lenient; + return this; + } + + /** + * Check that whether debugging is enabled for this API client. + * + * @return True if debugging is enabled, false otherwise. + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + * @return ApiClient + */ + public ApiClient setDebugging(boolean debugging) { + if (debugging != this.debugging) { + if (debugging) { + loggingInterceptor = new HttpLoggingInterceptor(); + loggingInterceptor.setLevel(Level.BODY); + httpClient.interceptors().add(loggingInterceptor); + } else { + httpClient.interceptors().remove(loggingInterceptor); + loggingInterceptor = null; + } + } + this.debugging = debugging; + return this; + } + + /** + * The path of temporary folder used to store downloaded files from endpoints + * with file response. The default value is null, i.e. using + * the system's default tempopary folder. + * + * @see createTempFile + * @return Temporary folder path + */ + public String getTempFolderPath() { + return tempFolderPath; + } + + /** + * Set the tempoaray folder path (for downloading files) + * + * @param tempFolderPath Temporary folder path + * @return ApiClient + */ + public ApiClient setTempFolderPath(String tempFolderPath) { + this.tempFolderPath = tempFolderPath; + return this; + } + + /** + * Get connection timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getConnectTimeout() { + return httpClient.getConnectTimeout(); + } + + /** + * Sets the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * + * @param connectionTimeout connection timeout in milliseconds + * @return Api client + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + httpClient.setConnectTimeout(connectionTimeout, TimeUnit.MILLISECONDS); + return this; + } + + /** + * Format the given parameter object into string. + * + * @param param Parameter + * @return String representation of the parameter + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDatetime((Date) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for (Object o : (Collection)param) { + if (b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /** + * Format to {@code Pair} objects. + * + * @param collectionFormat collection format (e.g. csv, tsv) + * @param name Name + * @param value Value + * @return A list of Pair objects + */ + public List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + + // create the params based on the collection format + if (collectionFormat.equals("multi")) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); + } + + return params; + } + + String delimiter = ","; + + if (collectionFormat.equals("csv")) { + delimiter = ","; + } else if (collectionFormat.equals("ssv")) { + delimiter = " "; + } else if (collectionFormat.equals("tsv")) { + delimiter = "\t"; + } else if (collectionFormat.equals("pipes")) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + + return params; + } + + /** + * Sanitize filename by removing path. + * e.g. ../../sun.gif becomes sun.gif + * + * @param filename The filename to be sanitized + * @return The sanitized filename + */ + public String sanitizeFilename(String filename) { + return filename.replaceAll(".*[/\\\\]", ""); + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * + * @param mime MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public boolean isJsonMime(String mime) { + return mime != null && mime.matches("(?i)application\\/json(;.*)?"); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } + return contentTypes[0]; + } + + /** + * Escape the given string to be used as URL query value. + * + * @param str String to be escaped + * @return Escaped string + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Deserialize response body to Java object, according to the return type and + * the Content-Type response header. + * + * @param Type + * @param response HTTP response + * @param returnType The type of the Java object + * @return The deserialized Java object + * @throws ApiException If fail to deserialize response body, i.e. cannot read response body + * or the Content-Type of the response is not supported. + */ + @SuppressWarnings("unchecked") + public T deserialize(Response response, Type returnType) throws ApiException { + if (response == null || returnType == null) { + return null; + } + + if ("byte[]".equals(returnType.toString())) { + // Handle binary response (byte array). + try { + return (T) response.body().bytes(); + } catch (IOException e) { + throw new ApiException(e); + } + } else if (returnType.equals(File.class)) { + // Handle file downloading. + return (T) downloadFileFromResponse(response); + } + + String respBody; + try { + if (response.body() != null) + respBody = response.body().string(); + else + respBody = null; + } catch (IOException e) { + throw new ApiException(e); + } + + if (respBody == null || "".equals(respBody)) { + return null; + } + + String contentType = response.headers().get("Content-Type"); + if (contentType == null) { + // ensuring a default content type + contentType = "application/json"; + } + if (isJsonMime(contentType)) { + return json.deserialize(respBody, returnType); + } else if (returnType.equals(String.class)) { + // Expecting string, return the raw response body. + return (T) respBody; + } else { + throw new ApiException( + "Content type \"" + contentType + "\" is not supported for type: " + returnType, + response.code(), + response.headers().toMultimap(), + respBody); + } + } + + /** + * Serialize the given Java object into request body according to the object's + * class and the request Content-Type. + * + * @param obj The Java object + * @param contentType The request Content-Type + * @return The serialized request body + * @throws ApiException If fail to serialize the given object + */ + public RequestBody serialize(Object obj, String contentType) throws ApiException { + if (obj instanceof byte[]) { + // Binary (byte array) body parameter support. + return RequestBody.create(MediaType.parse(contentType), (byte[]) obj); + } else if (obj instanceof File) { + // File body parameter support. + return RequestBody.create(MediaType.parse(contentType), (File) obj); + } else if (isJsonMime(contentType)) { + String content; + if (obj != null) { + content = json.serialize(obj); + } else { + content = null; + } + return RequestBody.create(MediaType.parse(contentType), content); } else { - 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 { - // 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, GenericType returnType) throws ApiException { - // Handle file downloading. - if (returnType.equals(File.class)) { - @SuppressWarnings("unchecked") - T file = (T) downloadFileFromResponse(response); - return file; - } - - String contentType = null; - List contentTypes = response.getHeaders().get("Content-Type"); - if (contentTypes != null && !contentTypes.isEmpty()) - contentType = String.valueOf(contentTypes.get(0)); - if (contentType == null) - throw new ApiException(500, "missing Content-Type in response"); - - return response.readEntity(returnType); - } - - /** - * Download file from the given response. - * @throws ApiException If fail to read file content from response and write to disk - */ - public File downloadFileFromResponse(Response response) throws ApiException { - try { - File file = prepareDownloadFile(response); - Files.copy(response.readEntity(InputStream.class), file.toPath()); - return file; - } catch (IOException e) { - throw new ApiException(e); - } - } - - public File prepareDownloadFile(Response response) throws IOException { - String filename = null; - String contentDisposition = (String) response.getHeaders().getFirst("Content-Disposition"); - if (contentDisposition != null && !"".equals(contentDisposition)) { - // Get filename from the Content-Disposition header. - Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); - Matcher matcher = pattern.matcher(contentDisposition); - if (matcher.find()) - filename = matcher.group(1); - } - - String prefix = null; - String suffix = null; - if (filename == null) { - prefix = "download-"; - suffix = ""; - } else { - int pos = filename.lastIndexOf("."); - if (pos == -1) { - prefix = filename + "-"; - } else { - prefix = filename.substring(0, pos) + "-"; - suffix = filename.substring(pos); - } - // File.createTempFile requires the prefix to be at least three characters long - if (prefix.length() < 3) - prefix = "download-"; - } - - if (tempFolderPath == null) - return File.createTempFile(prefix, suffix); - else - return File.createTempFile(prefix, suffix, new File(tempFolderPath)); - } - - /** - * Invoke API by sending HTTP request with the given options. - * - * @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 - * @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 - * @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, GenericType returnType) throws ApiException { - updateParamsForAuth(authNames, queryParams, headerParams); - - // Not using `.target(this.basePath).path(path)` below, - // to support (constant) query string in `path`, e.g. "/posts?draft=1" - WebTarget target = httpClient.target(this.basePath + path); - - if (queryParams != null) { - for (Pair queryParam : queryParams) { - if (queryParam.getValue() != null) { - target = target.queryParam(queryParam.getName(), queryParam.getValue()); - } - } - } - - Invocation.Builder invocationBuilder = target.request().accept(accept); - - for (String key : headerParams.keySet()) { - String value = headerParams.get(key); - if (value != null) { - invocationBuilder = invocationBuilder.header(key, value); - } - } - - for (String key : defaultHeaderMap.keySet()) { - if (!headerParams.containsKey(key)) { - String value = defaultHeaderMap.get(key); - if (value != null) { - invocationBuilder = invocationBuilder.header(key, value); - } - } - } - - Entity entity = serialize(body, formParams, contentType); - - Response response = null; - - if ("GET".equals(method)) { - response = invocationBuilder.get(); - } else if ("POST".equals(method)) { - response = invocationBuilder.post(entity); - } else if ("PUT".equals(method)) { - response = invocationBuilder.put(entity); - } else if ("DELETE".equals(method)) { - response = invocationBuilder.delete(); - } else { - throw new ApiException(500, "unknown method type " + method); - } - - statusCode = response.getStatusInfo().getStatusCode(); - responseHeaders = buildResponseHeaders(response); - - if (response.getStatus() == Status.NO_CONTENT.getStatusCode()) { - return null; - } else if (response.getStatusInfo().getFamily().equals(Status.Family.SUCCESSFUL)) { - if (returnType == null) - return null; - else - return deserialize(response, returnType); - } else { - String message = "error"; - String respBody = null; - if (response.hasEntity()) { + throw new ApiException("Content type \"" + contentType + "\" is not supported"); + } + } + + /** + * Download file from the given response. + * + * @param response An instance of the Response object + * @throws ApiException If fail to read file content from response and write to disk + * @return Downloaded file + */ + public File downloadFileFromResponse(Response response) throws ApiException { try { - respBody = String.valueOf(response.readEntity(String.class)); - message = respBody; - } catch (RuntimeException e) { - // e.printStackTrace(); - } - } - throw new ApiException( - response.getStatus(), - message, - buildResponseHeaders(response), - respBody); - } - } - - /** - * Build the Client used to make HTTP requests. - */ - private Client buildHttpClient(boolean debugging) { - final ClientConfig clientConfig = new ClientConfig(); - clientConfig.register(MultiPartFeature.class); - clientConfig.register(json); - clientConfig.register(JacksonFeature.class); - if (debugging) { - clientConfig.register(LoggingFilter.class); - } - return ClientBuilder.newClient(clientConfig); - } - - private Map> buildResponseHeaders(Response response) { - Map> responseHeaders = new HashMap>(); - for (Entry> entry: response.getHeaders().entrySet()) { - List values = entry.getValue(); - List headers = new ArrayList(); - for (Object o : values) { - headers.add(String.valueOf(o)); - } - responseHeaders.put(entry.getKey(), headers); - } - return responseHeaders; - } - - /** - * Update query and header parameters based on authentication settings. - * - * @param authNames The authentications to apply - */ - private void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { - for (String authName : authNames) { - Authentication auth = authentications.get(authName); - if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); - auth.applyToParams(queryParams, headerParams); - } - } + File file = prepareDownloadFile(response); + BufferedSink sink = Okio.buffer(Okio.sink(file)); + sink.writeAll(response.body().source()); + sink.close(); + return file; + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * Prepare file for download + * + * @param response An instance of the Response object + * @throws IOException If fail to prepare file for download + * @return Prepared file for the download + */ + public File prepareDownloadFile(Response response) throws IOException { + String filename = null; + String contentDisposition = response.header("Content-Disposition"); + if (contentDisposition != null && !"".equals(contentDisposition)) { + // Get filename from the Content-Disposition header. + Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); + Matcher matcher = pattern.matcher(contentDisposition); + if (matcher.find()) { + filename = sanitizeFilename(matcher.group(1)); + } + } + + String prefix = null; + String suffix = null; + if (filename == null) { + prefix = "download-"; + suffix = ""; + } else { + int pos = filename.lastIndexOf("."); + if (pos == -1) { + prefix = filename + "-"; + } else { + prefix = filename.substring(0, pos) + "-"; + suffix = filename.substring(pos); + } + // File.createTempFile requires the prefix to be at least three characters long + if (prefix.length() < 3) + prefix = "download-"; + } + + if (tempFolderPath == null) + return File.createTempFile(prefix, suffix); + else + return File.createTempFile(prefix, suffix, new File(tempFolderPath)); + } + + /** + * {@link #execute(Call, Type)} + * + * @param Type + * @param call An instance of the Call object + * @throws ApiException If fail to execute the call + * @return ApiResponse<T> + */ + public ApiResponse execute(Call call) throws ApiException { + return execute(call, null); + } + + /** + * Execute HTTP call and deserialize the HTTP response body into the given return type. + * + * @param returnType The return type used to deserialize HTTP response body + * @param The return type corresponding to (same with) returnType + * @param call Call + * @return ApiResponse object containing response status, headers and + * data, which is a Java object deserialized from response body and would be null + * when returnType is null. + * @throws ApiException If fail to execute the call + */ + public ApiResponse execute(Call call, Type returnType) throws ApiException { + try { + Response response = call.execute(); + T data = handleResponse(response, returnType); + return new ApiResponse(response.code(), response.headers().toMultimap(), data); + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * {@link #executeAsync(Call, Type, ApiCallback)} + * + * @param Type + * @param call An instance of the Call object + * @param callback ApiCallback<T> + */ + public void executeAsync(Call call, ApiCallback callback) { + executeAsync(call, null, callback); + } + + /** + * Execute HTTP call asynchronously. + * + * @see #execute(Call, Type) + * @param Type + * @param call The callback to be executed when the API call finishes + * @param returnType Return type + * @param callback ApiCallback + */ + @SuppressWarnings("unchecked") + public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { + call.enqueue(new Callback() { + @Override + public void onFailure(Request request, IOException e) { + callback.onFailure(new ApiException(e), 0, null); + } + + @Override + public void onResponse(Response response) throws IOException { + T result; + try { + result = (T) handleResponse(response, returnType); + } catch (ApiException e) { + callback.onFailure(e, response.code(), response.headers().toMultimap()); + return; + } + callback.onSuccess(result, response.code(), response.headers().toMultimap()); + } + }); + } + + /** + * Handle the given response, return the deserialized object when the response is successful. + * + * @param Type + * @param response Response + * @param returnType Return type + * @throws ApiException If the response has a unsuccessful status code or + * fail to deserialize the response body + * @return Type + */ + public T handleResponse(Response response, Type returnType) throws ApiException { + if (response.isSuccessful()) { + if (returnType == null || response.code() == 204) { + // returning null if the returnType is not defined, + // or the status code is 204 (No Content) + return null; + } else { + return deserialize(response, returnType); + } + } else { + String respBody = null; + if (response.body() != null) { + try { + respBody = response.body().string(); + } catch (IOException e) { + throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); + } + } + throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); + } + } + + /** + * Build HTTP call with the given options. + * + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param formParams The form parameters + * @param authNames The authentications to apply + * @param progressRequestListener Progress request listener + * @return The HTTP call + * @throws ApiException If fail to serialize the request body object + */ + public Call buildCall(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + updateParamsForAuth(authNames, queryParams, headerParams); + + final String url = buildUrl(path, queryParams); + final Request.Builder reqBuilder = new Request.Builder().url(url); + processHeaderParams(headerParams, reqBuilder); + + String contentType = (String) headerParams.get("Content-Type"); + // ensuring a default content type + if (contentType == null) { + contentType = "application/json"; + } + + RequestBody reqBody; + if (!HttpMethod.permitsRequestBody(method)) { + reqBody = null; + } else if ("application/x-www-form-urlencoded".equals(contentType)) { + reqBody = buildRequestBodyFormEncoding(formParams); + } else if ("multipart/form-data".equals(contentType)) { + reqBody = buildRequestBodyMultipart(formParams); + } else if (body == null) { + if ("DELETE".equals(method)) { + // allow calling DELETE without sending a request body + reqBody = null; + } else { + // use an empty request body (for POST, PUT and PATCH) + reqBody = RequestBody.create(MediaType.parse(contentType), ""); + } + } else { + reqBody = serialize(body, contentType); + } + + Request request = null; + + if(progressRequestListener != null && reqBody != null) { + ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener); + request = reqBuilder.method(method, progressRequestBody).build(); + } else { + request = reqBuilder.method(method, reqBody).build(); + } + + return httpClient.newCall(request); + } + + /** + * Build full URL by concatenating base path, the given sub path and query parameters. + * + * @param path The sub path + * @param queryParams The query parameters + * @return The full URL + */ + public String buildUrl(String path, List queryParams) { + final StringBuilder url = new StringBuilder(); + url.append(basePath).append(path); + + if (queryParams != null && !queryParams.isEmpty()) { + // support (constant) query string in `path`, e.g. "/posts?draft=1" + String prefix = path.contains("?") ? "&" : "?"; + for (Pair param : queryParams) { + if (param.getValue() != null) { + if (prefix != null) { + url.append(prefix); + prefix = null; + } else { + url.append("&"); + } + String value = parameterToString(param.getValue()); + url.append(escapeString(param.getName())).append("=").append(escapeString(value)); + } + } + } + + return url.toString(); + } + + /** + * Set header parameters to the request builder, including default headers. + * + * @param headerParams Header parameters in the ofrm of Map + * @param reqBuilder Reqeust.Builder + */ + public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { + for (Entry param : headerParams.entrySet()) { + reqBuilder.header(param.getKey(), parameterToString(param.getValue())); + } + for (Entry header : defaultHeaderMap.entrySet()) { + if (!headerParams.containsKey(header.getKey())) { + reqBuilder.header(header.getKey(), parameterToString(header.getValue())); + } + } + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + */ + public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); + auth.applyToParams(queryParams, headerParams); + } + } + + /** + * Build a form-encoding request body with the given form parameters. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyFormEncoding(Map formParams) { + FormEncodingBuilder formBuilder = new FormEncodingBuilder(); + for (Entry param : formParams.entrySet()) { + formBuilder.add(param.getKey(), parameterToString(param.getValue())); + } + return formBuilder.build(); + } + + /** + * Build a multipart (file uploading) request body with the given form parameters, + * which could contain text fields and file fields. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyMultipart(Map formParams) { + MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); + for (Entry param : formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\""); + MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); + mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file)); + } else { + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\""); + mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue()))); + } + } + return mpBuilder.build(); + } + + /** + * Guess Content-Type header from the given file (defaults to "application/octet-stream"). + * + * @param file The given file + * @return The guessed Content-Type + */ + public String guessContentTypeFromFile(File file) { + String contentType = URLConnection.guessContentTypeFromName(file.getName()); + if (contentType == null) { + return "application/octet-stream"; + } else { + return contentType; + } + } + + /** + * Initialize datetime format according to the current environment, e.g. Java 1.7 and Android. + */ + private void initDatetimeFormat() { + String formatWithTimeZone = null; + if (IS_ANDROID) { + if (ANDROID_SDK_VERSION >= 18) { + // The time zone format "ZZZZZ" is available since Android 4.3 (SDK version 18) + formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"; + } + } else if (JAVA_VERSION >= 1.7) { + // The time zone format "XXX" is available since Java 1.7 + formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; + } + if (formatWithTimeZone != null) { + this.datetimeFormat = new SimpleDateFormat(formatWithTimeZone); + // NOTE: Use the system's default time zone (mainly for datetime formatting). + } else { + // Use a common format that works across all systems. + this.datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + // Always use the UTC time zone as we are using a constant trailing "Z" here. + this.datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + } + } + + /** + * Apply SSL related settings to httpClient according to the current values of + * verifyingSsl and sslCaCert. + */ + private void applySslSettings() { + try { + KeyManager[] keyManagers = null; + TrustManager[] trustManagers = null; + HostnameVerifier hostnameVerifier = null; + if (!verifyingSsl) { + TrustManager trustAll = new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} + @Override + public X509Certificate[] getAcceptedIssuers() { return null; } + }; + SSLContext sslContext = SSLContext.getInstance("TLS"); + trustManagers = new TrustManager[]{ trustAll }; + hostnameVerifier = new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { return true; } + }; + } else if (sslCaCert != null) { + char[] password = null; // Any password will work. + CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); + Collection certificates = certificateFactory.generateCertificates(sslCaCert); + if (certificates.isEmpty()) { + throw new IllegalArgumentException("expected non-empty set of trusted certificates"); + } + KeyStore caKeyStore = newEmptyKeyStore(password); + int index = 0; + for (Certificate certificate : certificates) { + String certificateAlias = "ca" + Integer.toString(index++); + caKeyStore.setCertificateEntry(certificateAlias, certificate); + } + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagerFactory.init(caKeyStore); + trustManagers = trustManagerFactory.getTrustManagers(); + } + + if (keyManagers != null || trustManagers != null) { + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(keyManagers, trustManagers, new SecureRandom()); + httpClient.setSslSocketFactory(sslContext.getSocketFactory()); + } else { + httpClient.setSslSocketFactory(null); + } + httpClient.setHostnameVerifier(hostnameVerifier); + } catch (GeneralSecurityException e) { + throw new RuntimeException(e); + } + } + + private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { + try { + KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + keyStore.load(null, password); + return keyStore; + } catch (IOException e) { + throw new AssertionError(e); + } + } } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java index 600bb507f09..3bed001f002 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java @@ -1,6 +1,6 @@ /** * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiResponse.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiResponse.java new file mode 100644 index 00000000000..d7dde1ee939 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiResponse.java @@ -0,0 +1,71 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import java.util.List; +import java.util.Map; + +/** + * API response returned by API call. + * + * @param T The type of data that is deserialized from response body + */ +public class ApiResponse { + final private int statusCode; + final private Map> headers; + final private T data; + + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + */ + public ApiResponse(int statusCode, Map> headers) { + this(statusCode, headers, null); + } + + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + * @param data The object deserialized from response bod + */ + public ApiResponse(int statusCode, Map> headers, T data) { + this.statusCode = statusCode; + this.headers = headers; + this.data = data; + } + + public int getStatusCode() { + return statusCode; + } + + public Map> getHeaders() { + return headers; + } + + public T getData() { + return data; + } +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java index cbdadd6262d..5191b9b73c6 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java @@ -1,6 +1,6 @@ /** * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/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 d6f725b2caa..540611eab9d 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 @@ -1,36 +1,237 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.*; -import com.fasterxml.jackson.datatype.joda.*; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonNull; +import com.google.gson.JsonParseException; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +import java.io.IOException; +import java.io.StringReader; +import java.lang.reflect.Type; +import java.util.Date; + +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; + +public class JSON { + private ApiClient apiClient; + private Gson gson; + + /** + * JSON constructor. + * + * @param apiClient An instance of ApiClient + */ + public JSON(ApiClient apiClient) { + this.apiClient = apiClient; + gson = new GsonBuilder() + .registerTypeAdapter(Date.class, new DateAdapter(apiClient)) + .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) + .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) + .create(); + } + + /** + * Get Gson. + * + * @return Gson + */ + public Gson getGson() { + return gson; + } + + /** + * Set Gson. + * + * @param gson Gson + */ + public void setGson(Gson gson) { + this.gson = gson; + } + + /** + * Serialize the given Java object into JSON string. + * + * @param obj Object + * @return String representation of the JSON + */ + public String serialize(Object obj) { + return gson.toJson(obj); + } -import java.text.DateFormat; + /** + * Deserialize the given JSON string to Java object. + * + * @param Type + * @param body The JSON string + * @param returnType The type to deserialize inot + * @return The deserialized Java object + */ + @SuppressWarnings("unchecked") + public T deserialize(String body, Type returnType) { + try { + if (apiClient.isLenientOnJson()) { + JsonReader jsonReader = new JsonReader(new StringReader(body)); + // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) + jsonReader.setLenient(true); + return gson.fromJson(jsonReader, returnType); + } else { + return gson.fromJson(body, returnType); + } + } catch (JsonParseException e) { + // Fallback processing when failed to parse JSON form response body: + // return the response body string directly for the String return type; + // parse response body into date or datetime for the Date return type. + if (returnType.equals(String.class)) + return (T) body; + else if (returnType.equals(Date.class)) + return (T) apiClient.parseDateOrDatetime(body); + else throw(e); + } + } +} + +class DateAdapter implements JsonSerializer, JsonDeserializer { + private final ApiClient apiClient; + + /** + * Constructor for DateAdapter + * + * @param apiClient Api client + */ + public DateAdapter(ApiClient apiClient) { + super(); + this.apiClient = apiClient; + } -import javax.ws.rs.ext.ContextResolver; + /** + * Serialize + * + * @param src Date + * @param typeOfSrc Type + * @param context Json Serialization Context + * @return Json Element + */ + @Override + public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { + if (src == null) { + return JsonNull.INSTANCE; + } else { + return new JsonPrimitive(apiClient.formatDatetime(src)); + } + } + + /** + * Deserialize + * + * @param json Json element + * @param date Type + * @param typeOfSrc Type + * @param context Json Serialization Context + * @return Date + * @throw JsonParseException if fail to parse + */ + @Override + public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException { + String str = json.getAsJsonPrimitive().getAsString(); + try { + return apiClient.parseDateOrDatetime(str); + } catch (RuntimeException e) { + throw new JsonParseException(e); + } + } +} +/** + * Gson TypeAdapter for Joda DateTime type + */ +class DateTimeTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + + @Override + public void write(JsonWriter out, DateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public DateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseDateTime(date); + } + } +} -public class JSON implements ContextResolver { - private ObjectMapper mapper; +/** + * Gson TypeAdapter for Joda LocalDate type + */ +class LocalDateTypeAdapter extends TypeAdapter { - 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()); - } + private final DateTimeFormatter formatter = ISODateTimeFormat.date(); - /** - * Set the date format for JSON (de)serialization with Date properties. - */ - public void setDateFormat(DateFormat dateFormat) { - mapper.setDateFormat(dateFormat); - } + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } - @Override - public ObjectMapper getContext(Class type) { - return mapper; - } + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseLocalDate(date); + } + } } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java index 4b44c415812..15b247eea93 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java @@ -1,6 +1,6 @@ /** * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ProgressRequestBody.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ProgressRequestBody.java new file mode 100644 index 00000000000..d9ca742ecd2 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ProgressRequestBody.java @@ -0,0 +1,95 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.RequestBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSink; +import okio.ForwardingSink; +import okio.Okio; +import okio.Sink; + +public class ProgressRequestBody extends RequestBody { + + public interface ProgressRequestListener { + void onRequestProgress(long bytesWritten, long contentLength, boolean done); + } + + private final RequestBody requestBody; + + private final ProgressRequestListener progressListener; + + private BufferedSink bufferedSink; + + public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) { + this.requestBody = requestBody; + this.progressListener = progressListener; + } + + @Override + public MediaType contentType() { + return requestBody.contentType(); + } + + @Override + public long contentLength() throws IOException { + return requestBody.contentLength(); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + if (bufferedSink == null) { + bufferedSink = Okio.buffer(sink(sink)); + } + + requestBody.writeTo(bufferedSink); + bufferedSink.flush(); + + } + + private Sink sink(Sink sink) { + return new ForwardingSink(sink) { + + long bytesWritten = 0L; + long contentLength = 0L; + + @Override + public void write(Buffer source, long byteCount) throws IOException { + super.write(source, byteCount); + if (contentLength == 0) { + contentLength = contentLength(); + } + + bytesWritten += byteCount; + progressListener.onRequestProgress(bytesWritten, contentLength, bytesWritten == contentLength); + } + }; + } +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ProgressResponseBody.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ProgressResponseBody.java new file mode 100644 index 00000000000..f8af685999d --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ProgressResponseBody.java @@ -0,0 +1,88 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.ResponseBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSource; +import okio.ForwardingSource; +import okio.Okio; +import okio.Source; + +public class ProgressResponseBody extends ResponseBody { + + public interface ProgressListener { + void update(long bytesRead, long contentLength, boolean done); + } + + private final ResponseBody responseBody; + private final ProgressListener progressListener; + private BufferedSource bufferedSource; + + public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) { + this.responseBody = responseBody; + this.progressListener = progressListener; + } + + @Override + public MediaType contentType() { + return responseBody.contentType(); + } + + @Override + public long contentLength() throws IOException { + return responseBody.contentLength(); + } + + @Override + public BufferedSource source() throws IOException { + if (bufferedSource == null) { + bufferedSource = Okio.buffer(source(responseBody.source())); + } + return bufferedSource; + } + + private Source source(Source source) { + return new ForwardingSource(source) { + long totalBytesRead = 0L; + + @Override + public long read(Buffer sink, long byteCount) throws IOException { + long bytesRead = super.read(sink, byteCount); + // read() returns the number of bytes read, or -1 if this source is exhausted. + totalBytesRead += bytesRead != -1 ? bytesRead : 0; + progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1); + return bytesRead; + } + }; + } +} + + diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java index 03c6c81e434..fdcef6b1010 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ /** * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java index ce4830a1f77..52dce361e2a 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java @@ -1,129 +1,353 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.api; -import io.swagger.client.ApiException; +import io.swagger.client.ApiCallback; import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; import io.swagger.client.Configuration; import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; -import javax.ws.rs.core.GenericType; +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; import org.joda.time.LocalDate; -import java.math.BigDecimal; import org.joda.time.DateTime; +import java.math.BigDecimal; +import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - public class FakeApi { - private ApiClient apiClient; - - public FakeApi() { - this(Configuration.getDefaultApiClient()); - } - - public FakeApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * @param number None (required) - * @param _double None (required) - * @param string None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @throws ApiException if fails to make API call - */ - public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'number' is set - if (number == null) { - throw new ApiException(400, "Missing the required parameter 'number' when calling testEndpointParameters"); + private ApiClient apiClient; + + public FakeApi() { + this(Configuration.getDefaultApiClient()); + } + + public FakeApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; } - - // verify the required parameter '_double' is set - if (_double == null) { - throw new ApiException(400, "Missing the required parameter '_double' when calling testEndpointParameters"); + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; } - - // verify the required parameter 'string' is set - if (string == null) { - throw new ApiException(400, "Missing the required parameter 'string' when calling testEndpointParameters"); + + /* Build call for testEndpointParameters */ + private com.squareup.okhttp.Call testEndpointParametersCall(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'number' is set + if (number == null) { + throw new ApiException("Missing the required parameter 'number' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter '_double' is set + if (_double == null) { + throw new ApiException("Missing the required parameter '_double' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter 'string' is set + if (string == null) { + throw new ApiException("Missing the required parameter 'string' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter '_byte' is set + if (_byte == null) { + throw new ApiException("Missing the required parameter '_byte' when calling testEndpointParameters(Async)"); + } + + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (integer != null) + localVarFormParams.put("integer", integer); + if (int32 != null) + localVarFormParams.put("int32", int32); + if (int64 != null) + localVarFormParams.put("int64", int64); + if (number != null) + localVarFormParams.put("number", number); + if (_float != null) + localVarFormParams.put("float", _float); + if (_double != null) + localVarFormParams.put("double", _double); + if (string != null) + localVarFormParams.put("string", string); + if (_byte != null) + localVarFormParams.put("byte", _byte); + if (binary != null) + localVarFormParams.put("binary", binary); + if (date != null) + localVarFormParams.put("date", date); + if (dateTime != null) + localVarFormParams.put("dateTime", dateTime); + if (password != null) + localVarFormParams.put("password", password); + + final String[] localVarAccepts = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - - // verify the required parameter '_byte' is set - if (_byte == null) { - throw new ApiException(400, "Missing the required parameter '_byte' when calling testEndpointParameters"); + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param string None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { + testEndpointParametersWithHttpInfo(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param string None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { + com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password, null, null); + return apiClient.execute(call); + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 (asynchronously) + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param string None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call testEndpointParametersAsync(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for testEnumQueryParameters */ + private com.squareup.okhttp.Call testEnumQueryParametersCall(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (enumQueryInteger != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_integer", enumQueryInteger)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (enumQueryString != null) + localVarFormParams.put("enum_query_string", enumQueryString); + if (enumQueryDouble != null) + localVarFormParams.put("enum_query_double", enumQueryDouble); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * To test enum query parameters + * + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void testEnumQueryParameters(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { + testEnumQueryParametersWithHttpInfo(enumQueryString, enumQueryInteger, enumQueryDouble); + } + + /** + * To test enum query parameters + * + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse testEnumQueryParametersWithHttpInfo(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { + com.squareup.okhttp.Call call = testEnumQueryParametersCall(enumQueryString, enumQueryInteger, enumQueryDouble, null, null); + return apiClient.execute(call); + } + + /** + * To test enum query parameters (asynchronously) + * + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call testEnumQueryParametersAsync(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = testEnumQueryParametersCall(enumQueryString, enumQueryInteger, enumQueryDouble, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; } - - // create path and map variables - String localVarPath = "/fake".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - if (integer != null) - localVarFormParams.put("integer", integer); -if (int32 != null) - localVarFormParams.put("int32", int32); -if (int64 != null) - localVarFormParams.put("int64", int64); -if (number != null) - localVarFormParams.put("number", number); -if (_float != null) - localVarFormParams.put("float", _float); -if (_double != null) - localVarFormParams.put("double", _double); -if (string != null) - localVarFormParams.put("string", string); -if (_byte != null) - localVarFormParams.put("byte", _byte); -if (binary != null) - localVarFormParams.put("binary", binary); -if (date != null) - localVarFormParams.put("date", date); -if (dateTime != null) - localVarFormParams.put("dateTime", dateTime); -if (password != null) - localVarFormParams.put("password", password); - - final String[] localVarAccepts = { - "application/xml; charset=utf-8", "application/json; charset=utf-8" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - "application/xml; charset=utf-8", "application/json; charset=utf-8" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java index ad66598406d..2039a8842c1 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 @@ -1,384 +1,935 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.api; -import io.swagger.client.ApiException; +import io.swagger.client.ApiCallback; import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; import io.swagger.client.Configuration; import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; -import javax.ws.rs.core.GenericType; +import java.io.IOException; import io.swagger.client.model.Pet; -import io.swagger.client.model.ModelApiResponse; import java.io.File; +import io.swagger.client.model.ModelApiResponse; +import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - public class PetApi { - private ApiClient apiClient; - - public PetApi() { - this(Configuration.getDefaultApiClient()); - } - - public PetApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store (required) - * @throws ApiException if fails to make API call - */ - public void addPet(Pet body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling addPet"); - } - - // create path and map variables - String localVarPath = "/pet".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - "application/json", "application/xml" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - - apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Deletes a pet - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @throws ApiException if fails to make API call - */ - public void deletePet(Long petId, String apiKey) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling deletePet"); - } - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - if (apiKey != null) - localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - - apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Finds Pets by status - * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for filter (required) - * @return List - * @throws ApiException if fails to make API call - */ - public List findPetsByStatus(List status) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'status' is set - if (status == null) { - throw new ApiException(400, "Missing the required parameter 'status' when calling findPetsByStatus"); - } - - // create path and map variables - String localVarPath = "/pet/findByStatus".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "status", status)); - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - GenericType> localVarReturnType = new GenericType>() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Finds Pets by tags - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by (required) - * @return List - * @throws ApiException if fails to make API call - */ - public List findPetsByTags(List tags) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'tags' is set - if (tags == null) { - throw new ApiException(400, "Missing the required parameter 'tags' when calling findPetsByTags"); - } - - // create path and map variables - String localVarPath = "/pet/findByTags".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "tags", tags)); - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - GenericType> localVarReturnType = new GenericType>() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Find pet by ID - * Returns a single pet - * @param petId ID of pet to return (required) - * @return Pet - * @throws ApiException if fails to make API call - */ - public Pet getPetById(Long petId) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling getPetById"); - } - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "api_key" }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store (required) - * @throws ApiException if fails to make API call - */ - public void updatePet(Pet body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling updatePet"); - } - - // create path and map variables - String localVarPath = "/pet".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - "application/json", "application/xml" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - - apiClient.invokeAPI(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @throws ApiException if fails to make API call - */ - public void updatePetWithForm(Long petId, String name, String status) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling updatePetWithForm"); - } - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - if (name != null) - localVarFormParams.put("name", name); -if (status != null) - localVarFormParams.put("status", status); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - "application/x-www-form-urlencoded" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - - apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * uploads an image - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @return ModelApiResponse - * @throws ApiException if fails to make API call - */ - public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling uploadFile"); - } - - // create path and map variables - String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - if (additionalMetadata != null) - localVarFormParams.put("additionalMetadata", additionalMetadata); -if (file != null) - localVarFormParams.put("file", file); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - "multipart/form-data" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } + private ApiClient apiClient; + + public PetApi() { + this(Configuration.getDefaultApiClient()); + } + + public PetApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for addPet */ + private com.squareup.okhttp.Call addPetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling addPet(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void addPet(Pet body) throws ApiException { + addPetWithHttpInfo(body); + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse addPetWithHttpInfo(Pet body) throws ApiException { + com.squareup.okhttp.Call call = addPetCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Add a new pet to the store (asynchronously) + * + * @param body Pet object that needs to be added to the store (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call addPetAsync(Pet body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = addPetCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for deletePet */ + private com.squareup.okhttp.Call deletePetCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling deletePet(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + if (apiKey != null) + localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deletePet(Long petId, String apiKey) throws ApiException { + deletePetWithHttpInfo(petId, apiKey); + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deletePetWithHttpInfo(Long petId, String apiKey) throws ApiException { + com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, null, null); + return apiClient.execute(call); + } + + /** + * Deletes a pet (asynchronously) + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deletePetAsync(Long petId, String apiKey, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for findPetsByStatus */ + private com.squareup.okhttp.Call findPetsByStatusCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'status' is set + if (status == null) { + throw new ApiException("Missing the required parameter 'status' when calling findPetsByStatus(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/findByStatus".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (status != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "status", status)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return List<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public List findPetsByStatus(List status) throws ApiException { + ApiResponse> resp = findPetsByStatusWithHttpInfo(status); + return resp.getData(); + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return ApiResponse<List<Pet>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> findPetsByStatusWithHttpInfo(List status) throws ApiException { + com.squareup.okhttp.Call call = findPetsByStatusCall(status, null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Finds Pets by status (asynchronously) + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call findPetsByStatusAsync(List status, final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = findPetsByStatusCall(status, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for findPetsByTags */ + private com.squareup.okhttp.Call findPetsByTagsCall(List tags, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'tags' is set + if (tags == null) { + throw new ApiException("Missing the required parameter 'tags' when calling findPetsByTags(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/findByTags".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (tags != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "tags", tags)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return List<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public List findPetsByTags(List tags) throws ApiException { + ApiResponse> resp = findPetsByTagsWithHttpInfo(tags); + return resp.getData(); + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return ApiResponse<List<Pet>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> findPetsByTagsWithHttpInfo(List tags) throws ApiException { + com.squareup.okhttp.Call call = findPetsByTagsCall(tags, null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Finds Pets by tags (asynchronously) + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call findPetsByTagsAsync(List tags, final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = findPetsByTagsCall(tags, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for getPetById */ + private com.squareup.okhttp.Call getPetByIdCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling getPetById(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "api_key" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return Pet + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Pet getPetById(Long petId) throws ApiException { + ApiResponse resp = getPetByIdWithHttpInfo(petId); + return resp.getData(); + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return ApiResponse<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getPetByIdWithHttpInfo(Long petId) throws ApiException { + com.squareup.okhttp.Call call = getPetByIdCall(petId, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Find pet by ID (asynchronously) + * Returns a single pet + * @param petId ID of pet to return (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getPetByIdAsync(Long petId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getPetByIdCall(petId, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for updatePet */ + private com.squareup.okhttp.Call updatePetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling updatePet(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updatePet(Pet body) throws ApiException { + updatePetWithHttpInfo(body); + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updatePetWithHttpInfo(Pet body) throws ApiException { + com.squareup.okhttp.Call call = updatePetCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Update an existing pet (asynchronously) + * + * @param body Pet object that needs to be added to the store (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updatePetAsync(Pet body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updatePetCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for updatePetWithForm */ + private com.squareup.okhttp.Call updatePetWithFormCall(Long petId, String name, String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling updatePetWithForm(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (name != null) + localVarFormParams.put("name", name); + if (status != null) + localVarFormParams.put("status", status); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/x-www-form-urlencoded" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updatePetWithForm(Long petId, String name, String status) throws ApiException { + updatePetWithFormWithHttpInfo(petId, name, status); + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updatePetWithFormWithHttpInfo(Long petId, String name, String status) throws ApiException { + com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, null, null); + return apiClient.execute(call); + } + + /** + * Updates a pet in the store with form data (asynchronously) + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updatePetWithFormAsync(Long petId, String name, String status, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for uploadFile */ + private com.squareup.okhttp.Call uploadFileCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling uploadFile(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (additionalMetadata != null) + localVarFormParams.put("additionalMetadata", additionalMetadata); + if (file != null) + localVarFormParams.put("file", file); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ModelApiResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { + ApiResponse resp = uploadFileWithHttpInfo(petId, additionalMetadata, file); + return resp.getData(); + } + + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ApiResponse<ModelApiResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file) throws ApiException { + com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * uploads an image (asynchronously) + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call uploadFileAsync(Long petId, String additionalMetadata, File file, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } } diff --git a/samples/client/petstore/java/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 c0c9a166ad7..0768744c263 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 @@ -1,196 +1,482 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.api; -import io.swagger.client.ApiException; +import io.swagger.client.ApiCallback; import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; import io.swagger.client.Configuration; import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; -import javax.ws.rs.core.GenericType; +import java.io.IOException; import io.swagger.client.model.Order; +import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - public class StoreApi { - private ApiClient apiClient; - - public StoreApi() { - this(Configuration.getDefaultApiClient()); - } - - public StoreApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted (required) - * @throws ApiException if fails to make API call - */ - public void deleteOrder(String orderId) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder"); - } - - // create path and map variables - String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - * @return Map - * @throws ApiException if fails to make API call - */ - public Map getInventory() throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/store/inventory".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "api_key" }; - - GenericType> localVarReturnType = new GenericType>() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched (required) - * @return Order - * @throws ApiException if fails to make API call - */ - public Order getOrderById(Long orderId) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById"); - } - - // create path and map variables - String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet (required) - * @return Order - * @throws ApiException if fails to make API call - */ - public Order placeOrder(Order body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling placeOrder"); - } - - // create path and map variables - String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } + private ApiClient apiClient; + + public StoreApi() { + this(Configuration.getDefaultApiClient()); + } + + public StoreApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for deleteOrder */ + private com.squareup.okhttp.Call deleteOrderCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling deleteOrder(Async)"); + } + + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deleteOrder(String orderId) throws ApiException { + deleteOrderWithHttpInfo(orderId); + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deleteOrderWithHttpInfo(String orderId) throws ApiException { + com.squareup.okhttp.Call call = deleteOrderCall(orderId, null, null); + return apiClient.execute(call); + } + + /** + * Delete purchase order by ID (asynchronously) + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deleteOrderAsync(String orderId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = deleteOrderCall(orderId, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for getInventory */ + private com.squareup.okhttp.Call getInventoryCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + + // create path and map variables + String localVarPath = "/store/inventory".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "api_key" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return Map<String, Integer> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Map getInventory() throws ApiException { + ApiResponse> resp = getInventoryWithHttpInfo(); + return resp.getData(); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return ApiResponse<Map<String, Integer>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> getInventoryWithHttpInfo() throws ApiException { + com.squareup.okhttp.Call call = getInventoryCall(null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Returns pet inventories by status (asynchronously) + * Returns a map of status codes to quantities + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getInventoryAsync(final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getInventoryCall(progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for getOrderById */ + private com.squareup.okhttp.Call getOrderByIdCall(Long orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling getOrderById(Async)"); + } + + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @return Order + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Order getOrderById(Long orderId) throws ApiException { + ApiResponse resp = getOrderByIdWithHttpInfo(orderId); + return resp.getData(); + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @return ApiResponse<Order> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getOrderByIdWithHttpInfo(Long orderId) throws ApiException { + com.squareup.okhttp.Call call = getOrderByIdCall(orderId, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Find purchase order by ID (asynchronously) + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getOrderByIdAsync(Long orderId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getOrderByIdCall(orderId, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for placeOrder */ + private com.squareup.okhttp.Call placeOrderCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling placeOrder(Async)"); + } + + + // create path and map variables + String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet (required) + * @return Order + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Order placeOrder(Order body) throws ApiException { + ApiResponse resp = placeOrderWithHttpInfo(body); + return resp.getData(); + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet (required) + * @return ApiResponse<Order> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse placeOrderWithHttpInfo(Order body) throws ApiException { + com.squareup.okhttp.Call call = placeOrderCall(body, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Place an order for a pet (asynchronously) + * + * @param body order placed for purchasing the pet (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call placeOrderAsync(Order body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = placeOrderCall(body, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } } diff --git a/samples/client/petstore/java/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 7602f4e2ba9..1c4fc3101a1 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 @@ -1,370 +1,907 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.api; -import io.swagger.client.ApiException; +import io.swagger.client.ApiCallback; import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; import io.swagger.client.Configuration; import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; -import javax.ws.rs.core.GenericType; +import java.io.IOException; import io.swagger.client.model.User; +import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - public class UserApi { - private ApiClient apiClient; - - public UserApi() { - this(Configuration.getDefaultApiClient()); - } - - public UserApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object (required) - * @throws ApiException if fails to make API call - */ - public void createUser(User body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling createUser"); - } - - // create path and map variables - String localVarPath = "/user".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @throws ApiException if fails to make API call - */ - public void createUsersWithArrayInput(List body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling createUsersWithArrayInput"); - } - - // create path and map variables - String localVarPath = "/user/createWithArray".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @throws ApiException if fails to make API call - */ - public void createUsersWithListInput(List body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling createUsersWithListInput"); - } - - // create path and map variables - String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @throws ApiException if fails to make API call - */ - public void deleteUser(String username) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling deleteUser"); - } - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return User - * @throws ApiException if fails to make API call - */ - public User getUserByName(String username) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling getUserByName"); - } - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Logs user into the system - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @return String - * @throws ApiException if fails to make API call - */ - public String loginUser(String username, String password) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling loginUser"); - } - - // verify the required parameter 'password' is set - if (password == null) { - throw new ApiException(400, "Missing the required parameter 'password' when calling loginUser"); - } - - // create path and map variables - String localVarPath = "/user/login".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - localVarQueryParams.addAll(apiClient.parameterToPairs("", "username", username)); - localVarQueryParams.addAll(apiClient.parameterToPairs("", "password", password)); - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Logs out current logged in user session - * - * @throws ApiException if fails to make API call - */ - public void logoutUser() throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/user/logout".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @throws ApiException if fails to make API call - */ - public void updateUser(String username, User body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser"); - } - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling updateUser"); - } - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } + private ApiClient apiClient; + + public UserApi() { + this(Configuration.getDefaultApiClient()); + } + + public UserApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for createUser */ + private com.squareup.okhttp.Call createUserCall(User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUser(User body) throws ApiException { + createUserWithHttpInfo(body); + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUserWithHttpInfo(User body) throws ApiException { + com.squareup.okhttp.Call call = createUserCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Create user (asynchronously) + * This can only be done by the logged in user. + * @param body Created user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUserAsync(User body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = createUserCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for createUsersWithArrayInput */ + private com.squareup.okhttp.Call createUsersWithArrayInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUsersWithArrayInput(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/createWithArray".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUsersWithArrayInput(List body) throws ApiException { + createUsersWithArrayInputWithHttpInfo(body); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUsersWithArrayInputWithHttpInfo(List body) throws ApiException { + com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Creates list of users with given input array (asynchronously) + * + * @param body List of user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUsersWithArrayInputAsync(List body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for createUsersWithListInput */ + private com.squareup.okhttp.Call createUsersWithListInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUsersWithListInput(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUsersWithListInput(List body) throws ApiException { + createUsersWithListInputWithHttpInfo(body); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUsersWithListInputWithHttpInfo(List body) throws ApiException { + com.squareup.okhttp.Call call = createUsersWithListInputCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Creates list of users with given input array (asynchronously) + * + * @param body List of user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUsersWithListInputAsync(List body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = createUsersWithListInputCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for deleteUser */ + private com.squareup.okhttp.Call deleteUserCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling deleteUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deleteUser(String username) throws ApiException { + deleteUserWithHttpInfo(username); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deleteUserWithHttpInfo(String username) throws ApiException { + com.squareup.okhttp.Call call = deleteUserCall(username, null, null); + return apiClient.execute(call); + } + + /** + * Delete user (asynchronously) + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deleteUserAsync(String username, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = deleteUserCall(username, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for getUserByName */ + private com.squareup.okhttp.Call getUserByNameCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling getUserByName(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return User + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public User getUserByName(String username) throws ApiException { + ApiResponse resp = getUserByNameWithHttpInfo(username); + return resp.getData(); + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return ApiResponse<User> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getUserByNameWithHttpInfo(String username) throws ApiException { + com.squareup.okhttp.Call call = getUserByNameCall(username, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Get user by user name (asynchronously) + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getUserByNameAsync(String username, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getUserByNameCall(username, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for loginUser */ + private com.squareup.okhttp.Call loginUserCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling loginUser(Async)"); + } + + // verify the required parameter 'password' is set + if (password == null) { + throw new ApiException("Missing the required parameter 'password' when calling loginUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/login".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (username != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "username", username)); + if (password != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "password", password)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return String + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public String loginUser(String username, String password) throws ApiException { + ApiResponse resp = loginUserWithHttpInfo(username, password); + return resp.getData(); + } + + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return ApiResponse<String> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse loginUserWithHttpInfo(String username, String password) throws ApiException { + com.squareup.okhttp.Call call = loginUserCall(username, password, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Logs user into the system (asynchronously) + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call loginUserAsync(String username, String password, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = loginUserCall(username, password, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for logoutUser */ + private com.squareup.okhttp.Call logoutUserCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + + // create path and map variables + String localVarPath = "/user/logout".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Logs out current logged in user session + * + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void logoutUser() throws ApiException { + logoutUserWithHttpInfo(); + } + + /** + * Logs out current logged in user session + * + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse logoutUserWithHttpInfo() throws ApiException { + com.squareup.okhttp.Call call = logoutUserCall(null, null); + return apiClient.execute(call); + } + + /** + * Logs out current logged in user session (asynchronously) + * + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call logoutUserAsync(final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = logoutUserCall(progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for updateUser */ + private com.squareup.okhttp.Call updateUserCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling updateUser(Async)"); + } + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling updateUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updateUser(String username, User body) throws ApiException { + updateUserWithHttpInfo(username, body); + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updateUserWithHttpInfo(String username, User body) throws ApiException { + com.squareup.okhttp.Call call = updateUserCall(username, body, null, null); + return apiClient.execute(call); + } + + /** + * Updated user (asynchronously) + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updateUserAsync(String username, User body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updateUserCall(username, body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index 6ba15566b60..a125fff5f24 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -1,6 +1,6 @@ /** * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java index a063a6998b5..221a7d9dd1f 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java @@ -1,6 +1,6 @@ /** * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 5895370e4d4..4eb2300b69d 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -1,6 +1,6 @@ /** * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io @@ -27,44 +27,40 @@ import io.swagger.client.Pair; -import com.migcomponents.migbase64.Base64; +import com.squareup.okhttp.Credentials; import java.util.Map; import java.util.List; import java.io.UnsupportedEncodingException; - public class HttpBasicAuth implements Authentication { - private String username; - private String password; - - public String getUsername() { - return username; - } + private String username; + private String password; - public void setUsername(String username) { - this.username = username; - } + public String getUsername() { + return username; + } - public String getPassword() { - return password; - } + public void setUsername(String username) { + this.username = username; + } - public void setPassword(String password) { - this.password = password; - } + public String getPassword() { + return password; + } - @Override - public void applyToParams(List queryParams, Map headerParams) { - if (username == null && password == null) { - return; + public void setPassword(String password) { + this.password = password; } - String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); - try { - headerParams.put("Authorization", "Basic " + Base64.encodeToString(str.getBytes("UTF-8"), false)); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); + + @Override + public void applyToParams(List queryParams, Map headerParams) { + if (username == null && password == null) { + return; + } + headerParams.put("Authorization", Credentials.basic( + username == null ? "" : username, + password == null ? "" : password)); } - } } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java index 8802ebc92c8..14521f6ed7e 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java @@ -1,6 +1,6 @@ /** * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuthFlow.java index ec1f942b0f2..50d5260cfd9 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,6 +1,6 @@ /** * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index ccaba7709c4..1943e013fa1 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; @@ -15,40 +39,44 @@ */ public class AdditionalPropertiesClass { - + @SerializedName("map_property") private Map mapProperty = new HashMap(); + + @SerializedName("map_of_map_property") private Map> mapOfMapProperty = new HashMap>(); - - /** - **/ public AdditionalPropertiesClass mapProperty(Map mapProperty) { this.mapProperty = mapProperty; return this; } - + + /** + * Get mapProperty + * @return mapProperty + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("map_property") public Map getMapProperty() { return mapProperty; } + public void setMapProperty(Map mapProperty) { this.mapProperty = mapProperty; } - - /** - **/ public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { this.mapOfMapProperty = mapOfMapProperty; return this; } - + + /** + * Get mapOfMapProperty + * @return mapOfMapProperty + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("map_of_map_property") public Map> getMapOfMapProperty() { return mapOfMapProperty; } + public void setMapOfMapProperty(Map> mapOfMapProperty) { this.mapOfMapProperty = mapOfMapProperty; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java index 25c7d3e421c..ba3806dc875 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,40 +36,44 @@ */ public class Animal { - + @SerializedName("className") private String className = null; + + @SerializedName("color") private String color = "red"; - - /** - **/ public Animal className(String className) { this.className = className; return this; } - + + /** + * Get className + * @return className + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("className") public String getClassName() { return className; } + public void setClassName(String className) { this.className = className; } - - /** - **/ public Animal color(String color) { this.color = color; return this; } - + + /** + * Get color + * @return color + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("color") public String getColor() { return color; } + public void setColor(String color) { this.color = color; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AnimalFarm.java index 647e3a893e1..b54adb09d7b 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -1,6 +1,30 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import io.swagger.client.model.Animal; import java.util.ArrayList; @@ -12,9 +36,7 @@ */ public class AnimalFarm extends ArrayList { - - @Override public boolean equals(java.lang.Object o) { if (this == o) { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 00000000000..5446c2c439b --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,102 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + + +/** + * ArrayOfArrayOfNumberOnly + */ + +public class ArrayOfArrayOfNumberOnly { + @SerializedName("ArrayArrayNumber") + private List> arrayArrayNumber = new ArrayList>(); + + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + /** + * Get arrayArrayNumber + * @return arrayArrayNumber + **/ + @ApiModelProperty(example = "null", value = "") + public List> getArrayArrayNumber() { + return arrayArrayNumber; + } + + public void setArrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly = (ArrayOfArrayOfNumberOnly) o; + return Objects.equals(this.arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayArrayNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfArrayOfNumberOnly {\n"); + + sb.append(" arrayArrayNumber: ").append(toIndentedString(arrayArrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java new file mode 100644 index 00000000000..c9257a5d3ee --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -0,0 +1,102 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + + +/** + * ArrayOfNumberOnly + */ + +public class ArrayOfNumberOnly { + @SerializedName("ArrayNumber") + private List arrayNumber = new ArrayList(); + + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + /** + * Get arrayNumber + * @return arrayNumber + **/ + @ApiModelProperty(example = "null", value = "") + public List getArrayNumber() { + return arrayNumber; + } + + public void setArrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfNumberOnly arrayOfNumberOnly = (ArrayOfNumberOnly) o; + return Objects.equals(this.arrayNumber, arrayOfNumberOnly.arrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfNumberOnly {\n"); + + sb.append(" arrayNumber: ").append(toIndentedString(arrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayTest.java index 6c1eb23d8d0..8d58870bcdc 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayTest.java @@ -1,10 +1,35 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.ReadOnlyFirst; import java.util.ArrayList; import java.util.List; @@ -14,58 +39,65 @@ */ public class ArrayTest { - + @SerializedName("array_of_string") private List arrayOfString = new ArrayList(); + + @SerializedName("array_array_of_integer") private List> arrayArrayOfInteger = new ArrayList>(); + + @SerializedName("array_array_of_model") private List> arrayArrayOfModel = new ArrayList>(); - - /** - **/ public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; return this; } - + + /** + * Get arrayOfString + * @return arrayOfString + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("array_of_string") public List getArrayOfString() { return arrayOfString; } + public void setArrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; } - - /** - **/ public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; return this; } - + + /** + * Get arrayArrayOfInteger + * @return arrayArrayOfInteger + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("array_array_of_integer") public List> getArrayArrayOfInteger() { return arrayArrayOfInteger; } + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - - /** - **/ public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } - + + /** + * Get arrayArrayOfModel + * @return arrayArrayOfModel + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("array_array_of_model") public List> getArrayArrayOfModel() { return arrayArrayOfModel; } + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Cat.java index 5ef9e23bd96..21ed0f4c26b 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Cat.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -13,58 +37,65 @@ */ public class Cat extends Animal { - + @SerializedName("className") private String className = null; + + @SerializedName("color") private String color = "red"; + + @SerializedName("declawed") private Boolean declawed = null; - - /** - **/ public Cat className(String className) { this.className = className; return this; } - + + /** + * Get className + * @return className + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("className") public String getClassName() { return className; } + public void setClassName(String className) { this.className = className; } - - /** - **/ public Cat color(String color) { this.color = color; return this; } - + + /** + * Get color + * @return color + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("color") public String getColor() { return color; } + public void setColor(String color) { this.color = color; } - - /** - **/ public Cat declawed(Boolean declawed) { this.declawed = declawed; return this; } - + + /** + * Get declawed + * @return declawed + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("declawed") public Boolean getDeclawed() { return declawed; } + public void setDeclawed(Boolean declawed) { this.declawed = declawed; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java index c6cb703a89e..2178a866f62 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,40 +36,44 @@ */ public class Category { - + @SerializedName("id") private Long id = null; + + @SerializedName("name") private String name = null; - - /** - **/ public Category id(Long id) { this.id = id; return this; } - + + /** + * Get id + * @return id + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - - /** - **/ public Category name(String name) { this.name = name; return this; } - + + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Dog.java index 4b3cc947cc5..4ba5804553f 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Dog.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -13,58 +37,65 @@ */ public class Dog extends Animal { - + @SerializedName("className") private String className = null; + + @SerializedName("color") private String color = "red"; + + @SerializedName("breed") private String breed = null; - - /** - **/ public Dog className(String className) { this.className = className; return this; } - + + /** + * Get className + * @return className + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("className") public String getClassName() { return className; } + public void setClassName(String className) { this.className = className; } - - /** - **/ public Dog color(String color) { this.color = color; return this; } - + + /** + * Get color + * @return color + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("color") public String getColor() { return color; } + public void setColor(String color) { this.color = color; } - - /** - **/ public Dog breed(String breed) { this.breed = breed; return this; } - + + /** + * Get breed + * @return breed + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("breed") public String getBreed() { return breed; } + public void setBreed(String breed) { this.breed = breed; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumClass.java index 42434e297ff..73484907229 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumClass.java @@ -1,16 +1,46 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonValue; +import com.google.gson.annotations.SerializedName; /** * Gets or Sets EnumClass */ public enum EnumClass { + + @SerializedName("_abc") _ABC("_abc"), + + @SerializedName("-efg") _EFG("-efg"), + + @SerializedName("(xyz)") _XYZ_("(xyz)"); private String value; @@ -20,7 +50,6 @@ public enum EnumClass { } @Override - @JsonValue public String toString() { return String.valueOf(value); } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java index 1c8657fd3ec..9aad1223215 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java @@ -1,9 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonValue; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -13,13 +36,14 @@ */ public class EnumTest { - - /** * Gets or Sets enumString */ public enum EnumStringEnum { + @SerializedName("UPPER") UPPER("UPPER"), + + @SerializedName("lower") LOWER("lower"); private String value; @@ -29,19 +53,22 @@ public enum EnumStringEnum { } @Override - @JsonValue public String toString() { return String.valueOf(value); } } + @SerializedName("enum_string") private EnumStringEnum enumString = null; /** * Gets or Sets enumInteger */ public enum EnumIntegerEnum { + @SerializedName("1") NUMBER_1(1), + + @SerializedName("-1") NUMBER_MINUS_1(-1); private Integer value; @@ -51,19 +78,22 @@ public enum EnumIntegerEnum { } @Override - @JsonValue public String toString() { return String.valueOf(value); } } + @SerializedName("enum_integer") private EnumIntegerEnum enumInteger = null; /** * Gets or Sets enumNumber */ public enum EnumNumberEnum { + @SerializedName("1.1") NUMBER_1_DOT_1(1.1), + + @SerializedName("-1.2") NUMBER_MINUS_1_DOT_2(-1.2); private Double value; @@ -73,61 +103,64 @@ public enum EnumNumberEnum { } @Override - @JsonValue public String toString() { return String.valueOf(value); } } + @SerializedName("enum_number") private EnumNumberEnum enumNumber = null; - - /** - **/ public EnumTest enumString(EnumStringEnum enumString) { this.enumString = enumString; return this; } - + + /** + * Get enumString + * @return enumString + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("enum_string") public EnumStringEnum getEnumString() { return enumString; } + public void setEnumString(EnumStringEnum enumString) { this.enumString = enumString; } - - /** - **/ public EnumTest enumInteger(EnumIntegerEnum enumInteger) { this.enumInteger = enumInteger; return this; } - + + /** + * Get enumInteger + * @return enumInteger + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("enum_integer") public EnumIntegerEnum getEnumInteger() { return enumInteger; } + public void setEnumInteger(EnumIntegerEnum enumInteger) { this.enumInteger = enumInteger; } - - /** - **/ public EnumTest enumNumber(EnumNumberEnum enumNumber) { this.enumNumber = enumNumber; return this; } - + + /** + * Get enumNumber + * @return enumNumber + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("enum_number") public EnumNumberEnum getEnumNumber() { return enumNumber; } + public void setEnumNumber(EnumNumberEnum enumNumber) { this.enumNumber = enumNumber; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/FormatTest.java index 79376150017..91109681509 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/FormatTest.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; @@ -15,248 +39,285 @@ */ public class FormatTest { - + @SerializedName("integer") private Integer integer = null; + + @SerializedName("int32") private Integer int32 = null; + + @SerializedName("int64") private Long int64 = null; + + @SerializedName("number") private BigDecimal number = null; + + @SerializedName("float") private Float _float = null; + + @SerializedName("double") private Double _double = null; + + @SerializedName("string") private String string = null; + + @SerializedName("byte") private byte[] _byte = null; + + @SerializedName("binary") private byte[] binary = null; + + @SerializedName("date") private LocalDate date = null; + + @SerializedName("dateTime") private DateTime dateTime = null; + + @SerializedName("uuid") private String uuid = null; + + @SerializedName("password") private String password = null; - - /** - * minimum: 10.0 - * maximum: 100.0 - **/ public FormatTest integer(Integer integer) { this.integer = integer; return this; } - + + /** + * Get integer + * minimum: 10.0 + * maximum: 100.0 + * @return integer + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("integer") public Integer getInteger() { return integer; } + public void setInteger(Integer integer) { this.integer = integer; } - - /** - * minimum: 20.0 - * maximum: 200.0 - **/ public FormatTest int32(Integer int32) { this.int32 = int32; return this; } - + + /** + * Get int32 + * minimum: 20.0 + * maximum: 200.0 + * @return int32 + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("int32") public Integer getInt32() { return int32; } + public void setInt32(Integer int32) { this.int32 = int32; } - - /** - **/ public FormatTest int64(Long int64) { this.int64 = int64; return this; } - + + /** + * Get int64 + * @return int64 + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("int64") public Long getInt64() { return int64; } + public void setInt64(Long int64) { this.int64 = int64; } - - /** - * minimum: 32.1 - * maximum: 543.2 - **/ public FormatTest number(BigDecimal number) { this.number = number; return this; } - + + /** + * Get number + * minimum: 32.1 + * maximum: 543.2 + * @return number + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("number") public BigDecimal getNumber() { return number; } + public void setNumber(BigDecimal number) { this.number = number; } - - /** - * minimum: 54.3 - * maximum: 987.6 - **/ public FormatTest _float(Float _float) { this._float = _float; return this; } - + + /** + * Get _float + * minimum: 54.3 + * maximum: 987.6 + * @return _float + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("float") public Float getFloat() { return _float; } + public void setFloat(Float _float) { this._float = _float; } - - /** - * minimum: 67.8 - * maximum: 123.4 - **/ public FormatTest _double(Double _double) { this._double = _double; return this; } - + + /** + * Get _double + * minimum: 67.8 + * maximum: 123.4 + * @return _double + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("double") public Double getDouble() { return _double; } + public void setDouble(Double _double) { this._double = _double; } - - /** - **/ public FormatTest string(String string) { this.string = string; return this; } - + + /** + * Get string + * @return string + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("string") public String getString() { return string; } + public void setString(String string) { this.string = string; } - - /** - **/ public FormatTest _byte(byte[] _byte) { this._byte = _byte; return this; } - + + /** + * Get _byte + * @return _byte + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("byte") public byte[] getByte() { return _byte; } + public void setByte(byte[] _byte) { this._byte = _byte; } - - /** - **/ public FormatTest binary(byte[] binary) { this.binary = binary; return this; } - + + /** + * Get binary + * @return binary + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("binary") public byte[] getBinary() { return binary; } + public void setBinary(byte[] binary) { this.binary = binary; } - - /** - **/ public FormatTest date(LocalDate date) { this.date = date; return this; } - + + /** + * Get date + * @return date + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("date") public LocalDate getDate() { return date; } + public void setDate(LocalDate date) { this.date = date; } - - /** - **/ public FormatTest dateTime(DateTime dateTime) { this.dateTime = dateTime; return this; } - + + /** + * Get dateTime + * @return dateTime + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("dateTime") public DateTime getDateTime() { return dateTime; } + public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } - - /** - **/ public FormatTest uuid(String uuid) { this.uuid = uuid; return this; } - + + /** + * Get uuid + * @return uuid + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("uuid") public String getUuid() { return uuid; } + public void setUuid(String uuid) { this.uuid = uuid; } - - /** - **/ public FormatTest password(String password) { this.password = password; return this; } - + + /** + * Get password + * @return password + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("password") public String getPassword() { return password; } + public void setPassword(String password) { this.password = password; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java new file mode 100644 index 00000000000..d77fc7ac36b --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -0,0 +1,104 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +/** + * HasOnlyReadOnly + */ + +public class HasOnlyReadOnly { + @SerializedName("bar") + private String bar = null; + + @SerializedName("foo") + private String foo = null; + + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(example = "null", value = "") + public String getBar() { + return bar; + } + + /** + * Get foo + * @return foo + **/ + @ApiModelProperty(example = "null", value = "") + public String getFoo() { + return foo; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HasOnlyReadOnly hasOnlyReadOnly = (HasOnlyReadOnly) o; + return Objects.equals(this.bar, hasOnlyReadOnly.bar) && + Objects.equals(this.foo, hasOnlyReadOnly.foo); + } + + @Override + public int hashCode() { + return Objects.hash(bar, foo); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HasOnlyReadOnly {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" foo: ").append(toIndentedString(foo)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MapTest.java new file mode 100644 index 00000000000..61bdb6b2c65 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MapTest.java @@ -0,0 +1,147 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +/** + * MapTest + */ + +public class MapTest { + @SerializedName("map_map_of_string") + private Map> mapMapOfString = new HashMap>(); + + /** + * Gets or Sets inner + */ + public enum InnerEnum { + @SerializedName("UPPER") + UPPER("UPPER"), + + @SerializedName("lower") + LOWER("lower"); + + private String value; + + InnerEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + @SerializedName("map_of_enum_string") + private Map mapOfEnumString = new HashMap(); + + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + /** + * Get mapMapOfString + * @return mapMapOfString + **/ + @ApiModelProperty(example = "null", value = "") + public Map> getMapMapOfString() { + return mapMapOfString; + } + + public void setMapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + } + + public MapTest mapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + return this; + } + + /** + * Get mapOfEnumString + * @return mapOfEnumString + **/ + @ApiModelProperty(example = "null", value = "") + public Map getMapOfEnumString() { + return mapOfEnumString; + } + + public void setMapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MapTest mapTest = (MapTest) o; + return Objects.equals(this.mapMapOfString, mapTest.mapMapOfString) && + Objects.equals(this.mapOfEnumString, mapTest.mapOfEnumString); + } + + @Override + public int hashCode() { + return Objects.hash(mapMapOfString, mapOfEnumString); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MapTest {\n"); + + sb.append(" mapMapOfString: ").append(toIndentedString(mapMapOfString)).append("\n"); + sb.append(" mapOfEnumString: ").append(toIndentedString(mapOfEnumString)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 2f0972bf41e..6e587b1bf97 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -17,58 +41,65 @@ */ public class MixedPropertiesAndAdditionalPropertiesClass { - + @SerializedName("uuid") private String uuid = null; + + @SerializedName("dateTime") private DateTime dateTime = null; + + @SerializedName("map") private Map map = new HashMap(); - - /** - **/ public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { this.uuid = uuid; return this; } - + + /** + * Get uuid + * @return uuid + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("uuid") public String getUuid() { return uuid; } + public void setUuid(String uuid) { this.uuid = uuid; } - - /** - **/ public MixedPropertiesAndAdditionalPropertiesClass dateTime(DateTime dateTime) { this.dateTime = dateTime; return this; } - + + /** + * Get dateTime + * @return dateTime + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("dateTime") public DateTime getDateTime() { return dateTime; } + public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } - - /** - **/ public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { this.map = map; return this; } - + + /** + * Get map + * @return map + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("map") public Map getMap() { return map; } + public void setMap(Map map) { this.map = map; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Model200Response.java index eed3902b922..d8da58aca9c 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Model200Response.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -13,40 +37,44 @@ @ApiModel(description = "Model for testing model name starting with number") public class Model200Response { - + @SerializedName("name") private Integer name = null; + + @SerializedName("class") private String PropertyClass = null; - - /** - **/ public Model200Response name(Integer name) { this.name = name; return this; } - + + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("name") public Integer getName() { return name; } + public void setName(Integer name) { this.name = name; } - - /** - **/ public Model200Response PropertyClass(String PropertyClass) { this.PropertyClass = PropertyClass; return this; } - + + /** + * Get PropertyClass + * @return PropertyClass + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("class") public String getPropertyClass() { return PropertyClass; } + public void setPropertyClass(String PropertyClass) { this.PropertyClass = PropertyClass; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelApiResponse.java index 32fb86dd323..2a823298323 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,58 +36,65 @@ */ public class ModelApiResponse { - + @SerializedName("code") private Integer code = null; + + @SerializedName("type") private String type = null; + + @SerializedName("message") private String message = null; - - /** - **/ public ModelApiResponse code(Integer code) { this.code = code; return this; } - + + /** + * Get code + * @return code + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("code") public Integer getCode() { return code; } + public void setCode(Integer code) { this.code = code; } - - /** - **/ public ModelApiResponse type(String type) { this.type = type; return this; } - + + /** + * Get type + * @return type + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("type") public String getType() { return type; } + public void setType(String type) { this.type = type; } - - /** - **/ public ModelApiResponse message(String message) { this.message = message; return this; } - + + /** + * Get message + * @return message + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("message") public String getMessage() { return message; } + public void setMessage(String message) { this.message = message; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelReturn.java index a076d16f964..024a9c0df1c 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelReturn.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -13,22 +37,23 @@ @ApiModel(description = "Model for testing reserved words") public class ModelReturn { - + @SerializedName("return") private Integer _return = null; - - /** - **/ public ModelReturn _return(Integer _return) { this._return = _return; return this; } - + + /** + * Get _return + * @return _return + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("return") public Integer getReturn() { return _return; } + public void setReturn(Integer _return) { this._return = _return; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Name.java index 1ba2cc5e4a3..318a2ddd50e 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Name.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -13,56 +37,68 @@ @ApiModel(description = "Model for testing model name same as property name") public class Name { - + @SerializedName("name") private Integer name = null; + + @SerializedName("snake_case") private Integer snakeCase = null; + + @SerializedName("property") private String property = null; + + @SerializedName("123Number") private Integer _123Number = null; - - /** - **/ public Name name(Integer name) { this.name = name; return this; } - + + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("name") public Integer getName() { return name; } + public void setName(Integer name) { this.name = name; } - + /** + * Get snakeCase + * @return snakeCase + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("snake_case") public Integer getSnakeCase() { return snakeCase; } - - /** - **/ public Name property(String property) { this.property = property; return this; } - + + /** + * Get property + * @return property + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("property") public String getProperty() { return property; } + public void setProperty(String property) { this.property = property; } - + /** + * Get _123Number + * @return _123Number + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("123Number") public Integer get123Number() { return _123Number; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/NumberOnly.java new file mode 100644 index 00000000000..9b9ca048dfb --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/NumberOnly.java @@ -0,0 +1,100 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; + + +/** + * NumberOnly + */ + +public class NumberOnly { + @SerializedName("JustNumber") + private BigDecimal justNumber = null; + + public NumberOnly justNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + return this; + } + + /** + * Get justNumber + * @return justNumber + **/ + @ApiModelProperty(example = "null", value = "") + public BigDecimal getJustNumber() { + return justNumber; + } + + public void setJustNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NumberOnly numberOnly = (NumberOnly) o; + return Objects.equals(this.justNumber, numberOnly.justNumber); + } + + @Override + public int hashCode() { + return Objects.hash(justNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NumberOnly {\n"); + + sb.append(" justNumber: ").append(toIndentedString(justNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java index cec651e73a6..90cfd2f3892 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java @@ -1,9 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonValue; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.joda.time.DateTime; @@ -14,18 +37,29 @@ */ public class Order { - + @SerializedName("id") private Long id = null; + + @SerializedName("petId") private Long petId = null; + + @SerializedName("quantity") private Integer quantity = null; + + @SerializedName("shipDate") private DateTime shipDate = null; /** * Order Status */ public enum StatusEnum { + @SerializedName("placed") PLACED("placed"), + + @SerializedName("approved") APPROVED("approved"), + + @SerializedName("delivered") DELIVERED("delivered"); private String value; @@ -35,114 +69,121 @@ public enum StatusEnum { } @Override - @JsonValue public String toString() { return String.valueOf(value); } } + @SerializedName("status") private StatusEnum status = null; + + @SerializedName("complete") private Boolean complete = false; - - /** - **/ public Order id(Long id) { this.id = id; return this; } - + + /** + * Get id + * @return id + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - - /** - **/ public Order petId(Long petId) { this.petId = petId; return this; } - + + /** + * Get petId + * @return petId + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("petId") public Long getPetId() { return petId; } + public void setPetId(Long petId) { this.petId = petId; } - - /** - **/ public Order quantity(Integer quantity) { this.quantity = quantity; return this; } - + + /** + * Get quantity + * @return quantity + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("quantity") public Integer getQuantity() { return quantity; } + public void setQuantity(Integer quantity) { this.quantity = quantity; } - - /** - **/ public Order shipDate(DateTime shipDate) { this.shipDate = shipDate; return this; } - + + /** + * Get shipDate + * @return shipDate + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("shipDate") public DateTime getShipDate() { return shipDate; } + public void setShipDate(DateTime shipDate) { this.shipDate = shipDate; } - - /** - * Order Status - **/ public Order status(StatusEnum status) { this.status = status; return this; } - + + /** + * Order Status + * @return status + **/ @ApiModelProperty(example = "null", value = "Order Status") - @JsonProperty("status") public StatusEnum getStatus() { return status; } + public void setStatus(StatusEnum status) { this.status = status; } - - /** - **/ public Order complete(Boolean complete) { this.complete = complete; return this; } - + + /** + * Get complete + * @return complete + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("complete") public Boolean getComplete() { return complete; } + public void setComplete(Boolean complete) { this.complete = complete; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java index da8b76ad024..b80fdeaf923 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java @@ -1,9 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonValue; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Category; @@ -17,19 +40,32 @@ */ public class Pet { - + @SerializedName("id") private Long id = null; + + @SerializedName("category") private Category category = null; + + @SerializedName("name") private String name = null; + + @SerializedName("photoUrls") private List photoUrls = new ArrayList(); + + @SerializedName("tags") private List tags = new ArrayList(); /** * pet status in the store */ public enum StatusEnum { + @SerializedName("available") AVAILABLE("available"), + + @SerializedName("pending") PENDING("pending"), + + @SerializedName("sold") SOLD("sold"); private String value; @@ -39,113 +75,118 @@ public enum StatusEnum { } @Override - @JsonValue public String toString() { return String.valueOf(value); } } + @SerializedName("status") private StatusEnum status = null; - - /** - **/ public Pet id(Long id) { this.id = id; return this; } - + + /** + * Get id + * @return id + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - - /** - **/ public Pet category(Category category) { this.category = category; return this; } - + + /** + * Get category + * @return category + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("category") public Category getCategory() { return category; } + public void setCategory(Category category) { this.category = category; } - - /** - **/ public Pet name(String name) { this.name = name; return this; } - + + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "doggie", required = true, value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } - - /** - **/ public Pet photoUrls(List photoUrls) { this.photoUrls = photoUrls; return this; } - + + /** + * Get photoUrls + * @return photoUrls + **/ @ApiModelProperty(example = "null", required = true, value = "") - @JsonProperty("photoUrls") public List getPhotoUrls() { return photoUrls; } + public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } - - /** - **/ public Pet tags(List tags) { this.tags = tags; return this; } - + + /** + * Get tags + * @return tags + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("tags") public List getTags() { return tags; } + public void setTags(List tags) { this.tags = tags; } - - /** - * pet status in the store - **/ public Pet status(StatusEnum status) { this.status = status; return this; } - + + /** + * pet status in the store + * @return status + **/ @ApiModelProperty(example = "null", value = "pet status in the store") - @JsonProperty("status") public StatusEnum getStatus() { return status; } + public void setStatus(StatusEnum status) { this.status = status; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index fdc3587df0e..13b729bb94d 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,30 +36,35 @@ */ public class ReadOnlyFirst { - + @SerializedName("bar") private String bar = null; + + @SerializedName("baz") private String baz = null; - + /** + * Get bar + * @return bar + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("bar") public String getBar() { return bar; } - - /** - **/ public ReadOnlyFirst baz(String baz) { this.baz = baz; return this; } - + + /** + * Get baz + * @return baz + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("baz") public String getBaz() { return baz; } + public void setBaz(String baz) { this.baz = baz; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/SpecialModelName.java index 24e57756cb2..b46b8367a01 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,22 +36,23 @@ */ public class SpecialModelName { - + @SerializedName("$special[property.name]") private Long specialPropertyName = null; - - /** - **/ public SpecialModelName specialPropertyName(Long specialPropertyName) { this.specialPropertyName = specialPropertyName; return this; } - + + /** + * Get specialPropertyName + * @return specialPropertyName + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("$special[property.name]") public Long getSpecialPropertyName() { return specialPropertyName; } + public void setSpecialPropertyName(Long specialPropertyName) { this.specialPropertyName = specialPropertyName; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java index 9d3bdd8cb9e..e56eb535d1e 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,40 +36,44 @@ */ public class Tag { - + @SerializedName("id") private Long id = null; + + @SerializedName("name") private String name = null; - - /** - **/ public Tag id(Long id) { this.id = id; return this; } - + + /** + * Get id + * @return id + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - - /** - **/ public Tag name(String name) { this.name = name; return this; } - + + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java index f23553660de..6c1ed6ceacc 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java @@ -1,8 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; -import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -12,149 +36,170 @@ */ public class User { - + @SerializedName("id") private Long id = null; + + @SerializedName("username") private String username = null; + + @SerializedName("firstName") private String firstName = null; + + @SerializedName("lastName") private String lastName = null; + + @SerializedName("email") private String email = null; + + @SerializedName("password") private String password = null; + + @SerializedName("phone") private String phone = null; + + @SerializedName("userStatus") private Integer userStatus = null; - - /** - **/ public User id(Long id) { this.id = id; return this; } - + + /** + * Get id + * @return id + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - - /** - **/ public User username(String username) { this.username = username; return this; } - + + /** + * Get username + * @return username + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("username") public String getUsername() { return username; } + public void setUsername(String username) { this.username = username; } - - /** - **/ public User firstName(String firstName) { this.firstName = firstName; return this; } - + + /** + * Get firstName + * @return firstName + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("firstName") public String getFirstName() { return firstName; } + public void setFirstName(String firstName) { this.firstName = firstName; } - - /** - **/ public User lastName(String lastName) { this.lastName = lastName; return this; } - + + /** + * Get lastName + * @return lastName + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("lastName") public String getLastName() { return lastName; } + public void setLastName(String lastName) { this.lastName = lastName; } - - /** - **/ public User email(String email) { this.email = email; return this; } - + + /** + * Get email + * @return email + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("email") public String getEmail() { return email; } + public void setEmail(String email) { this.email = email; } - - /** - **/ public User password(String password) { this.password = password; return this; } - + + /** + * Get password + * @return password + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("password") public String getPassword() { return password; } + public void setPassword(String password) { this.password = password; } - - /** - **/ public User phone(String phone) { this.phone = phone; return this; } - + + /** + * Get phone + * @return phone + **/ @ApiModelProperty(example = "null", value = "") - @JsonProperty("phone") public String getPhone() { return phone; } + public void setPhone(String phone) { this.phone = phone; } - - /** - * User Status - **/ public User userStatus(Integer userStatus) { this.userStatus = userStatus; return this; } - + + /** + * User Status + * @return userStatus + **/ @ApiModelProperty(example = "null", value = "User Status") - @JsonProperty("userStatus") public Integer getUserStatus() { return userStatus; } + public void setUserStatus(Integer userStatus) { this.userStatus = userStatus; } diff --git a/samples/client/petstore/java/retrofit/.travis.yml b/samples/client/petstore/java/retrofit/.travis.yml new file mode 100644 index 00000000000..33e79472abd --- /dev/null +++ b/samples/client/petstore/java/retrofit/.travis.yml @@ -0,0 +1,29 @@ +# +# Generated by: https://github.com/swagger-api/swagger-codegen.git +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +language: java +jdk: + - oraclejdk8 + - oraclejdk7 +before_install: + # ensure gradlew has proper permission + - chmod a+x ./gradlew +script: + # test using maven + - mvn test + # uncomment below to test using gradle + # - gradle test + # uncomment below to test using sbt + # - sbt test diff --git a/samples/client/petstore/java/retrofit/build.gradle b/samples/client/petstore/java/retrofit/build.gradle index 401b362d172..172055c892e 100644 --- a/samples/client/petstore/java/retrofit/build.gradle +++ b/samples/client/petstore/java/retrofit/build.gradle @@ -23,7 +23,7 @@ if(hasProperty('target') && target == 'android') { apply plugin: 'com.android.library' apply plugin: 'com.github.dcendents.android-maven' - + android { compileSdkVersion 23 buildToolsVersion '23.0.2' @@ -35,7 +35,7 @@ if(hasProperty('target') && target == 'android') { sourceCompatibility JavaVersion.VERSION_1_7 targetCompatibility JavaVersion.VERSION_1_7 } - + // Rename the aar correctly libraryVariants.all { variant -> variant.outputs.each { output -> @@ -51,7 +51,7 @@ if(hasProperty('target') && target == 'android') { provided 'javax.annotation:jsr250-api:1.0' } } - + afterEvaluate { android.libraryVariants.all { variant -> def task = project.tasks.create "jar${variant.name.capitalize()}", Jar @@ -63,12 +63,12 @@ if(hasProperty('target') && target == 'android') { artifacts.add('archives', task); } } - + task sourcesJar(type: Jar) { from android.sourceSets.main.java.srcDirs classifier = 'sources' } - + artifacts { archives sourcesJar } @@ -77,36 +77,27 @@ if(hasProperty('target') && target == 'android') { apply plugin: 'java' apply plugin: 'maven' - + sourceCompatibility = JavaVersion.VERSION_1_7 targetCompatibility = JavaVersion.VERSION_1_7 - + install { repositories.mavenInstaller { pom.artifactId = 'swagger-petstore-retrofit' } } - + task execute(type:JavaExec) { main = System.getProperty('mainClass') classpath = sourceSets.main.runtimeClasspath } } -ext { - okhttp_version = "2.7.5" - oltu_version = "1.0.1" - retrofit_version = "1.9.0" - swagger_annotations_version = "1.5.8" - junit_version = "4.12" - jodatime_version = "2.9.3" -} - dependencies { - compile "com.squareup.okhttp:okhttp:$okhttp_version" - compile "com.squareup.retrofit:retrofit:$retrofit_version" - compile "io.swagger:swagger-annotations:$swagger_annotations_version" - compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version" - compile "joda-time:joda-time:$jodatime_version" - testCompile "junit:junit:$junit_version" + compile 'io.swagger:swagger-annotations:1.5.8' + compile 'com.squareup.okhttp:okhttp:2.7.5' + compile 'com.squareup.okhttp:logging-interceptor:2.7.5' + compile 'com.google.code.gson:gson:2.6.2' + compile 'joda-time:joda-time:2.9.3' + testCompile 'junit:junit:4.12' } diff --git a/samples/client/petstore/java/retrofit/build.sbt b/samples/client/petstore/java/retrofit/build.sbt index 629c85c2bf3..f665bcc952a 100644 --- a/samples/client/petstore/java/retrofit/build.sbt +++ b/samples/client/petstore/java/retrofit/build.sbt @@ -9,10 +9,10 @@ lazy val root = (project in file(".")). publishArtifact in (Compile, packageDoc) := false, resolvers += Resolver.mavenLocal, libraryDependencies ++= Seq( - "com.squareup.okhttp" % "okhttp" % "2.7.5" % "compile", - "com.squareup.retrofit" % "retrofit" % "1.9.0" % "compile", - "io.swagger" % "swagger-annotations" % "1.5.8" % "compile", - "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", + "io.swagger" % "swagger-annotations" % "1.5.8", + "com.squareup.okhttp" % "okhttp" % "2.7.5", + "com.squareup.okhttp" % "logging-interceptor" % "2.7.5", + "com.google.code.gson" % "gson" % "2.6.2", "joda-time" % "joda-time" % "2.9.3" % "compile", "junit" % "junit" % "4.12" % "test", "com.novocode" % "junit-interface" % "0.10" % "test" diff --git a/samples/client/petstore/java/retrofit/docs/AdditionalPropertiesClass.md b/samples/client/petstore/java/retrofit/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..0437c4dd8cc --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/AdditionalPropertiesClass.md @@ -0,0 +1,11 @@ + +# AdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapProperty** | **Map<String, String>** | | [optional] +**mapOfMapProperty** | [**Map<String, Map<String, String>>**](Map.md) | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit/docs/Animal.md b/samples/client/petstore/java/retrofit/docs/Animal.md new file mode 100644 index 00000000000..b3f325c3524 --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/Animal.md @@ -0,0 +1,11 @@ + +# Animal + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit/docs/AnimalFarm.md b/samples/client/petstore/java/retrofit/docs/AnimalFarm.md new file mode 100644 index 00000000000..c7c7f1ddcce --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/AnimalFarm.md @@ -0,0 +1,9 @@ + +# AnimalFarm + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + + diff --git a/samples/client/petstore/java/retrofit/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/java/retrofit/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 00000000000..77292549927 --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/ArrayOfArrayOfNumberOnly.md @@ -0,0 +1,10 @@ + +# ArrayOfArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayArrayNumber** | [**List<List<BigDecimal>>**](List.md) | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit/docs/ArrayOfNumberOnly.md b/samples/client/petstore/java/retrofit/docs/ArrayOfNumberOnly.md new file mode 100644 index 00000000000..e8cc4cd36dc --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/ArrayOfNumberOnly.md @@ -0,0 +1,10 @@ + +# ArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayNumber** | [**List<BigDecimal>**](BigDecimal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit/docs/ArrayTest.md b/samples/client/petstore/java/retrofit/docs/ArrayTest.md new file mode 100644 index 00000000000..9feee16427f --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/ArrayTest.md @@ -0,0 +1,12 @@ + +# ArrayTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayOfString** | **List<String>** | | [optional] +**arrayArrayOfInteger** | [**List<List<Long>>**](List.md) | | [optional] +**arrayArrayOfModel** | [**List<List<ReadOnlyFirst>>**](List.md) | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit/docs/Cat.md b/samples/client/petstore/java/retrofit/docs/Cat.md new file mode 100644 index 00000000000..be6e56fa8ce --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/Cat.md @@ -0,0 +1,12 @@ + +# Cat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | [optional] +**declawed** | **Boolean** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit/docs/Category.md b/samples/client/petstore/java/retrofit/docs/Category.md new file mode 100644 index 00000000000..e2df0803278 --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/Category.md @@ -0,0 +1,11 @@ + +# Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**name** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit/docs/Dog.md b/samples/client/petstore/java/retrofit/docs/Dog.md new file mode 100644 index 00000000000..71a7dbe809e --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/Dog.md @@ -0,0 +1,12 @@ + +# Dog + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | [optional] +**breed** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit/docs/EnumClass.md b/samples/client/petstore/java/retrofit/docs/EnumClass.md new file mode 100644 index 00000000000..c746edc3cb1 --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/EnumClass.md @@ -0,0 +1,14 @@ + +# EnumClass + +## Enum + + +* `_ABC` (value: `"_abc"`) + +* `_EFG` (value: `"-efg"`) + +* `_XYZ_` (value: `"(xyz)"`) + + + diff --git a/samples/client/petstore/java/retrofit/docs/EnumTest.md b/samples/client/petstore/java/retrofit/docs/EnumTest.md new file mode 100644 index 00000000000..deb1951c552 --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/EnumTest.md @@ -0,0 +1,36 @@ + +# EnumTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enumString** | [**EnumStringEnum**](#EnumStringEnum) | | [optional] +**enumInteger** | [**EnumIntegerEnum**](#EnumIntegerEnum) | | [optional] +**enumNumber** | [**EnumNumberEnum**](#EnumNumberEnum) | | [optional] + + + +## Enum: EnumStringEnum +Name | Value +---- | ----- +UPPER | "UPPER" +LOWER | "lower" + + + +## Enum: EnumIntegerEnum +Name | Value +---- | ----- +NUMBER_1 | 1 +NUMBER_MINUS_1 | -1 + + + +## Enum: EnumNumberEnum +Name | Value +---- | ----- +NUMBER_1_DOT_1 | 1.1 +NUMBER_MINUS_1_DOT_2 | -1.2 + + + diff --git a/samples/client/petstore/java/retrofit/docs/FakeApi.md b/samples/client/petstore/java/retrofit/docs/FakeApi.md new file mode 100644 index 00000000000..21a4db7c377 --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/FakeApi.md @@ -0,0 +1,122 @@ +# FakeApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters + + + +# **testEndpointParameters** +> testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +BigDecimal number = new BigDecimal(); // BigDecimal | None +Double _double = 3.4D; // Double | None +String string = "string_example"; // String | None +byte[] _byte = B; // byte[] | None +Integer integer = 56; // Integer | None +Integer int32 = 56; // Integer | None +Long int64 = 789L; // Long | None +Float _float = 3.4F; // Float | None +byte[] binary = B; // byte[] | None +LocalDate date = new LocalDate(); // LocalDate | None +DateTime dateTime = new DateTime(); // DateTime | None +String password = "password_example"; // String | None +try { + apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEndpointParameters"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **number** | **BigDecimal**| None | + **_double** | **Double**| None | + **string** | **String**| None | + **_byte** | **byte[]**| None | + **integer** | **Integer**| None | [optional] + **int32** | **Integer**| None | [optional] + **int64** | **Long**| None | [optional] + **_float** | **Float**| None | [optional] + **binary** | **byte[]**| None | [optional] + **date** | **LocalDate**| None | [optional] + **dateTime** | **DateTime**| None | [optional] + **password** | **String**| None | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/xml; charset=utf-8, application/json; charset=utf-8 + - **Accept**: application/xml; charset=utf-8, application/json; charset=utf-8 + + +# **testEnumQueryParameters** +> testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble) + +To test enum query parameters + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +String enumQueryString = "-efg"; // String | Query parameter enum test (string) +BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | Query parameter enum test (double) +Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) +try { + apiInstance.testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEnumQueryParameters"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + **enumQueryInteger** | **BigDecimal**| Query parameter enum test (double) | [optional] + **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + diff --git a/samples/client/petstore/java/retrofit/docs/FormatTest.md b/samples/client/petstore/java/retrofit/docs/FormatTest.md new file mode 100644 index 00000000000..44de7d9511a --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/FormatTest.md @@ -0,0 +1,22 @@ + +# FormatTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**integer** | **Integer** | | [optional] +**int32** | **Integer** | | [optional] +**int64** | **Long** | | [optional] +**number** | [**BigDecimal**](BigDecimal.md) | | +**_float** | **Float** | | [optional] +**_double** | **Double** | | [optional] +**string** | **String** | | [optional] +**_byte** | **byte[]** | | +**binary** | **byte[]** | | [optional] +**date** | [**LocalDate**](LocalDate.md) | | +**dateTime** | [**DateTime**](DateTime.md) | | [optional] +**uuid** | **String** | | [optional] +**password** | **String** | | + + + diff --git a/samples/client/petstore/java/retrofit/docs/HasOnlyReadOnly.md b/samples/client/petstore/java/retrofit/docs/HasOnlyReadOnly.md new file mode 100644 index 00000000000..c1d0aac5672 --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/HasOnlyReadOnly.md @@ -0,0 +1,11 @@ + +# HasOnlyReadOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] +**foo** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit/docs/MapTest.md b/samples/client/petstore/java/retrofit/docs/MapTest.md new file mode 100644 index 00000000000..c671e97ffbc --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/MapTest.md @@ -0,0 +1,17 @@ + +# MapTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapMapOfString** | [**Map<String, Map<String, String>>**](Map.md) | | [optional] +**mapOfEnumString** | [**Map<String, InnerEnum>**](#Map<String, InnerEnum>) | | [optional] + + + +## Enum: Map<String, InnerEnum> +Name | Value +---- | ----- + + + diff --git a/samples/client/petstore/java/retrofit/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/java/retrofit/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..e3487bcc501 --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,12 @@ + +# MixedPropertiesAndAdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | **String** | | [optional] +**dateTime** | [**DateTime**](DateTime.md) | | [optional] +**map** | [**Map<String, Animal>**](Animal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit/docs/Model200Response.md b/samples/client/petstore/java/retrofit/docs/Model200Response.md new file mode 100644 index 00000000000..b47618b28cc --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/Model200Response.md @@ -0,0 +1,11 @@ + +# Model200Response + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Integer** | | [optional] +**PropertyClass** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit/docs/ModelApiResponse.md b/samples/client/petstore/java/retrofit/docs/ModelApiResponse.md new file mode 100644 index 00000000000..3eec8686cc9 --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/ModelApiResponse.md @@ -0,0 +1,12 @@ + +# ModelApiResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **Integer** | | [optional] +**type** | **String** | | [optional] +**message** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit/docs/ModelReturn.md b/samples/client/petstore/java/retrofit/docs/ModelReturn.md new file mode 100644 index 00000000000..a679b04953e --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/ModelReturn.md @@ -0,0 +1,10 @@ + +# ModelReturn + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_return** | **Integer** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit/docs/Name.md b/samples/client/petstore/java/retrofit/docs/Name.md new file mode 100644 index 00000000000..ce2fb4dee50 --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/Name.md @@ -0,0 +1,13 @@ + +# Name + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Integer** | | +**snakeCase** | **Integer** | | [optional] +**property** | **String** | | [optional] +**_123Number** | **Integer** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit/docs/NumberOnly.md b/samples/client/petstore/java/retrofit/docs/NumberOnly.md new file mode 100644 index 00000000000..a3feac7fadc --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/NumberOnly.md @@ -0,0 +1,10 @@ + +# NumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**justNumber** | [**BigDecimal**](BigDecimal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit/docs/Order.md b/samples/client/petstore/java/retrofit/docs/Order.md new file mode 100644 index 00000000000..a1089f5384e --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/Order.md @@ -0,0 +1,24 @@ + +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**petId** | **Long** | | [optional] +**quantity** | **Integer** | | [optional] +**shipDate** | [**DateTime**](DateTime.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] +**complete** | **Boolean** | | [optional] + + + +## Enum: StatusEnum +Name | Value +---- | ----- +PLACED | "placed" +APPROVED | "approved" +DELIVERED | "delivered" + + + diff --git a/samples/client/petstore/java/retrofit/docs/Pet.md b/samples/client/petstore/java/retrofit/docs/Pet.md new file mode 100644 index 00000000000..5b63109ef92 --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/Pet.md @@ -0,0 +1,24 @@ + +# Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**name** | **String** | | +**photoUrls** | **List<String>** | | +**tags** | [**List<Tag>**](Tag.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] + + + +## Enum: StatusEnum +Name | Value +---- | ----- +AVAILABLE | "available" +PENDING | "pending" +SOLD | "sold" + + + diff --git a/samples/client/petstore/java/retrofit/docs/PetApi.md b/samples/client/petstore/java/retrofit/docs/PetApi.md new file mode 100644 index 00000000000..e0314e20e51 --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/PetApi.md @@ -0,0 +1,448 @@ +# PetApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image + + + +# **addPet** +> addPet(body) + +Add a new pet to the store + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Pet body = new Pet(); // Pet | Pet object that needs to be added to the store +try { + apiInstance.addPet(body); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#addPet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/xml, application/json + + +# **deletePet** +> deletePet(petId, apiKey) + +Deletes a pet + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | Pet id to delete +String apiKey = "apiKey_example"; // String | +try { + apiInstance.deletePet(petId, apiKey); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#deletePet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| Pet id to delete | + **apiKey** | **String**| | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **findPetsByStatus** +> List<Pet> findPetsByStatus(status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +List status = Arrays.asList("status_example"); // List | Status values that need to be considered for filter +try { + List result = apiInstance.findPetsByStatus(status); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByStatus"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **findPetsByTags** +> List<Pet> findPetsByTags(tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +List tags = Arrays.asList("tags_example"); // List | Tags to filter by +try { + List result = apiInstance.findPetsByTags(tags); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByTags"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**List<String>**](String.md)| Tags to filter by | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **getPetById** +> Pet getPetById(petId) + +Find pet by ID + +Returns a single pet + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure API key authorization: api_key +ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); +api_key.setApiKey("YOUR API KEY"); +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//api_key.setApiKeyPrefix("Token"); + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | ID of pet to return +try { + Pet result = apiInstance.getPetById(petId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#getPetById"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **updatePet** +> updatePet(body) + +Update an existing pet + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Pet body = new Pet(); // Pet | Pet object that needs to be added to the store +try { + apiInstance.updatePet(body); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/xml, application/json + + +# **updatePetWithForm** +> updatePetWithForm(petId, name, status) + +Updates a pet in the store with form data + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | ID of pet that needs to be updated +String name = "name_example"; // String | Updated name of the pet +String status = "status_example"; // String | Updated status of the pet +try { + apiInstance.updatePetWithForm(petId, name, status); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePetWithForm"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet that needs to be updated | + **name** | **String**| Updated name of the pet | [optional] + **status** | **String**| Updated status of the pet | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: application/xml, application/json + + +# **uploadFile** +> ModelApiResponse uploadFile(petId, additionalMetadata, file) + +uploads an image + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | ID of pet to update +String additionalMetadata = "additionalMetadata_example"; // String | Additional data to pass to server +File file = new File("/path/to/file.txt"); // File | file to upload +try { + ModelApiResponse result = apiInstance.uploadFile(petId, additionalMetadata, file); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#uploadFile"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to update | + **additionalMetadata** | **String**| Additional data to pass to server | [optional] + **file** | **File**| file to upload | [optional] + +### Return type + +[**ModelApiResponse**](ModelApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + diff --git a/samples/client/petstore/java/retrofit/docs/ReadOnlyFirst.md b/samples/client/petstore/java/retrofit/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..426b7cde95a --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/ReadOnlyFirst.md @@ -0,0 +1,11 @@ + +# ReadOnlyFirst + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] +**baz** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit/docs/SpecialModelName.md b/samples/client/petstore/java/retrofit/docs/SpecialModelName.md new file mode 100644 index 00000000000..c2c6117c552 --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/SpecialModelName.md @@ -0,0 +1,10 @@ + +# SpecialModelName + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**specialPropertyName** | **Long** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit/docs/StoreApi.md b/samples/client/petstore/java/retrofit/docs/StoreApi.md new file mode 100644 index 00000000000..0b30791725a --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/StoreApi.md @@ -0,0 +1,197 @@ +# StoreApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet + + + +# **deleteOrder** +> deleteOrder(orderId) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +String orderId = "orderId_example"; // String | ID of the order that needs to be deleted +try { + apiInstance.deleteOrder(orderId); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#deleteOrder"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **String**| ID of the order that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **getInventory** +> Map<String, Integer> getInventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.StoreApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure API key authorization: api_key +ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); +api_key.setApiKey("YOUR API KEY"); +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//api_key.setApiKeyPrefix("Token"); + +StoreApi apiInstance = new StoreApi(); +try { + Map result = apiInstance.getInventory(); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getInventory"); + e.printStackTrace(); +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**Map<String, Integer>**](Map.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +# **getOrderById** +> Order getOrderById(orderId) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +Long orderId = 789L; // Long | ID of pet that needs to be fetched +try { + Order result = apiInstance.getOrderById(orderId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getOrderById"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **Long**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **placeOrder** +> Order placeOrder(body) + +Place an order for a pet + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +Order body = new Order(); // Order | order placed for purchasing the pet +try { + Order result = apiInstance.placeOrder(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#placeOrder"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + diff --git a/samples/client/petstore/java/retrofit/docs/Tag.md b/samples/client/petstore/java/retrofit/docs/Tag.md new file mode 100644 index 00000000000..de6814b55d5 --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/Tag.md @@ -0,0 +1,11 @@ + +# Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**name** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit/docs/User.md b/samples/client/petstore/java/retrofit/docs/User.md new file mode 100644 index 00000000000..8b6753dd284 --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/User.md @@ -0,0 +1,17 @@ + +# User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**username** | **String** | | [optional] +**firstName** | **String** | | [optional] +**lastName** | **String** | | [optional] +**email** | **String** | | [optional] +**password** | **String** | | [optional] +**phone** | **String** | | [optional] +**userStatus** | **Integer** | User Status | [optional] + + + diff --git a/samples/client/petstore/java/retrofit/docs/UserApi.md b/samples/client/petstore/java/retrofit/docs/UserApi.md new file mode 100644 index 00000000000..8cdc15992ee --- /dev/null +++ b/samples/client/petstore/java/retrofit/docs/UserApi.md @@ -0,0 +1,370 @@ +# UserApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createUser**](UserApi.md#createUser) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + + +# **createUser** +> createUser(body) + +Create user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +User body = new User(); // User | Created user object +try { + apiInstance.createUser(body); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md)| Created user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **createUsersWithArrayInput** +> createUsersWithArrayInput(body) + +Creates list of users with given input array + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +List body = Arrays.asList(new User()); // List | List of user object +try { + apiInstance.createUsersWithArrayInput(body); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithArrayInput"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List<User>**](User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **createUsersWithListInput** +> createUsersWithListInput(body) + +Creates list of users with given input array + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +List body = Arrays.asList(new User()); // List | List of user object +try { + apiInstance.createUsersWithListInput(body); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithListInput"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List<User>**](User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **deleteUser** +> deleteUser(username) + +Delete user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The name that needs to be deleted +try { + apiInstance.deleteUser(username); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#deleteUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **getUserByName** +> User getUserByName(username) + +Get user by user name + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The name that needs to be fetched. Use user1 for testing. +try { + User result = apiInstance.getUserByName(username); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#getUserByName"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **loginUser** +> String loginUser(username, password) + +Logs user into the system + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The user name for login +String password = "password_example"; // String | The password for login in clear text +try { + String result = apiInstance.loginUser(username, password); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#loginUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The user name for login | + **password** | **String**| The password for login in clear text | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **logoutUser** +> logoutUser() + +Logs out current logged in user session + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +try { + apiInstance.logoutUser(); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#logoutUser"); + e.printStackTrace(); +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **updateUser** +> updateUser(username, body) + +Updated user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | name that need to be deleted +User body = new User(); // User | Updated user object +try { + apiInstance.updateUser(username, body); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#updateUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| name that need to be deleted | + **body** | [**User**](User.md)| Updated user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + diff --git a/samples/client/petstore/java/retrofit/pom.xml b/samples/client/petstore/java/retrofit/pom.xml index ee6ce62988f..0791f9f10ad 100644 --- a/samples/client/petstore/java/retrofit/pom.xml +++ b/samples/client/petstore/java/retrofit/pom.xml @@ -68,6 +68,7 @@ org.codehaus.mojo build-helper-maven-plugin + 1.10 add_sources @@ -95,15 +96,6 @@ - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.2 - - 1.7 - 1.7 - - @@ -113,25 +105,25 @@ ${swagger-core-version} - com.squareup.retrofit - retrofit - ${retrofit-version} + com.squareup.okhttp + okhttp + ${okhttp-version} - org.apache.oltu.oauth2 - org.apache.oltu.oauth2.client - ${oltu-version} - - com.squareup.okhttp - okhttp + logging-interceptor ${okhttp-version} + + com.google.code.gson + gson + ${gson-version} + joda-time joda-time ${jodatime-version} - + @@ -142,12 +134,15 @@ - 1.5.8 - 1.9.0 + 1.7 + ${java.version} + ${java.version} + 1.5.9 2.7.5 + 2.6.2 2.9.3 - 1.0.1 1.0.0 4.12 + UTF-8 diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiCallback.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiCallback.java new file mode 100644 index 00000000000..3ca33cf8017 --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiCallback.java @@ -0,0 +1,74 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import java.io.IOException; + +import java.util.Map; +import java.util.List; + +/** + * Callback for asynchronous API call. + * + * @param The return type + */ +public interface ApiCallback { + /** + * This is called when the API call fails. + * + * @param e The exception causing the failure + * @param statusCode Status code of the response if available, otherwise it would be 0 + * @param responseHeaders Headers of the response if available, otherwise it would be null + */ + void onFailure(ApiException e, int statusCode, Map> responseHeaders); + + /** + * This is called when the API call succeeded. + * + * @param result The result deserialized from response + * @param statusCode Status code of the response + * @param responseHeaders Headers of the response + */ + void onSuccess(T result, int statusCode, Map> responseHeaders); + + /** + * This is called when the API upload processing. + * + * @param bytesWritten bytes Written + * @param contentLength content length of request body + * @param done write end + */ + void onUploadProgress(long bytesWritten, long contentLength, boolean done); + + /** + * This is called when the API downlond processing. + * + * @param bytesRead bytes Read + * @param contentLength content lenngth of the response + * @param done Read end + */ + void onDownloadProgress(long bytesRead, long contentLength, boolean done); +} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java index 0453c60ae01..b7b04e3e4c5 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java @@ -1,407 +1,1326 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; +import com.squareup.okhttp.Call; +import com.squareup.okhttp.Callback; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Response; +import com.squareup.okhttp.RequestBody; +import com.squareup.okhttp.FormEncodingBuilder; +import com.squareup.okhttp.MultipartBuilder; +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.Headers; +import com.squareup.okhttp.internal.http.HttpMethod; +import com.squareup.okhttp.logging.HttpLoggingInterceptor; +import com.squareup.okhttp.logging.HttpLoggingInterceptor.Level; + import java.lang.reflect.Type; -import java.util.LinkedHashMap; + +import java.util.Collection; +import java.util.Collections; import java.util.Map; +import java.util.Map.Entry; +import java.util.HashMap; +import java.util.List; +import java.util.ArrayList; +import java.util.Date; +import java.util.TimeZone; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; -import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; -import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; -import org.joda.time.DateTime; -import org.joda.time.LocalDate; -import org.joda.time.format.DateTimeFormatter; -import org.joda.time.format.ISODateTimeFormat; - -import retrofit.RestAdapter; -import retrofit.client.OkClient; -import retrofit.converter.ConversionException; -import retrofit.converter.Converter; -import retrofit.converter.GsonConverter; -import retrofit.mime.TypedByteArray; -import retrofit.mime.TypedInput; -import retrofit.mime.TypedOutput; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.squareup.okhttp.Interceptor; -import com.squareup.okhttp.OkHttpClient; +import java.net.URLEncoder; +import java.net.URLConnection; +import java.io.File; +import java.io.InputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; + +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.security.SecureRandom; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.text.ParseException; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.KeyManager; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509TrustManager; + +import okio.BufferedSink; +import okio.Okio; + +import io.swagger.client.auth.Authentication; import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; -import io.swagger.client.auth.OAuth.AccessTokenListener; -import io.swagger.client.auth.OAuthFlow; - public class ApiClient { + public static final double JAVA_VERSION; + public static final boolean IS_ANDROID; + public static final int ANDROID_SDK_VERSION; - private Map apiAuthorizations; - private OkHttpClient okClient; - private RestAdapter.Builder adapterBuilder; - - public ApiClient() { - apiAuthorizations = new LinkedHashMap(); - createDefaultAdapter(); - } - - public ApiClient(String[] authNames) { - this(); - for(String authName : authNames) { - Interceptor auth; - if (authName == "api_key") { - auth = new ApiKeyAuth("header", "api_key"); - } else if (authName == "petstore_auth") { - auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); - } else { - throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); + static { + JAVA_VERSION = Double.parseDouble(System.getProperty("java.specification.version")); + boolean isAndroid; + try { + Class.forName("android.app.Activity"); + isAndroid = true; + } catch (ClassNotFoundException e) { + isAndroid = false; + } + IS_ANDROID = isAndroid; + int sdkVersion = 0; + if (IS_ANDROID) { + try { + sdkVersion = Class.forName("android.os.Build$VERSION").getField("SDK_INT").getInt(null); + } catch (Exception e) { + try { + sdkVersion = Integer.parseInt((String) Class.forName("android.os.Build$VERSION").getField("SDK").get(null)); + } catch (Exception e2) { } } - addAuthorization(authName, auth); } + ANDROID_SDK_VERSION = sdkVersion; } /** - * Basic constructor for single auth name - * @param authName + * The datetime format to be used when lenientDatetimeFormat is enabled. + */ + public static final String LENIENT_DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; + + private String basePath = "http://petstore.swagger.io/v2"; + private boolean lenientOnJson = false; + private boolean debugging = false; + private Map defaultHeaderMap = new HashMap(); + private String tempFolderPath = null; + + private Map authentications; + + private DateFormat dateFormat; + private DateFormat datetimeFormat; + private boolean lenientDatetimeFormat; + private int dateLength; + + private InputStream sslCaCert; + private boolean verifyingSsl; + + private OkHttpClient httpClient; + private JSON json; + + private HttpLoggingInterceptor loggingInterceptor; + + /* + * Constructor for ApiClient */ - public ApiClient(String authName) { - this(new String[]{authName}); + public ApiClient() { + httpClient = new OkHttpClient(); + + verifyingSsl = true; + + json = new JSON(this); + + /* + * Use RFC3339 format for date and datetime. + * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + */ + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + // Always use UTC as the default time zone when dealing with date (without time). + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + initDatetimeFormat(); + + // Be lenient on datetime formats when parsing datetime from string. + // See parseDatetime. + this.lenientDatetimeFormat = true; + + // Set default User-Agent. + setUserAgent("Swagger-Codegen/1.0.0/java"); + + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap(); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("petstore_auth", new OAuth()); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); } /** - * Helper constructor for single api key - * @param authName - * @param apiKey + * Get base path + * + * @return Baes path */ - public ApiClient(String authName, String apiKey) { - this(authName); - this.setApiKey(apiKey); + public String getBasePath() { + return basePath; } /** - * Helper constructor for single basic auth or password oauth2 - * @param authName - * @param username - * @param password + * Set base path + * + * @param basePath Base path of the URL (e.g http://petstore.swagger.io/v2 + * @return An instance of OkHttpClient */ - public ApiClient(String authName, String username, String password) { - this(authName); - this.setCredentials(username, password); + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; } /** - * Helper constructor for single password oauth2 - * @param authName - * @param clientId - * @param secret - * @param username - * @param password + * Get HTTP client + * + * @return An instance of OkHttpClient */ - public ApiClient(String authName, String clientId, String secret, String username, String password) { - this(authName); - this.getTokenEndPoint() - .setClientId(clientId) - .setClientSecret(secret) - .setUsername(username) - .setPassword(password); + public OkHttpClient getHttpClient() { + return httpClient; } - - public void createDefaultAdapter() { - Gson gson = new GsonBuilder() - .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") - .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) - .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) - .create(); - okClient = new OkHttpClient(); + /** + * Set HTTP client + * + * @param httpClient An instance of OkHttpClient + * @return Api Client + */ + public ApiClient setHttpClient(OkHttpClient httpClient) { + this.httpClient = httpClient; + return this; + } - adapterBuilder = new RestAdapter - .Builder() - .setEndpoint("http://petstore.swagger.io/v2") - .setClient(new OkClient(okClient)) - .setConverter(new GsonConverterWrapper(gson)); + /** + * Get JSON + * + * @return JSON object + */ + public JSON getJSON() { + return json; } - public S createService(Class serviceClass) { - return adapterBuilder.build().create(serviceClass); - + /** + * Set JSON + * + * @param json JSON object + * @return Api client + */ + public ApiClient setJSON(JSON json) { + this.json = json; + return this; } /** - * Helper method to configure the first api key found - * @param apiKey + * True if isVerifyingSsl flag is on + * + * @return True if isVerifySsl flag is on */ - private void setApiKey(String apiKey) { - for(Interceptor apiAuthorization : apiAuthorizations.values()) { - if (apiAuthorization instanceof ApiKeyAuth) { - ApiKeyAuth keyAuth = (ApiKeyAuth) apiAuthorization; - keyAuth.setApiKey(apiKey); - return; - } + public boolean isVerifyingSsl() { + return verifyingSsl; + } + + /** + * Configure whether to verify certificate and hostname when making https requests. + * Default to true. + * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. + * + * @param verifyingSsl True to verify TLS/SSL connection + * @return ApiClient + */ + public ApiClient setVerifyingSsl(boolean verifyingSsl) { + this.verifyingSsl = verifyingSsl; + applySslSettings(); + return this; + } + + /** + * Get SSL CA cert. + * + * @return Input stream to the SSL CA cert + */ + public InputStream getSslCaCert() { + return sslCaCert; + } + + /** + * Configure the CA certificate to be trusted when making https requests. + * Use null to reset to default. + * + * @param sslCaCert input stream for SSL CA cert + * @return ApiClient + */ + public ApiClient setSslCaCert(InputStream sslCaCert) { + this.sslCaCert = sslCaCert; + applySslSettings(); + return this; + } + + public DateFormat getDateFormat() { + return dateFormat; + } + + public ApiClient setDateFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + this.dateLength = this.dateFormat.format(new Date()).length(); + return this; + } + + public DateFormat getDatetimeFormat() { + return datetimeFormat; + } + + public ApiClient setDatetimeFormat(DateFormat datetimeFormat) { + this.datetimeFormat = datetimeFormat; + return this; + } + + /** + * Whether to allow various ISO 8601 datetime formats when parsing a datetime string. + * @see #parseDatetime(String) + * @return True if lenientDatetimeFormat flag is set to true + */ + public boolean isLenientDatetimeFormat() { + return lenientDatetimeFormat; + } + + public ApiClient setLenientDatetimeFormat(boolean lenientDatetimeFormat) { + this.lenientDatetimeFormat = lenientDatetimeFormat; + return this; + } + + /** + * Parse the given date string into Date object. + * The default dateFormat supports these ISO 8601 date formats: + * 2015-08-16 + * 2015-8-16 + * @param str String to be parsed + * @return Date + */ + public Date parseDate(String str) { + if (str == null) + return null; + try { + return dateFormat.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Parse the given datetime string into Date object. + * When lenientDatetimeFormat is enabled, the following ISO 8601 datetime formats are supported: + * 2015-08-16T08:20:05Z + * 2015-8-16T8:20:05Z + * 2015-08-16T08:20:05+00:00 + * 2015-08-16T08:20:05+0000 + * 2015-08-16T08:20:05.376Z + * 2015-08-16T08:20:05.376+00:00 + * 2015-08-16T08:20:05.376+00 + * Note: The 3-digit milli-seconds is optional. Time zone is required and can be in one of + * these formats: + * Z (same with +0000) + * +08:00 (same with +0800) + * -02 (same with -0200) + * -0200 + * @see ISO 8601 + * @param str Date time string to be parsed + * @return Date representation of the string + */ + public Date parseDatetime(String str) { + if (str == null) + return null; + + DateFormat format; + if (lenientDatetimeFormat) { + /* + * When lenientDatetimeFormat is enabled, normalize the date string + * into LENIENT_DATETIME_FORMAT to support various formats + * defined by ISO 8601. + */ + // normalize time zone + // trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000 + str = str.replaceAll("[zZ]\\z", "+0000"); + // remove colon in time zone: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000 + str = str.replaceAll("([+-]\\d{2}):(\\d{2})\\z", "$1$2"); + // expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000 + str = str.replaceAll("([+-]\\d{2})\\z", "$100"); + // add milliseconds when missing + // 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000 + str = str.replaceAll("(:\\d{1,2})([+-]\\d{4})\\z", "$1.000$2"); + format = new SimpleDateFormat(LENIENT_DATETIME_FORMAT); + } else { + format = this.datetimeFormat; + } + + try { + return format.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); } } + /* + * Parse date or date time in string format into Date object. + * + * @param str Date time string to be parsed + * @return Date representation of the string + */ + public Date parseDateOrDatetime(String str) { + if (str == null) + return null; + else if (str.length() <= dateLength) + return parseDate(str); + else + return parseDatetime(str); + } + + /** + * Format the given Date object into string (Date format). + * + * @param date Date object + * @return Formatted date in string representation + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } + + /** + * Format the given Date object into string (Datetime format). + * + * @param date Date object + * @return Formatted datetime in string representation + */ + public String formatDatetime(Date date) { + return datetimeFormat.format(date); + } + + /** + * Get authentications (key: authentication name, value: authentication). + * + * @return Map of authentication objects + */ + public Map getAuthentications() { + return authentications; + } + /** - * Helper method to configure the username/password for basic auth or password oauth - * @param username - * @param password + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found */ - private void setCredentials(String username, String password) { - for(Interceptor apiAuthorization : apiAuthorizations.values()) { - if (apiAuthorization instanceof HttpBasicAuth) { - HttpBasicAuth basicAuth = (HttpBasicAuth) apiAuthorization; - basicAuth.setCredentials(username, password); + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + * + * @param username Username + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); return; } - if (apiAuthorization instanceof OAuth) { - OAuth oauth = (OAuth) apiAuthorization; - oauth.getTokenRequestBuilder().setUsername(username).setPassword(password); + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + * + * @param password Password + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); return; } } + throw new RuntimeException("No HTTP basic authentication configured!"); } /** - * Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one) - * @return + * Helper method to set API key value for the first API key authentication. + * + * @param apiKey API key */ - public TokenRequestBuilder getTokenEndPoint() { - for(Interceptor apiAuthorization : apiAuthorizations.values()) { - if (apiAuthorization instanceof OAuth) { - OAuth oauth = (OAuth) apiAuthorization; - return oauth.getTokenRequestBuilder(); + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; } } - return null; + throw new RuntimeException("No API key authentication configured!"); } /** - * Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one) - * @return + * Helper method to set API key prefix for the first API key authentication. + * + * @param apiKeyPrefix API key prefix */ - public AuthenticationRequestBuilder getAuthorizationEndPoint() { - for(Interceptor apiAuthorization : apiAuthorizations.values()) { - if (apiAuthorization instanceof OAuth) { - OAuth oauth = (OAuth) apiAuthorization; - return oauth.getAuthenticationRequestBuilder(); + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; } } - return null; + throw new RuntimeException("No API key authentication configured!"); } /** - * Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one) - * @param accessToken + * Helper method to set access token for the first OAuth2 authentication. + * + * @param accessToken Access token */ public void setAccessToken(String accessToken) { - for(Interceptor apiAuthorization : apiAuthorizations.values()) { - if (apiAuthorization instanceof OAuth) { - OAuth oauth = (OAuth) apiAuthorization; - oauth.setAccessToken(accessToken); + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); return; } } + throw new RuntimeException("No OAuth2 authentication configured!"); } - - /** - * Helper method to configure the oauth accessCode/implicit flow parameters - * @param clientId - * @param clientSecret - * @param redirectURI - */ - public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) { - for(Interceptor apiAuthorization : apiAuthorizations.values()) { - if (apiAuthorization instanceof OAuth) { - OAuth oauth = (OAuth) apiAuthorization; - oauth.getTokenRequestBuilder() - .setClientId(clientId) - .setClientSecret(clientSecret) - .setRedirectURI(redirectURI); - oauth.getAuthenticationRequestBuilder() - .setClientId(clientId) - .setRedirectURI(redirectURI); - return; + + /** + * Set the User-Agent header's value (by adding to the default header map). + * + * @param userAgent HTTP request's user agent + * @return ApiClient + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + * @return ApiClient + */ + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + /** + * @see setLenient + * + * @return True if lenientOnJson is enabled, false otherwise. + */ + public boolean isLenientOnJson() { + return lenientOnJson; + } + + /** + * Set LenientOnJson + * + * @param lenient True to enable lenientOnJson + * @return ApiClient + */ + public ApiClient setLenientOnJson(boolean lenient) { + this.lenientOnJson = lenient; + return this; + } + + /** + * Check that whether debugging is enabled for this API client. + * + * @return True if debugging is enabled, false otherwise. + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + * @return ApiClient + */ + public ApiClient setDebugging(boolean debugging) { + if (debugging != this.debugging) { + if (debugging) { + loggingInterceptor = new HttpLoggingInterceptor(); + loggingInterceptor.setLevel(Level.BODY); + httpClient.interceptors().add(loggingInterceptor); + } else { + httpClient.interceptors().remove(loggingInterceptor); + loggingInterceptor = null; } } + this.debugging = debugging; + return this; + } + + /** + * The path of temporary folder used to store downloaded files from endpoints + * with file response. The default value is null, i.e. using + * the system's default tempopary folder. + * + * @see createTempFile + * @return Temporary folder path + */ + public String getTempFolderPath() { + return tempFolderPath; } - + /** - * Configures a listener which is notified when a new access token is received. - * @param accessTokenListener + * Set the tempoaray folder path (for downloading files) + * + * @param tempFolderPath Temporary folder path + * @return ApiClient */ - public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { - for(Interceptor apiAuthorization : apiAuthorizations.values()) { - if (apiAuthorization instanceof OAuth) { - OAuth oauth = (OAuth) apiAuthorization; - oauth.registerAccessTokenListener(accessTokenListener); - return; + public ApiClient setTempFolderPath(String tempFolderPath) { + this.tempFolderPath = tempFolderPath; + return this; + } + + /** + * Get connection timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getConnectTimeout() { + return httpClient.getConnectTimeout(); + } + + /** + * Sets the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * + * @param connectionTimeout connection timeout in milliseconds + * @return Api client + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + httpClient.setConnectTimeout(connectionTimeout, TimeUnit.MILLISECONDS); + return this; + } + + /** + * Format the given parameter object into string. + * + * @param param Parameter + * @return String representation of the parameter + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDatetime((Date) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for (Object o : (Collection)param) { + if (b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); } + return b.toString(); + } else { + return String.valueOf(param); } } /** - * Adds an authorization to be used by the client - * @param authName - * @param authorization + * Format to {@code Pair} objects. + * + * @param collectionFormat collection format (e.g. csv, tsv) + * @param name Name + * @param value Value + * @return A list of Pair objects */ - public void addAuthorization(String authName, Interceptor authorization) { - if (apiAuthorizations.containsKey(authName)) { - throw new RuntimeException("auth name \"" + authName + "\" already in api authorizations"); + public List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); + return params; } - apiAuthorizations.put(authName, authorization); - okClient.interceptors().add(authorization); - } - public Map getApiAuthorizations() { - return apiAuthorizations; - } + if (valueCollection.isEmpty()){ + return params; + } - public void setApiAuthorizations(Map apiAuthorizations) { - this.apiAuthorizations = apiAuthorizations; + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + + // create the params based on the collection format + if (collectionFormat.equals("multi")) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); + } + + return params; + } + + String delimiter = ","; + + if (collectionFormat.equals("csv")) { + delimiter = ","; + } else if (collectionFormat.equals("ssv")) { + delimiter = " "; + } else if (collectionFormat.equals("tsv")) { + delimiter = "\t"; + } else if (collectionFormat.equals("pipes")) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + + return params; } - public RestAdapter.Builder getAdapterBuilder() { - return adapterBuilder; + /** + * Sanitize filename by removing path. + * e.g. ../../sun.gif becomes sun.gif + * + * @param filename The filename to be sanitized + * @return The sanitized filename + */ + public String sanitizeFilename(String filename) { + return filename.replaceAll(".*[/\\\\]", ""); } - public void setAdapterBuilder(RestAdapter.Builder adapterBuilder) { - this.adapterBuilder = adapterBuilder; + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * + * @param mime MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public boolean isJsonMime(String mime) { + return mime != null && mime.matches("(?i)application\\/json(;.*)?"); } - public OkHttpClient getOkClient() { - return okClient; + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } + return StringUtil.join(accepts, ","); } - - public void addAuthsToOkClient(OkHttpClient okClient) { - for(Interceptor apiAuthorization : apiAuthorizations.values()) { - okClient.interceptors().add(apiAuthorization); + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } } + return contentTypes[0]; } /** - * Clones the okClient given in parameter, adds the auth interceptors and uses it to configure the RestAdapter - * @param okClient + * Escape the given string to be used as URL query value. + * + * @param str String to be escaped + * @return Escaped string */ - public void configureFromOkclient(OkHttpClient okClient) { - OkHttpClient clone = okClient.clone(); - addAuthsToOkClient(clone); - adapterBuilder.setClient(new OkClient(clone)); + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } } -} -/** - * This wrapper is to take care of this case: - * when the deserialization fails due to JsonParseException and the - * expected type is String, then just return the body string. - */ -class GsonConverterWrapper implements Converter { - private GsonConverter converter; + /** + * Deserialize response body to Java object, according to the return type and + * the Content-Type response header. + * + * @param Type + * @param response HTTP response + * @param returnType The type of the Java object + * @return The deserialized Java object + * @throws ApiException If fail to deserialize response body, i.e. cannot read response body + * or the Content-Type of the response is not supported. + */ + @SuppressWarnings("unchecked") + public T deserialize(Response response, Type returnType) throws ApiException { + if (response == null || returnType == null) { + return null; + } + + if ("byte[]".equals(returnType.toString())) { + // Handle binary response (byte array). + try { + return (T) response.body().bytes(); + } catch (IOException e) { + throw new ApiException(e); + } + } else if (returnType.equals(File.class)) { + // Handle file downloading. + return (T) downloadFileFromResponse(response); + } + + String respBody; + try { + if (response.body() != null) + respBody = response.body().string(); + else + respBody = null; + } catch (IOException e) { + throw new ApiException(e); + } + + if (respBody == null || "".equals(respBody)) { + return null; + } - public GsonConverterWrapper(Gson gson) { - converter = new GsonConverter(gson); + String contentType = response.headers().get("Content-Type"); + if (contentType == null) { + // ensuring a default content type + contentType = "application/json"; + } + if (isJsonMime(contentType)) { + return json.deserialize(respBody, returnType); + } else if (returnType.equals(String.class)) { + // Expecting string, return the raw response body. + return (T) respBody; + } else { + throw new ApiException( + "Content type \"" + contentType + "\" is not supported for type: " + returnType, + response.code(), + response.headers().toMultimap(), + respBody); + } + } + + /** + * Serialize the given Java object into request body according to the object's + * class and the request Content-Type. + * + * @param obj The Java object + * @param contentType The request Content-Type + * @return The serialized request body + * @throws ApiException If fail to serialize the given object + */ + public RequestBody serialize(Object obj, String contentType) throws ApiException { + if (obj instanceof byte[]) { + // Binary (byte array) body parameter support. + return RequestBody.create(MediaType.parse(contentType), (byte[]) obj); + } else if (obj instanceof File) { + // File body parameter support. + return RequestBody.create(MediaType.parse(contentType), (File) obj); + } else if (isJsonMime(contentType)) { + String content; + if (obj != null) { + content = json.serialize(obj); + } else { + content = null; + } + return RequestBody.create(MediaType.parse(contentType), content); + } else { + throw new ApiException("Content type \"" + contentType + "\" is not supported"); + } } - @Override public Object fromBody(TypedInput body, Type type) throws ConversionException { - byte[] bodyBytes = readInBytes(body); - TypedByteArray newBody = new TypedByteArray(body.mimeType(), bodyBytes); + /** + * Download file from the given response. + * + * @param response An instance of the Response object + * @throws ApiException If fail to read file content from response and write to disk + * @return Downloaded file + */ + public File downloadFileFromResponse(Response response) throws ApiException { try { - return converter.fromBody(newBody, type); - } catch (ConversionException e) { - if (e.getCause() instanceof JsonParseException && type.equals(String.class)) { - return new String(bodyBytes); + File file = prepareDownloadFile(response); + BufferedSink sink = Okio.buffer(Okio.sink(file)); + sink.writeAll(response.body().source()); + sink.close(); + return file; + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * Prepare file for download + * + * @param response An instance of the Response object + * @throws IOException If fail to prepare file for download + * @return Prepared file for the download + */ + public File prepareDownloadFile(Response response) throws IOException { + String filename = null; + String contentDisposition = response.header("Content-Disposition"); + if (contentDisposition != null && !"".equals(contentDisposition)) { + // Get filename from the Content-Disposition header. + Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); + Matcher matcher = pattern.matcher(contentDisposition); + if (matcher.find()) { + filename = sanitizeFilename(matcher.group(1)); + } + } + + String prefix = null; + String suffix = null; + if (filename == null) { + prefix = "download-"; + suffix = ""; + } else { + int pos = filename.lastIndexOf("."); + if (pos == -1) { + prefix = filename + "-"; } else { - throw e; + prefix = filename.substring(0, pos) + "-"; + suffix = filename.substring(pos); } + // File.createTempFile requires the prefix to be at least three characters long + if (prefix.length() < 3) + prefix = "download-"; } + + if (tempFolderPath == null) + return File.createTempFile(prefix, suffix); + else + return File.createTempFile(prefix, suffix, new File(tempFolderPath)); } - @Override public TypedOutput toBody(Object object) { - return converter.toBody(object); + /** + * {@link #execute(Call, Type)} + * + * @param Type + * @param call An instance of the Call object + * @throws ApiException If fail to execute the call + * @return ApiResponse<T> + */ + public ApiResponse execute(Call call) throws ApiException { + return execute(call, null); } - private byte[] readInBytes(TypedInput body) throws ConversionException { - InputStream in = null; + /** + * Execute HTTP call and deserialize the HTTP response body into the given return type. + * + * @param returnType The return type used to deserialize HTTP response body + * @param The return type corresponding to (same with) returnType + * @param call Call + * @return ApiResponse object containing response status, headers and + * data, which is a Java object deserialized from response body and would be null + * when returnType is null. + * @throws ApiException If fail to execute the call + */ + public ApiResponse execute(Call call, Type returnType) throws ApiException { try { - in = body.in(); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - byte[] buffer = new byte[0xFFFF]; - for (int len; (len = in.read(buffer)) != -1;) - os.write(buffer, 0, len); - os.flush(); - return os.toByteArray(); + Response response = call.execute(); + T data = handleResponse(response, returnType); + return new ApiResponse(response.code(), response.headers().toMultimap(), data); } catch (IOException e) { - throw new ConversionException(e); - } finally { - if (in != null) { + throw new ApiException(e); + } + } + + /** + * {@link #executeAsync(Call, Type, ApiCallback)} + * + * @param Type + * @param call An instance of the Call object + * @param callback ApiCallback<T> + */ + public void executeAsync(Call call, ApiCallback callback) { + executeAsync(call, null, callback); + } + + /** + * Execute HTTP call asynchronously. + * + * @see #execute(Call, Type) + * @param Type + * @param call The callback to be executed when the API call finishes + * @param returnType Return type + * @param callback ApiCallback + */ + @SuppressWarnings("unchecked") + public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { + call.enqueue(new Callback() { + @Override + public void onFailure(Request request, IOException e) { + callback.onFailure(new ApiException(e), 0, null); + } + + @Override + public void onResponse(Response response) throws IOException { + T result; try { - in.close(); - } catch (IOException ignored) { + result = (T) handleResponse(response, returnType); + } catch (ApiException e) { + callback.onFailure(e, response.code(), response.headers().toMultimap()); + return; } + callback.onSuccess(result, response.code(), response.headers().toMultimap()); } - } + }); + } + /** + * Handle the given response, return the deserialized object when the response is successful. + * + * @param Type + * @param response Response + * @param returnType Return type + * @throws ApiException If the response has a unsuccessful status code or + * fail to deserialize the response body + * @return Type + */ + public T handleResponse(Response response, Type returnType) throws ApiException { + if (response.isSuccessful()) { + if (returnType == null || response.code() == 204) { + // returning null if the returnType is not defined, + // or the status code is 204 (No Content) + return null; + } else { + return deserialize(response, returnType); + } + } else { + String respBody = null; + if (response.body() != null) { + try { + respBody = response.body().string(); + } catch (IOException e) { + throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); + } + } + throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); + } } -} -/** - * Gson TypeAdapter for Joda DateTime type - */ -class DateTimeTypeAdapter extends TypeAdapter { + /** + * Build HTTP call with the given options. + * + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param formParams The form parameters + * @param authNames The authentications to apply + * @param progressRequestListener Progress request listener + * @return The HTTP call + * @throws ApiException If fail to serialize the request body object + */ + public Call buildCall(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + updateParamsForAuth(authNames, queryParams, headerParams); + + final String url = buildUrl(path, queryParams); + final Request.Builder reqBuilder = new Request.Builder().url(url); + processHeaderParams(headerParams, reqBuilder); - private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + String contentType = (String) headerParams.get("Content-Type"); + // ensuring a default content type + if (contentType == null) { + contentType = "application/json"; + } - @Override - public void write(JsonWriter out, DateTime date) throws IOException { - if (date == null) { - out.nullValue(); + RequestBody reqBody; + if (!HttpMethod.permitsRequestBody(method)) { + reqBody = null; + } else if ("application/x-www-form-urlencoded".equals(contentType)) { + reqBody = buildRequestBodyFormEncoding(formParams); + } else if ("multipart/form-data".equals(contentType)) { + reqBody = buildRequestBodyMultipart(formParams); + } else if (body == null) { + if ("DELETE".equals(method)) { + // allow calling DELETE without sending a request body + reqBody = null; + } else { + // use an empty request body (for POST, PUT and PATCH) + reqBody = RequestBody.create(MediaType.parse(contentType), ""); + } } else { - out.value(formatter.print(date)); + reqBody = serialize(body, contentType); } + + Request request = null; + + if(progressRequestListener != null && reqBody != null) { + ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener); + request = reqBuilder.method(method, progressRequestBody).build(); + } else { + request = reqBuilder.method(method, reqBody).build(); + } + + return httpClient.newCall(request); } - @Override - public DateTime read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - return formatter.parseDateTime(date); + /** + * Build full URL by concatenating base path, the given sub path and query parameters. + * + * @param path The sub path + * @param queryParams The query parameters + * @return The full URL + */ + public String buildUrl(String path, List queryParams) { + final StringBuilder url = new StringBuilder(); + url.append(basePath).append(path); + + if (queryParams != null && !queryParams.isEmpty()) { + // support (constant) query string in `path`, e.g. "/posts?draft=1" + String prefix = path.contains("?") ? "&" : "?"; + for (Pair param : queryParams) { + if (param.getValue() != null) { + if (prefix != null) { + url.append(prefix); + prefix = null; + } else { + url.append("&"); + } + String value = parameterToString(param.getValue()); + url.append(escapeString(param.getName())).append("=").append(escapeString(value)); + } + } + } + + return url.toString(); + } + + /** + * Set header parameters to the request builder, including default headers. + * + * @param headerParams Header parameters in the ofrm of Map + * @param reqBuilder Reqeust.Builder + */ + public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { + for (Entry param : headerParams.entrySet()) { + reqBuilder.header(param.getKey(), parameterToString(param.getValue())); + } + for (Entry header : defaultHeaderMap.entrySet()) { + if (!headerParams.containsKey(header.getKey())) { + reqBuilder.header(header.getKey(), parameterToString(header.getValue())); + } } } -} -/** - * Gson TypeAdapter for Joda DateTime type - */ -class LocalDateTypeAdapter extends TypeAdapter { + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + */ + public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); + auth.applyToParams(queryParams, headerParams); + } + } - private final DateTimeFormatter formatter = ISODateTimeFormat.date(); + /** + * Build a form-encoding request body with the given form parameters. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyFormEncoding(Map formParams) { + FormEncodingBuilder formBuilder = new FormEncodingBuilder(); + for (Entry param : formParams.entrySet()) { + formBuilder.add(param.getKey(), parameterToString(param.getValue())); + } + return formBuilder.build(); + } - @Override - public void write(JsonWriter out, LocalDate date) throws IOException { - if (date == null) { - out.nullValue(); + /** + * Build a multipart (file uploading) request body with the given form parameters, + * which could contain text fields and file fields. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyMultipart(Map formParams) { + MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); + for (Entry param : formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\""); + MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); + mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file)); + } else { + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\""); + mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue()))); + } + } + return mpBuilder.build(); + } + + /** + * Guess Content-Type header from the given file (defaults to "application/octet-stream"). + * + * @param file The given file + * @return The guessed Content-Type + */ + public String guessContentTypeFromFile(File file) { + String contentType = URLConnection.guessContentTypeFromName(file.getName()); + if (contentType == null) { + return "application/octet-stream"; } else { - out.value(formatter.print(date)); + return contentType; } } - @Override - public LocalDate read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - return formatter.parseLocalDate(date); + /** + * Initialize datetime format according to the current environment, e.g. Java 1.7 and Android. + */ + private void initDatetimeFormat() { + String formatWithTimeZone = null; + if (IS_ANDROID) { + if (ANDROID_SDK_VERSION >= 18) { + // The time zone format "ZZZZZ" is available since Android 4.3 (SDK version 18) + formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"; + } + } else if (JAVA_VERSION >= 1.7) { + // The time zone format "XXX" is available since Java 1.7 + formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; + } + if (formatWithTimeZone != null) { + this.datetimeFormat = new SimpleDateFormat(formatWithTimeZone); + // NOTE: Use the system's default time zone (mainly for datetime formatting). + } else { + // Use a common format that works across all systems. + this.datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + // Always use the UTC time zone as we are using a constant trailing "Z" here. + this.datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + } + } + + /** + * Apply SSL related settings to httpClient according to the current values of + * verifyingSsl and sslCaCert. + */ + private void applySslSettings() { + try { + KeyManager[] keyManagers = null; + TrustManager[] trustManagers = null; + HostnameVerifier hostnameVerifier = null; + if (!verifyingSsl) { + TrustManager trustAll = new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} + @Override + public X509Certificate[] getAcceptedIssuers() { return null; } + }; + SSLContext sslContext = SSLContext.getInstance("TLS"); + trustManagers = new TrustManager[]{ trustAll }; + hostnameVerifier = new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { return true; } + }; + } else if (sslCaCert != null) { + char[] password = null; // Any password will work. + CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); + Collection certificates = certificateFactory.generateCertificates(sslCaCert); + if (certificates.isEmpty()) { + throw new IllegalArgumentException("expected non-empty set of trusted certificates"); + } + KeyStore caKeyStore = newEmptyKeyStore(password); + int index = 0; + for (Certificate certificate : certificates) { + String certificateAlias = "ca" + Integer.toString(index++); + caKeyStore.setCertificateEntry(certificateAlias, certificate); + } + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagerFactory.init(caKeyStore); + trustManagers = trustManagerFactory.getTrustManagers(); + } + + if (keyManagers != null || trustManagers != null) { + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(keyManagers, trustManagers, new SecureRandom()); + httpClient.setSslSocketFactory(sslContext.getSocketFactory()); + } else { + httpClient.setSslSocketFactory(null); + } + httpClient.setHostnameVerifier(hostnameVerifier); + } catch (GeneralSecurityException e) { + throw new RuntimeException(e); + } + } + + private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { + try { + KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + keyStore.load(null, password); + return keyStore; + } catch (IOException e) { + throw new AssertionError(e); } } -} \ No newline at end of file +} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiException.java new file mode 100644 index 00000000000..3bed001f002 --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiException.java @@ -0,0 +1,103 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import java.util.Map; +import java.util.List; + + +public class ApiException extends Exception { + private int code = 0; + private Map> responseHeaders = null; + private String responseBody = null; + + public ApiException() {} + + public ApiException(Throwable throwable) { + super(throwable); + } + + public ApiException(String message) { + super(message); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } + + public ApiException(int code, Map> responseHeaders, String responseBody) { + this((String) null, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(int code, String message) { + super(message); + this.code = code; + } + + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this(code, message); + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + /** + * Get the HTTP status code. + * + * @return HTTP status code + */ + public int getCode() { + return code; + } + + /** + * Get the HTTP response headers. + * + * @return A map of list of string + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + + /** + * Get the HTTP response body. + * + * @return Response body in the form of string + */ + public String getResponseBody() { + return responseBody; + } +} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiResponse.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiResponse.java new file mode 100644 index 00000000000..d7dde1ee939 --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiResponse.java @@ -0,0 +1,71 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import java.util.List; +import java.util.Map; + +/** + * API response returned by API call. + * + * @param T The type of data that is deserialized from response body + */ +public class ApiResponse { + final private int statusCode; + final private Map> headers; + final private T data; + + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + */ + public ApiResponse(int statusCode, Map> headers) { + this(statusCode, headers, null); + } + + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + * @param data The object deserialized from response bod + */ + public ApiResponse(int statusCode, Map> headers, T data) { + this.statusCode = statusCode; + this.headers = headers; + this.data = data; + } + + public int getStatusCode() { + return statusCode; + } + + public Map> getHeaders() { + return headers; + } + + public T getData() { + return data; + } +} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/CollectionFormats.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/CollectionFormats.java deleted file mode 100644 index c3cf5257514..00000000000 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/CollectionFormats.java +++ /dev/null @@ -1,95 +0,0 @@ -package io.swagger.client; - -import java.util.Arrays; -import java.util.List; - -public class CollectionFormats { - - public static class CSVParams { - - protected List params; - - public CSVParams() { - } - - public CSVParams(List params) { - this.params = params; - } - - public CSVParams(String... params) { - this.params = Arrays.asList(params); - } - - public List getParams() { - return params; - } - - public void setParams(List params) { - this.params = params; - } - - @Override - public String toString() { - return StringUtil.join(params.toArray(new String[0]), ","); - } - - } - - public static class SSVParams extends CSVParams { - - public SSVParams() { - } - - public SSVParams(List params) { - super(params); - } - - public SSVParams(String... params) { - super(params); - } - - @Override - public String toString() { - return StringUtil.join(params.toArray(new String[0]), " "); - } - } - - public static class TSVParams extends CSVParams { - - public TSVParams() { - } - - public TSVParams(List params) { - super(params); - } - - public TSVParams(String... params) { - super(params); - } - - @Override - public String toString() { - return StringUtil.join( params.toArray(new String[0]), "\t"); - } - } - - public static class PIPESParams extends CSVParams { - - public PIPESParams() { - } - - public PIPESParams(List params) { - super(params); - } - - public PIPESParams(String... params) { - super(params); - } - - @Override - public String toString() { - return StringUtil.join(params.toArray(new String[0]), "|"); - } - } - -} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/Configuration.java new file mode 100644 index 00000000000..5191b9b73c6 --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/Configuration.java @@ -0,0 +1,51 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + + +public class Configuration { + private static ApiClient defaultApiClient = new ApiClient(); + + /** + * Get the default API client, which would be used when creating API + * instances without providing an API client. + * + * @return Default API client + */ + public static ApiClient getDefaultApiClient() { + return defaultApiClient; + } + + /** + * Set the default API client, which would be used when creating API + * instances without providing an API client. + * + * @param apiClient API client + */ + public static void setDefaultApiClient(ApiClient apiClient) { + defaultApiClient = apiClient; + } +} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/JSON.java new file mode 100644 index 00000000000..540611eab9d --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/JSON.java @@ -0,0 +1,237 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonNull; +import com.google.gson.JsonParseException; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +import java.io.IOException; +import java.io.StringReader; +import java.lang.reflect.Type; +import java.util.Date; + +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; + +public class JSON { + private ApiClient apiClient; + private Gson gson; + + /** + * JSON constructor. + * + * @param apiClient An instance of ApiClient + */ + public JSON(ApiClient apiClient) { + this.apiClient = apiClient; + gson = new GsonBuilder() + .registerTypeAdapter(Date.class, new DateAdapter(apiClient)) + .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) + .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) + .create(); + } + + /** + * Get Gson. + * + * @return Gson + */ + public Gson getGson() { + return gson; + } + + /** + * Set Gson. + * + * @param gson Gson + */ + public void setGson(Gson gson) { + this.gson = gson; + } + + /** + * Serialize the given Java object into JSON string. + * + * @param obj Object + * @return String representation of the JSON + */ + public String serialize(Object obj) { + return gson.toJson(obj); + } + + /** + * Deserialize the given JSON string to Java object. + * + * @param Type + * @param body The JSON string + * @param returnType The type to deserialize inot + * @return The deserialized Java object + */ + @SuppressWarnings("unchecked") + public T deserialize(String body, Type returnType) { + try { + if (apiClient.isLenientOnJson()) { + JsonReader jsonReader = new JsonReader(new StringReader(body)); + // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) + jsonReader.setLenient(true); + return gson.fromJson(jsonReader, returnType); + } else { + return gson.fromJson(body, returnType); + } + } catch (JsonParseException e) { + // Fallback processing when failed to parse JSON form response body: + // return the response body string directly for the String return type; + // parse response body into date or datetime for the Date return type. + if (returnType.equals(String.class)) + return (T) body; + else if (returnType.equals(Date.class)) + return (T) apiClient.parseDateOrDatetime(body); + else throw(e); + } + } +} + +class DateAdapter implements JsonSerializer, JsonDeserializer { + private final ApiClient apiClient; + + /** + * Constructor for DateAdapter + * + * @param apiClient Api client + */ + public DateAdapter(ApiClient apiClient) { + super(); + this.apiClient = apiClient; + } + + /** + * Serialize + * + * @param src Date + * @param typeOfSrc Type + * @param context Json Serialization Context + * @return Json Element + */ + @Override + public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { + if (src == null) { + return JsonNull.INSTANCE; + } else { + return new JsonPrimitive(apiClient.formatDatetime(src)); + } + } + + /** + * Deserialize + * + * @param json Json element + * @param date Type + * @param typeOfSrc Type + * @param context Json Serialization Context + * @return Date + * @throw JsonParseException if fail to parse + */ + @Override + public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException { + String str = json.getAsJsonPrimitive().getAsString(); + try { + return apiClient.parseDateOrDatetime(str); + } catch (RuntimeException e) { + throw new JsonParseException(e); + } + } +} + +/** + * Gson TypeAdapter for Joda DateTime type + */ +class DateTimeTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + + @Override + public void write(JsonWriter out, DateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public DateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseDateTime(date); + } + } +} + +/** + * Gson TypeAdapter for Joda LocalDate type + */ +class LocalDateTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.date(); + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseLocalDate(date); + } + } +} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/Pair.java new file mode 100644 index 00000000000..15b247eea93 --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/Pair.java @@ -0,0 +1,64 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + + +public class Pair { + private String name = ""; + private String value = ""; + + public Pair (String name, String value) { + setName(name); + setValue(value); + } + + private void setName(String name) { + if (!isValidString(name)) return; + + this.name = name; + } + + private void setValue(String value) { + if (!isValidString(value)) return; + + this.value = value; + } + + public String getName() { + return this.name; + } + + public String getValue() { + return this.value; + } + + private boolean isValidString(String arg) { + if (arg == null) return false; + if (arg.trim().isEmpty()) return false; + + return true; + } +} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ProgressRequestBody.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ProgressRequestBody.java new file mode 100644 index 00000000000..d9ca742ecd2 --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ProgressRequestBody.java @@ -0,0 +1,95 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.RequestBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSink; +import okio.ForwardingSink; +import okio.Okio; +import okio.Sink; + +public class ProgressRequestBody extends RequestBody { + + public interface ProgressRequestListener { + void onRequestProgress(long bytesWritten, long contentLength, boolean done); + } + + private final RequestBody requestBody; + + private final ProgressRequestListener progressListener; + + private BufferedSink bufferedSink; + + public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) { + this.requestBody = requestBody; + this.progressListener = progressListener; + } + + @Override + public MediaType contentType() { + return requestBody.contentType(); + } + + @Override + public long contentLength() throws IOException { + return requestBody.contentLength(); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + if (bufferedSink == null) { + bufferedSink = Okio.buffer(sink(sink)); + } + + requestBody.writeTo(bufferedSink); + bufferedSink.flush(); + + } + + private Sink sink(Sink sink) { + return new ForwardingSink(sink) { + + long bytesWritten = 0L; + long contentLength = 0L; + + @Override + public void write(Buffer source, long byteCount) throws IOException { + super.write(source, byteCount); + if (contentLength == 0) { + contentLength = contentLength(); + } + + bytesWritten += byteCount; + progressListener.onRequestProgress(bytesWritten, contentLength, bytesWritten == contentLength); + } + }; + } +} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ProgressResponseBody.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ProgressResponseBody.java new file mode 100644 index 00000000000..f8af685999d --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ProgressResponseBody.java @@ -0,0 +1,88 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.ResponseBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSource; +import okio.ForwardingSource; +import okio.Okio; +import okio.Source; + +public class ProgressResponseBody extends ResponseBody { + + public interface ProgressListener { + void update(long bytesRead, long contentLength, boolean done); + } + + private final ResponseBody responseBody; + private final ProgressListener progressListener; + private BufferedSource bufferedSource; + + public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) { + this.responseBody = responseBody; + this.progressListener = progressListener; + } + + @Override + public MediaType contentType() { + return responseBody.contentType(); + } + + @Override + public long contentLength() throws IOException { + return responseBody.contentLength(); + } + + @Override + public BufferedSource source() throws IOException { + if (bufferedSource == null) { + bufferedSource = Okio.buffer(source(responseBody.source())); + } + return bufferedSource; + } + + private Source source(Source source) { + return new ForwardingSource(source) { + long totalBytesRead = 0L; + + @Override + public long read(Buffer sink, long byteCount) throws IOException { + long bytesRead = super.read(sink, byteCount); + // read() returns the number of bytes read, or -1 if this source is exhausted. + totalBytesRead += bytesRead != -1 ? bytesRead : 0; + progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1); + return bytesRead; + } + }; + } +} + + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java index 03c6c81e434..fdcef6b1010 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ /** * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java index 99df18ed71f..52dce361e2a 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java @@ -1,68 +1,353 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.api; -import io.swagger.client.CollectionFormats.*; +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; -import retrofit.Callback; -import retrofit.http.*; -import retrofit.mime.*; +import java.io.IOException; import org.joda.time.LocalDate; import org.joda.time.DateTime; import java.math.BigDecimal; +import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -public interface FakeApi { - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * Sync method - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * @param number None (required) - * @param _double None (required) - * @param string None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @return Void - */ - - @FormUrlEncoded - @POST("/fake") - Void testEndpointParameters( - @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password - ); - - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * Async method - * @param number None (required) - * @param _double None (required) - * @param string None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @param cb callback method - * @return void - */ - - @FormUrlEncoded - @POST("/fake") - void testEndpointParameters( - @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password, Callback cb - ); +public class FakeApi { + private ApiClient apiClient; + + public FakeApi() { + this(Configuration.getDefaultApiClient()); + } + + public FakeApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for testEndpointParameters */ + private com.squareup.okhttp.Call testEndpointParametersCall(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'number' is set + if (number == null) { + throw new ApiException("Missing the required parameter 'number' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter '_double' is set + if (_double == null) { + throw new ApiException("Missing the required parameter '_double' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter 'string' is set + if (string == null) { + throw new ApiException("Missing the required parameter 'string' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter '_byte' is set + if (_byte == null) { + throw new ApiException("Missing the required parameter '_byte' when calling testEndpointParameters(Async)"); + } + + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (integer != null) + localVarFormParams.put("integer", integer); + if (int32 != null) + localVarFormParams.put("int32", int32); + if (int64 != null) + localVarFormParams.put("int64", int64); + if (number != null) + localVarFormParams.put("number", number); + if (_float != null) + localVarFormParams.put("float", _float); + if (_double != null) + localVarFormParams.put("double", _double); + if (string != null) + localVarFormParams.put("string", string); + if (_byte != null) + localVarFormParams.put("byte", _byte); + if (binary != null) + localVarFormParams.put("binary", binary); + if (date != null) + localVarFormParams.put("date", date); + if (dateTime != null) + localVarFormParams.put("dateTime", dateTime); + if (password != null) + localVarFormParams.put("password", password); + + final String[] localVarAccepts = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param string None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { + testEndpointParametersWithHttpInfo(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param string None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { + com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password, null, null); + return apiClient.execute(call); + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 (asynchronously) + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param string None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call testEndpointParametersAsync(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for testEnumQueryParameters */ + private com.squareup.okhttp.Call testEnumQueryParametersCall(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (enumQueryInteger != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_integer", enumQueryInteger)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (enumQueryString != null) + localVarFormParams.put("enum_query_string", enumQueryString); + if (enumQueryDouble != null) + localVarFormParams.put("enum_query_double", enumQueryDouble); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * To test enum query parameters + * + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void testEnumQueryParameters(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { + testEnumQueryParametersWithHttpInfo(enumQueryString, enumQueryInteger, enumQueryDouble); + } + + /** + * To test enum query parameters + * + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse testEnumQueryParametersWithHttpInfo(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { + com.squareup.okhttp.Call call = testEnumQueryParametersCall(enumQueryString, enumQueryInteger, enumQueryDouble, null, null); + return apiClient.execute(call); + } + + /** + * To test enum query parameters (asynchronously) + * + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call testEnumQueryParametersAsync(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = testEnumQueryParametersCall(enumQueryString, enumQueryInteger, enumQueryDouble, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java index 66ed6aea981..2039a8842c1 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java @@ -1,233 +1,935 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.api; -import io.swagger.client.CollectionFormats.*; +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; -import retrofit.Callback; -import retrofit.http.*; -import retrofit.mime.*; +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; import io.swagger.client.model.Pet; import java.io.File; import io.swagger.client.model.ModelApiResponse; +import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -public interface PetApi { - /** - * Add a new pet to the store - * Sync method - * - * @param body Pet object that needs to be added to the store (required) - * @return Void - */ - - @POST("/pet") - Void addPet( - @Body Pet body - ); - - /** - * Add a new pet to the store - * Async method - * @param body Pet object that needs to be added to the store (required) - * @param cb callback method - * @return void - */ - - @POST("/pet") - void addPet( - @Body Pet body, Callback cb - ); - /** - * Deletes a pet - * Sync method - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @return Void - */ - - @DELETE("/pet/{petId}") - Void deletePet( - @Path("petId") Long petId, @Header("api_key") String apiKey - ); - - /** - * Deletes a pet - * Async method - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @param cb callback method - * @return void - */ - - @DELETE("/pet/{petId}") - void deletePet( - @Path("petId") Long petId, @Header("api_key") String apiKey, Callback cb - ); - /** - * Finds Pets by status - * Sync method - * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for filter (required) - * @return List - */ - - @GET("/pet/findByStatus") - List findPetsByStatus( - @Query("status") CSVParams status - ); - - /** - * Finds Pets by status - * Async method - * @param status Status values that need to be considered for filter (required) - * @param cb callback method - * @return void - */ - - @GET("/pet/findByStatus") - void findPetsByStatus( - @Query("status") CSVParams status, Callback> cb - ); - /** - * Finds Pets by tags - * Sync method - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by (required) - * @return List - */ - - @GET("/pet/findByTags") - List findPetsByTags( - @Query("tags") CSVParams tags - ); - - /** - * Finds Pets by tags - * Async method - * @param tags Tags to filter by (required) - * @param cb callback method - * @return void - */ - - @GET("/pet/findByTags") - void findPetsByTags( - @Query("tags") CSVParams tags, Callback> cb - ); - /** - * Find pet by ID - * Sync method - * Returns a single pet - * @param petId ID of pet to return (required) - * @return Pet - */ - - @GET("/pet/{petId}") - Pet getPetById( - @Path("petId") Long petId - ); - - /** - * Find pet by ID - * Async method - * @param petId ID of pet to return (required) - * @param cb callback method - * @return void - */ - - @GET("/pet/{petId}") - void getPetById( - @Path("petId") Long petId, Callback cb - ); - /** - * Update an existing pet - * Sync method - * - * @param body Pet object that needs to be added to the store (required) - * @return Void - */ - - @PUT("/pet") - Void updatePet( - @Body Pet body - ); - - /** - * Update an existing pet - * Async method - * @param body Pet object that needs to be added to the store (required) - * @param cb callback method - * @return void - */ - - @PUT("/pet") - void updatePet( - @Body Pet body, Callback cb - ); - /** - * Updates a pet in the store with form data - * Sync method - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @return Void - */ - - @FormUrlEncoded - @POST("/pet/{petId}") - Void updatePetWithForm( - @Path("petId") Long petId, @Field("name") String name, @Field("status") String status - ); - - /** - * Updates a pet in the store with form data - * Async method - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @param cb callback method - * @return void - */ - - @FormUrlEncoded - @POST("/pet/{petId}") - void updatePetWithForm( - @Path("petId") Long petId, @Field("name") String name, @Field("status") String status, Callback cb - ); - /** - * uploads an image - * Sync method - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @return ModelApiResponse - */ - - @Multipart - @POST("/pet/{petId}/uploadImage") - ModelApiResponse uploadFile( - @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file") TypedFile file - ); - - /** - * uploads an image - * Async method - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @param cb callback method - * @return void - */ - - @Multipart - @POST("/pet/{petId}/uploadImage") - void uploadFile( - @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file") TypedFile file, Callback cb - ); +public class PetApi { + private ApiClient apiClient; + + public PetApi() { + this(Configuration.getDefaultApiClient()); + } + + public PetApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for addPet */ + private com.squareup.okhttp.Call addPetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling addPet(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void addPet(Pet body) throws ApiException { + addPetWithHttpInfo(body); + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse addPetWithHttpInfo(Pet body) throws ApiException { + com.squareup.okhttp.Call call = addPetCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Add a new pet to the store (asynchronously) + * + * @param body Pet object that needs to be added to the store (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call addPetAsync(Pet body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = addPetCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for deletePet */ + private com.squareup.okhttp.Call deletePetCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling deletePet(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + if (apiKey != null) + localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deletePet(Long petId, String apiKey) throws ApiException { + deletePetWithHttpInfo(petId, apiKey); + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deletePetWithHttpInfo(Long petId, String apiKey) throws ApiException { + com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, null, null); + return apiClient.execute(call); + } + + /** + * Deletes a pet (asynchronously) + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deletePetAsync(Long petId, String apiKey, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for findPetsByStatus */ + private com.squareup.okhttp.Call findPetsByStatusCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'status' is set + if (status == null) { + throw new ApiException("Missing the required parameter 'status' when calling findPetsByStatus(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/findByStatus".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (status != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "status", status)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return List<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public List findPetsByStatus(List status) throws ApiException { + ApiResponse> resp = findPetsByStatusWithHttpInfo(status); + return resp.getData(); + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return ApiResponse<List<Pet>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> findPetsByStatusWithHttpInfo(List status) throws ApiException { + com.squareup.okhttp.Call call = findPetsByStatusCall(status, null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Finds Pets by status (asynchronously) + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call findPetsByStatusAsync(List status, final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = findPetsByStatusCall(status, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for findPetsByTags */ + private com.squareup.okhttp.Call findPetsByTagsCall(List tags, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'tags' is set + if (tags == null) { + throw new ApiException("Missing the required parameter 'tags' when calling findPetsByTags(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/findByTags".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (tags != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "tags", tags)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return List<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public List findPetsByTags(List tags) throws ApiException { + ApiResponse> resp = findPetsByTagsWithHttpInfo(tags); + return resp.getData(); + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return ApiResponse<List<Pet>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> findPetsByTagsWithHttpInfo(List tags) throws ApiException { + com.squareup.okhttp.Call call = findPetsByTagsCall(tags, null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Finds Pets by tags (asynchronously) + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call findPetsByTagsAsync(List tags, final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = findPetsByTagsCall(tags, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for getPetById */ + private com.squareup.okhttp.Call getPetByIdCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling getPetById(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "api_key" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return Pet + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Pet getPetById(Long petId) throws ApiException { + ApiResponse resp = getPetByIdWithHttpInfo(petId); + return resp.getData(); + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return ApiResponse<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getPetByIdWithHttpInfo(Long petId) throws ApiException { + com.squareup.okhttp.Call call = getPetByIdCall(petId, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Find pet by ID (asynchronously) + * Returns a single pet + * @param petId ID of pet to return (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getPetByIdAsync(Long petId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getPetByIdCall(petId, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for updatePet */ + private com.squareup.okhttp.Call updatePetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling updatePet(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updatePet(Pet body) throws ApiException { + updatePetWithHttpInfo(body); + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updatePetWithHttpInfo(Pet body) throws ApiException { + com.squareup.okhttp.Call call = updatePetCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Update an existing pet (asynchronously) + * + * @param body Pet object that needs to be added to the store (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updatePetAsync(Pet body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updatePetCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for updatePetWithForm */ + private com.squareup.okhttp.Call updatePetWithFormCall(Long petId, String name, String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling updatePetWithForm(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (name != null) + localVarFormParams.put("name", name); + if (status != null) + localVarFormParams.put("status", status); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/x-www-form-urlencoded" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updatePetWithForm(Long petId, String name, String status) throws ApiException { + updatePetWithFormWithHttpInfo(petId, name, status); + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updatePetWithFormWithHttpInfo(Long petId, String name, String status) throws ApiException { + com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, null, null); + return apiClient.execute(call); + } + + /** + * Updates a pet in the store with form data (asynchronously) + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updatePetWithFormAsync(Long petId, String name, String status, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for uploadFile */ + private com.squareup.okhttp.Call uploadFileCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling uploadFile(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (additionalMetadata != null) + localVarFormParams.put("additionalMetadata", additionalMetadata); + if (file != null) + localVarFormParams.put("file", file); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ModelApiResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { + ApiResponse resp = uploadFileWithHttpInfo(petId, additionalMetadata, file); + return resp.getData(); + } + + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ApiResponse<ModelApiResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file) throws ApiException { + com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * uploads an image (asynchronously) + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call uploadFileAsync(Long petId, String additionalMetadata, File file, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java index def4aa2efc7..0768744c263 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java @@ -1,114 +1,482 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.api; -import io.swagger.client.CollectionFormats.*; +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; -import retrofit.Callback; -import retrofit.http.*; -import retrofit.mime.*; +import java.io.IOException; import io.swagger.client.model.Order; +import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -public interface StoreApi { - /** - * Delete purchase order by ID - * Sync method - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted (required) - * @return Void - */ - - @DELETE("/store/order/{orderId}") - Void deleteOrder( - @Path("orderId") String orderId - ); - - /** - * Delete purchase order by ID - * Async method - * @param orderId ID of the order that needs to be deleted (required) - * @param cb callback method - * @return void - */ - - @DELETE("/store/order/{orderId}") - void deleteOrder( - @Path("orderId") String orderId, Callback cb - ); - /** - * Returns pet inventories by status - * Sync method - * Returns a map of status codes to quantities - * @return Map - */ - - @GET("/store/inventory") - Map getInventory(); - - - /** - * Returns pet inventories by status - * Async method - * @param cb callback method - * @return void - */ - - @GET("/store/inventory") - void getInventory( - Callback> cb - ); - /** - * Find purchase order by ID - * Sync method - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched (required) - * @return Order - */ - - @GET("/store/order/{orderId}") - Order getOrderById( - @Path("orderId") Long orderId - ); - - /** - * Find purchase order by ID - * Async method - * @param orderId ID of pet that needs to be fetched (required) - * @param cb callback method - * @return void - */ - - @GET("/store/order/{orderId}") - void getOrderById( - @Path("orderId") Long orderId, Callback cb - ); - /** - * Place an order for a pet - * Sync method - * - * @param body order placed for purchasing the pet (required) - * @return Order - */ - - @POST("/store/order") - Order placeOrder( - @Body Order body - ); - - /** - * Place an order for a pet - * Async method - * @param body order placed for purchasing the pet (required) - * @param cb callback method - * @return void - */ - - @POST("/store/order") - void placeOrder( - @Body Order body, Callback cb - ); +public class StoreApi { + private ApiClient apiClient; + + public StoreApi() { + this(Configuration.getDefaultApiClient()); + } + + public StoreApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for deleteOrder */ + private com.squareup.okhttp.Call deleteOrderCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling deleteOrder(Async)"); + } + + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deleteOrder(String orderId) throws ApiException { + deleteOrderWithHttpInfo(orderId); + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deleteOrderWithHttpInfo(String orderId) throws ApiException { + com.squareup.okhttp.Call call = deleteOrderCall(orderId, null, null); + return apiClient.execute(call); + } + + /** + * Delete purchase order by ID (asynchronously) + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deleteOrderAsync(String orderId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = deleteOrderCall(orderId, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for getInventory */ + private com.squareup.okhttp.Call getInventoryCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + + // create path and map variables + String localVarPath = "/store/inventory".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "api_key" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return Map<String, Integer> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Map getInventory() throws ApiException { + ApiResponse> resp = getInventoryWithHttpInfo(); + return resp.getData(); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return ApiResponse<Map<String, Integer>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> getInventoryWithHttpInfo() throws ApiException { + com.squareup.okhttp.Call call = getInventoryCall(null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Returns pet inventories by status (asynchronously) + * Returns a map of status codes to quantities + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getInventoryAsync(final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getInventoryCall(progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for getOrderById */ + private com.squareup.okhttp.Call getOrderByIdCall(Long orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling getOrderById(Async)"); + } + + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @return Order + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Order getOrderById(Long orderId) throws ApiException { + ApiResponse resp = getOrderByIdWithHttpInfo(orderId); + return resp.getData(); + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @return ApiResponse<Order> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getOrderByIdWithHttpInfo(Long orderId) throws ApiException { + com.squareup.okhttp.Call call = getOrderByIdCall(orderId, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Find purchase order by ID (asynchronously) + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getOrderByIdAsync(Long orderId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getOrderByIdCall(orderId, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for placeOrder */ + private com.squareup.okhttp.Call placeOrderCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling placeOrder(Async)"); + } + + + // create path and map variables + String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet (required) + * @return Order + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Order placeOrder(Order body) throws ApiException { + ApiResponse resp = placeOrderWithHttpInfo(body); + return resp.getData(); + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet (required) + * @return ApiResponse<Order> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse placeOrderWithHttpInfo(Order body) throws ApiException { + com.squareup.okhttp.Call call = placeOrderCall(body, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Place an order for a pet (asynchronously) + * + * @param body order placed for purchasing the pet (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call placeOrderAsync(Order body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = placeOrderCall(body, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java index 8c3380d07d4..1c4fc3101a1 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java @@ -1,218 +1,907 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.api; -import io.swagger.client.CollectionFormats.*; +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; -import retrofit.Callback; -import retrofit.http.*; -import retrofit.mime.*; +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; import io.swagger.client.model.User; +import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -public interface UserApi { - /** - * Create user - * Sync method - * This can only be done by the logged in user. - * @param body Created user object (required) - * @return Void - */ - - @POST("/user") - Void createUser( - @Body User body - ); - - /** - * Create user - * Async method - * @param body Created user object (required) - * @param cb callback method - * @return void - */ - - @POST("/user") - void createUser( - @Body User body, Callback cb - ); - /** - * Creates list of users with given input array - * Sync method - * - * @param body List of user object (required) - * @return Void - */ - - @POST("/user/createWithArray") - Void createUsersWithArrayInput( - @Body List body - ); - - /** - * Creates list of users with given input array - * Async method - * @param body List of user object (required) - * @param cb callback method - * @return void - */ - - @POST("/user/createWithArray") - void createUsersWithArrayInput( - @Body List body, Callback cb - ); - /** - * Creates list of users with given input array - * Sync method - * - * @param body List of user object (required) - * @return Void - */ - - @POST("/user/createWithList") - Void createUsersWithListInput( - @Body List body - ); - - /** - * Creates list of users with given input array - * Async method - * @param body List of user object (required) - * @param cb callback method - * @return void - */ - - @POST("/user/createWithList") - void createUsersWithListInput( - @Body List body, Callback cb - ); - /** - * Delete user - * Sync method - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @return Void - */ - - @DELETE("/user/{username}") - Void deleteUser( - @Path("username") String username - ); - - /** - * Delete user - * Async method - * @param username The name that needs to be deleted (required) - * @param cb callback method - * @return void - */ - - @DELETE("/user/{username}") - void deleteUser( - @Path("username") String username, Callback cb - ); - /** - * Get user by user name - * Sync method - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return User - */ - - @GET("/user/{username}") - User getUserByName( - @Path("username") String username - ); - - /** - * Get user by user name - * Async method - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @param cb callback method - * @return void - */ - - @GET("/user/{username}") - void getUserByName( - @Path("username") String username, Callback cb - ); - /** - * Logs user into the system - * Sync method - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @return String - */ - - @GET("/user/login") - String loginUser( - @Query("username") String username, @Query("password") String password - ); - - /** - * Logs user into the system - * Async method - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @param cb callback method - * @return void - */ - - @GET("/user/login") - void loginUser( - @Query("username") String username, @Query("password") String password, Callback cb - ); - /** - * Logs out current logged in user session - * Sync method - * - * @return Void - */ - - @GET("/user/logout") - Void logoutUser(); - - - /** - * Logs out current logged in user session - * Async method - * @param cb callback method - * @return void - */ - - @GET("/user/logout") - void logoutUser( - Callback cb - ); - /** - * Updated user - * Sync method - * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @return Void - */ - - @PUT("/user/{username}") - Void updateUser( - @Path("username") String username, @Body User body - ); - - /** - * Updated user - * Async method - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @param cb callback method - * @return void - */ - - @PUT("/user/{username}") - void updateUser( - @Path("username") String username, @Body User body, Callback cb - ); +public class UserApi { + private ApiClient apiClient; + + public UserApi() { + this(Configuration.getDefaultApiClient()); + } + + public UserApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for createUser */ + private com.squareup.okhttp.Call createUserCall(User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUser(User body) throws ApiException { + createUserWithHttpInfo(body); + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUserWithHttpInfo(User body) throws ApiException { + com.squareup.okhttp.Call call = createUserCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Create user (asynchronously) + * This can only be done by the logged in user. + * @param body Created user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUserAsync(User body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = createUserCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for createUsersWithArrayInput */ + private com.squareup.okhttp.Call createUsersWithArrayInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUsersWithArrayInput(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/createWithArray".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUsersWithArrayInput(List body) throws ApiException { + createUsersWithArrayInputWithHttpInfo(body); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUsersWithArrayInputWithHttpInfo(List body) throws ApiException { + com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Creates list of users with given input array (asynchronously) + * + * @param body List of user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUsersWithArrayInputAsync(List body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for createUsersWithListInput */ + private com.squareup.okhttp.Call createUsersWithListInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUsersWithListInput(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUsersWithListInput(List body) throws ApiException { + createUsersWithListInputWithHttpInfo(body); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUsersWithListInputWithHttpInfo(List body) throws ApiException { + com.squareup.okhttp.Call call = createUsersWithListInputCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Creates list of users with given input array (asynchronously) + * + * @param body List of user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUsersWithListInputAsync(List body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = createUsersWithListInputCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for deleteUser */ + private com.squareup.okhttp.Call deleteUserCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling deleteUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deleteUser(String username) throws ApiException { + deleteUserWithHttpInfo(username); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deleteUserWithHttpInfo(String username) throws ApiException { + com.squareup.okhttp.Call call = deleteUserCall(username, null, null); + return apiClient.execute(call); + } + + /** + * Delete user (asynchronously) + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deleteUserAsync(String username, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = deleteUserCall(username, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for getUserByName */ + private com.squareup.okhttp.Call getUserByNameCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling getUserByName(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return User + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public User getUserByName(String username) throws ApiException { + ApiResponse resp = getUserByNameWithHttpInfo(username); + return resp.getData(); + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return ApiResponse<User> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getUserByNameWithHttpInfo(String username) throws ApiException { + com.squareup.okhttp.Call call = getUserByNameCall(username, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Get user by user name (asynchronously) + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getUserByNameAsync(String username, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getUserByNameCall(username, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for loginUser */ + private com.squareup.okhttp.Call loginUserCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling loginUser(Async)"); + } + + // verify the required parameter 'password' is set + if (password == null) { + throw new ApiException("Missing the required parameter 'password' when calling loginUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/login".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (username != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "username", username)); + if (password != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "password", password)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return String + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public String loginUser(String username, String password) throws ApiException { + ApiResponse resp = loginUserWithHttpInfo(username, password); + return resp.getData(); + } + + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return ApiResponse<String> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse loginUserWithHttpInfo(String username, String password) throws ApiException { + com.squareup.okhttp.Call call = loginUserCall(username, password, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Logs user into the system (asynchronously) + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call loginUserAsync(String username, String password, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = loginUserCall(username, password, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for logoutUser */ + private com.squareup.okhttp.Call logoutUserCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + + // create path and map variables + String localVarPath = "/user/logout".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Logs out current logged in user session + * + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void logoutUser() throws ApiException { + logoutUserWithHttpInfo(); + } + + /** + * Logs out current logged in user session + * + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse logoutUserWithHttpInfo() throws ApiException { + com.squareup.okhttp.Call call = logoutUserCall(null, null); + return apiClient.execute(call); + } + + /** + * Logs out current logged in user session (asynchronously) + * + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call logoutUserAsync(final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = logoutUserCall(progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for updateUser */ + private com.squareup.okhttp.Call updateUserCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling updateUser(Async)"); + } + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling updateUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updateUser(String username, User body) throws ApiException { + updateUserWithHttpInfo(username, body); + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updateUserWithHttpInfo(String username, User body) throws ApiException { + com.squareup.okhttp.Call call = updateUserCall(username, body, null, null); + return apiClient.execute(call); + } + + /** + * Updated user (asynchronously) + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updateUserAsync(String username, User body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updateUserCall(username, body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index 59d01238796..a125fff5f24 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -1,68 +1,87 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; +import io.swagger.client.Pair; -import com.squareup.okhttp.Interceptor; -import com.squareup.okhttp.Request; -import com.squareup.okhttp.Response; +import java.util.Map; +import java.util.List; -public class ApiKeyAuth implements Interceptor { - private final String location; - private final String paramName; - private String apiKey; +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; - public ApiKeyAuth(String location, String paramName) { - this.location = location; - this.paramName = paramName; - } + private String apiKey; + private String apiKeyPrefix; - public String getLocation() { - return location; - } + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } - public String getParamName() { - return paramName; - } + public String getLocation() { + return location; + } - public String getApiKey() { - return apiKey; - } + public String getParamName() { + return paramName; + } - public void setApiKey(String apiKey) { - this.apiKey = apiKey; - } + public String getApiKey() { + return apiKey; + } - @Override - public Response intercept(Chain chain) throws IOException { - String paramValue; - Request request = chain.request(); + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } - if (location == "query") { - String newQuery = request.uri().getQuery(); - paramValue = paramName + "=" + apiKey; - if (newQuery == null) { - newQuery = paramValue; - } else { - newQuery += "&" + paramValue; - } + public String getApiKeyPrefix() { + return apiKeyPrefix; + } - URI newUri; - try { - newUri = new URI(request.uri().getScheme(), request.uri().getAuthority(), - request.uri().getPath(), newQuery, request.uri().getFragment()); - } catch (URISyntaxException e) { - throw new IOException(e); - } + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } - request = request.newBuilder().url(newUri.toURL()).build(); - } else if (location == "header") { - request = request.newBuilder() - .addHeader(paramName, apiKey) - .build(); - } - return chain.proceed(request); + @Override + public void applyToParams(List queryParams, Map headerParams) { + if (apiKey == null) { + return; + } + String value; + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if (location == "query") { + queryParams.add(new Pair(paramName, value)); + } else if (location == "header") { + headerParams.put(paramName, value); } -} \ No newline at end of file + } +} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/Authentication.java new file mode 100644 index 00000000000..221a7d9dd1f --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/Authentication.java @@ -0,0 +1,41 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + +public interface Authentication { + /** + * Apply authentication settings to header and query params. + * + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + */ + void applyToParams(List queryParams, Map headerParams); +} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index cb7c617767b..4eb2300b69d 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -1,17 +1,43 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; -import java.io.IOException; +import io.swagger.client.Pair; import com.squareup.okhttp.Credentials; -import com.squareup.okhttp.Interceptor; -import com.squareup.okhttp.Request; -import com.squareup.okhttp.Response; -public class HttpBasicAuth implements Interceptor { +import java.util.Map; +import java.util.List; +import java.io.UnsupportedEncodingException; + +public class HttpBasicAuth implements Authentication { private String username; private String password; - + public String getUsername() { return username; } @@ -28,22 +54,13 @@ public void setPassword(String password) { this.password = password; } - public void setCredentials(String username, String password) { - this.username = username; - this.password = password; - } - @Override - public Response intercept(Chain chain) throws IOException { - Request request = chain.request(); - - // If the request already have an authorization (eg. Basic auth), do nothing - if (request.header("Authorization") == null) { - String credentials = Credentials.basic(username, password); - request = request.newBuilder() - .addHeader("Authorization", credentials) - .build(); + public void applyToParams(List queryParams, Map headerParams) { + if (username == null && password == null) { + return; } - return chain.proceed(request); + headerParams.put("Authorization", Credentials.basic( + username == null ? "" : username, + password == null ? "" : password)); } } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuth.java index b725e019aff..14521f6ed7e 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuth.java @@ -1,176 +1,51 @@ -package io.swagger.client.auth; - -import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; -import static java.net.HttpURLConnection.HTTP_FORBIDDEN; - -import java.io.IOException; -import java.util.Map; - -import org.apache.oltu.oauth2.client.OAuthClient; -import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest; -import org.apache.oltu.oauth2.client.request.OAuthClientRequest; -import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; -import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; -import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse; -import org.apache.oltu.oauth2.common.exception.OAuthProblemException; -import org.apache.oltu.oauth2.common.exception.OAuthSystemException; -import org.apache.oltu.oauth2.common.message.types.GrantType; -import org.apache.oltu.oauth2.common.token.BasicOAuthToken; - -import com.squareup.okhttp.Interceptor; -import com.squareup.okhttp.OkHttpClient; -import com.squareup.okhttp.Request; -import com.squareup.okhttp.Request.Builder; -import com.squareup.okhttp.Response; - -public class OAuth implements Interceptor { - - public interface AccessTokenListener { - public void notify(BasicOAuthToken token); - } +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ - private volatile String accessToken; - private OAuthClient oauthClient; - private TokenRequestBuilder tokenRequestBuilder; - private AuthenticationRequestBuilder authenticationRequestBuilder; - - private AccessTokenListener accessTokenListener; - - public OAuth( OkHttpClient client, TokenRequestBuilder requestBuilder ) { - this.oauthClient = new OAuthClient(new OAuthOkHttpClient(client)); - this.tokenRequestBuilder = requestBuilder; - } - - public OAuth(TokenRequestBuilder requestBuilder ) { - this(new OkHttpClient(), requestBuilder); - } - - public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { - this(OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes)); - setFlow(flow); - authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl); - } - - public void setFlow(OAuthFlow flow) { - switch(flow) { - case accessCode: - case implicit: - tokenRequestBuilder.setGrantType(GrantType.AUTHORIZATION_CODE); - break; - case password: - tokenRequestBuilder.setGrantType(GrantType.PASSWORD); - break; - case application: - tokenRequestBuilder.setGrantType(GrantType.CLIENT_CREDENTIALS); - break; - default: - break; - } - } - - @Override - public Response intercept(Chain chain) - throws IOException { - - Request request = chain.request(); - - // If the request already have an authorization (eg. Basic auth), do nothing - if (request.header("Authorization") != null) { - return chain.proceed(request); - } - - // If first time, get the token - OAuthClientRequest oAuthRequest; - if (getAccessToken() == null) { - updateAccessToken(null); - } - - if (getAccessToken() != null) { - // Build the request - Builder rb = request.newBuilder(); - - String requestAccessToken = new String(getAccessToken()); - try { - oAuthRequest = new OAuthBearerClientRequest(request.urlString()) - .setAccessToken(requestAccessToken) - .buildHeaderMessage(); - } catch (OAuthSystemException e) { - throw new IOException(e); - } - - for ( Map.Entry header : oAuthRequest.getHeaders().entrySet() ) { - rb.addHeader(header.getKey(), header.getValue()); - } - rb.url( oAuthRequest.getLocationUri()); - - //Execute the request - Response response = chain.proceed(rb.build()); - - // 401 most likely indicates that access token has expired. - // Time to refresh and resend the request - if ( response != null && (response.code() == HTTP_UNAUTHORIZED | response.code() == HTTP_FORBIDDEN) ) { - if (updateAccessToken(requestAccessToken)) { - return intercept( chain ); - } - } - return response; - } else { - return chain.proceed(chain.request()); - } - } +package io.swagger.client.auth; - /* - * Returns true if the access token has been updated - */ - public synchronized boolean updateAccessToken(String requestAccessToken) throws IOException { - if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) { - try { - OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(this.tokenRequestBuilder.buildBodyMessage()); - if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) { - setAccessToken(accessTokenResponse.getAccessToken()); - if (accessTokenListener != null) { - accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); - } - return getAccessToken().equals(requestAccessToken); - } else { - return false; - } - } catch (OAuthSystemException e) { - throw new IOException(e); - } catch (OAuthProblemException e) { - throw new IOException(e); - } - } - return true; - } +import io.swagger.client.Pair; - public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { - this.accessTokenListener = accessTokenListener; - } - - public synchronized String getAccessToken() { - return accessToken; - } +import java.util.Map; +import java.util.List; - public synchronized void setAccessToken(String accessToken) { - this.accessToken = accessToken; - } - public TokenRequestBuilder getTokenRequestBuilder() { - return tokenRequestBuilder; - } +public class OAuth implements Authentication { + private String accessToken; - public void setTokenRequestBuilder(TokenRequestBuilder tokenRequestBuilder) { - this.tokenRequestBuilder = tokenRequestBuilder; - } + public String getAccessToken() { + return accessToken; + } - public AuthenticationRequestBuilder getAuthenticationRequestBuilder() { - return authenticationRequestBuilder; - } + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } - public void setAuthenticationRequestBuilder(AuthenticationRequestBuilder authenticationRequestBuilder) { - this.authenticationRequestBuilder = authenticationRequestBuilder; + @Override + public void applyToParams(List queryParams, Map headerParams) { + if (accessToken != null) { + headerParams.put("Authorization", "Bearer " + accessToken); } - + } } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthFlow.java index ec1f942b0f2..50d5260cfd9 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,6 +1,6 @@ /** * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java deleted file mode 100644 index c872901ba24..00000000000 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java +++ /dev/null @@ -1,69 +0,0 @@ -package io.swagger.client.auth; - -import java.io.IOException; -import java.util.Map; -import java.util.Map.Entry; - -import org.apache.oltu.oauth2.client.HttpClient; -import org.apache.oltu.oauth2.client.request.OAuthClientRequest; -import org.apache.oltu.oauth2.client.response.OAuthClientResponse; -import org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory; -import org.apache.oltu.oauth2.common.exception.OAuthProblemException; -import org.apache.oltu.oauth2.common.exception.OAuthSystemException; - -import com.squareup.okhttp.MediaType; -import com.squareup.okhttp.OkHttpClient; -import com.squareup.okhttp.Request; -import com.squareup.okhttp.RequestBody; -import com.squareup.okhttp.Response; - - -public class OAuthOkHttpClient implements HttpClient { - - private OkHttpClient client; - - public OAuthOkHttpClient() { - this.client = new OkHttpClient(); - } - - public OAuthOkHttpClient(OkHttpClient client) { - this.client = client; - } - - public T execute(OAuthClientRequest request, Map headers, - String requestMethod, Class responseClass) - throws OAuthSystemException, OAuthProblemException { - - MediaType mediaType = MediaType.parse("application/json"); - Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri()); - - if(headers != null) { - for (Entry entry : headers.entrySet()) { - if (entry.getKey().equalsIgnoreCase("Content-Type")) { - mediaType = MediaType.parse(entry.getValue()); - } else { - requestBuilder.addHeader(entry.getKey(), entry.getValue()); - } - } - } - - RequestBody body = request.getBody() != null ? RequestBody.create(mediaType, request.getBody()) : null; - requestBuilder.method(requestMethod, body); - - try { - Response response = client.newCall(requestBuilder.build()).execute(); - return OAuthClientResponseFactory.createCustomResponse( - response.body().string(), - response.body().contentType().toString(), - response.code(), - responseClass); - } catch (IOException e) { - throw new OAuthSystemException(e); - } - } - - public void shutdown() { - // Nothing to do here - } - -} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 839b04aa6c5..1943e013fa1 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -1,49 +1,89 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; import java.util.List; import java.util.Map; -import com.google.gson.annotations.SerializedName; - - - +/** + * AdditionalPropertiesClass + */ public class AdditionalPropertiesClass { - @SerializedName("map_property") private Map mapProperty = new HashMap(); @SerializedName("map_of_map_property") private Map> mapOfMapProperty = new HashMap>(); - /** - **/ - @ApiModelProperty(value = "") + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + /** + * Get mapProperty + * @return mapProperty + **/ + @ApiModelProperty(example = "null", value = "") public Map getMapProperty() { return mapProperty; } + public void setMapProperty(Map mapProperty) { this.mapProperty = mapProperty; } - /** - **/ - @ApiModelProperty(value = "") + public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + return this; + } + + /** + * Get mapOfMapProperty + * @return mapOfMapProperty + **/ + @ApiModelProperty(example = "null", value = "") public Map> getMapOfMapProperty() { return mapOfMapProperty; } + public void setMapOfMapProperty(Map> mapOfMapProperty) { this.mapOfMapProperty = mapOfMapProperty; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -51,8 +91,8 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; - return Objects.equals(mapProperty, additionalPropertiesClass.mapProperty) && - Objects.equals(mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); + return Objects.equals(this.mapProperty, additionalPropertiesClass.mapProperty) && + Objects.equals(this.mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); } @Override @@ -75,10 +115,11 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } } + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Animal.java index 9a14a1289fe..ba3806dc875 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Animal.java @@ -1,46 +1,86 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import com.google.gson.annotations.SerializedName; - - - +/** + * Animal + */ public class Animal { - @SerializedName("className") private String className = null; @SerializedName("color") private String color = "red"; - /** - **/ - @ApiModelProperty(required = true, value = "") + public Animal className(String className) { + this.className = className; + return this; + } + + /** + * Get className + * @return className + **/ + @ApiModelProperty(example = "null", required = true, value = "") public String getClassName() { return className; } + public void setClassName(String className) { this.className = className; } - /** - **/ - @ApiModelProperty(value = "") + public Animal color(String color) { + this.color = color; + return this; + } + + /** + * Get color + * @return color + **/ + @ApiModelProperty(example = "null", value = "") public String getColor() { return color; } + public void setColor(String color) { this.color = color; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -48,8 +88,8 @@ public boolean equals(Object o) { return false; } Animal animal = (Animal) o; - return Objects.equals(className, animal.className) && - Objects.equals(color, animal.color); + return Objects.equals(this.className, animal.className) && + Objects.equals(this.color, animal.color); } @Override @@ -72,10 +112,11 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } } + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AnimalFarm.java index c7d37b1512c..b54adb09d7b 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -5,30 +30,27 @@ import java.util.ArrayList; import java.util.List; -import com.google.gson.annotations.SerializedName; - - - +/** + * AnimalFarm + */ public class AnimalFarm extends ArrayList { - @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } - AnimalFarm animalFarm = (AnimalFarm) o; return true; } @Override public int hashCode() { - return Objects.hash(); + return Objects.hash(super.hashCode()); } @Override @@ -44,10 +66,11 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } } + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 00000000000..5446c2c439b --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,102 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + + +/** + * ArrayOfArrayOfNumberOnly + */ + +public class ArrayOfArrayOfNumberOnly { + @SerializedName("ArrayArrayNumber") + private List> arrayArrayNumber = new ArrayList>(); + + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + /** + * Get arrayArrayNumber + * @return arrayArrayNumber + **/ + @ApiModelProperty(example = "null", value = "") + public List> getArrayArrayNumber() { + return arrayArrayNumber; + } + + public void setArrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly = (ArrayOfArrayOfNumberOnly) o; + return Objects.equals(this.arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayArrayNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfArrayOfNumberOnly {\n"); + + sb.append(" arrayArrayNumber: ").append(toIndentedString(arrayArrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java new file mode 100644 index 00000000000..c9257a5d3ee --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -0,0 +1,102 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + + +/** + * ArrayOfNumberOnly + */ + +public class ArrayOfNumberOnly { + @SerializedName("ArrayNumber") + private List arrayNumber = new ArrayList(); + + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + /** + * Get arrayNumber + * @return arrayNumber + **/ + @ApiModelProperty(example = "null", value = "") + public List getArrayNumber() { + return arrayNumber; + } + + public void setArrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfNumberOnly arrayOfNumberOnly = (ArrayOfNumberOnly) o; + return Objects.equals(this.arrayNumber, arrayOfNumberOnly.arrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfNumberOnly {\n"); + + sb.append(" arrayNumber: ").append(toIndentedString(arrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayTest.java index 92337cc0246..8d58870bcdc 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayTest.java @@ -1,19 +1,44 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.ReadOnlyFirst; import java.util.ArrayList; import java.util.List; -import com.google.gson.annotations.SerializedName; - - - +/** + * ArrayTest + */ public class ArrayTest { - @SerializedName("array_of_string") private List arrayOfString = new ArrayList(); @@ -23,39 +48,63 @@ public class ArrayTest { @SerializedName("array_array_of_model") private List> arrayArrayOfModel = new ArrayList>(); - /** - **/ - @ApiModelProperty(value = "") + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + /** + * Get arrayOfString + * @return arrayOfString + **/ + @ApiModelProperty(example = "null", value = "") public List getArrayOfString() { return arrayOfString; } + public void setArrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; } - /** - **/ - @ApiModelProperty(value = "") + public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + return this; + } + + /** + * Get arrayArrayOfInteger + * @return arrayArrayOfInteger + **/ + @ApiModelProperty(example = "null", value = "") public List> getArrayArrayOfInteger() { return arrayArrayOfInteger; } + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - /** - **/ - @ApiModelProperty(value = "") + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + return this; + } + + /** + * Get arrayArrayOfModel + * @return arrayArrayOfModel + **/ + @ApiModelProperty(example = "null", value = "") public List> getArrayArrayOfModel() { return arrayArrayOfModel; } + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -63,9 +112,9 @@ public boolean equals(Object o) { return false; } ArrayTest arrayTest = (ArrayTest) o; - return Objects.equals(arrayOfString, arrayTest.arrayOfString) && - Objects.equals(arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && - Objects.equals(arrayArrayOfModel, arrayTest.arrayArrayOfModel); + return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && + Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); } @Override @@ -89,10 +138,11 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } } + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Cat.java index 287d6a4d94c..21ed0f4c26b 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Cat.java @@ -1,18 +1,42 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; -import com.google.gson.annotations.SerializedName; - - - +/** + * Cat + */ public class Cat extends Animal { - @SerializedName("className") private String className = null; @@ -22,39 +46,63 @@ public class Cat extends Animal { @SerializedName("declawed") private Boolean declawed = null; - /** - **/ - @ApiModelProperty(required = true, value = "") + public Cat className(String className) { + this.className = className; + return this; + } + + /** + * Get className + * @return className + **/ + @ApiModelProperty(example = "null", required = true, value = "") public String getClassName() { return className; } + public void setClassName(String className) { this.className = className; } - /** - **/ - @ApiModelProperty(value = "") + public Cat color(String color) { + this.color = color; + return this; + } + + /** + * Get color + * @return color + **/ + @ApiModelProperty(example = "null", value = "") public String getColor() { return color; } + public void setColor(String color) { this.color = color; } - /** - **/ - @ApiModelProperty(value = "") + public Cat declawed(Boolean declawed) { + this.declawed = declawed; + return this; + } + + /** + * Get declawed + * @return declawed + **/ + @ApiModelProperty(example = "null", value = "") public Boolean getDeclawed() { return declawed; } + public void setDeclawed(Boolean declawed) { this.declawed = declawed; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -62,14 +110,15 @@ public boolean equals(Object o) { return false; } Cat cat = (Cat) o; - return Objects.equals(className, cat.className) && - Objects.equals(color, cat.color) && - Objects.equals(declawed, cat.declawed); + return Objects.equals(this.className, cat.className) && + Objects.equals(this.color, cat.color) && + Objects.equals(this.declawed, cat.declawed) && + super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, color, declawed); + return Objects.hash(className, color, declawed, super.hashCode()); } @Override @@ -88,10 +137,11 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } } + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Category.java index 93ec7bd0877..2178a866f62 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Category.java @@ -1,46 +1,86 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import com.google.gson.annotations.SerializedName; - - - +/** + * Category + */ public class Category { - @SerializedName("id") private Long id = null; @SerializedName("name") private String name = null; - /** - **/ - @ApiModelProperty(value = "") + public Category id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(example = "null", value = "") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ - @ApiModelProperty(value = "") + public Category name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(example = "null", value = "") public String getName() { return name; } + public void setName(String name) { this.name = name; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -48,8 +88,8 @@ public boolean equals(Object o) { return false; } Category category = (Category) o; - return Objects.equals(id, category.id) && - Objects.equals(name, category.name); + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); } @Override @@ -72,10 +112,11 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } } + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Dog.java index 5d2ead15f07..4ba5804553f 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Dog.java @@ -1,18 +1,42 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; -import com.google.gson.annotations.SerializedName; - - - +/** + * Dog + */ public class Dog extends Animal { - @SerializedName("className") private String className = null; @@ -22,39 +46,63 @@ public class Dog extends Animal { @SerializedName("breed") private String breed = null; - /** - **/ - @ApiModelProperty(required = true, value = "") + public Dog className(String className) { + this.className = className; + return this; + } + + /** + * Get className + * @return className + **/ + @ApiModelProperty(example = "null", required = true, value = "") public String getClassName() { return className; } + public void setClassName(String className) { this.className = className; } - /** - **/ - @ApiModelProperty(value = "") + public Dog color(String color) { + this.color = color; + return this; + } + + /** + * Get color + * @return color + **/ + @ApiModelProperty(example = "null", value = "") public String getColor() { return color; } + public void setColor(String color) { this.color = color; } - /** - **/ - @ApiModelProperty(value = "") + public Dog breed(String breed) { + this.breed = breed; + return this; + } + + /** + * Get breed + * @return breed + **/ + @ApiModelProperty(example = "null", value = "") public String getBreed() { return breed; } + public void setBreed(String breed) { this.breed = breed; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -62,14 +110,15 @@ public boolean equals(Object o) { return false; } Dog dog = (Dog) o; - return Objects.equals(className, dog.className) && - Objects.equals(color, dog.color) && - Objects.equals(breed, dog.breed); + return Objects.equals(this.className, dog.className) && + Objects.equals(this.color, dog.color) && + Objects.equals(this.breed, dog.breed) && + super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, color, breed); + return Objects.hash(className, color, breed, super.hashCode()); } @Override @@ -88,10 +137,11 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } } + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumClass.java index 8f9357fbd32..73484907229 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumClass.java @@ -1,50 +1,57 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; - import com.google.gson.annotations.SerializedName; - - - -public class EnumClass { +/** + * Gets or Sets EnumClass + */ +public enum EnumClass { + + @SerializedName("_abc") + _ABC("_abc"), + @SerializedName("-efg") + _EFG("-efg"), + + @SerializedName("(xyz)") + _XYZ_("(xyz)"); - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - EnumClass enumClass = (EnumClass) o; - return true; - } + private String value; - @Override - public int hashCode() { - return Objects.hash(); + EnumClass(String value) { + this.value = value; } @Override public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class EnumClass {\n"); - - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); + return String.valueOf(value); } } + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumTest.java index 8db392afccc..9aad1223215 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumTest.java @@ -1,25 +1,48 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import com.google.gson.annotations.SerializedName; - - - +/** + * EnumTest + */ public class EnumTest { - - /** * Gets or Sets enumString */ public enum EnumStringEnum { @SerializedName("UPPER") UPPER("UPPER"), - + @SerializedName("lower") LOWER("lower"); @@ -38,14 +61,13 @@ public String toString() { @SerializedName("enum_string") private EnumStringEnum enumString = null; - /** * Gets or Sets enumInteger */ public enum EnumIntegerEnum { @SerializedName("1") NUMBER_1(1), - + @SerializedName("-1") NUMBER_MINUS_1(-1); @@ -64,14 +86,13 @@ public String toString() { @SerializedName("enum_integer") private EnumIntegerEnum enumInteger = null; - /** * Gets or Sets enumNumber */ public enum EnumNumberEnum { @SerializedName("1.1") NUMBER_1_DOT_1(1.1), - + @SerializedName("-1.2") NUMBER_MINUS_1_DOT_2(-1.2); @@ -90,39 +111,63 @@ public String toString() { @SerializedName("enum_number") private EnumNumberEnum enumNumber = null; - /** - **/ - @ApiModelProperty(value = "") + public EnumTest enumString(EnumStringEnum enumString) { + this.enumString = enumString; + return this; + } + + /** + * Get enumString + * @return enumString + **/ + @ApiModelProperty(example = "null", value = "") public EnumStringEnum getEnumString() { return enumString; } + public void setEnumString(EnumStringEnum enumString) { this.enumString = enumString; } - /** - **/ - @ApiModelProperty(value = "") + public EnumTest enumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + return this; + } + + /** + * Get enumInteger + * @return enumInteger + **/ + @ApiModelProperty(example = "null", value = "") public EnumIntegerEnum getEnumInteger() { return enumInteger; } + public void setEnumInteger(EnumIntegerEnum enumInteger) { this.enumInteger = enumInteger; } - /** - **/ - @ApiModelProperty(value = "") + public EnumTest enumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + return this; + } + + /** + * Get enumNumber + * @return enumNumber + **/ + @ApiModelProperty(example = "null", value = "") public EnumNumberEnum getEnumNumber() { return enumNumber; } + public void setEnumNumber(EnumNumberEnum enumNumber) { this.enumNumber = enumNumber; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -130,9 +175,9 @@ public boolean equals(Object o) { return false; } EnumTest enumTest = (EnumTest) o; - return Objects.equals(enumString, enumTest.enumString) && - Objects.equals(enumInteger, enumTest.enumInteger) && - Objects.equals(enumNumber, enumTest.enumNumber); + return Objects.equals(this.enumString, enumTest.enumString) && + Objects.equals(this.enumInteger, enumTest.enumInteger) && + Objects.equals(this.enumNumber, enumTest.enumNumber); } @Override @@ -156,10 +201,11 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } } + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/FormatTest.java index 6063cf33f77..91109681509 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/FormatTest.java @@ -1,20 +1,44 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import org.joda.time.DateTime; import org.joda.time.LocalDate; -import com.google.gson.annotations.SerializedName; - - - +/** + * FormatTest + */ public class FormatTest { - @SerializedName("integer") private Integer integer = null; @@ -54,149 +78,253 @@ public class FormatTest { @SerializedName("password") private String password = null; - /** + public FormatTest integer(Integer integer) { + this.integer = integer; + return this; + } + + /** + * Get integer * minimum: 10.0 * maximum: 100.0 - **/ - @ApiModelProperty(value = "") + * @return integer + **/ + @ApiModelProperty(example = "null", value = "") public Integer getInteger() { return integer; } + public void setInteger(Integer integer) { this.integer = integer; } - /** + public FormatTest int32(Integer int32) { + this.int32 = int32; + return this; + } + + /** + * Get int32 * minimum: 20.0 * maximum: 200.0 - **/ - @ApiModelProperty(value = "") + * @return int32 + **/ + @ApiModelProperty(example = "null", value = "") public Integer getInt32() { return int32; } + public void setInt32(Integer int32) { this.int32 = int32; } - /** - **/ - @ApiModelProperty(value = "") + public FormatTest int64(Long int64) { + this.int64 = int64; + return this; + } + + /** + * Get int64 + * @return int64 + **/ + @ApiModelProperty(example = "null", value = "") public Long getInt64() { return int64; } + public void setInt64(Long int64) { this.int64 = int64; } - /** + public FormatTest number(BigDecimal number) { + this.number = number; + return this; + } + + /** + * Get number * minimum: 32.1 * maximum: 543.2 - **/ - @ApiModelProperty(required = true, value = "") + * @return number + **/ + @ApiModelProperty(example = "null", required = true, value = "") public BigDecimal getNumber() { return number; } + public void setNumber(BigDecimal number) { this.number = number; } - /** + public FormatTest _float(Float _float) { + this._float = _float; + return this; + } + + /** + * Get _float * minimum: 54.3 * maximum: 987.6 - **/ - @ApiModelProperty(value = "") + * @return _float + **/ + @ApiModelProperty(example = "null", value = "") public Float getFloat() { return _float; } + public void setFloat(Float _float) { this._float = _float; } - /** + public FormatTest _double(Double _double) { + this._double = _double; + return this; + } + + /** + * Get _double * minimum: 67.8 * maximum: 123.4 - **/ - @ApiModelProperty(value = "") + * @return _double + **/ + @ApiModelProperty(example = "null", value = "") public Double getDouble() { return _double; } + public void setDouble(Double _double) { this._double = _double; } - /** - **/ - @ApiModelProperty(value = "") + public FormatTest string(String string) { + this.string = string; + return this; + } + + /** + * Get string + * @return string + **/ + @ApiModelProperty(example = "null", value = "") public String getString() { return string; } + public void setString(String string) { this.string = string; } - /** - **/ - @ApiModelProperty(required = true, value = "") + public FormatTest _byte(byte[] _byte) { + this._byte = _byte; + return this; + } + + /** + * Get _byte + * @return _byte + **/ + @ApiModelProperty(example = "null", required = true, value = "") public byte[] getByte() { return _byte; } + public void setByte(byte[] _byte) { this._byte = _byte; } - /** - **/ - @ApiModelProperty(value = "") + public FormatTest binary(byte[] binary) { + this.binary = binary; + return this; + } + + /** + * Get binary + * @return binary + **/ + @ApiModelProperty(example = "null", value = "") public byte[] getBinary() { return binary; } + public void setBinary(byte[] binary) { this.binary = binary; } - /** - **/ - @ApiModelProperty(required = true, value = "") + public FormatTest date(LocalDate date) { + this.date = date; + return this; + } + + /** + * Get date + * @return date + **/ + @ApiModelProperty(example = "null", required = true, value = "") public LocalDate getDate() { return date; } + public void setDate(LocalDate date) { this.date = date; } - /** - **/ - @ApiModelProperty(value = "") + public FormatTest dateTime(DateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(example = "null", value = "") public DateTime getDateTime() { return dateTime; } + public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } - /** - **/ - @ApiModelProperty(value = "") + public FormatTest uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(example = "null", value = "") public String getUuid() { return uuid; } + public void setUuid(String uuid) { this.uuid = uuid; } - /** - **/ - @ApiModelProperty(required = true, value = "") + public FormatTest password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @ApiModelProperty(example = "null", required = true, value = "") public String getPassword() { return password; } + public void setPassword(String password) { this.password = password; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -204,19 +332,19 @@ public boolean equals(Object o) { return false; } FormatTest formatTest = (FormatTest) o; - return Objects.equals(integer, formatTest.integer) && - Objects.equals(int32, formatTest.int32) && - Objects.equals(int64, formatTest.int64) && - Objects.equals(number, formatTest.number) && - Objects.equals(_float, formatTest._float) && - Objects.equals(_double, formatTest._double) && - Objects.equals(string, formatTest.string) && - Objects.equals(_byte, formatTest._byte) && - Objects.equals(binary, formatTest.binary) && - Objects.equals(date, formatTest.date) && - Objects.equals(dateTime, formatTest.dateTime) && - Objects.equals(uuid, formatTest.uuid) && - Objects.equals(password, formatTest.password); + return Objects.equals(this.integer, formatTest.integer) && + Objects.equals(this.int32, formatTest.int32) && + Objects.equals(this.int64, formatTest.int64) && + Objects.equals(this.number, formatTest.number) && + Objects.equals(this._float, formatTest._float) && + Objects.equals(this._double, formatTest._double) && + Objects.equals(this.string, formatTest.string) && + Objects.equals(this._byte, formatTest._byte) && + Objects.equals(this.binary, formatTest.binary) && + Objects.equals(this.date, formatTest.date) && + Objects.equals(this.dateTime, formatTest.dateTime) && + Objects.equals(this.uuid, formatTest.uuid) && + Objects.equals(this.password, formatTest.password); } @Override @@ -250,10 +378,11 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } } + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java new file mode 100644 index 00000000000..d77fc7ac36b --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -0,0 +1,104 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +/** + * HasOnlyReadOnly + */ + +public class HasOnlyReadOnly { + @SerializedName("bar") + private String bar = null; + + @SerializedName("foo") + private String foo = null; + + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(example = "null", value = "") + public String getBar() { + return bar; + } + + /** + * Get foo + * @return foo + **/ + @ApiModelProperty(example = "null", value = "") + public String getFoo() { + return foo; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HasOnlyReadOnly hasOnlyReadOnly = (HasOnlyReadOnly) o; + return Objects.equals(this.bar, hasOnlyReadOnly.bar) && + Objects.equals(this.foo, hasOnlyReadOnly.foo); + } + + @Override + public int hashCode() { + return Objects.hash(bar, foo); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HasOnlyReadOnly {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" foo: ").append(toIndentedString(foo)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MapTest.java new file mode 100644 index 00000000000..61bdb6b2c65 --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MapTest.java @@ -0,0 +1,147 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +/** + * MapTest + */ + +public class MapTest { + @SerializedName("map_map_of_string") + private Map> mapMapOfString = new HashMap>(); + + /** + * Gets or Sets inner + */ + public enum InnerEnum { + @SerializedName("UPPER") + UPPER("UPPER"), + + @SerializedName("lower") + LOWER("lower"); + + private String value; + + InnerEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + @SerializedName("map_of_enum_string") + private Map mapOfEnumString = new HashMap(); + + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + /** + * Get mapMapOfString + * @return mapMapOfString + **/ + @ApiModelProperty(example = "null", value = "") + public Map> getMapMapOfString() { + return mapMapOfString; + } + + public void setMapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + } + + public MapTest mapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + return this; + } + + /** + * Get mapOfEnumString + * @return mapOfEnumString + **/ + @ApiModelProperty(example = "null", value = "") + public Map getMapOfEnumString() { + return mapOfEnumString; + } + + public void setMapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MapTest mapTest = (MapTest) o; + return Objects.equals(this.mapMapOfString, mapTest.mapMapOfString) && + Objects.equals(this.mapOfEnumString, mapTest.mapOfEnumString); + } + + @Override + public int hashCode() { + return Objects.hash(mapMapOfString, mapOfEnumString); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MapTest {\n"); + + sb.append(" mapMapOfString: ").append(toIndentedString(mapMapOfString)).append("\n"); + sb.append(" mapOfEnumString: ").append(toIndentedString(mapOfEnumString)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index cf7f73c705f..6e587b1bf97 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -1,6 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -9,14 +35,12 @@ import java.util.Map; import org.joda.time.DateTime; -import com.google.gson.annotations.SerializedName; - - - +/** + * MixedPropertiesAndAdditionalPropertiesClass + */ public class MixedPropertiesAndAdditionalPropertiesClass { - @SerializedName("uuid") private String uuid = null; @@ -26,39 +50,63 @@ public class MixedPropertiesAndAdditionalPropertiesClass { @SerializedName("map") private Map map = new HashMap(); - /** - **/ - @ApiModelProperty(value = "") + public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(example = "null", value = "") public String getUuid() { return uuid; } + public void setUuid(String uuid) { this.uuid = uuid; } - /** - **/ - @ApiModelProperty(value = "") + public MixedPropertiesAndAdditionalPropertiesClass dateTime(DateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(example = "null", value = "") public DateTime getDateTime() { return dateTime; } + public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } - /** - **/ - @ApiModelProperty(value = "") + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + this.map = map; + return this; + } + + /** + * Get map + * @return map + **/ + @ApiModelProperty(example = "null", value = "") public Map getMap() { return map; } + public void setMap(Map map) { this.map = map; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -66,9 +114,9 @@ public boolean equals(Object o) { return false; } MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; - return Objects.equals(uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && - Objects.equals(dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && - Objects.equals(map, mixedPropertiesAndAdditionalPropertiesClass.map); + return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(this.dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(this.map, mixedPropertiesAndAdditionalPropertiesClass.map); } @Override @@ -92,10 +140,11 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } } + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Model200Response.java index 22d2bbd763d..d8da58aca9c 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Model200Response.java @@ -1,49 +1,87 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import com.google.gson.annotations.SerializedName; - - - /** * Model for testing model name starting with number - **/ + */ @ApiModel(description = "Model for testing model name starting with number") + public class Model200Response { - @SerializedName("name") private Integer name = null; @SerializedName("class") private String PropertyClass = null; - /** - **/ - @ApiModelProperty(value = "") + public Model200Response name(Integer name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(example = "null", value = "") public Integer getName() { return name; } + public void setName(Integer name) { this.name = name; } - /** - **/ - @ApiModelProperty(value = "") + public Model200Response PropertyClass(String PropertyClass) { + this.PropertyClass = PropertyClass; + return this; + } + + /** + * Get PropertyClass + * @return PropertyClass + **/ + @ApiModelProperty(example = "null", value = "") public String getPropertyClass() { return PropertyClass; } + public void setPropertyClass(String PropertyClass) { this.PropertyClass = PropertyClass; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -51,8 +89,8 @@ public boolean equals(Object o) { return false; } Model200Response _200Response = (Model200Response) o; - return Objects.equals(name, _200Response.name) && - Objects.equals(PropertyClass, _200Response.PropertyClass); + return Objects.equals(this.name, _200Response.name) && + Objects.equals(this.PropertyClass, _200Response.PropertyClass); } @Override @@ -75,10 +113,11 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } } + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ModelApiResponse.java index bb5313b42d4..2a823298323 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -1,17 +1,41 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import com.google.gson.annotations.SerializedName; - - - +/** + * ModelApiResponse + */ public class ModelApiResponse { - @SerializedName("code") private Integer code = null; @@ -21,39 +45,63 @@ public class ModelApiResponse { @SerializedName("message") private String message = null; - /** - **/ - @ApiModelProperty(value = "") + public ModelApiResponse code(Integer code) { + this.code = code; + return this; + } + + /** + * Get code + * @return code + **/ + @ApiModelProperty(example = "null", value = "") public Integer getCode() { return code; } + public void setCode(Integer code) { this.code = code; } - /** - **/ - @ApiModelProperty(value = "") + public ModelApiResponse type(String type) { + this.type = type; + return this; + } + + /** + * Get type + * @return type + **/ + @ApiModelProperty(example = "null", value = "") public String getType() { return type; } + public void setType(String type) { this.type = type; } - /** - **/ - @ApiModelProperty(value = "") + public ModelApiResponse message(String message) { + this.message = message; + return this; + } + + /** + * Get message + * @return message + **/ + @ApiModelProperty(example = "null", value = "") public String getMessage() { return message; } + public void setMessage(String message) { this.message = message; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -61,9 +109,9 @@ public boolean equals(Object o) { return false; } ModelApiResponse _apiResponse = (ModelApiResponse) o; - return Objects.equals(code, _apiResponse.code) && - Objects.equals(type, _apiResponse.type) && - Objects.equals(message, _apiResponse.message); + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); } @Override @@ -87,10 +135,11 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } } + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ModelReturn.java index a3ecfb92156..024a9c0df1c 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ModelReturn.java @@ -1,36 +1,66 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import com.google.gson.annotations.SerializedName; - - - /** * Model for testing reserved words - **/ + */ @ApiModel(description = "Model for testing reserved words") + public class ModelReturn { - @SerializedName("return") private Integer _return = null; - /** - **/ - @ApiModelProperty(value = "") + public ModelReturn _return(Integer _return) { + this._return = _return; + return this; + } + + /** + * Get _return + * @return _return + **/ + @ApiModelProperty(example = "null", value = "") public Integer getReturn() { return _return; } + public void setReturn(Integer _return) { this._return = _return; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -38,7 +68,7 @@ public boolean equals(Object o) { return false; } ModelReturn _return = (ModelReturn) o; - return Objects.equals(_return, _return._return); + return Objects.equals(this._return, _return._return); } @Override @@ -60,10 +90,11 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } } + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Name.java index 5aa60a1f6f1..318a2ddd50e 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Name.java @@ -1,20 +1,42 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import com.google.gson.annotations.SerializedName; - - - /** * Model for testing model name same as property name - **/ + */ @ApiModel(description = "Model for testing model name same as property name") + public class Name { - @SerializedName("name") private Integer name = null; @@ -27,43 +49,63 @@ public class Name { @SerializedName("123Number") private Integer _123Number = null; - /** - **/ - @ApiModelProperty(required = true, value = "") + public Name name(Integer name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(example = "null", required = true, value = "") public Integer getName() { return name; } + public void setName(Integer name) { this.name = name; } - /** - **/ - @ApiModelProperty(value = "") + /** + * Get snakeCase + * @return snakeCase + **/ + @ApiModelProperty(example = "null", value = "") public Integer getSnakeCase() { return snakeCase; } - /** - **/ - @ApiModelProperty(value = "") + public Name property(String property) { + this.property = property; + return this; + } + + /** + * Get property + * @return property + **/ + @ApiModelProperty(example = "null", value = "") public String getProperty() { return property; } + public void setProperty(String property) { this.property = property; } - /** - **/ - @ApiModelProperty(value = "") + /** + * Get _123Number + * @return _123Number + **/ + @ApiModelProperty(example = "null", value = "") public Integer get123Number() { return _123Number; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -71,10 +113,10 @@ public boolean equals(Object o) { return false; } Name name = (Name) o; - return Objects.equals(name, name.name) && - Objects.equals(snakeCase, name.snakeCase) && - Objects.equals(property, name.property) && - Objects.equals(_123Number, name._123Number); + return Objects.equals(this.name, name.name) && + Objects.equals(this.snakeCase, name.snakeCase) && + Objects.equals(this.property, name.property) && + Objects.equals(this._123Number, name._123Number); } @Override @@ -99,10 +141,11 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } } + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/NumberOnly.java new file mode 100644 index 00000000000..9b9ca048dfb --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/NumberOnly.java @@ -0,0 +1,100 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; + + +/** + * NumberOnly + */ + +public class NumberOnly { + @SerializedName("JustNumber") + private BigDecimal justNumber = null; + + public NumberOnly justNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + return this; + } + + /** + * Get justNumber + * @return justNumber + **/ + @ApiModelProperty(example = "null", value = "") + public BigDecimal getJustNumber() { + return justNumber; + } + + public void setJustNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NumberOnly numberOnly = (NumberOnly) o; + return Objects.equals(this.justNumber, numberOnly.justNumber); + } + + @Override + public int hashCode() { + return Objects.hash(justNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NumberOnly {\n"); + + sb.append(" justNumber: ").append(toIndentedString(justNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java index 569d1c0fe46..90cfd2f3892 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java @@ -1,18 +1,42 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.joda.time.DateTime; -import com.google.gson.annotations.SerializedName; - - - +/** + * Order + */ public class Order { - @SerializedName("id") private Long id = null; @@ -25,17 +49,16 @@ public class Order { @SerializedName("shipDate") private DateTime shipDate = null; - /** * Order Status */ public enum StatusEnum { @SerializedName("placed") PLACED("placed"), - + @SerializedName("approved") APPROVED("approved"), - + @SerializedName("delivered") DELIVERED("delivered"); @@ -57,70 +80,117 @@ public String toString() { @SerializedName("complete") private Boolean complete = false; - /** - **/ - @ApiModelProperty(value = "") + public Order id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(example = "null", value = "") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ - @ApiModelProperty(value = "") + public Order petId(Long petId) { + this.petId = petId; + return this; + } + + /** + * Get petId + * @return petId + **/ + @ApiModelProperty(example = "null", value = "") public Long getPetId() { return petId; } + public void setPetId(Long petId) { this.petId = petId; } - /** - **/ - @ApiModelProperty(value = "") + public Order quantity(Integer quantity) { + this.quantity = quantity; + return this; + } + + /** + * Get quantity + * @return quantity + **/ + @ApiModelProperty(example = "null", value = "") public Integer getQuantity() { return quantity; } + public void setQuantity(Integer quantity) { this.quantity = quantity; } - /** - **/ - @ApiModelProperty(value = "") + public Order shipDate(DateTime shipDate) { + this.shipDate = shipDate; + return this; + } + + /** + * Get shipDate + * @return shipDate + **/ + @ApiModelProperty(example = "null", value = "") public DateTime getShipDate() { return shipDate; } + public void setShipDate(DateTime shipDate) { this.shipDate = shipDate; } - /** + public Order status(StatusEnum status) { + this.status = status; + return this; + } + + /** * Order Status - **/ - @ApiModelProperty(value = "Order Status") + * @return status + **/ + @ApiModelProperty(example = "null", value = "Order Status") public StatusEnum getStatus() { return status; } + public void setStatus(StatusEnum status) { this.status = status; } - /** - **/ - @ApiModelProperty(value = "") + public Order complete(Boolean complete) { + this.complete = complete; + return this; + } + + /** + * Get complete + * @return complete + **/ + @ApiModelProperty(example = "null", value = "") public Boolean getComplete() { return complete; } + public void setComplete(Boolean complete) { this.complete = complete; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -128,12 +198,12 @@ public boolean equals(Object o) { 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); + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); } @Override @@ -160,10 +230,11 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } } + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Pet.java index 8efc46bc471..b80fdeaf923 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Pet.java @@ -1,6 +1,32 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Category; @@ -8,14 +34,12 @@ import java.util.ArrayList; import java.util.List; -import com.google.gson.annotations.SerializedName; - - - +/** + * Pet + */ public class Pet { - @SerializedName("id") private Long id = null; @@ -31,17 +55,16 @@ public class Pet { @SerializedName("tags") private List tags = new ArrayList(); - /** * pet status in the store */ public enum StatusEnum { @SerializedName("available") AVAILABLE("available"), - + @SerializedName("pending") PENDING("pending"), - + @SerializedName("sold") SOLD("sold"); @@ -60,70 +83,117 @@ public String toString() { @SerializedName("status") private StatusEnum status = null; - /** - **/ - @ApiModelProperty(value = "") + public Pet id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(example = "null", value = "") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ - @ApiModelProperty(value = "") + public Pet category(Category category) { + this.category = category; + return this; + } + + /** + * Get category + * @return category + **/ + @ApiModelProperty(example = "null", value = "") public Category getCategory() { return category; } + public void setCategory(Category category) { this.category = category; } - /** - **/ - @ApiModelProperty(required = true, value = "") + public Pet name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(example = "doggie", required = true, value = "") public String getName() { return name; } + public void setName(String name) { this.name = name; } - /** - **/ - @ApiModelProperty(required = true, value = "") + public Pet photoUrls(List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + /** + * Get photoUrls + * @return photoUrls + **/ + @ApiModelProperty(example = "null", required = true, value = "") public List getPhotoUrls() { return photoUrls; } + public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } - /** - **/ - @ApiModelProperty(value = "") + public Pet tags(List tags) { + this.tags = tags; + return this; + } + + /** + * Get tags + * @return tags + **/ + @ApiModelProperty(example = "null", value = "") public List getTags() { return tags; } + public void setTags(List tags) { this.tags = tags; } - /** + public Pet status(StatusEnum status) { + this.status = status; + return this; + } + + /** * pet status in the store - **/ - @ApiModelProperty(value = "pet status in the store") + * @return status + **/ + @ApiModelProperty(example = "null", value = "pet status in the store") public StatusEnum getStatus() { return status; } + public void setStatus(StatusEnum status) { this.status = status; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -131,12 +201,12 @@ public boolean equals(Object o) { 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); + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); } @Override @@ -163,10 +233,11 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } } + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index 32e4f515bce..13b729bb94d 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -1,43 +1,77 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import com.google.gson.annotations.SerializedName; - - - +/** + * ReadOnlyFirst + */ public class ReadOnlyFirst { - @SerializedName("bar") private String bar = null; @SerializedName("baz") private String baz = null; - /** - **/ - @ApiModelProperty(value = "") + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(example = "null", value = "") public String getBar() { return bar; } - /** - **/ - @ApiModelProperty(value = "") + public ReadOnlyFirst baz(String baz) { + this.baz = baz; + return this; + } + + /** + * Get baz + * @return baz + **/ + @ApiModelProperty(example = "null", value = "") public String getBaz() { return baz; } + public void setBaz(String baz) { this.baz = baz; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -45,8 +79,8 @@ public boolean equals(Object o) { return false; } ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; - return Objects.equals(bar, readOnlyFirst.bar) && - Objects.equals(baz, readOnlyFirst.baz); + return Objects.equals(this.bar, readOnlyFirst.bar) && + Objects.equals(this.baz, readOnlyFirst.baz); } @Override @@ -69,10 +103,11 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } } + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/SpecialModelName.java index e2354b064b2..b46b8367a01 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -1,33 +1,65 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import com.google.gson.annotations.SerializedName; - - - +/** + * SpecialModelName + */ public class SpecialModelName { - @SerializedName("$special[property.name]") private Long specialPropertyName = null; - /** - **/ - @ApiModelProperty(value = "") + public SpecialModelName specialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + return this; + } + + /** + * Get specialPropertyName + * @return specialPropertyName + **/ + @ApiModelProperty(example = "null", value = "") public Long getSpecialPropertyName() { return specialPropertyName; } + public void setSpecialPropertyName(Long specialPropertyName) { this.specialPropertyName = specialPropertyName; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -35,7 +67,7 @@ public boolean equals(Object o) { return false; } SpecialModelName specialModelName = (SpecialModelName) o; - return Objects.equals(specialPropertyName, specialModelName.specialPropertyName); + return Objects.equals(this.specialPropertyName, specialModelName.specialPropertyName); } @Override @@ -57,10 +89,11 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } } + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Tag.java index 9c5ac6cf9a7..e56eb535d1e 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Tag.java @@ -1,46 +1,86 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import com.google.gson.annotations.SerializedName; - - - +/** + * Tag + */ public class Tag { - @SerializedName("id") private Long id = null; @SerializedName("name") private String name = null; - /** - **/ - @ApiModelProperty(value = "") + public Tag id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(example = "null", value = "") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ - @ApiModelProperty(value = "") + public Tag name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(example = "null", value = "") public String getName() { return name; } + public void setName(String name) { this.name = name; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -48,8 +88,8 @@ public boolean equals(Object o) { return false; } Tag tag = (Tag) o; - return Objects.equals(id, tag.id) && - Objects.equals(name, tag.name); + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); } @Override @@ -72,10 +112,11 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } } + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/User.java index 39e40837a6a..6c1ed6ceacc 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/User.java @@ -1,17 +1,41 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import com.google.gson.annotations.SerializedName; - - - +/** + * User + */ public class User { - @SerializedName("id") private Long id = null; @@ -36,90 +60,153 @@ public class User { @SerializedName("userStatus") private Integer userStatus = null; - /** - **/ - @ApiModelProperty(value = "") + public User id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(example = "null", value = "") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ - @ApiModelProperty(value = "") + public User username(String username) { + this.username = username; + return this; + } + + /** + * Get username + * @return username + **/ + @ApiModelProperty(example = "null", value = "") public String getUsername() { return username; } + public void setUsername(String username) { this.username = username; } - /** - **/ - @ApiModelProperty(value = "") + public User firstName(String firstName) { + this.firstName = firstName; + return this; + } + + /** + * Get firstName + * @return firstName + **/ + @ApiModelProperty(example = "null", value = "") public String getFirstName() { return firstName; } + public void setFirstName(String firstName) { this.firstName = firstName; } - /** - **/ - @ApiModelProperty(value = "") + public User lastName(String lastName) { + this.lastName = lastName; + return this; + } + + /** + * Get lastName + * @return lastName + **/ + @ApiModelProperty(example = "null", value = "") public String getLastName() { return lastName; } + public void setLastName(String lastName) { this.lastName = lastName; } - /** - **/ - @ApiModelProperty(value = "") + public User email(String email) { + this.email = email; + return this; + } + + /** + * Get email + * @return email + **/ + @ApiModelProperty(example = "null", value = "") public String getEmail() { return email; } + public void setEmail(String email) { this.email = email; } - /** - **/ - @ApiModelProperty(value = "") + public User password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @ApiModelProperty(example = "null", value = "") public String getPassword() { return password; } + public void setPassword(String password) { this.password = password; } - /** - **/ - @ApiModelProperty(value = "") + public User phone(String phone) { + this.phone = phone; + return this; + } + + /** + * Get phone + * @return phone + **/ + @ApiModelProperty(example = "null", value = "") public String getPhone() { return phone; } + public void setPhone(String phone) { this.phone = phone; } - /** + public User userStatus(Integer userStatus) { + this.userStatus = userStatus; + return this; + } + + /** * User Status - **/ - @ApiModelProperty(value = "User Status") + * @return userStatus + **/ + @ApiModelProperty(example = "null", value = "User Status") public Integer getUserStatus() { return userStatus; } + public void setUserStatus(Integer userStatus) { this.userStatus = userStatus; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -127,14 +214,14 @@ public boolean equals(Object o) { 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); + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); } @Override @@ -163,10 +250,11 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } } + diff --git a/samples/client/petstore/java/retrofit2/docs/FakeApi.md b/samples/client/petstore/java/retrofit2/docs/FakeApi.md index decba432a56..21a4db7c377 100644 --- a/samples/client/petstore/java/retrofit2/docs/FakeApi.md +++ b/samples/client/petstore/java/retrofit2/docs/FakeApi.md @@ -4,13 +4,13 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -[**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** fake | To test enum query parameters +[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters # **testEndpointParameters** -> Void testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) +> testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -37,8 +37,7 @@ LocalDate date = new LocalDate(); // LocalDate | None DateTime dateTime = new DateTime(); // DateTime | None String password = "password_example"; // String | None try { - Void result = apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); - System.out.println(result); + apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); } catch (ApiException e) { System.err.println("Exception when calling FakeApi#testEndpointParameters"); e.printStackTrace(); @@ -64,7 +63,7 @@ Name | Type | Description | Notes ### Return type -[**Void**](.md) +null (empty response body) ### Authorization @@ -77,7 +76,7 @@ No authorization required # **testEnumQueryParameters** -> Void testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble) +> testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble) To test enum query parameters @@ -93,8 +92,7 @@ String enumQueryString = "-efg"; // String | Query parameter enum test (string) BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | Query parameter enum test (double) Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) try { - Void result = apiInstance.testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); - System.out.println(result); + apiInstance.testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); } catch (ApiException e) { System.err.println("Exception when calling FakeApi#testEnumQueryParameters"); e.printStackTrace(); @@ -111,7 +109,7 @@ Name | Type | Description | Notes ### Return type -[**Void**](.md) +null (empty response body) ### Authorization diff --git a/samples/client/petstore/java/retrofit2/docs/PetApi.md b/samples/client/petstore/java/retrofit2/docs/PetApi.md index 40ea199b153..e0314e20e51 100644 --- a/samples/client/petstore/java/retrofit2/docs/PetApi.md +++ b/samples/client/petstore/java/retrofit2/docs/PetApi.md @@ -4,19 +4,19 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**addPet**](PetApi.md#addPet) | **POST** pet | Add a new pet to the store -[**deletePet**](PetApi.md#deletePet) | **DELETE** pet/{petId} | Deletes a pet -[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** pet/findByStatus | Finds Pets by status -[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** pet/findByTags | Finds Pets by tags -[**getPetById**](PetApi.md#getPetById) | **GET** pet/{petId} | Find pet by ID -[**updatePet**](PetApi.md#updatePet) | **PUT** pet | Update an existing pet -[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** pet/{petId} | Updates a pet in the store with form data -[**uploadFile**](PetApi.md#uploadFile) | **POST** pet/{petId}/uploadImage | uploads an image +[**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image # **addPet** -> Void addPet(body) +> addPet(body) Add a new pet to the store @@ -40,8 +40,7 @@ petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); PetApi apiInstance = new PetApi(); Pet body = new Pet(); // Pet | Pet object that needs to be added to the store try { - Void result = apiInstance.addPet(body); - System.out.println(result); + apiInstance.addPet(body); } catch (ApiException e) { System.err.println("Exception when calling PetApi#addPet"); e.printStackTrace(); @@ -56,7 +55,7 @@ Name | Type | Description | Notes ### Return type -[**Void**](.md) +null (empty response body) ### Authorization @@ -69,7 +68,7 @@ Name | Type | Description | Notes # **deletePet** -> Void deletePet(petId, apiKey) +> deletePet(petId, apiKey) Deletes a pet @@ -94,8 +93,7 @@ PetApi apiInstance = new PetApi(); Long petId = 789L; // Long | Pet id to delete String apiKey = "apiKey_example"; // String | try { - Void result = apiInstance.deletePet(petId, apiKey); - System.out.println(result); + apiInstance.deletePet(petId, apiKey); } catch (ApiException e) { System.err.println("Exception when calling PetApi#deletePet"); e.printStackTrace(); @@ -111,7 +109,7 @@ Name | Type | Description | Notes ### Return type -[**Void**](.md) +null (empty response body) ### Authorization @@ -285,7 +283,7 @@ Name | Type | Description | Notes # **updatePet** -> Void updatePet(body) +> updatePet(body) Update an existing pet @@ -309,8 +307,7 @@ petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); PetApi apiInstance = new PetApi(); Pet body = new Pet(); // Pet | Pet object that needs to be added to the store try { - Void result = apiInstance.updatePet(body); - System.out.println(result); + apiInstance.updatePet(body); } catch (ApiException e) { System.err.println("Exception when calling PetApi#updatePet"); e.printStackTrace(); @@ -325,7 +322,7 @@ Name | Type | Description | Notes ### Return type -[**Void**](.md) +null (empty response body) ### Authorization @@ -338,7 +335,7 @@ Name | Type | Description | Notes # **updatePetWithForm** -> Void updatePetWithForm(petId, name, status) +> updatePetWithForm(petId, name, status) Updates a pet in the store with form data @@ -364,8 +361,7 @@ Long petId = 789L; // Long | ID of pet that needs to be updated String name = "name_example"; // String | Updated name of the pet String status = "status_example"; // String | Updated status of the pet try { - Void result = apiInstance.updatePetWithForm(petId, name, status); - System.out.println(result); + apiInstance.updatePetWithForm(petId, name, status); } catch (ApiException e) { System.err.println("Exception when calling PetApi#updatePetWithForm"); e.printStackTrace(); @@ -382,7 +378,7 @@ Name | Type | Description | Notes ### Return type -[**Void**](.md) +null (empty response body) ### Authorization diff --git a/samples/client/petstore/java/retrofit2/docs/StoreApi.md b/samples/client/petstore/java/retrofit2/docs/StoreApi.md index 30e3c11d440..0b30791725a 100644 --- a/samples/client/petstore/java/retrofit2/docs/StoreApi.md +++ b/samples/client/petstore/java/retrofit2/docs/StoreApi.md @@ -4,15 +4,15 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** store/order/{orderId} | Delete purchase order by ID -[**getInventory**](StoreApi.md#getInventory) | **GET** store/inventory | Returns pet inventories by status -[**getOrderById**](StoreApi.md#getOrderById) | **GET** store/order/{orderId} | Find purchase order by ID -[**placeOrder**](StoreApi.md#placeOrder) | **POST** store/order | Place an order for a pet +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet # **deleteOrder** -> Void deleteOrder(orderId) +> deleteOrder(orderId) Delete purchase order by ID @@ -28,8 +28,7 @@ For valid response try integer IDs with value < 1000. Anything above 1000 or StoreApi apiInstance = new StoreApi(); String orderId = "orderId_example"; // String | ID of the order that needs to be deleted try { - Void result = apiInstance.deleteOrder(orderId); - System.out.println(result); + apiInstance.deleteOrder(orderId); } catch (ApiException e) { System.err.println("Exception when calling StoreApi#deleteOrder"); e.printStackTrace(); @@ -44,7 +43,7 @@ Name | Type | Description | Notes ### Return type -[**Void**](.md) +null (empty response body) ### Authorization diff --git a/samples/client/petstore/java/retrofit2/docs/UserApi.md b/samples/client/petstore/java/retrofit2/docs/UserApi.md index b0a0149a50a..8cdc15992ee 100644 --- a/samples/client/petstore/java/retrofit2/docs/UserApi.md +++ b/samples/client/petstore/java/retrofit2/docs/UserApi.md @@ -4,19 +4,19 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**createUser**](UserApi.md#createUser) | **POST** user | Create user -[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** user/createWithArray | Creates list of users with given input array -[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** user/createWithList | Creates list of users with given input array -[**deleteUser**](UserApi.md#deleteUser) | **DELETE** user/{username} | Delete user -[**getUserByName**](UserApi.md#getUserByName) | **GET** user/{username} | Get user by user name -[**loginUser**](UserApi.md#loginUser) | **GET** user/login | Logs user into the system -[**logoutUser**](UserApi.md#logoutUser) | **GET** user/logout | Logs out current logged in user session -[**updateUser**](UserApi.md#updateUser) | **PUT** user/{username} | Updated user +[**createUser**](UserApi.md#createUser) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user # **createUser** -> Void createUser(body) +> createUser(body) Create user @@ -32,8 +32,7 @@ This can only be done by the logged in user. UserApi apiInstance = new UserApi(); User body = new User(); // User | Created user object try { - Void result = apiInstance.createUser(body); - System.out.println(result); + apiInstance.createUser(body); } catch (ApiException e) { System.err.println("Exception when calling UserApi#createUser"); e.printStackTrace(); @@ -48,7 +47,7 @@ Name | Type | Description | Notes ### Return type -[**Void**](.md) +null (empty response body) ### Authorization @@ -61,7 +60,7 @@ No authorization required # **createUsersWithArrayInput** -> Void createUsersWithArrayInput(body) +> createUsersWithArrayInput(body) Creates list of users with given input array @@ -77,8 +76,7 @@ Creates list of users with given input array UserApi apiInstance = new UserApi(); List body = Arrays.asList(new User()); // List | List of user object try { - Void result = apiInstance.createUsersWithArrayInput(body); - System.out.println(result); + apiInstance.createUsersWithArrayInput(body); } catch (ApiException e) { System.err.println("Exception when calling UserApi#createUsersWithArrayInput"); e.printStackTrace(); @@ -93,7 +91,7 @@ Name | Type | Description | Notes ### Return type -[**Void**](.md) +null (empty response body) ### Authorization @@ -106,7 +104,7 @@ No authorization required # **createUsersWithListInput** -> Void createUsersWithListInput(body) +> createUsersWithListInput(body) Creates list of users with given input array @@ -122,8 +120,7 @@ Creates list of users with given input array UserApi apiInstance = new UserApi(); List body = Arrays.asList(new User()); // List | List of user object try { - Void result = apiInstance.createUsersWithListInput(body); - System.out.println(result); + apiInstance.createUsersWithListInput(body); } catch (ApiException e) { System.err.println("Exception when calling UserApi#createUsersWithListInput"); e.printStackTrace(); @@ -138,7 +135,7 @@ Name | Type | Description | Notes ### Return type -[**Void**](.md) +null (empty response body) ### Authorization @@ -151,7 +148,7 @@ No authorization required # **deleteUser** -> Void deleteUser(username) +> deleteUser(username) Delete user @@ -167,8 +164,7 @@ This can only be done by the logged in user. UserApi apiInstance = new UserApi(); String username = "username_example"; // String | The name that needs to be deleted try { - Void result = apiInstance.deleteUser(username); - System.out.println(result); + apiInstance.deleteUser(username); } catch (ApiException e) { System.err.println("Exception when calling UserApi#deleteUser"); e.printStackTrace(); @@ -183,7 +179,7 @@ Name | Type | Description | Notes ### Return type -[**Void**](.md) +null (empty response body) ### Authorization @@ -288,7 +284,7 @@ No authorization required # **logoutUser** -> Void logoutUser() +> logoutUser() Logs out current logged in user session @@ -303,8 +299,7 @@ Logs out current logged in user session UserApi apiInstance = new UserApi(); try { - Void result = apiInstance.logoutUser(); - System.out.println(result); + apiInstance.logoutUser(); } catch (ApiException e) { System.err.println("Exception when calling UserApi#logoutUser"); e.printStackTrace(); @@ -316,7 +311,7 @@ This endpoint does not need any parameter. ### Return type -[**Void**](.md) +null (empty response body) ### Authorization @@ -329,7 +324,7 @@ No authorization required # **updateUser** -> Void updateUser(username, body) +> updateUser(username, body) Updated user @@ -346,8 +341,7 @@ UserApi apiInstance = new UserApi(); String username = "username_example"; // String | name that need to be deleted User body = new User(); // User | Updated user object try { - Void result = apiInstance.updateUser(username, body); - System.out.println(result); + apiInstance.updateUser(username, body); } catch (ApiException e) { System.err.println("Exception when calling UserApi#updateUser"); e.printStackTrace(); @@ -363,7 +357,7 @@ Name | Type | Description | Notes ### Return type -[**Void**](.md) +null (empty response body) ### Authorization diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiCallback.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiCallback.java new file mode 100644 index 00000000000..3ca33cf8017 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiCallback.java @@ -0,0 +1,74 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import java.io.IOException; + +import java.util.Map; +import java.util.List; + +/** + * Callback for asynchronous API call. + * + * @param The return type + */ +public interface ApiCallback { + /** + * This is called when the API call fails. + * + * @param e The exception causing the failure + * @param statusCode Status code of the response if available, otherwise it would be 0 + * @param responseHeaders Headers of the response if available, otherwise it would be null + */ + void onFailure(ApiException e, int statusCode, Map> responseHeaders); + + /** + * This is called when the API call succeeded. + * + * @param result The result deserialized from response + * @param statusCode Status code of the response + * @param responseHeaders Headers of the response + */ + void onSuccess(T result, int statusCode, Map> responseHeaders); + + /** + * This is called when the API upload processing. + * + * @param bytesWritten bytes Written + * @param contentLength content length of request body + * @param done write end + */ + void onUploadProgress(long bytesWritten, long contentLength, boolean done); + + /** + * This is called when the API downlond processing. + * + * @param bytesRead bytes Read + * @param contentLength content lenngth of the response + * @param done Read end + */ + void onDownloadProgress(long bytesRead, long contentLength, boolean done); +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiException.java new file mode 100644 index 00000000000..3bed001f002 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiException.java @@ -0,0 +1,103 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import java.util.Map; +import java.util.List; + + +public class ApiException extends Exception { + private int code = 0; + private Map> responseHeaders = null; + private String responseBody = null; + + public ApiException() {} + + public ApiException(Throwable throwable) { + super(throwable); + } + + public ApiException(String message) { + super(message); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } + + public ApiException(int code, Map> responseHeaders, String responseBody) { + this((String) null, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(int code, String message) { + super(message); + this.code = code; + } + + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this(code, message); + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + /** + * Get the HTTP status code. + * + * @return HTTP status code + */ + public int getCode() { + return code; + } + + /** + * Get the HTTP response headers. + * + * @return A map of list of string + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + + /** + * Get the HTTP response body. + * + * @return Response body in the form of string + */ + public String getResponseBody() { + return responseBody; + } +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiResponse.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiResponse.java new file mode 100644 index 00000000000..d7dde1ee939 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiResponse.java @@ -0,0 +1,71 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import java.util.List; +import java.util.Map; + +/** + * API response returned by API call. + * + * @param T The type of data that is deserialized from response body + */ +public class ApiResponse { + final private int statusCode; + final private Map> headers; + final private T data; + + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + */ + public ApiResponse(int statusCode, Map> headers) { + this(statusCode, headers, null); + } + + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + * @param data The object deserialized from response bod + */ + public ApiResponse(int statusCode, Map> headers, T data) { + this.statusCode = statusCode; + this.headers = headers; + this.data = data; + } + + public int getStatusCode() { + return statusCode; + } + + public Map> getHeaders() { + return headers; + } + + public T getData() { + return data; + } +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/CollectionFormats.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/CollectionFormats.java deleted file mode 100644 index e96d1561a7c..00000000000 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/CollectionFormats.java +++ /dev/null @@ -1,95 +0,0 @@ -package io.swagger.client; - -import java.util.Arrays; -import java.util.List; - -public class CollectionFormats { - - public static class CSVParams { - - protected List params; - - public CSVParams() { - } - - public CSVParams(List params) { - this.params = params; - } - - public CSVParams(String... params) { - this.params = Arrays.asList(params); - } - - public List getParams() { - return params; - } - - public void setParams(List params) { - this.params = params; - } - - @Override - public String toString() { - return StringUtil.join(params.toArray(new String[0]), ","); - } - - } - - public static class SSVParams extends CSVParams { - - public SSVParams() { - } - - public SSVParams(List params) { - super(params); - } - - public SSVParams(String... params) { - super(params); - } - - @Override - public String toString() { - return StringUtil.join(params.toArray(new String[0]), " "); - } - } - - public static class TSVParams extends CSVParams { - - public TSVParams() { - } - - public TSVParams(List params) { - super(params); - } - - public TSVParams(String... params) { - super(params); - } - - @Override - public String toString() { - return StringUtil.join( params.toArray(new String[0]), "\t"); - } - } - - public static class PIPESParams extends CSVParams { - - public PIPESParams() { - } - - public PIPESParams(List params) { - super(params); - } - - public PIPESParams(String... params) { - super(params); - } - - @Override - public String toString() { - return StringUtil.join(params.toArray(new String[0]), "|"); - } - } - -} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/Configuration.java new file mode 100644 index 00000000000..5191b9b73c6 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/Configuration.java @@ -0,0 +1,51 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + + +public class Configuration { + private static ApiClient defaultApiClient = new ApiClient(); + + /** + * Get the default API client, which would be used when creating API + * instances without providing an API client. + * + * @return Default API client + */ + public static ApiClient getDefaultApiClient() { + return defaultApiClient; + } + + /** + * Set the default API client, which would be used when creating API + * instances without providing an API client. + * + * @param apiClient API client + */ + public static void setDefaultApiClient(ApiClient apiClient) { + defaultApiClient = apiClient; + } +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/JSON.java new file mode 100644 index 00000000000..540611eab9d --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/JSON.java @@ -0,0 +1,237 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonNull; +import com.google.gson.JsonParseException; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +import java.io.IOException; +import java.io.StringReader; +import java.lang.reflect.Type; +import java.util.Date; + +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; + +public class JSON { + private ApiClient apiClient; + private Gson gson; + + /** + * JSON constructor. + * + * @param apiClient An instance of ApiClient + */ + public JSON(ApiClient apiClient) { + this.apiClient = apiClient; + gson = new GsonBuilder() + .registerTypeAdapter(Date.class, new DateAdapter(apiClient)) + .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) + .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) + .create(); + } + + /** + * Get Gson. + * + * @return Gson + */ + public Gson getGson() { + return gson; + } + + /** + * Set Gson. + * + * @param gson Gson + */ + public void setGson(Gson gson) { + this.gson = gson; + } + + /** + * Serialize the given Java object into JSON string. + * + * @param obj Object + * @return String representation of the JSON + */ + public String serialize(Object obj) { + return gson.toJson(obj); + } + + /** + * Deserialize the given JSON string to Java object. + * + * @param Type + * @param body The JSON string + * @param returnType The type to deserialize inot + * @return The deserialized Java object + */ + @SuppressWarnings("unchecked") + public T deserialize(String body, Type returnType) { + try { + if (apiClient.isLenientOnJson()) { + JsonReader jsonReader = new JsonReader(new StringReader(body)); + // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) + jsonReader.setLenient(true); + return gson.fromJson(jsonReader, returnType); + } else { + return gson.fromJson(body, returnType); + } + } catch (JsonParseException e) { + // Fallback processing when failed to parse JSON form response body: + // return the response body string directly for the String return type; + // parse response body into date or datetime for the Date return type. + if (returnType.equals(String.class)) + return (T) body; + else if (returnType.equals(Date.class)) + return (T) apiClient.parseDateOrDatetime(body); + else throw(e); + } + } +} + +class DateAdapter implements JsonSerializer, JsonDeserializer { + private final ApiClient apiClient; + + /** + * Constructor for DateAdapter + * + * @param apiClient Api client + */ + public DateAdapter(ApiClient apiClient) { + super(); + this.apiClient = apiClient; + } + + /** + * Serialize + * + * @param src Date + * @param typeOfSrc Type + * @param context Json Serialization Context + * @return Json Element + */ + @Override + public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { + if (src == null) { + return JsonNull.INSTANCE; + } else { + return new JsonPrimitive(apiClient.formatDatetime(src)); + } + } + + /** + * Deserialize + * + * @param json Json element + * @param date Type + * @param typeOfSrc Type + * @param context Json Serialization Context + * @return Date + * @throw JsonParseException if fail to parse + */ + @Override + public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException { + String str = json.getAsJsonPrimitive().getAsString(); + try { + return apiClient.parseDateOrDatetime(str); + } catch (RuntimeException e) { + throw new JsonParseException(e); + } + } +} + +/** + * Gson TypeAdapter for Joda DateTime type + */ +class DateTimeTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + + @Override + public void write(JsonWriter out, DateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public DateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseDateTime(date); + } + } +} + +/** + * Gson TypeAdapter for Joda LocalDate type + */ +class LocalDateTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.date(); + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseLocalDate(date); + } + } +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/Pair.java new file mode 100644 index 00000000000..15b247eea93 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/Pair.java @@ -0,0 +1,64 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + + +public class Pair { + private String name = ""; + private String value = ""; + + public Pair (String name, String value) { + setName(name); + setValue(value); + } + + private void setName(String name) { + if (!isValidString(name)) return; + + this.name = name; + } + + private void setValue(String value) { + if (!isValidString(value)) return; + + this.value = value; + } + + public String getName() { + return this.name; + } + + public String getValue() { + return this.value; + } + + private boolean isValidString(String arg) { + if (arg == null) return false; + if (arg.trim().isEmpty()) return false; + + return true; + } +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ProgressRequestBody.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ProgressRequestBody.java new file mode 100644 index 00000000000..d9ca742ecd2 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ProgressRequestBody.java @@ -0,0 +1,95 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.RequestBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSink; +import okio.ForwardingSink; +import okio.Okio; +import okio.Sink; + +public class ProgressRequestBody extends RequestBody { + + public interface ProgressRequestListener { + void onRequestProgress(long bytesWritten, long contentLength, boolean done); + } + + private final RequestBody requestBody; + + private final ProgressRequestListener progressListener; + + private BufferedSink bufferedSink; + + public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) { + this.requestBody = requestBody; + this.progressListener = progressListener; + } + + @Override + public MediaType contentType() { + return requestBody.contentType(); + } + + @Override + public long contentLength() throws IOException { + return requestBody.contentLength(); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + if (bufferedSink == null) { + bufferedSink = Okio.buffer(sink(sink)); + } + + requestBody.writeTo(bufferedSink); + bufferedSink.flush(); + + } + + private Sink sink(Sink sink) { + return new ForwardingSink(sink) { + + long bytesWritten = 0L; + long contentLength = 0L; + + @Override + public void write(Buffer source, long byteCount) throws IOException { + super.write(source, byteCount); + if (contentLength == 0) { + contentLength = contentLength(); + } + + bytesWritten += byteCount; + progressListener.onRequestProgress(bytesWritten, contentLength, bytesWritten == contentLength); + } + }; + } +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ProgressResponseBody.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ProgressResponseBody.java new file mode 100644 index 00000000000..f8af685999d --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ProgressResponseBody.java @@ -0,0 +1,88 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.ResponseBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSource; +import okio.ForwardingSource; +import okio.Okio; +import okio.Source; + +public class ProgressResponseBody extends ResponseBody { + + public interface ProgressListener { + void update(long bytesRead, long contentLength, boolean done); + } + + private final ResponseBody responseBody; + private final ProgressListener progressListener; + private BufferedSource bufferedSource; + + public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) { + this.responseBody = responseBody; + this.progressListener = progressListener; + } + + @Override + public MediaType contentType() { + return responseBody.contentType(); + } + + @Override + public long contentLength() throws IOException { + return responseBody.contentLength(); + } + + @Override + public BufferedSource source() throws IOException { + if (bufferedSource == null) { + bufferedSource = Okio.buffer(source(responseBody.source())); + } + return bufferedSource; + } + + private Source source(Source source) { + return new ForwardingSource(source) { + long totalBytesRead = 0L; + + @Override + public long read(Buffer sink, long byteCount) throws IOException { + long bytesRead = super.read(sink, byteCount); + // read() returns the number of bytes read, or -1 if this source is exhausted. + totalBytesRead += bytesRead != -1 ? bytesRead : 0; + progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1); + return bytesRead; + } + }; + } +} + + diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java index 042a6ba37e5..4595a80e745 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java @@ -33,12 +33,12 @@ public interface FakeApi { * @param date None (optional) * @param dateTime None (optional) * @param password None (optional) - * @return Call<Void> + * @return Call<Object> */ @FormUrlEncoded - @POST("fake") - Call testEndpointParameters( + @POST("/fake") + Call testEndpointParameters( @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password ); @@ -48,12 +48,12 @@ Call testEndpointParameters( * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) * @param enumQueryInteger Query parameter enum test (double) (optional) * @param enumQueryDouble Query parameter enum test (double) (optional) - * @return Call<Void> + * @return Call<Object> */ @FormUrlEncoded - @GET("fake") - Call testEnumQueryParameters( + @GET("/fake") + Call testEnumQueryParameters( @Field("enum_query_string") String enumQueryString, @Query("enum_query_integer") BigDecimal enumQueryInteger, @Field("enum_query_double") Double enumQueryDouble ); diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java index a55cb2ee17f..523bde3b9cc 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java @@ -22,11 +22,11 @@ public interface PetApi { * Add a new pet to the store * * @param body Pet object that needs to be added to the store (required) - * @return Call<Void> + * @return Call<Object> */ - @POST("pet") - Call addPet( + @POST("/pet") + Call addPet( @Body Pet body ); @@ -35,11 +35,11 @@ Call addPet( * * @param petId Pet id to delete (required) * @param apiKey (optional) - * @return Call<Void> + * @return Call<Object> */ - @DELETE("pet/{petId}") - Call deletePet( + @DELETE("/pet/{petId}") + Call deletePet( @Path("petId") Long petId, @Header("api_key") String apiKey ); @@ -50,7 +50,7 @@ Call deletePet( * @return Call<List> */ - @GET("pet/findByStatus") + @GET("/pet/findByStatus") Call> findPetsByStatus( @Query("status") CSVParams status ); @@ -62,7 +62,7 @@ Call> findPetsByStatus( * @return Call<List> */ - @GET("pet/findByTags") + @GET("/pet/findByTags") Call> findPetsByTags( @Query("tags") CSVParams tags ); @@ -74,7 +74,7 @@ Call> findPetsByTags( * @return Call<Pet> */ - @GET("pet/{petId}") + @GET("/pet/{petId}") Call getPetById( @Path("petId") Long petId ); @@ -83,11 +83,11 @@ Call getPetById( * Update an existing pet * * @param body Pet object that needs to be added to the store (required) - * @return Call<Void> + * @return Call<Object> */ - @PUT("pet") - Call updatePet( + @PUT("/pet") + Call updatePet( @Body Pet body ); @@ -97,12 +97,12 @@ Call updatePet( * @param petId ID of pet that needs to be updated (required) * @param name Updated name of the pet (optional) * @param status Updated status of the pet (optional) - * @return Call<Void> + * @return Call<Object> */ @FormUrlEncoded - @POST("pet/{petId}") - Call updatePetWithForm( + @POST("/pet/{petId}") + Call updatePetWithForm( @Path("petId") Long petId, @Field("name") String name, @Field("status") String status ); @@ -115,10 +115,10 @@ Call updatePetWithForm( * @return Call<ModelApiResponse> */ - @Multipart - @POST("pet/{petId}/uploadImage") + @FormUrlEncoded + @POST("/pet/{petId}/uploadImage") Call uploadFile( - @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file\"; filename=\"file\"") RequestBody file + @Path("petId") Long petId, @Field("additionalMetadata") String additionalMetadata, @Field("file\"; filename=\"file\"") RequestBody file ); } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java index 3e19600bedb..3a811ac7a2e 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java @@ -20,11 +20,11 @@ public interface StoreApi { * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * @param orderId ID of the order that needs to be deleted (required) - * @return Call<Void> + * @return Call<Object> */ - @DELETE("store/order/{orderId}") - Call deleteOrder( + @DELETE("/store/order/{orderId}") + Call deleteOrder( @Path("orderId") String orderId ); @@ -34,7 +34,7 @@ Call deleteOrder( * @return Call<Map> */ - @GET("store/inventory") + @GET("/store/inventory") Call> getInventory(); @@ -45,7 +45,7 @@ Call deleteOrder( * @return Call<Order> */ - @GET("store/order/{orderId}") + @GET("/store/order/{orderId}") Call getOrderById( @Path("orderId") Long orderId ); @@ -57,7 +57,7 @@ Call getOrderById( * @return Call<Order> */ - @POST("store/order") + @POST("/store/order") Call placeOrder( @Body Order body ); diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java index 3fc76b6a1b2..8c564b8423b 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java @@ -20,11 +20,11 @@ public interface UserApi { * Create user * This can only be done by the logged in user. * @param body Created user object (required) - * @return Call<Void> + * @return Call<Object> */ - @POST("user") - Call createUser( + @POST("/user") + Call createUser( @Body User body ); @@ -32,11 +32,11 @@ Call createUser( * Creates list of users with given input array * * @param body List of user object (required) - * @return Call<Void> + * @return Call<Object> */ - @POST("user/createWithArray") - Call createUsersWithArrayInput( + @POST("/user/createWithArray") + Call createUsersWithArrayInput( @Body List body ); @@ -44,11 +44,11 @@ Call createUsersWithArrayInput( * Creates list of users with given input array * * @param body List of user object (required) - * @return Call<Void> + * @return Call<Object> */ - @POST("user/createWithList") - Call createUsersWithListInput( + @POST("/user/createWithList") + Call createUsersWithListInput( @Body List body ); @@ -56,11 +56,11 @@ Call createUsersWithListInput( * Delete user * This can only be done by the logged in user. * @param username The name that needs to be deleted (required) - * @return Call<Void> + * @return Call<Object> */ - @DELETE("user/{username}") - Call deleteUser( + @DELETE("/user/{username}") + Call deleteUser( @Path("username") String username ); @@ -71,7 +71,7 @@ Call deleteUser( * @return Call<User> */ - @GET("user/{username}") + @GET("/user/{username}") Call getUserByName( @Path("username") String username ); @@ -84,7 +84,7 @@ Call getUserByName( * @return Call<String> */ - @GET("user/login") + @GET("/user/login") Call loginUser( @Query("username") String username, @Query("password") String password ); @@ -92,11 +92,11 @@ Call loginUser( /** * Logs out current logged in user session * - * @return Call<Void> + * @return Call<Object> */ - @GET("user/logout") - Call logoutUser(); + @GET("/user/logout") + Call logoutUser(); /** @@ -104,11 +104,11 @@ Call loginUser( * This can only be done by the logged in user. * @param username name that need to be deleted (required) * @param body Updated user object (required) - * @return Call<Void> + * @return Call<Object> */ - @PUT("user/{username}") - Call updateUser( + @PUT("/user/{username}") + Call updateUser( @Path("username") String username, @Body User body ); diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/Authentication.java new file mode 100644 index 00000000000..221a7d9dd1f --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/Authentication.java @@ -0,0 +1,41 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + +public interface Authentication { + /** + * Apply authentication settings to header and query params. + * + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + */ + void applyToParams(List queryParams, Map headerParams); +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java deleted file mode 100644 index c9b6e124d51..00000000000 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java +++ /dev/null @@ -1,72 +0,0 @@ -package io.swagger.client.auth; - -import java.io.IOException; -import java.util.Map; -import java.util.Map.Entry; - -import org.apache.oltu.oauth2.client.HttpClient; -import org.apache.oltu.oauth2.client.request.OAuthClientRequest; -import org.apache.oltu.oauth2.client.response.OAuthClientResponse; -import org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory; -import org.apache.oltu.oauth2.common.exception.OAuthProblemException; -import org.apache.oltu.oauth2.common.exception.OAuthSystemException; - - -import okhttp3.Interceptor; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Request.Builder; -import okhttp3.Response; -import okhttp3.MediaType; -import okhttp3.RequestBody; - - -public class OAuthOkHttpClient implements HttpClient { - - private OkHttpClient client; - - public OAuthOkHttpClient() { - this.client = new OkHttpClient(); - } - - public OAuthOkHttpClient(OkHttpClient client) { - this.client = client; - } - - public T execute(OAuthClientRequest request, Map headers, - String requestMethod, Class responseClass) - throws OAuthSystemException, OAuthProblemException { - - MediaType mediaType = MediaType.parse("application/json"); - Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri()); - - if(headers != null) { - for (Entry entry : headers.entrySet()) { - if (entry.getKey().equalsIgnoreCase("Content-Type")) { - mediaType = MediaType.parse(entry.getValue()); - } else { - requestBuilder.addHeader(entry.getKey(), entry.getValue()); - } - } - } - - RequestBody body = request.getBody() != null ? RequestBody.create(mediaType, request.getBody()) : null; - requestBuilder.method(requestMethod, body); - - try { - Response response = client.newCall(requestBuilder.build()).execute(); - return OAuthClientResponseFactory.createCustomResponse( - response.body().string(), - response.body().contentType().toString(), - response.code(), - responseClass); - } catch (IOException e) { - throw new OAuthSystemException(e); - } - } - - public void shutdown() { - // Nothing to do here - } - -} diff --git a/samples/client/petstore/java/retrofit2rx/docs/ArrayTest.md b/samples/client/petstore/java/retrofit2rx/docs/ArrayTest.md index 2cd4b9d33f9..9feee16427f 100644 --- a/samples/client/petstore/java/retrofit2rx/docs/ArrayTest.md +++ b/samples/client/petstore/java/retrofit2rx/docs/ArrayTest.md @@ -7,13 +7,6 @@ Name | Type | Description | Notes **arrayOfString** | **List<String>** | | [optional] **arrayArrayOfInteger** | [**List<List<Long>>**](List.md) | | [optional] **arrayArrayOfModel** | [**List<List<ReadOnlyFirst>>**](List.md) | | [optional] -**arrayOfEnum** | [**List<ArrayOfEnumEnum>**](#List<ArrayOfEnumEnum>) | | [optional] - - - -## Enum: List<ArrayOfEnumEnum> -Name | Value ----- | ----- diff --git a/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md b/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md index 0e646d63479..21a4db7c377 100644 --- a/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md +++ b/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md @@ -4,57 +4,13 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**testCodeInjectEnd**](FakeApi.md#testCodeInjectEnd) | **PUT** fake | To test code injection =end -[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -[**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** fake | To test enum query parameters +[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters - -# **testCodeInjectEnd** -> Void testCodeInjectEnd(testCodeInjectEnd) - -To test code injection =end - -### Example -```java -// Import classes: -//import io.swagger.client.ApiException; -//import io.swagger.client.api.FakeApi; - - -FakeApi apiInstance = new FakeApi(); -String testCodeInjectEnd = "testCodeInjectEnd_example"; // String | To test code injection =end -try { - Void result = apiInstance.testCodeInjectEnd(testCodeInjectEnd); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testCodeInjectEnd"); - e.printStackTrace(); -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **testCodeInjectEnd** | **String**| To test code injection =end | [optional] - -### Return type - -[**Void**](.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json, */ =end'));(phpinfo(' - - **Accept**: application/json, */ end - # **testEndpointParameters** -> Void testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) +> testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -81,8 +37,7 @@ LocalDate date = new LocalDate(); // LocalDate | None DateTime dateTime = new DateTime(); // DateTime | None String password = "password_example"; // String | None try { - Void result = apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); - System.out.println(result); + apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); } catch (ApiException e) { System.err.println("Exception when calling FakeApi#testEndpointParameters"); e.printStackTrace(); @@ -108,7 +63,7 @@ Name | Type | Description | Notes ### Return type -[**Void**](.md) +null (empty response body) ### Authorization @@ -121,7 +76,7 @@ No authorization required # **testEnumQueryParameters** -> Void testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble) +> testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble) To test enum query parameters @@ -137,8 +92,7 @@ String enumQueryString = "-efg"; // String | Query parameter enum test (string) BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | Query parameter enum test (double) Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) try { - Void result = apiInstance.testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); - System.out.println(result); + apiInstance.testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); } catch (ApiException e) { System.err.println("Exception when calling FakeApi#testEnumQueryParameters"); e.printStackTrace(); @@ -155,7 +109,7 @@ Name | Type | Description | Notes ### Return type -[**Void**](.md) +null (empty response body) ### Authorization diff --git a/samples/client/petstore/java/retrofit2rx/docs/PetApi.md b/samples/client/petstore/java/retrofit2rx/docs/PetApi.md index 40ea199b153..e0314e20e51 100644 --- a/samples/client/petstore/java/retrofit2rx/docs/PetApi.md +++ b/samples/client/petstore/java/retrofit2rx/docs/PetApi.md @@ -4,19 +4,19 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**addPet**](PetApi.md#addPet) | **POST** pet | Add a new pet to the store -[**deletePet**](PetApi.md#deletePet) | **DELETE** pet/{petId} | Deletes a pet -[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** pet/findByStatus | Finds Pets by status -[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** pet/findByTags | Finds Pets by tags -[**getPetById**](PetApi.md#getPetById) | **GET** pet/{petId} | Find pet by ID -[**updatePet**](PetApi.md#updatePet) | **PUT** pet | Update an existing pet -[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** pet/{petId} | Updates a pet in the store with form data -[**uploadFile**](PetApi.md#uploadFile) | **POST** pet/{petId}/uploadImage | uploads an image +[**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image # **addPet** -> Void addPet(body) +> addPet(body) Add a new pet to the store @@ -40,8 +40,7 @@ petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); PetApi apiInstance = new PetApi(); Pet body = new Pet(); // Pet | Pet object that needs to be added to the store try { - Void result = apiInstance.addPet(body); - System.out.println(result); + apiInstance.addPet(body); } catch (ApiException e) { System.err.println("Exception when calling PetApi#addPet"); e.printStackTrace(); @@ -56,7 +55,7 @@ Name | Type | Description | Notes ### Return type -[**Void**](.md) +null (empty response body) ### Authorization @@ -69,7 +68,7 @@ Name | Type | Description | Notes # **deletePet** -> Void deletePet(petId, apiKey) +> deletePet(petId, apiKey) Deletes a pet @@ -94,8 +93,7 @@ PetApi apiInstance = new PetApi(); Long petId = 789L; // Long | Pet id to delete String apiKey = "apiKey_example"; // String | try { - Void result = apiInstance.deletePet(petId, apiKey); - System.out.println(result); + apiInstance.deletePet(petId, apiKey); } catch (ApiException e) { System.err.println("Exception when calling PetApi#deletePet"); e.printStackTrace(); @@ -111,7 +109,7 @@ Name | Type | Description | Notes ### Return type -[**Void**](.md) +null (empty response body) ### Authorization @@ -285,7 +283,7 @@ Name | Type | Description | Notes # **updatePet** -> Void updatePet(body) +> updatePet(body) Update an existing pet @@ -309,8 +307,7 @@ petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); PetApi apiInstance = new PetApi(); Pet body = new Pet(); // Pet | Pet object that needs to be added to the store try { - Void result = apiInstance.updatePet(body); - System.out.println(result); + apiInstance.updatePet(body); } catch (ApiException e) { System.err.println("Exception when calling PetApi#updatePet"); e.printStackTrace(); @@ -325,7 +322,7 @@ Name | Type | Description | Notes ### Return type -[**Void**](.md) +null (empty response body) ### Authorization @@ -338,7 +335,7 @@ Name | Type | Description | Notes # **updatePetWithForm** -> Void updatePetWithForm(petId, name, status) +> updatePetWithForm(petId, name, status) Updates a pet in the store with form data @@ -364,8 +361,7 @@ Long petId = 789L; // Long | ID of pet that needs to be updated String name = "name_example"; // String | Updated name of the pet String status = "status_example"; // String | Updated status of the pet try { - Void result = apiInstance.updatePetWithForm(petId, name, status); - System.out.println(result); + apiInstance.updatePetWithForm(petId, name, status); } catch (ApiException e) { System.err.println("Exception when calling PetApi#updatePetWithForm"); e.printStackTrace(); @@ -382,7 +378,7 @@ Name | Type | Description | Notes ### Return type -[**Void**](.md) +null (empty response body) ### Authorization diff --git a/samples/client/petstore/java/retrofit2rx/docs/StoreApi.md b/samples/client/petstore/java/retrofit2rx/docs/StoreApi.md index 30e3c11d440..0b30791725a 100644 --- a/samples/client/petstore/java/retrofit2rx/docs/StoreApi.md +++ b/samples/client/petstore/java/retrofit2rx/docs/StoreApi.md @@ -4,15 +4,15 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** store/order/{orderId} | Delete purchase order by ID -[**getInventory**](StoreApi.md#getInventory) | **GET** store/inventory | Returns pet inventories by status -[**getOrderById**](StoreApi.md#getOrderById) | **GET** store/order/{orderId} | Find purchase order by ID -[**placeOrder**](StoreApi.md#placeOrder) | **POST** store/order | Place an order for a pet +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet # **deleteOrder** -> Void deleteOrder(orderId) +> deleteOrder(orderId) Delete purchase order by ID @@ -28,8 +28,7 @@ For valid response try integer IDs with value < 1000. Anything above 1000 or StoreApi apiInstance = new StoreApi(); String orderId = "orderId_example"; // String | ID of the order that needs to be deleted try { - Void result = apiInstance.deleteOrder(orderId); - System.out.println(result); + apiInstance.deleteOrder(orderId); } catch (ApiException e) { System.err.println("Exception when calling StoreApi#deleteOrder"); e.printStackTrace(); @@ -44,7 +43,7 @@ Name | Type | Description | Notes ### Return type -[**Void**](.md) +null (empty response body) ### Authorization diff --git a/samples/client/petstore/java/retrofit2rx/docs/UserApi.md b/samples/client/petstore/java/retrofit2rx/docs/UserApi.md index b0a0149a50a..8cdc15992ee 100644 --- a/samples/client/petstore/java/retrofit2rx/docs/UserApi.md +++ b/samples/client/petstore/java/retrofit2rx/docs/UserApi.md @@ -4,19 +4,19 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**createUser**](UserApi.md#createUser) | **POST** user | Create user -[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** user/createWithArray | Creates list of users with given input array -[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** user/createWithList | Creates list of users with given input array -[**deleteUser**](UserApi.md#deleteUser) | **DELETE** user/{username} | Delete user -[**getUserByName**](UserApi.md#getUserByName) | **GET** user/{username} | Get user by user name -[**loginUser**](UserApi.md#loginUser) | **GET** user/login | Logs user into the system -[**logoutUser**](UserApi.md#logoutUser) | **GET** user/logout | Logs out current logged in user session -[**updateUser**](UserApi.md#updateUser) | **PUT** user/{username} | Updated user +[**createUser**](UserApi.md#createUser) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user # **createUser** -> Void createUser(body) +> createUser(body) Create user @@ -32,8 +32,7 @@ This can only be done by the logged in user. UserApi apiInstance = new UserApi(); User body = new User(); // User | Created user object try { - Void result = apiInstance.createUser(body); - System.out.println(result); + apiInstance.createUser(body); } catch (ApiException e) { System.err.println("Exception when calling UserApi#createUser"); e.printStackTrace(); @@ -48,7 +47,7 @@ Name | Type | Description | Notes ### Return type -[**Void**](.md) +null (empty response body) ### Authorization @@ -61,7 +60,7 @@ No authorization required # **createUsersWithArrayInput** -> Void createUsersWithArrayInput(body) +> createUsersWithArrayInput(body) Creates list of users with given input array @@ -77,8 +76,7 @@ Creates list of users with given input array UserApi apiInstance = new UserApi(); List body = Arrays.asList(new User()); // List | List of user object try { - Void result = apiInstance.createUsersWithArrayInput(body); - System.out.println(result); + apiInstance.createUsersWithArrayInput(body); } catch (ApiException e) { System.err.println("Exception when calling UserApi#createUsersWithArrayInput"); e.printStackTrace(); @@ -93,7 +91,7 @@ Name | Type | Description | Notes ### Return type -[**Void**](.md) +null (empty response body) ### Authorization @@ -106,7 +104,7 @@ No authorization required # **createUsersWithListInput** -> Void createUsersWithListInput(body) +> createUsersWithListInput(body) Creates list of users with given input array @@ -122,8 +120,7 @@ Creates list of users with given input array UserApi apiInstance = new UserApi(); List body = Arrays.asList(new User()); // List | List of user object try { - Void result = apiInstance.createUsersWithListInput(body); - System.out.println(result); + apiInstance.createUsersWithListInput(body); } catch (ApiException e) { System.err.println("Exception when calling UserApi#createUsersWithListInput"); e.printStackTrace(); @@ -138,7 +135,7 @@ Name | Type | Description | Notes ### Return type -[**Void**](.md) +null (empty response body) ### Authorization @@ -151,7 +148,7 @@ No authorization required # **deleteUser** -> Void deleteUser(username) +> deleteUser(username) Delete user @@ -167,8 +164,7 @@ This can only be done by the logged in user. UserApi apiInstance = new UserApi(); String username = "username_example"; // String | The name that needs to be deleted try { - Void result = apiInstance.deleteUser(username); - System.out.println(result); + apiInstance.deleteUser(username); } catch (ApiException e) { System.err.println("Exception when calling UserApi#deleteUser"); e.printStackTrace(); @@ -183,7 +179,7 @@ Name | Type | Description | Notes ### Return type -[**Void**](.md) +null (empty response body) ### Authorization @@ -288,7 +284,7 @@ No authorization required # **logoutUser** -> Void logoutUser() +> logoutUser() Logs out current logged in user session @@ -303,8 +299,7 @@ Logs out current logged in user session UserApi apiInstance = new UserApi(); try { - Void result = apiInstance.logoutUser(); - System.out.println(result); + apiInstance.logoutUser(); } catch (ApiException e) { System.err.println("Exception when calling UserApi#logoutUser"); e.printStackTrace(); @@ -316,7 +311,7 @@ This endpoint does not need any parameter. ### Return type -[**Void**](.md) +null (empty response body) ### Authorization @@ -329,7 +324,7 @@ No authorization required # **updateUser** -> Void updateUser(username, body) +> updateUser(username, body) Updated user @@ -346,8 +341,7 @@ UserApi apiInstance = new UserApi(); String username = "username_example"; // String | name that need to be deleted User body = new User(); // User | Updated user object try { - Void result = apiInstance.updateUser(username, body); - System.out.println(result); + apiInstance.updateUser(username, body); } catch (ApiException e) { System.err.println("Exception when calling UserApi#updateUser"); e.printStackTrace(); @@ -363,7 +357,7 @@ Name | Type | Description | Notes ### Return type -[**Void**](.md) +null (empty response body) ### Authorization diff --git a/samples/client/petstore/java/retrofit2rx/pom.xml b/samples/client/petstore/java/retrofit2rx/pom.xml index a56d38dc759..449a3dae137 100644 --- a/samples/client/petstore/java/retrofit2rx/pom.xml +++ b/samples/client/petstore/java/retrofit2rx/pom.xml @@ -68,6 +68,7 @@ org.codehaus.mojo build-helper-maven-plugin + 1.10 add_sources @@ -148,6 +149,7 @@ + UTF-8 1.7 ${java.version} ${java.version} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiCallback.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiCallback.java new file mode 100644 index 00000000000..3ca33cf8017 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiCallback.java @@ -0,0 +1,74 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import java.io.IOException; + +import java.util.Map; +import java.util.List; + +/** + * Callback for asynchronous API call. + * + * @param The return type + */ +public interface ApiCallback { + /** + * This is called when the API call fails. + * + * @param e The exception causing the failure + * @param statusCode Status code of the response if available, otherwise it would be 0 + * @param responseHeaders Headers of the response if available, otherwise it would be null + */ + void onFailure(ApiException e, int statusCode, Map> responseHeaders); + + /** + * This is called when the API call succeeded. + * + * @param result The result deserialized from response + * @param statusCode Status code of the response + * @param responseHeaders Headers of the response + */ + void onSuccess(T result, int statusCode, Map> responseHeaders); + + /** + * This is called when the API upload processing. + * + * @param bytesWritten bytes Written + * @param contentLength content length of request body + * @param done write end + */ + void onUploadProgress(long bytesWritten, long contentLength, boolean done); + + /** + * This is called when the API downlond processing. + * + * @param bytesRead bytes Read + * @param contentLength content lenngth of the response + * @param done Read end + */ + void onDownloadProgress(long bytesRead, long contentLength, boolean done); +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java index ea73efea029..43eaeba87f4 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java @@ -53,10 +53,10 @@ public ApiClient(String[] authNames) { this(); for(String authName : authNames) { Interceptor auth; - if (authName == "petstore_auth") { - auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); - } else if (authName == "api_key") { + if (authName == "api_key") { auth = new ApiKeyAuth("header", "api_key"); + } else if (authName == "petstore_auth") { + auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); } else { throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); } @@ -66,7 +66,7 @@ public ApiClient(String[] authNames) { /** * Basic constructor for single auth name - * @param authName + * @param authName Authentication name */ public ApiClient(String authName) { this(new String[]{authName}); @@ -74,8 +74,8 @@ public ApiClient(String authName) { /** * Helper constructor for single api key - * @param authName - * @param apiKey + * @param authName Authentication name + * @param apiKey API key */ public ApiClient(String authName, String apiKey) { this(authName); @@ -84,9 +84,9 @@ public ApiClient(String authName, String apiKey) { /** * Helper constructor for single basic auth or password oauth2 - * @param authName - * @param username - * @param password + * @param authName Authentication name + * @param username Username + * @param password Password */ public ApiClient(String authName, String username, String password) { this(authName); @@ -95,11 +95,11 @@ public ApiClient(String authName, String username, String password) { /** * Helper constructor for single password oauth2 - * @param authName - * @param clientId - * @param secret - * @param username - * @param password + * @param authName Authentication name + * @param clientId Client ID + * @param secret Client Secret + * @param username Username + * @param password Password */ public ApiClient(String authName, String clientId, String secret, String username, String password) { this(authName); @@ -141,7 +141,7 @@ public S createService(Class serviceClass) { /** * Helper method to configure the first api key found - * @param apiKey + * @param apiKey API key */ private void setApiKey(String apiKey) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -155,8 +155,8 @@ private void setApiKey(String apiKey) { /** * Helper method to configure the username/password for basic auth or password oauth - * @param username - * @param password + * @param username Username + * @param password Password */ private void setCredentials(String username, String password) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -175,7 +175,7 @@ private void setCredentials(String username, String password) { /** * Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one) - * @return + * @return Token request builder */ public TokenRequestBuilder getTokenEndPoint() { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -189,7 +189,7 @@ public TokenRequestBuilder getTokenEndPoint() { /** * Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one) - * @return + * @return Authentication request builder */ public AuthenticationRequestBuilder getAuthorizationEndPoint() { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -203,7 +203,7 @@ public AuthenticationRequestBuilder getAuthorizationEndPoint() { /** * Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one) - * @param accessToken + * @param accessToken Access token */ public void setAccessToken(String accessToken) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -217,9 +217,9 @@ public void setAccessToken(String accessToken) { /** * Helper method to configure the oauth accessCode/implicit flow parameters - * @param clientId - * @param clientSecret - * @param redirectURI + * @param clientId Client ID + * @param clientSecret Client secret + * @param redirectURI Redirect URI */ public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -239,7 +239,7 @@ public void configureAuthorizationFlow(String clientId, String clientSecret, Str /** * Configures a listener which is notified when a new access token is received. - * @param accessTokenListener + * @param accessTokenListener Access token listener */ public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -253,8 +253,8 @@ public void registerAccessTokenListener(AccessTokenListener accessTokenListener) /** * Adds an authorization to be used by the client - * @param authName - * @param authorization + * @param authName Authentication name + * @param authorization Authorization interceptor */ public void addAuthorization(String authName, Interceptor authorization) { if (apiAuthorizations.containsKey(authName)) { @@ -292,7 +292,7 @@ public void addAuthsToOkBuilder(OkHttpClient.Builder okBuilder) { /** * Clones the okBuilder given in parameter, adds the auth interceptors and uses it to configure the Retrofit - * @param okClient + * @param okClient An instance of OK HTTP client */ public void configureFromOkclient(OkHttpClient okClient) { this.okBuilder = okClient.newBuilder(); diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiException.java new file mode 100644 index 00000000000..3bed001f002 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiException.java @@ -0,0 +1,103 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import java.util.Map; +import java.util.List; + + +public class ApiException extends Exception { + private int code = 0; + private Map> responseHeaders = null; + private String responseBody = null; + + public ApiException() {} + + public ApiException(Throwable throwable) { + super(throwable); + } + + public ApiException(String message) { + super(message); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } + + public ApiException(int code, Map> responseHeaders, String responseBody) { + this((String) null, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(int code, String message) { + super(message); + this.code = code; + } + + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this(code, message); + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + /** + * Get the HTTP status code. + * + * @return HTTP status code + */ + public int getCode() { + return code; + } + + /** + * Get the HTTP response headers. + * + * @return A map of list of string + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + + /** + * Get the HTTP response body. + * + * @return Response body in the form of string + */ + public String getResponseBody() { + return responseBody; + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiResponse.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiResponse.java new file mode 100644 index 00000000000..d7dde1ee939 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiResponse.java @@ -0,0 +1,71 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import java.util.List; +import java.util.Map; + +/** + * API response returned by API call. + * + * @param T The type of data that is deserialized from response body + */ +public class ApiResponse { + final private int statusCode; + final private Map> headers; + final private T data; + + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + */ + public ApiResponse(int statusCode, Map> headers) { + this(statusCode, headers, null); + } + + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + * @param data The object deserialized from response bod + */ + public ApiResponse(int statusCode, Map> headers, T data) { + this.statusCode = statusCode; + this.headers = headers; + this.data = data; + } + + public int getStatusCode() { + return statusCode; + } + + public Map> getHeaders() { + return headers; + } + + public T getData() { + return data; + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/CollectionFormats.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/CollectionFormats.java deleted file mode 100644 index e96d1561a7c..00000000000 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/CollectionFormats.java +++ /dev/null @@ -1,95 +0,0 @@ -package io.swagger.client; - -import java.util.Arrays; -import java.util.List; - -public class CollectionFormats { - - public static class CSVParams { - - protected List params; - - public CSVParams() { - } - - public CSVParams(List params) { - this.params = params; - } - - public CSVParams(String... params) { - this.params = Arrays.asList(params); - } - - public List getParams() { - return params; - } - - public void setParams(List params) { - this.params = params; - } - - @Override - public String toString() { - return StringUtil.join(params.toArray(new String[0]), ","); - } - - } - - public static class SSVParams extends CSVParams { - - public SSVParams() { - } - - public SSVParams(List params) { - super(params); - } - - public SSVParams(String... params) { - super(params); - } - - @Override - public String toString() { - return StringUtil.join(params.toArray(new String[0]), " "); - } - } - - public static class TSVParams extends CSVParams { - - public TSVParams() { - } - - public TSVParams(List params) { - super(params); - } - - public TSVParams(String... params) { - super(params); - } - - @Override - public String toString() { - return StringUtil.join( params.toArray(new String[0]), "\t"); - } - } - - public static class PIPESParams extends CSVParams { - - public PIPESParams() { - } - - public PIPESParams(List params) { - super(params); - } - - public PIPESParams(String... params) { - super(params); - } - - @Override - public String toString() { - return StringUtil.join(params.toArray(new String[0]), "|"); - } - } - -} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/Configuration.java new file mode 100644 index 00000000000..5191b9b73c6 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/Configuration.java @@ -0,0 +1,51 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + + +public class Configuration { + private static ApiClient defaultApiClient = new ApiClient(); + + /** + * Get the default API client, which would be used when creating API + * instances without providing an API client. + * + * @return Default API client + */ + public static ApiClient getDefaultApiClient() { + return defaultApiClient; + } + + /** + * Set the default API client, which would be used when creating API + * instances without providing an API client. + * + * @param apiClient API client + */ + public static void setDefaultApiClient(ApiClient apiClient) { + defaultApiClient = apiClient; + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/JSON.java new file mode 100644 index 00000000000..540611eab9d --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/JSON.java @@ -0,0 +1,237 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonNull; +import com.google.gson.JsonParseException; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +import java.io.IOException; +import java.io.StringReader; +import java.lang.reflect.Type; +import java.util.Date; + +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; + +public class JSON { + private ApiClient apiClient; + private Gson gson; + + /** + * JSON constructor. + * + * @param apiClient An instance of ApiClient + */ + public JSON(ApiClient apiClient) { + this.apiClient = apiClient; + gson = new GsonBuilder() + .registerTypeAdapter(Date.class, new DateAdapter(apiClient)) + .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) + .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) + .create(); + } + + /** + * Get Gson. + * + * @return Gson + */ + public Gson getGson() { + return gson; + } + + /** + * Set Gson. + * + * @param gson Gson + */ + public void setGson(Gson gson) { + this.gson = gson; + } + + /** + * Serialize the given Java object into JSON string. + * + * @param obj Object + * @return String representation of the JSON + */ + public String serialize(Object obj) { + return gson.toJson(obj); + } + + /** + * Deserialize the given JSON string to Java object. + * + * @param Type + * @param body The JSON string + * @param returnType The type to deserialize inot + * @return The deserialized Java object + */ + @SuppressWarnings("unchecked") + public T deserialize(String body, Type returnType) { + try { + if (apiClient.isLenientOnJson()) { + JsonReader jsonReader = new JsonReader(new StringReader(body)); + // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) + jsonReader.setLenient(true); + return gson.fromJson(jsonReader, returnType); + } else { + return gson.fromJson(body, returnType); + } + } catch (JsonParseException e) { + // Fallback processing when failed to parse JSON form response body: + // return the response body string directly for the String return type; + // parse response body into date or datetime for the Date return type. + if (returnType.equals(String.class)) + return (T) body; + else if (returnType.equals(Date.class)) + return (T) apiClient.parseDateOrDatetime(body); + else throw(e); + } + } +} + +class DateAdapter implements JsonSerializer, JsonDeserializer { + private final ApiClient apiClient; + + /** + * Constructor for DateAdapter + * + * @param apiClient Api client + */ + public DateAdapter(ApiClient apiClient) { + super(); + this.apiClient = apiClient; + } + + /** + * Serialize + * + * @param src Date + * @param typeOfSrc Type + * @param context Json Serialization Context + * @return Json Element + */ + @Override + public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { + if (src == null) { + return JsonNull.INSTANCE; + } else { + return new JsonPrimitive(apiClient.formatDatetime(src)); + } + } + + /** + * Deserialize + * + * @param json Json element + * @param date Type + * @param typeOfSrc Type + * @param context Json Serialization Context + * @return Date + * @throw JsonParseException if fail to parse + */ + @Override + public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException { + String str = json.getAsJsonPrimitive().getAsString(); + try { + return apiClient.parseDateOrDatetime(str); + } catch (RuntimeException e) { + throw new JsonParseException(e); + } + } +} + +/** + * Gson TypeAdapter for Joda DateTime type + */ +class DateTimeTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + + @Override + public void write(JsonWriter out, DateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public DateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseDateTime(date); + } + } +} + +/** + * Gson TypeAdapter for Joda LocalDate type + */ +class LocalDateTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.date(); + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseLocalDate(date); + } + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/Pair.java new file mode 100644 index 00000000000..15b247eea93 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/Pair.java @@ -0,0 +1,64 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + + +public class Pair { + private String name = ""; + private String value = ""; + + public Pair (String name, String value) { + setName(name); + setValue(value); + } + + private void setName(String name) { + if (!isValidString(name)) return; + + this.name = name; + } + + private void setValue(String value) { + if (!isValidString(value)) return; + + this.value = value; + } + + public String getName() { + return this.name; + } + + public String getValue() { + return this.value; + } + + private boolean isValidString(String arg) { + if (arg == null) return false; + if (arg.trim().isEmpty()) return false; + + return true; + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ProgressRequestBody.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ProgressRequestBody.java new file mode 100644 index 00000000000..d9ca742ecd2 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ProgressRequestBody.java @@ -0,0 +1,95 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.RequestBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSink; +import okio.ForwardingSink; +import okio.Okio; +import okio.Sink; + +public class ProgressRequestBody extends RequestBody { + + public interface ProgressRequestListener { + void onRequestProgress(long bytesWritten, long contentLength, boolean done); + } + + private final RequestBody requestBody; + + private final ProgressRequestListener progressListener; + + private BufferedSink bufferedSink; + + public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) { + this.requestBody = requestBody; + this.progressListener = progressListener; + } + + @Override + public MediaType contentType() { + return requestBody.contentType(); + } + + @Override + public long contentLength() throws IOException { + return requestBody.contentLength(); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + if (bufferedSink == null) { + bufferedSink = Okio.buffer(sink(sink)); + } + + requestBody.writeTo(bufferedSink); + bufferedSink.flush(); + + } + + private Sink sink(Sink sink) { + return new ForwardingSink(sink) { + + long bytesWritten = 0L; + long contentLength = 0L; + + @Override + public void write(Buffer source, long byteCount) throws IOException { + super.write(source, byteCount); + if (contentLength == 0) { + contentLength = contentLength(); + } + + bytesWritten += byteCount; + progressListener.onRequestProgress(bytesWritten, contentLength, bytesWritten == contentLength); + } + }; + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ProgressResponseBody.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ProgressResponseBody.java new file mode 100644 index 00000000000..f8af685999d --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ProgressResponseBody.java @@ -0,0 +1,88 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.ResponseBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSource; +import okio.ForwardingSource; +import okio.Okio; +import okio.Source; + +public class ProgressResponseBody extends ResponseBody { + + public interface ProgressListener { + void update(long bytesRead, long contentLength, boolean done); + } + + private final ResponseBody responseBody; + private final ProgressListener progressListener; + private BufferedSource bufferedSource; + + public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) { + this.responseBody = responseBody; + this.progressListener = progressListener; + } + + @Override + public MediaType contentType() { + return responseBody.contentType(); + } + + @Override + public long contentLength() throws IOException { + return responseBody.contentLength(); + } + + @Override + public BufferedSource source() throws IOException { + if (bufferedSource == null) { + bufferedSource = Okio.buffer(source(responseBody.source())); + } + return bufferedSource; + } + + private Source source(Source source) { + return new ForwardingSource(source) { + long totalBytesRead = 0L; + + @Override + public long read(Buffer sink, long byteCount) throws IOException { + long bytesRead = super.read(sink, byteCount); + // read() returns the number of bytes read, or -1 if this source is exhausted. + totalBytesRead += bytesRead != -1 ? bytesRead : 0; + progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1); + return bytesRead; + } + }; + } +} + + diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java index fd700761fac..ce407e91f48 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java @@ -9,8 +9,8 @@ import okhttp3.RequestBody; import org.joda.time.LocalDate; -import java.math.BigDecimal; import org.joda.time.DateTime; +import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; @@ -18,19 +18,6 @@ import java.util.Map; public interface FakeApi { - /** - * To test code injection =end - * - * @param testCodeInjectEnd To test code injection =end (optional) - * @return Call - */ - - @FormUrlEncoded - @PUT("fake") - Observable testCodeInjectEnd( - @Field("test code inject */ =end") String testCodeInjectEnd - ); - /** * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -46,12 +33,12 @@ Observable testCodeInjectEnd( * @param date None (optional) * @param dateTime None (optional) * @param password None (optional) - * @return Call + * @return Call<Object> */ @FormUrlEncoded - @POST("fake") - Observable testEndpointParameters( + @POST("/fake") + Observable testEndpointParameters( @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password ); @@ -61,12 +48,12 @@ Observable testEndpointParameters( * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) * @param enumQueryInteger Query parameter enum test (double) (optional) * @param enumQueryDouble Query parameter enum test (double) (optional) - * @return Call + * @return Call<Object> */ @FormUrlEncoded - @GET("fake") - Observable testEnumQueryParameters( + @GET("/fake") + Observable testEnumQueryParameters( @Field("enum_query_string") String enumQueryString, @Query("enum_query_integer") BigDecimal enumQueryInteger, @Field("enum_query_double") Double enumQueryDouble ); diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java index 4a2e64b726e..15e0c85a2d4 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java @@ -9,8 +9,8 @@ import okhttp3.RequestBody; import io.swagger.client.model.Pet; -import io.swagger.client.model.ModelApiResponse; import java.io.File; +import io.swagger.client.model.ModelApiResponse; import java.util.ArrayList; import java.util.HashMap; @@ -22,11 +22,11 @@ public interface PetApi { * Add a new pet to the store * * @param body Pet object that needs to be added to the store (required) - * @return Call + * @return Call<Object> */ - @POST("pet") - Observable addPet( + @POST("/pet") + Observable addPet( @Body Pet body ); @@ -35,11 +35,11 @@ Observable addPet( * * @param petId Pet id to delete (required) * @param apiKey (optional) - * @return Call + * @return Call<Object> */ - @DELETE("pet/{petId}") - Observable deletePet( + @DELETE("/pet/{petId}") + Observable deletePet( @Path("petId") Long petId, @Header("api_key") String apiKey ); @@ -47,10 +47,10 @@ Observable deletePet( * Finds Pets by status * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter (required) - * @return Call> + * @return Call<List> */ - @GET("pet/findByStatus") + @GET("/pet/findByStatus") Observable> findPetsByStatus( @Query("status") CSVParams status ); @@ -59,10 +59,10 @@ Observable> findPetsByStatus( * Finds Pets by tags * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by (required) - * @return Call> + * @return Call<List> */ - @GET("pet/findByTags") + @GET("/pet/findByTags") Observable> findPetsByTags( @Query("tags") CSVParams tags ); @@ -71,10 +71,10 @@ Observable> findPetsByTags( * Find pet by ID * Returns a single pet * @param petId ID of pet to return (required) - * @return Call + * @return Call<Pet> */ - @GET("pet/{petId}") + @GET("/pet/{petId}") Observable getPetById( @Path("petId") Long petId ); @@ -83,11 +83,11 @@ Observable getPetById( * Update an existing pet * * @param body Pet object that needs to be added to the store (required) - * @return Call + * @return Call<Object> */ - @PUT("pet") - Observable updatePet( + @PUT("/pet") + Observable updatePet( @Body Pet body ); @@ -97,12 +97,12 @@ Observable updatePet( * @param petId ID of pet that needs to be updated (required) * @param name Updated name of the pet (optional) * @param status Updated status of the pet (optional) - * @return Call + * @return Call<Object> */ @FormUrlEncoded - @POST("pet/{petId}") - Observable updatePetWithForm( + @POST("/pet/{petId}") + Observable updatePetWithForm( @Path("petId") Long petId, @Field("name") String name, @Field("status") String status ); @@ -112,13 +112,13 @@ Observable updatePetWithForm( * @param petId ID of pet to update (required) * @param additionalMetadata Additional data to pass to server (optional) * @param file file to upload (optional) - * @return Call + * @return Call<ModelApiResponse> */ - @Multipart - @POST("pet/{petId}/uploadImage") + @FormUrlEncoded + @POST("/pet/{petId}/uploadImage") Observable uploadFile( - @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file\"; filename=\"file\"") RequestBody file + @Path("petId") Long petId, @Field("additionalMetadata") String additionalMetadata, @Field("file\"; filename=\"file\"") RequestBody file ); } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java index 19be150428b..ff3e4dcd791 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java @@ -20,21 +20,21 @@ public interface StoreApi { * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * @param orderId ID of the order that needs to be deleted (required) - * @return Call + * @return Call<Object> */ - @DELETE("store/order/{orderId}") - Observable deleteOrder( + @DELETE("/store/order/{orderId}") + Observable deleteOrder( @Path("orderId") String orderId ); /** * Returns pet inventories by status * Returns a map of status codes to quantities - * @return Call> + * @return Call<Map> */ - @GET("store/inventory") + @GET("/store/inventory") Observable> getInventory(); @@ -42,10 +42,10 @@ Observable deleteOrder( * Find purchase order by ID * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * @param orderId ID of pet that needs to be fetched (required) - * @return Call + * @return Call<Order> */ - @GET("store/order/{orderId}") + @GET("/store/order/{orderId}") Observable getOrderById( @Path("orderId") Long orderId ); @@ -54,10 +54,10 @@ Observable getOrderById( * Place an order for a pet * * @param body order placed for purchasing the pet (required) - * @return Call + * @return Call<Order> */ - @POST("store/order") + @POST("/store/order") Observable placeOrder( @Body Order body ); diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/UserApi.java index 4cad0d804d7..52db68a9332 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/UserApi.java @@ -20,11 +20,11 @@ public interface UserApi { * Create user * This can only be done by the logged in user. * @param body Created user object (required) - * @return Call + * @return Call<Object> */ - @POST("user") - Observable createUser( + @POST("/user") + Observable createUser( @Body User body ); @@ -32,11 +32,11 @@ Observable createUser( * Creates list of users with given input array * * @param body List of user object (required) - * @return Call + * @return Call<Object> */ - @POST("user/createWithArray") - Observable createUsersWithArrayInput( + @POST("/user/createWithArray") + Observable createUsersWithArrayInput( @Body List body ); @@ -44,11 +44,11 @@ Observable createUsersWithArrayInput( * Creates list of users with given input array * * @param body List of user object (required) - * @return Call + * @return Call<Object> */ - @POST("user/createWithList") - Observable createUsersWithListInput( + @POST("/user/createWithList") + Observable createUsersWithListInput( @Body List body ); @@ -56,11 +56,11 @@ Observable createUsersWithListInput( * Delete user * This can only be done by the logged in user. * @param username The name that needs to be deleted (required) - * @return Call + * @return Call<Object> */ - @DELETE("user/{username}") - Observable deleteUser( + @DELETE("/user/{username}") + Observable deleteUser( @Path("username") String username ); @@ -68,10 +68,10 @@ Observable deleteUser( * Get user by user name * * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return Call + * @return Call<User> */ - @GET("user/{username}") + @GET("/user/{username}") Observable getUserByName( @Path("username") String username ); @@ -81,10 +81,10 @@ Observable getUserByName( * * @param username The user name for login (required) * @param password The password for login in clear text (required) - * @return Call + * @return Call<String> */ - @GET("user/login") + @GET("/user/login") Observable loginUser( @Query("username") String username, @Query("password") String password ); @@ -92,11 +92,11 @@ Observable loginUser( /** * Logs out current logged in user session * - * @return Call + * @return Call<Object> */ - @GET("user/logout") - Observable logoutUser(); + @GET("/user/logout") + Observable logoutUser(); /** @@ -104,11 +104,11 @@ Observable loginUser( * This can only be done by the logged in user. * @param username name that need to be deleted (required) * @param body Updated user object (required) - * @return Call + * @return Call<Object> */ - @PUT("user/{username}") - Observable updateUser( + @PUT("/user/{username}") + Observable updateUser( @Path("username") String username, @Body User body ); diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/Authentication.java new file mode 100644 index 00000000000..221a7d9dd1f --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/Authentication.java @@ -0,0 +1,41 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + +public interface Authentication { + /** + * Apply authentication settings to header and query params. + * + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + */ + void applyToParams(List queryParams, Map headerParams); +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java deleted file mode 100644 index c9b6e124d51..00000000000 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java +++ /dev/null @@ -1,72 +0,0 @@ -package io.swagger.client.auth; - -import java.io.IOException; -import java.util.Map; -import java.util.Map.Entry; - -import org.apache.oltu.oauth2.client.HttpClient; -import org.apache.oltu.oauth2.client.request.OAuthClientRequest; -import org.apache.oltu.oauth2.client.response.OAuthClientResponse; -import org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory; -import org.apache.oltu.oauth2.common.exception.OAuthProblemException; -import org.apache.oltu.oauth2.common.exception.OAuthSystemException; - - -import okhttp3.Interceptor; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Request.Builder; -import okhttp3.Response; -import okhttp3.MediaType; -import okhttp3.RequestBody; - - -public class OAuthOkHttpClient implements HttpClient { - - private OkHttpClient client; - - public OAuthOkHttpClient() { - this.client = new OkHttpClient(); - } - - public OAuthOkHttpClient(OkHttpClient client) { - this.client = client; - } - - public T execute(OAuthClientRequest request, Map headers, - String requestMethod, Class responseClass) - throws OAuthSystemException, OAuthProblemException { - - MediaType mediaType = MediaType.parse("application/json"); - Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri()); - - if(headers != null) { - for (Entry entry : headers.entrySet()) { - if (entry.getKey().equalsIgnoreCase("Content-Type")) { - mediaType = MediaType.parse(entry.getValue()); - } else { - requestBuilder.addHeader(entry.getKey(), entry.getValue()); - } - } - } - - RequestBody body = request.getBody() != null ? RequestBody.create(mediaType, request.getBody()) : null; - requestBuilder.method(requestMethod, body); - - try { - Response response = client.newCall(requestBuilder.build()).execute(); - return OAuthClientResponseFactory.createCustomResponse( - response.body().string(), - response.body().contentType().toString(), - response.code(), - responseClass); - } catch (IOException e) { - throw new OAuthSystemException(e); - } - } - - public void shutdown() { - // Nothing to do here - } - -} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayTest.java index b853a0b035a..8d58870bcdc 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayTest.java @@ -48,31 +48,6 @@ public class ArrayTest { @SerializedName("array_array_of_model") private List> arrayArrayOfModel = new ArrayList>(); - /** - * Gets or Sets arrayOfEnum - */ - public enum ArrayOfEnumEnum { - @SerializedName("UPPER") - UPPER("UPPER"), - - @SerializedName("lower") - LOWER("lower"); - - private String value; - - ArrayOfEnumEnum(String value) { - this.value = value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - } - - @SerializedName("array_of_enum") - private List arrayOfEnum = new ArrayList(); - public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; return this; @@ -127,24 +102,6 @@ public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } - public ArrayTest arrayOfEnum(List arrayOfEnum) { - this.arrayOfEnum = arrayOfEnum; - return this; - } - - /** - * Get arrayOfEnum - * @return arrayOfEnum - **/ - @ApiModelProperty(example = "null", value = "") - public List getArrayOfEnum() { - return arrayOfEnum; - } - - public void setArrayOfEnum(List arrayOfEnum) { - this.arrayOfEnum = arrayOfEnum; - } - @Override public boolean equals(java.lang.Object o) { @@ -157,13 +114,12 @@ public boolean equals(java.lang.Object o) { ArrayTest arrayTest = (ArrayTest) o; return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && - Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel) && - Objects.equals(this.arrayOfEnum, arrayTest.arrayOfEnum); + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); } @Override public int hashCode() { - return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel, arrayOfEnum); + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); } @Override @@ -174,7 +130,6 @@ public String toString() { sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); - sb.append(" arrayOfEnum: ").append(toIndentedString(arrayOfEnum)).append("\n"); sb.append("}"); return sb.toString(); } From c5cc0bbb2a448e3487f948988e8a4b3b17faeae1 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 7 Jul 2016 15:29:13 +0800 Subject: [PATCH 070/470] fix issue with java feign client --- .../codegen/languages/JavaClientCodegen.java | 11 +- .../main/resources/Java/build.sbt.mustache | 0 .../java/io/swagger/client/ApiCallback.java | 74 - .../java/io/swagger/client/ApiException.java | 103 - .../java/io/swagger/client/ApiResponse.java | 71 - .../java/io/swagger/client/Configuration.java | 51 - .../io/swagger/client/FormAwareEncoder.java | 197 ++ .../src/main/java/io/swagger/client/JSON.java | 237 -- .../src/main/java/io/swagger/client/Pair.java | 64 - .../swagger/client/ProgressRequestBody.java | 95 - .../swagger/client/ProgressResponseBody.java | 88 - .../swagger/client/auth/Authentication.java | 41 - .../model/AdditionalPropertiesClass.java | 6 +- .../java/io/swagger/client/model/Animal.java | 6 +- .../model/ArrayOfArrayOfNumberOnly.java | 4 +- .../client/model/ArrayOfNumberOnly.java | 4 +- .../io/swagger/client/model/ArrayTest.java | 8 +- .../java/io/swagger/client/model/Cat.java | 8 +- .../io/swagger/client/model/Category.java | 6 +- .../java/io/swagger/client/model/Dog.java | 8 +- .../io/swagger/client/model/EnumClass.java | 4 - .../io/swagger/client/model/EnumTest.java | 14 +- .../io/swagger/client/model/FormatTest.java | 28 +- .../swagger/client/model/HasOnlyReadOnly.java | 6 +- .../java/io/swagger/client/model/MapTest.java | 8 +- ...ropertiesAndAdditionalPropertiesClass.java | 8 +- .../client/model/Model200Response.java | 6 +- .../client/model/ModelApiResponse.java | 8 +- .../io/swagger/client/model/ModelReturn.java | 4 +- .../java/io/swagger/client/model/Name.java | 10 +- .../io/swagger/client/model/NumberOnly.java | 4 +- .../java/io/swagger/client/model/Order.java | 17 +- .../java/io/swagger/client/model/Pet.java | 17 +- .../swagger/client/model/ReadOnlyFirst.java | 6 +- .../client/model/SpecialModelName.java | 4 +- .../java/io/swagger/client/model/Tag.java | 6 +- .../java/io/swagger/client/model/User.java | 18 +- .../client/petstore/java/jersey1/build.gradle | 39 +- .../client/petstore/java/jersey1/build.sbt | 20 - samples/client/petstore/java/jersey1/pom.xml | 79 +- .../java/io/swagger/client/ApiCallback.java | 74 - .../java/io/swagger/client/ApiClient.java | 1905 ++++++---------- .../java/io/swagger/client/ApiResponse.java | 71 - .../src/main/java/io/swagger/client/JSON.java | 237 -- .../swagger/client/ProgressRequestBody.java | 95 - .../swagger/client/ProgressResponseBody.java | 88 - .../java/io/swagger/client/api/FakeApi.java | 460 ++-- .../java/io/swagger/client/api/PetApi.java | 1263 ++++------- .../java/io/swagger/client/api/StoreApi.java | 626 ++---- .../java/io/swagger/client/api/UserApi.java | 1225 +++------- .../io/swagger/client/auth/HttpBasicAuth.java | 50 +- .../model/AdditionalPropertiesClass.java | 6 +- .../java/io/swagger/client/model/Animal.java | 6 +- .../model/ArrayOfArrayOfNumberOnly.java | 4 +- .../client/model/ArrayOfNumberOnly.java | 4 +- .../io/swagger/client/model/ArrayTest.java | 8 +- .../java/io/swagger/client/model/Cat.java | 8 +- .../io/swagger/client/model/Category.java | 6 +- .../java/io/swagger/client/model/Dog.java | 8 +- .../io/swagger/client/model/EnumClass.java | 4 - .../io/swagger/client/model/EnumTest.java | 14 +- .../io/swagger/client/model/FormatTest.java | 28 +- .../swagger/client/model/HasOnlyReadOnly.java | 6 +- .../java/io/swagger/client/model/MapTest.java | 8 +- ...ropertiesAndAdditionalPropertiesClass.java | 8 +- .../client/model/Model200Response.java | 6 +- .../client/model/ModelApiResponse.java | 8 +- .../io/swagger/client/model/ModelReturn.java | 4 +- .../java/io/swagger/client/model/Name.java | 10 +- .../io/swagger/client/model/NumberOnly.java | 4 +- .../java/io/swagger/client/model/Order.java | 17 +- .../java/io/swagger/client/model/Pet.java | 17 +- .../swagger/client/model/ReadOnlyFirst.java | 6 +- .../client/model/SpecialModelName.java | 4 +- .../java/io/swagger/client/model/Tag.java | 6 +- .../java/io/swagger/client/model/User.java | 18 +- .../petstore/java/jersey2-java8/build.gradle | 27 +- .../petstore/java/jersey2-java8/build.sbt | 11 +- .../petstore/java/jersey2-java8/pom.xml | 72 +- .../java/io/swagger/client/ApiCallback.java | 74 - .../java/io/swagger/client/ApiClient.java | 1964 ++++++----------- .../java/io/swagger/client/ApiResponse.java | 71 - .../src/main/java/io/swagger/client/JSON.java | 256 +-- .../swagger/client/ProgressRequestBody.java | 95 - .../swagger/client/ProgressResponseBody.java | 88 - .../java/io/swagger/client/api/FakeApi.java | 480 ++-- .../java/io/swagger/client/api/PetApi.java | 1283 +++-------- .../java/io/swagger/client/api/StoreApi.java | 646 ++---- .../java/io/swagger/client/api/UserApi.java | 1245 +++-------- .../io/swagger/client/auth/HttpBasicAuth.java | 50 +- .../model/AdditionalPropertiesClass.java | 6 +- .../java/io/swagger/client/model/Animal.java | 6 +- .../model/ArrayOfArrayOfNumberOnly.java | 4 +- .../client/model/ArrayOfNumberOnly.java | 4 +- .../io/swagger/client/model/ArrayTest.java | 8 +- .../java/io/swagger/client/model/Cat.java | 8 +- .../io/swagger/client/model/Category.java | 6 +- .../java/io/swagger/client/model/Dog.java | 8 +- .../io/swagger/client/model/EnumClass.java | 4 - .../io/swagger/client/model/EnumTest.java | 14 +- .../io/swagger/client/model/FormatTest.java | 28 +- .../swagger/client/model/HasOnlyReadOnly.java | 6 +- .../java/io/swagger/client/model/MapTest.java | 8 +- ...ropertiesAndAdditionalPropertiesClass.java | 8 +- .../client/model/Model200Response.java | 6 +- .../client/model/ModelApiResponse.java | 8 +- .../io/swagger/client/model/ModelReturn.java | 4 +- .../java/io/swagger/client/model/Name.java | 10 +- .../io/swagger/client/model/NumberOnly.java | 4 +- .../java/io/swagger/client/model/Order.java | 17 +- .../java/io/swagger/client/model/Pet.java | 17 +- .../swagger/client/model/ReadOnlyFirst.java | 6 +- .../client/model/SpecialModelName.java | 4 +- .../java/io/swagger/client/model/Tag.java | 6 +- .../java/io/swagger/client/model/User.java | 18 +- .../client/petstore/java/jersey2/build.gradle | 26 +- .../client/petstore/java/jersey2/build.sbt | 13 +- samples/client/petstore/java/jersey2/pom.xml | 73 +- .../java/io/swagger/client/ApiCallback.java | 74 - .../java/io/swagger/client/ApiClient.java | 1964 ++++++----------- .../java/io/swagger/client/ApiResponse.java | 71 - .../src/main/java/io/swagger/client/JSON.java | 253 +-- .../swagger/client/ProgressRequestBody.java | 95 - .../swagger/client/ProgressResponseBody.java | 88 - .../java/io/swagger/client/api/FakeApi.java | 480 ++-- .../java/io/swagger/client/api/PetApi.java | 1283 +++-------- .../java/io/swagger/client/api/StoreApi.java | 646 ++---- .../java/io/swagger/client/api/UserApi.java | 1245 +++-------- .../io/swagger/client/auth/HttpBasicAuth.java | 50 +- .../model/AdditionalPropertiesClass.java | 6 +- .../java/io/swagger/client/model/Animal.java | 6 +- .../model/ArrayOfArrayOfNumberOnly.java | 4 +- .../client/model/ArrayOfNumberOnly.java | 4 +- .../io/swagger/client/model/ArrayTest.java | 8 +- .../java/io/swagger/client/model/Cat.java | 8 +- .../io/swagger/client/model/Category.java | 6 +- .../java/io/swagger/client/model/Dog.java | 8 +- .../io/swagger/client/model/EnumClass.java | 4 - .../io/swagger/client/model/EnumTest.java | 14 +- .../io/swagger/client/model/FormatTest.java | 28 +- .../swagger/client/model/HasOnlyReadOnly.java | 6 +- .../java/io/swagger/client/model/MapTest.java | 8 +- ...ropertiesAndAdditionalPropertiesClass.java | 8 +- .../client/model/Model200Response.java | 6 +- .../client/model/ModelApiResponse.java | 8 +- .../io/swagger/client/model/ModelReturn.java | 4 +- .../java/io/swagger/client/model/Name.java | 10 +- .../io/swagger/client/model/NumberOnly.java | 4 +- .../java/io/swagger/client/model/Order.java | 17 +- .../java/io/swagger/client/model/Pet.java | 17 +- .../swagger/client/model/ReadOnlyFirst.java | 6 +- .../client/model/SpecialModelName.java | 4 +- .../java/io/swagger/client/model/Tag.java | 6 +- .../java/io/swagger/client/model/User.java | 18 +- .../petstore/java/retrofit/build.gradle | 37 +- .../client/petstore/java/retrofit/build.sbt | 8 +- samples/client/petstore/java/retrofit/pom.xml | 39 +- .../java/io/swagger/client/ApiCallback.java | 74 - .../java/io/swagger/client/ApiClient.java | 1463 +++--------- .../java/io/swagger/client/ApiException.java | 103 - .../java/io/swagger/client/ApiResponse.java | 71 - .../io/swagger/client/CollectionFormats.java | 95 + .../java/io/swagger/client/Configuration.java | 51 - .../src/main/java/io/swagger/client/JSON.java | 237 -- .../src/main/java/io/swagger/client/Pair.java | 64 - .../swagger/client/ProgressRequestBody.java | 95 - .../swagger/client/ProgressResponseBody.java | 88 - .../java/io/swagger/client/api/FakeApi.java | 424 +--- .../java/io/swagger/client/api/PetApi.java | 1140 ++-------- .../java/io/swagger/client/api/StoreApi.java | 572 +---- .../java/io/swagger/client/api/UserApi.java | 1101 ++------- .../io/swagger/client/auth/ApiKeyAuth.java | 125 +- .../swagger/client/auth/Authentication.java | 41 - .../io/swagger/client/auth/HttpBasicAuth.java | 59 +- .../java/io/swagger/client/auth/OAuth.java | 205 +- .../client/auth/OAuthOkHttpClient.java | 69 + .../petstore/java/retrofit2/docs/FakeApi.md | 18 +- .../petstore/java/retrofit2/docs/PetApi.md | 44 +- .../petstore/java/retrofit2/docs/StoreApi.md | 15 +- .../petstore/java/retrofit2/docs/UserApi.md | 58 +- .../java/io/swagger/client/ApiCallback.java | 74 - .../java/io/swagger/client/ApiException.java | 103 - .../java/io/swagger/client/ApiResponse.java | 71 - .../io/swagger/client/CollectionFormats.java | 95 + .../java/io/swagger/client/Configuration.java | 51 - .../src/main/java/io/swagger/client/JSON.java | 237 -- .../src/main/java/io/swagger/client/Pair.java | 64 - .../swagger/client/ProgressRequestBody.java | 95 - .../swagger/client/ProgressResponseBody.java | 88 - .../java/io/swagger/client/api/FakeApi.java | 12 +- .../java/io/swagger/client/api/PetApi.java | 36 +- .../java/io/swagger/client/api/StoreApi.java | 12 +- .../java/io/swagger/client/api/UserApi.java | 40 +- .../swagger/client/auth/Authentication.java | 41 - .../client/auth/OAuthOkHttpClient.java | 72 + .../petstore/java/retrofit2rx/docs/FakeApi.md | 18 +- .../petstore/java/retrofit2rx/docs/PetApi.md | 44 +- .../java/retrofit2rx/docs/StoreApi.md | 15 +- .../petstore/java/retrofit2rx/docs/UserApi.md | 58 +- .../java/io/swagger/client/ApiCallback.java | 74 - .../java/io/swagger/client/ApiException.java | 103 - .../java/io/swagger/client/ApiResponse.java | 71 - .../io/swagger/client/CollectionFormats.java | 95 + .../java/io/swagger/client/Configuration.java | 51 - .../src/main/java/io/swagger/client/JSON.java | 237 -- .../src/main/java/io/swagger/client/Pair.java | 64 - .../swagger/client/ProgressRequestBody.java | 95 - .../swagger/client/ProgressResponseBody.java | 88 - .../java/io/swagger/client/api/FakeApi.java | 12 +- .../java/io/swagger/client/api/PetApi.java | 36 +- .../java/io/swagger/client/api/StoreApi.java | 12 +- .../java/io/swagger/client/api/UserApi.java | 40 +- .../swagger/client/auth/Authentication.java | 41 - .../client/auth/OAuthOkHttpClient.java | 72 + 214 files changed, 8022 insertions(+), 21450 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/Java/build.sbt.mustache delete mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiCallback.java delete mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiException.java delete mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiResponse.java delete mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/Configuration.java create mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java delete mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/JSON.java delete mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/Pair.java delete mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/ProgressRequestBody.java delete mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/ProgressResponseBody.java delete mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/Authentication.java delete mode 100644 samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiCallback.java delete mode 100644 samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiResponse.java delete mode 100644 samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/JSON.java delete mode 100644 samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ProgressRequestBody.java delete mode 100644 samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ProgressResponseBody.java delete mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiCallback.java delete mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiResponse.java delete mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ProgressRequestBody.java delete mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ProgressResponseBody.java delete mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiCallback.java delete mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiResponse.java delete mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ProgressRequestBody.java delete mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ProgressResponseBody.java delete mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiCallback.java delete mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiException.java delete mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiResponse.java create mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/CollectionFormats.java delete mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/Configuration.java delete mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/JSON.java delete mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/Pair.java delete mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ProgressRequestBody.java delete mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ProgressResponseBody.java delete mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/Authentication.java create mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java delete mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiCallback.java delete mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiException.java delete mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiResponse.java create mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/CollectionFormats.java delete mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/Configuration.java delete mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/JSON.java delete mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/Pair.java delete mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ProgressRequestBody.java delete mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ProgressResponseBody.java delete mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/Authentication.java create mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java delete mode 100644 samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiCallback.java delete mode 100644 samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiException.java delete mode 100644 samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiResponse.java create mode 100644 samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/CollectionFormats.java delete mode 100644 samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/Configuration.java delete mode 100644 samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/JSON.java delete mode 100644 samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/Pair.java delete mode 100644 samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ProgressRequestBody.java delete mode 100644 samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ProgressResponseBody.java delete mode 100644 samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/Authentication.java create mode 100644 samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java 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 c365f2b7035..09dbb97ab7c 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 @@ -78,6 +78,7 @@ public void processOpts() { writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md")); writeOptional(outputFolder, new SupportingFile("build.gradle.mustache", "", "build.gradle")); + writeOptional(outputFolder, new SupportingFile("build.sbt.mustache", "", "build.sbt")); writeOptional(outputFolder, new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); writeOptional(outputFolder, new SupportingFile("gradle.properties.mustache", "", "gradle.properties")); writeOptional(outputFolder, new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml")); @@ -97,14 +98,6 @@ public void processOpts() { supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); - if (!StringUtils.isEmpty(getLibrary())) { - // set library to okhttp-gson as default - setLibrary("okhttp-gson"); - - //TODO: add sbt support to default client - supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); - } - //TODO: add doc to retrofit1 and feign if ( "feign".equals(getLibrary()) || "retrofit".equals(getLibrary()) ){ modelDocTemplateFiles.remove("model_doc.mustache"); @@ -139,7 +132,7 @@ public void processOpts() { } else if("jersey1".equals(getLibrary())) { additionalProperties.put("jackson", "true"); } else { - LOGGER.error("Unknown library option (-l/--library): " + StringUtils.isEmpty(getLibrary())); + LOGGER.error("Unknown library option (-l/--library): " + getLibrary()); } } diff --git a/modules/swagger-codegen/src/main/resources/Java/build.sbt.mustache b/modules/swagger-codegen/src/main/resources/Java/build.sbt.mustache new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiCallback.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiCallback.java deleted file mode 100644 index 3ca33cf8017..00000000000 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiCallback.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import java.io.IOException; - -import java.util.Map; -import java.util.List; - -/** - * Callback for asynchronous API call. - * - * @param The return type - */ -public interface ApiCallback { - /** - * This is called when the API call fails. - * - * @param e The exception causing the failure - * @param statusCode Status code of the response if available, otherwise it would be 0 - * @param responseHeaders Headers of the response if available, otherwise it would be null - */ - void onFailure(ApiException e, int statusCode, Map> responseHeaders); - - /** - * This is called when the API call succeeded. - * - * @param result The result deserialized from response - * @param statusCode Status code of the response - * @param responseHeaders Headers of the response - */ - void onSuccess(T result, int statusCode, Map> responseHeaders); - - /** - * This is called when the API upload processing. - * - * @param bytesWritten bytes Written - * @param contentLength content length of request body - * @param done write end - */ - void onUploadProgress(long bytesWritten, long contentLength, boolean done); - - /** - * This is called when the API downlond processing. - * - * @param bytesRead bytes Read - * @param contentLength content lenngth of the response - * @param done Read end - */ - void onDownloadProgress(long bytesRead, long contentLength, boolean done); -} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiException.java deleted file mode 100644 index 3bed001f002..00000000000 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiException.java +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import java.util.Map; -import java.util.List; - - -public class ApiException extends Exception { - private int code = 0; - private Map> responseHeaders = null; - private String responseBody = null; - - public ApiException() {} - - public ApiException(Throwable throwable) { - super(throwable); - } - - public ApiException(String message) { - super(message); - } - - public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { - super(message, throwable); - this.code = code; - this.responseHeaders = responseHeaders; - this.responseBody = responseBody; - } - - public ApiException(String message, int code, Map> responseHeaders, String responseBody) { - this(message, (Throwable) null, code, responseHeaders, responseBody); - } - - public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { - this(message, throwable, code, responseHeaders, null); - } - - public ApiException(int code, Map> responseHeaders, String responseBody) { - this((String) null, (Throwable) null, code, responseHeaders, responseBody); - } - - public ApiException(int code, String message) { - super(message); - this.code = code; - } - - public ApiException(int code, String message, Map> responseHeaders, String responseBody) { - this(code, message); - this.responseHeaders = responseHeaders; - this.responseBody = responseBody; - } - - /** - * Get the HTTP status code. - * - * @return HTTP status code - */ - public int getCode() { - return code; - } - - /** - * Get the HTTP response headers. - * - * @return A map of list of string - */ - public Map> getResponseHeaders() { - return responseHeaders; - } - - /** - * Get the HTTP response body. - * - * @return Response body in the form of string - */ - public String getResponseBody() { - return responseBody; - } -} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiResponse.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiResponse.java deleted file mode 100644 index d7dde1ee939..00000000000 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiResponse.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import java.util.List; -import java.util.Map; - -/** - * API response returned by API call. - * - * @param T The type of data that is deserialized from response body - */ -public class ApiResponse { - final private int statusCode; - final private Map> headers; - final private T data; - - /** - * @param statusCode The status code of HTTP response - * @param headers The headers of HTTP response - */ - public ApiResponse(int statusCode, Map> headers) { - this(statusCode, headers, null); - } - - /** - * @param statusCode The status code of HTTP response - * @param headers The headers of HTTP response - * @param data The object deserialized from response bod - */ - public ApiResponse(int statusCode, Map> headers, T data) { - this.statusCode = statusCode; - this.headers = headers; - this.data = data; - } - - public int getStatusCode() { - return statusCode; - } - - public Map> getHeaders() { - return headers; - } - - public T getData() { - return data; - } -} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/Configuration.java deleted file mode 100644 index 5191b9b73c6..00000000000 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/Configuration.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - - -public class Configuration { - private static ApiClient defaultApiClient = new ApiClient(); - - /** - * Get the default API client, which would be used when creating API - * instances without providing an API client. - * - * @return Default API client - */ - public static ApiClient getDefaultApiClient() { - return defaultApiClient; - } - - /** - * Set the default API client, which would be used when creating API - * instances without providing an API client. - * - * @param apiClient API client - */ - public static void setDefaultApiClient(ApiClient apiClient) { - defaultApiClient = apiClient; - } -} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java new file mode 100644 index 00000000000..179a2834da9 --- /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; + + +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/JSON.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/JSON.java deleted file mode 100644 index 540611eab9d..00000000000 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/JSON.java +++ /dev/null @@ -1,237 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonNull; -import com.google.gson.JsonParseException; -import com.google.gson.JsonPrimitive; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; - -import java.io.IOException; -import java.io.StringReader; -import java.lang.reflect.Type; -import java.util.Date; - -import org.joda.time.DateTime; -import org.joda.time.LocalDate; -import org.joda.time.format.DateTimeFormatter; -import org.joda.time.format.ISODateTimeFormat; - -public class JSON { - private ApiClient apiClient; - private Gson gson; - - /** - * JSON constructor. - * - * @param apiClient An instance of ApiClient - */ - public JSON(ApiClient apiClient) { - this.apiClient = apiClient; - gson = new GsonBuilder() - .registerTypeAdapter(Date.class, new DateAdapter(apiClient)) - .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) - .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) - .create(); - } - - /** - * Get Gson. - * - * @return Gson - */ - public Gson getGson() { - return gson; - } - - /** - * Set Gson. - * - * @param gson Gson - */ - public void setGson(Gson gson) { - this.gson = gson; - } - - /** - * Serialize the given Java object into JSON string. - * - * @param obj Object - * @return String representation of the JSON - */ - public String serialize(Object obj) { - return gson.toJson(obj); - } - - /** - * Deserialize the given JSON string to Java object. - * - * @param Type - * @param body The JSON string - * @param returnType The type to deserialize inot - * @return The deserialized Java object - */ - @SuppressWarnings("unchecked") - public T deserialize(String body, Type returnType) { - try { - if (apiClient.isLenientOnJson()) { - JsonReader jsonReader = new JsonReader(new StringReader(body)); - // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) - jsonReader.setLenient(true); - return gson.fromJson(jsonReader, returnType); - } else { - return gson.fromJson(body, returnType); - } - } catch (JsonParseException e) { - // Fallback processing when failed to parse JSON form response body: - // return the response body string directly for the String return type; - // parse response body into date or datetime for the Date return type. - if (returnType.equals(String.class)) - return (T) body; - else if (returnType.equals(Date.class)) - return (T) apiClient.parseDateOrDatetime(body); - else throw(e); - } - } -} - -class DateAdapter implements JsonSerializer, JsonDeserializer { - private final ApiClient apiClient; - - /** - * Constructor for DateAdapter - * - * @param apiClient Api client - */ - public DateAdapter(ApiClient apiClient) { - super(); - this.apiClient = apiClient; - } - - /** - * Serialize - * - * @param src Date - * @param typeOfSrc Type - * @param context Json Serialization Context - * @return Json Element - */ - @Override - public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { - if (src == null) { - return JsonNull.INSTANCE; - } else { - return new JsonPrimitive(apiClient.formatDatetime(src)); - } - } - - /** - * Deserialize - * - * @param json Json element - * @param date Type - * @param typeOfSrc Type - * @param context Json Serialization Context - * @return Date - * @throw JsonParseException if fail to parse - */ - @Override - public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException { - String str = json.getAsJsonPrimitive().getAsString(); - try { - return apiClient.parseDateOrDatetime(str); - } catch (RuntimeException e) { - throw new JsonParseException(e); - } - } -} - -/** - * Gson TypeAdapter for Joda DateTime type - */ -class DateTimeTypeAdapter extends TypeAdapter { - - private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); - - @Override - public void write(JsonWriter out, DateTime date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - out.value(formatter.print(date)); - } - } - - @Override - public DateTime read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - return formatter.parseDateTime(date); - } - } -} - -/** - * Gson TypeAdapter for Joda LocalDate type - */ -class LocalDateTypeAdapter extends TypeAdapter { - - private final DateTimeFormatter formatter = ISODateTimeFormat.date(); - - @Override - public void write(JsonWriter out, LocalDate date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - out.value(formatter.print(date)); - } - } - - @Override - public LocalDate read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - return formatter.parseLocalDate(date); - } - } -} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/Pair.java deleted file mode 100644 index 15b247eea93..00000000000 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/Pair.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - - -public class Pair { - private String name = ""; - private String value = ""; - - public Pair (String name, String value) { - setName(name); - setValue(value); - } - - private void setName(String name) { - if (!isValidString(name)) return; - - this.name = name; - } - - private void setValue(String value) { - if (!isValidString(value)) return; - - this.value = value; - } - - public String getName() { - return this.name; - } - - public String getValue() { - return this.value; - } - - private boolean isValidString(String arg) { - if (arg == null) return false; - if (arg.trim().isEmpty()) return false; - - return true; - } -} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ProgressRequestBody.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ProgressRequestBody.java deleted file mode 100644 index d9ca742ecd2..00000000000 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ProgressRequestBody.java +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import com.squareup.okhttp.MediaType; -import com.squareup.okhttp.RequestBody; - -import java.io.IOException; - -import okio.Buffer; -import okio.BufferedSink; -import okio.ForwardingSink; -import okio.Okio; -import okio.Sink; - -public class ProgressRequestBody extends RequestBody { - - public interface ProgressRequestListener { - void onRequestProgress(long bytesWritten, long contentLength, boolean done); - } - - private final RequestBody requestBody; - - private final ProgressRequestListener progressListener; - - private BufferedSink bufferedSink; - - public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) { - this.requestBody = requestBody; - this.progressListener = progressListener; - } - - @Override - public MediaType contentType() { - return requestBody.contentType(); - } - - @Override - public long contentLength() throws IOException { - return requestBody.contentLength(); - } - - @Override - public void writeTo(BufferedSink sink) throws IOException { - if (bufferedSink == null) { - bufferedSink = Okio.buffer(sink(sink)); - } - - requestBody.writeTo(bufferedSink); - bufferedSink.flush(); - - } - - private Sink sink(Sink sink) { - return new ForwardingSink(sink) { - - long bytesWritten = 0L; - long contentLength = 0L; - - @Override - public void write(Buffer source, long byteCount) throws IOException { - super.write(source, byteCount); - if (contentLength == 0) { - contentLength = contentLength(); - } - - bytesWritten += byteCount; - progressListener.onRequestProgress(bytesWritten, contentLength, bytesWritten == contentLength); - } - }; - } -} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ProgressResponseBody.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ProgressResponseBody.java deleted file mode 100644 index f8af685999d..00000000000 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ProgressResponseBody.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import com.squareup.okhttp.MediaType; -import com.squareup.okhttp.ResponseBody; - -import java.io.IOException; - -import okio.Buffer; -import okio.BufferedSource; -import okio.ForwardingSource; -import okio.Okio; -import okio.Source; - -public class ProgressResponseBody extends ResponseBody { - - public interface ProgressListener { - void update(long bytesRead, long contentLength, boolean done); - } - - private final ResponseBody responseBody; - private final ProgressListener progressListener; - private BufferedSource bufferedSource; - - public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) { - this.responseBody = responseBody; - this.progressListener = progressListener; - } - - @Override - public MediaType contentType() { - return responseBody.contentType(); - } - - @Override - public long contentLength() throws IOException { - return responseBody.contentLength(); - } - - @Override - public BufferedSource source() throws IOException { - if (bufferedSource == null) { - bufferedSource = Okio.buffer(source(responseBody.source())); - } - return bufferedSource; - } - - private Source source(Source source) { - return new ForwardingSource(source) { - long totalBytesRead = 0L; - - @Override - public long read(Buffer sink, long byteCount) throws IOException { - long bytesRead = super.read(sink, byteCount); - // read() returns the number of bytes read, or -1 if this source is exhausted. - totalBytesRead += bytesRead != -1 ? bytesRead : 0; - progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1); - return bytesRead; - } - }; - } -} - - diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/Authentication.java deleted file mode 100644 index 221a7d9dd1f..00000000000 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/Authentication.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client.auth; - -import io.swagger.client.Pair; - -import java.util.Map; -import java.util.List; - -public interface Authentication { - /** - * Apply authentication settings to header and query params. - * - * @param queryParams List of query parameters - * @param headerParams Map of header parameters - */ - void applyToParams(List queryParams, Map headerParams); -} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 1943e013fa1..1e2d40891a2 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; @@ -39,10 +39,10 @@ */ public class AdditionalPropertiesClass { - @SerializedName("map_property") + @JsonProperty("map_property") private Map mapProperty = new HashMap(); - @SerializedName("map_of_map_property") + @JsonProperty("map_of_map_property") private Map> mapOfMapProperty = new HashMap>(); public AdditionalPropertiesClass mapProperty(Map mapProperty) { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java index ba3806dc875..3ed2c6d9660 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,10 +36,10 @@ */ public class Animal { - @SerializedName("className") + @JsonProperty("className") private String className = null; - @SerializedName("color") + @JsonProperty("color") private String color = "red"; public Animal className(String className) { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 5446c2c439b..4d0dc41ee70 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; @@ -39,7 +39,7 @@ */ public class ArrayOfArrayOfNumberOnly { - @SerializedName("ArrayArrayNumber") + @JsonProperty("ArrayArrayNumber") private List> arrayArrayNumber = new ArrayList>(); public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index c9257a5d3ee..bd3f05a2ad4 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; @@ -39,7 +39,7 @@ */ public class ArrayOfNumberOnly { - @SerializedName("ArrayNumber") + @JsonProperty("ArrayNumber") private List arrayNumber = new ArrayList(); public ArrayOfNumberOnly arrayNumber(List arrayNumber) { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayTest.java index 8d58870bcdc..900b8375eb0 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayTest.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.ReadOnlyFirst; @@ -39,13 +39,13 @@ */ public class ArrayTest { - @SerializedName("array_of_string") + @JsonProperty("array_of_string") private List arrayOfString = new ArrayList(); - @SerializedName("array_array_of_integer") + @JsonProperty("array_array_of_integer") private List> arrayArrayOfInteger = new ArrayList>(); - @SerializedName("array_array_of_model") + @JsonProperty("array_array_of_model") private List> arrayArrayOfModel = new ArrayList>(); public ArrayTest arrayOfString(List arrayOfString) { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java index 21ed0f4c26b..f39b159f0b4 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -37,13 +37,13 @@ */ public class Cat extends Animal { - @SerializedName("className") + @JsonProperty("className") private String className = null; - @SerializedName("color") + @JsonProperty("color") private String color = "red"; - @SerializedName("declawed") + @JsonProperty("declawed") private Boolean declawed = null; public Cat className(String className) { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java index 2178a866f62..c9bbbf525c5 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,10 +36,10 @@ */ public class Category { - @SerializedName("id") + @JsonProperty("id") private Long id = null; - @SerializedName("name") + @JsonProperty("name") private String name = null; public Category id(Long id) { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java index 4ba5804553f..dbcd1a7207b 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -37,13 +37,13 @@ */ public class Dog extends Animal { - @SerializedName("className") + @JsonProperty("className") private String className = null; - @SerializedName("color") + @JsonProperty("color") private String color = "red"; - @SerializedName("breed") + @JsonProperty("breed") private String breed = null; public Dog className(String className) { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumClass.java index 73484907229..4433dca5f48 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumClass.java @@ -26,7 +26,6 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; /** @@ -34,13 +33,10 @@ */ public enum EnumClass { - @SerializedName("_abc") _ABC("_abc"), - @SerializedName("-efg") _EFG("-efg"), - @SerializedName("(xyz)") _XYZ_("(xyz)"); private String value; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java index 9aad1223215..de36ef40ed4 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -40,10 +40,8 @@ public class EnumTest { * Gets or Sets enumString */ public enum EnumStringEnum { - @SerializedName("UPPER") UPPER("UPPER"), - @SerializedName("lower") LOWER("lower"); private String value; @@ -58,17 +56,15 @@ public String toString() { } } - @SerializedName("enum_string") + @JsonProperty("enum_string") private EnumStringEnum enumString = null; /** * Gets or Sets enumInteger */ public enum EnumIntegerEnum { - @SerializedName("1") NUMBER_1(1), - @SerializedName("-1") NUMBER_MINUS_1(-1); private Integer value; @@ -83,17 +79,15 @@ public String toString() { } } - @SerializedName("enum_integer") + @JsonProperty("enum_integer") private EnumIntegerEnum enumInteger = null; /** * Gets or Sets enumNumber */ public enum EnumNumberEnum { - @SerializedName("1.1") NUMBER_1_DOT_1(1.1), - @SerializedName("-1.2") NUMBER_MINUS_1_DOT_2(-1.2); private Double value; @@ -108,7 +102,7 @@ public String toString() { } } - @SerializedName("enum_number") + @JsonProperty("enum_number") private EnumNumberEnum enumNumber = null; public EnumTest enumString(EnumStringEnum enumString) { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java index 91109681509..9e17949ebc8 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; @@ -39,43 +39,43 @@ */ public class FormatTest { - @SerializedName("integer") + @JsonProperty("integer") private Integer integer = null; - @SerializedName("int32") + @JsonProperty("int32") private Integer int32 = null; - @SerializedName("int64") + @JsonProperty("int64") private Long int64 = null; - @SerializedName("number") + @JsonProperty("number") private BigDecimal number = null; - @SerializedName("float") + @JsonProperty("float") private Float _float = null; - @SerializedName("double") + @JsonProperty("double") private Double _double = null; - @SerializedName("string") + @JsonProperty("string") private String string = null; - @SerializedName("byte") + @JsonProperty("byte") private byte[] _byte = null; - @SerializedName("binary") + @JsonProperty("binary") private byte[] binary = null; - @SerializedName("date") + @JsonProperty("date") private LocalDate date = null; - @SerializedName("dateTime") + @JsonProperty("dateTime") private DateTime dateTime = null; - @SerializedName("uuid") + @JsonProperty("uuid") private String uuid = null; - @SerializedName("password") + @JsonProperty("password") private String password = null; public FormatTest integer(Integer integer) { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java index d77fc7ac36b..a3d01218197 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,10 +36,10 @@ */ public class HasOnlyReadOnly { - @SerializedName("bar") + @JsonProperty("bar") private String bar = null; - @SerializedName("foo") + @JsonProperty("foo") private String foo = null; /** diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MapTest.java index 61bdb6b2c65..6c0fc91ac41 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MapTest.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; @@ -39,17 +39,15 @@ */ public class MapTest { - @SerializedName("map_map_of_string") + @JsonProperty("map_map_of_string") private Map> mapMapOfString = new HashMap>(); /** * Gets or Sets inner */ public enum InnerEnum { - @SerializedName("UPPER") UPPER("UPPER"), - @SerializedName("lower") LOWER("lower"); private String value; @@ -64,7 +62,7 @@ public String toString() { } } - @SerializedName("map_of_enum_string") + @JsonProperty("map_of_enum_string") private Map mapOfEnumString = new HashMap(); public MapTest mapMapOfString(Map> mapMapOfString) { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 6e587b1bf97..c37d141f972 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -41,13 +41,13 @@ */ public class MixedPropertiesAndAdditionalPropertiesClass { - @SerializedName("uuid") + @JsonProperty("uuid") private String uuid = null; - @SerializedName("dateTime") + @JsonProperty("dateTime") private DateTime dateTime = null; - @SerializedName("map") + @JsonProperty("map") private Map map = new HashMap(); public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java index d8da58aca9c..3f4edf12daa 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -37,10 +37,10 @@ @ApiModel(description = "Model for testing model name starting with number") public class Model200Response { - @SerializedName("name") + @JsonProperty("name") private Integer name = null; - @SerializedName("class") + @JsonProperty("class") private String PropertyClass = null; public Model200Response name(Integer name) { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java index 2a823298323..7b86d07a148 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,13 +36,13 @@ */ public class ModelApiResponse { - @SerializedName("code") + @JsonProperty("code") private Integer code = null; - @SerializedName("type") + @JsonProperty("type") private String type = null; - @SerializedName("message") + @JsonProperty("message") private String message = null; public ModelApiResponse code(Integer code) { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java index 024a9c0df1c..e8762f850db 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -37,7 +37,7 @@ @ApiModel(description = "Model for testing reserved words") public class ModelReturn { - @SerializedName("return") + @JsonProperty("return") private Integer _return = null; public ModelReturn _return(Integer _return) { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java index 318a2ddd50e..de446cdf30d 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -37,16 +37,16 @@ @ApiModel(description = "Model for testing model name same as property name") public class Name { - @SerializedName("name") + @JsonProperty("name") private Integer name = null; - @SerializedName("snake_case") + @JsonProperty("snake_case") private Integer snakeCase = null; - @SerializedName("property") + @JsonProperty("property") private String property = null; - @SerializedName("123Number") + @JsonProperty("123Number") private Integer _123Number = null; public Name name(Integer name) { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/NumberOnly.java index 9b9ca048dfb..88c33f00f02 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/NumberOnly.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/NumberOnly.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; @@ -37,7 +37,7 @@ */ public class NumberOnly { - @SerializedName("JustNumber") + @JsonProperty("JustNumber") private BigDecimal justNumber = null; public NumberOnly justNumber(BigDecimal justNumber) { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java index 90cfd2f3892..ddebd7f8e48 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.joda.time.DateTime; @@ -37,29 +37,26 @@ */ public class Order { - @SerializedName("id") + @JsonProperty("id") private Long id = null; - @SerializedName("petId") + @JsonProperty("petId") private Long petId = null; - @SerializedName("quantity") + @JsonProperty("quantity") private Integer quantity = null; - @SerializedName("shipDate") + @JsonProperty("shipDate") private DateTime shipDate = null; /** * Order Status */ public enum StatusEnum { - @SerializedName("placed") PLACED("placed"), - @SerializedName("approved") APPROVED("approved"), - @SerializedName("delivered") DELIVERED("delivered"); private String value; @@ -74,10 +71,10 @@ public String toString() { } } - @SerializedName("status") + @JsonProperty("status") private StatusEnum status = null; - @SerializedName("complete") + @JsonProperty("complete") private Boolean complete = false; public Order id(Long id) { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java index b80fdeaf923..b468ebf1237 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Category; @@ -40,32 +40,29 @@ */ public class Pet { - @SerializedName("id") + @JsonProperty("id") private Long id = null; - @SerializedName("category") + @JsonProperty("category") private Category category = null; - @SerializedName("name") + @JsonProperty("name") private String name = null; - @SerializedName("photoUrls") + @JsonProperty("photoUrls") private List photoUrls = new ArrayList(); - @SerializedName("tags") + @JsonProperty("tags") private List tags = new ArrayList(); /** * pet status in the store */ public enum StatusEnum { - @SerializedName("available") AVAILABLE("available"), - @SerializedName("pending") PENDING("pending"), - @SerializedName("sold") SOLD("sold"); private String value; @@ -80,7 +77,7 @@ public String toString() { } } - @SerializedName("status") + @JsonProperty("status") private StatusEnum status = null; public Pet id(Long id) { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index 13b729bb94d..7f56ef2ff35 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,10 +36,10 @@ */ public class ReadOnlyFirst { - @SerializedName("bar") + @JsonProperty("bar") private String bar = null; - @SerializedName("baz") + @JsonProperty("baz") private String baz = null; /** diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java index b46b8367a01..bc4863f101a 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,7 +36,7 @@ */ public class SpecialModelName { - @SerializedName("$special[property.name]") + @JsonProperty("$special[property.name]") private Long specialPropertyName = null; public SpecialModelName specialPropertyName(Long specialPropertyName) { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java index e56eb535d1e..f27e45ea2aa 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,10 +36,10 @@ */ public class Tag { - @SerializedName("id") + @JsonProperty("id") private Long id = null; - @SerializedName("name") + @JsonProperty("name") private String name = null; public Tag id(Long id) { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java index 6c1ed6ceacc..7c0421fa09e 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,28 +36,28 @@ */ public class User { - @SerializedName("id") + @JsonProperty("id") private Long id = null; - @SerializedName("username") + @JsonProperty("username") private String username = null; - @SerializedName("firstName") + @JsonProperty("firstName") private String firstName = null; - @SerializedName("lastName") + @JsonProperty("lastName") private String lastName = null; - @SerializedName("email") + @JsonProperty("email") private String email = null; - @SerializedName("password") + @JsonProperty("password") private String password = null; - @SerializedName("phone") + @JsonProperty("phone") private String phone = null; - @SerializedName("userStatus") + @JsonProperty("userStatus") private Integer userStatus = null; public User id(Long id) { diff --git a/samples/client/petstore/java/jersey1/build.gradle b/samples/client/petstore/java/jersey1/build.gradle index 0ec352a14c8..1e4969e26fd 100644 --- a/samples/client/petstore/java/jersey1/build.gradle +++ b/samples/client/petstore/java/jersey1/build.gradle @@ -23,7 +23,7 @@ if(hasProperty('target') && target == 'android') { apply plugin: 'com.android.library' apply plugin: 'com.github.dcendents.android-maven' - + android { compileSdkVersion 23 buildToolsVersion '23.0.2' @@ -35,7 +35,7 @@ if(hasProperty('target') && target == 'android') { sourceCompatibility JavaVersion.VERSION_1_7 targetCompatibility JavaVersion.VERSION_1_7 } - + // Rename the aar correctly libraryVariants.all { variant -> variant.outputs.each { output -> @@ -51,7 +51,7 @@ if(hasProperty('target') && target == 'android') { provided 'javax.annotation:jsr250-api:1.0' } } - + afterEvaluate { android.libraryVariants.all { variant -> def task = project.tasks.create "jar${variant.name.capitalize()}", Jar @@ -63,12 +63,12 @@ if(hasProperty('target') && target == 'android') { artifacts.add('archives', task); } } - + task sourcesJar(type: Jar) { from android.sourceSets.main.java.srcDirs classifier = 'sources' } - + artifacts { archives sourcesJar } @@ -80,24 +80,37 @@ if(hasProperty('target') && target == 'android') { sourceCompatibility = JavaVersion.VERSION_1_7 targetCompatibility = JavaVersion.VERSION_1_7 - + install { repositories.mavenInstaller { pom.artifactId = 'swagger-java-client' } } - + task execute(type:JavaExec) { main = System.getProperty('mainClass') classpath = sourceSets.main.runtimeClasspath } } +ext { + swagger_annotations_version = "1.5.8" + jackson_version = "2.7.5" + jersey_version = "1.19.1" + jodatime_version = "2.9.4" + junit_version = "4.12" +} + dependencies { - compile 'io.swagger:swagger-annotations:1.5.8' - compile 'com.squareup.okhttp:okhttp:2.7.5' - compile 'com.squareup.okhttp:logging-interceptor:2.7.5' - compile 'com.google.code.gson:gson:2.6.2' - compile 'joda-time:joda-time:2.9.3' - testCompile 'junit:junit:4.12' + compile "io.swagger:swagger-annotations:$swagger_annotations_version" + compile "com.sun.jersey:jersey-client:$jersey_version" + compile "com.sun.jersey.contribs:jersey-multipart:$jersey_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.jaxrs:jackson-jaxrs-json-provider:$jackson_version" + compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version" + 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/jersey1/build.sbt b/samples/client/petstore/java/jersey1/build.sbt index 59bf09eb5a7..e69de29bb2d 100644 --- a/samples/client/petstore/java/jersey1/build.sbt +++ b/samples/client/petstore/java/jersey1/build.sbt @@ -1,20 +0,0 @@ -lazy val root = (project in file(".")). - settings( - organization := "io.swagger", - name := "swagger-java-client", - version := "1.0.0", - scalaVersion := "2.11.4", - scalacOptions ++= Seq("-feature"), - javacOptions in compile ++= Seq("-Xlint:deprecation"), - publishArtifact in (Compile, packageDoc) := false, - resolvers += Resolver.mavenLocal, - libraryDependencies ++= Seq( - "io.swagger" % "swagger-annotations" % "1.5.8", - "com.squareup.okhttp" % "okhttp" % "2.7.5", - "com.squareup.okhttp" % "logging-interceptor" % "2.7.5", - "com.google.code.gson" % "gson" % "2.6.2", - "joda-time" % "joda-time" % "2.9.3" % "compile", - "junit" % "junit" % "4.12" % "test", - "com.novocode" % "junit-interface" % "0.10" % "test" - ) - ) diff --git a/samples/client/petstore/java/jersey1/pom.xml b/samples/client/petstore/java/jersey1/pom.xml index 638d5395d46..c4cb68e99f4 100644 --- a/samples/client/petstore/java/jersey1/pom.xml +++ b/samples/client/petstore/java/jersey1/pom.xml @@ -6,11 +6,7 @@ jar swagger-java-client 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 @@ -96,28 +92,61 @@ + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.7 + 1.7 + + io.swagger swagger-annotations - ${swagger-core-version} + ${swagger-annotations-version} + + - com.squareup.okhttp - okhttp - ${okhttp-version} + com.sun.jersey + jersey-client + ${jersey-version} - com.squareup.okhttp - logging-interceptor - ${okhttp-version} + com.sun.jersey.contribs + jersey-multipart + ${jersey-version} + + - com.google.code.gson - gson - ${gson-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.jaxrs + jackson-jaxrs-json-provider + ${jackson-version} + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + ${jackson-version} joda-time @@ -125,6 +154,13 @@ ${jodatime-version} + + + com.brsanthu + migbase64 + 2.2 + + junit @@ -134,15 +170,12 @@ - 1.7 - ${java.version} - ${java.version} - 1.5.9 - 2.7.5 - 2.6.2 - 2.9.3 + UTF-8 + 1.5.8 + 1.19.1 + 2.7.5 + 2.9.4 1.0.0 4.12 - UTF-8 diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiCallback.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiCallback.java deleted file mode 100644 index 3ca33cf8017..00000000000 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiCallback.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import java.io.IOException; - -import java.util.Map; -import java.util.List; - -/** - * Callback for asynchronous API call. - * - * @param The return type - */ -public interface ApiCallback { - /** - * This is called when the API call fails. - * - * @param e The exception causing the failure - * @param statusCode Status code of the response if available, otherwise it would be 0 - * @param responseHeaders Headers of the response if available, otherwise it would be null - */ - void onFailure(ApiException e, int statusCode, Map> responseHeaders); - - /** - * This is called when the API call succeeded. - * - * @param result The result deserialized from response - * @param statusCode Status code of the response - * @param responseHeaders Headers of the response - */ - void onSuccess(T result, int statusCode, Map> responseHeaders); - - /** - * This is called when the API upload processing. - * - * @param bytesWritten bytes Written - * @param contentLength content length of request body - * @param done write end - */ - void onUploadProgress(long bytesWritten, long contentLength, boolean done); - - /** - * This is called when the API downlond processing. - * - * @param bytesRead bytes Read - * @param contentLength content lenngth of the response - * @param done Read end - */ - void onDownloadProgress(long bytesRead, long contentLength, boolean done); -} diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java index b7b04e3e4c5..b16fdbbdfa9 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java @@ -22,24 +22,25 @@ * limitations under the License. */ - package io.swagger.client; -import com.squareup.okhttp.Call; -import com.squareup.okhttp.Callback; -import com.squareup.okhttp.OkHttpClient; -import com.squareup.okhttp.Request; -import com.squareup.okhttp.Response; -import com.squareup.okhttp.RequestBody; -import com.squareup.okhttp.FormEncodingBuilder; -import com.squareup.okhttp.MultipartBuilder; -import com.squareup.okhttp.MediaType; -import com.squareup.okhttp.Headers; -import com.squareup.okhttp.internal.http.HttpMethod; -import com.squareup.okhttp.logging.HttpLoggingInterceptor; -import com.squareup.okhttp.logging.HttpLoggingInterceptor.Level; - -import java.lang.reflect.Type; +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.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; + +import com.sun.jersey.multipart.FormDataMultiPart; +import com.sun.jersey.multipart.file.FileDataBodyPart; + +import javax.ws.rs.core.Response.Status.Family; +import javax.ws.rs.core.MediaType; import java.util.Collection; import java.util.Collections; @@ -50,1277 +51,637 @@ import java.util.ArrayList; import java.util.Date; import java.util.TimeZone; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import java.net.URLEncoder; -import java.net.URLConnection; import java.io.File; -import java.io.InputStream; -import java.io.IOException; import java.io.UnsupportedEncodingException; -import java.security.GeneralSecurityException; -import java.security.KeyStore; -import java.security.SecureRandom; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; - import java.text.DateFormat; import java.text.SimpleDateFormat; -import java.text.ParseException; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.KeyManager; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.X509TrustManager; - -import okio.BufferedSink; -import okio.Okio; import io.swagger.client.auth.Authentication; import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; -public class ApiClient { - public static final double JAVA_VERSION; - public static final boolean IS_ANDROID; - public static final int ANDROID_SDK_VERSION; - - static { - JAVA_VERSION = Double.parseDouble(System.getProperty("java.specification.version")); - boolean isAndroid; - try { - Class.forName("android.app.Activity"); - isAndroid = true; - } catch (ClassNotFoundException e) { - isAndroid = false; - } - IS_ANDROID = isAndroid; - int sdkVersion = 0; - if (IS_ANDROID) { - try { - sdkVersion = Class.forName("android.os.Build$VERSION").getField("SDK_INT").getInt(null); - } catch (Exception e) { - try { - sdkVersion = Integer.parseInt((String) Class.forName("android.os.Build$VERSION").getField("SDK").get(null)); - } catch (Exception e2) { } - } - } - ANDROID_SDK_VERSION = sdkVersion; - } - - /** - * The datetime format to be used when lenientDatetimeFormat is enabled. - */ - public static final String LENIENT_DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; - - private String basePath = "http://petstore.swagger.io/v2"; - private boolean lenientOnJson = false; - private boolean debugging = false; - private Map defaultHeaderMap = new HashMap(); - private String tempFolderPath = null; - - private Map authentications; - - private DateFormat dateFormat; - private DateFormat datetimeFormat; - private boolean lenientDatetimeFormat; - private int dateLength; - - private InputStream sslCaCert; - private boolean verifyingSsl; - - private OkHttpClient httpClient; - private JSON json; - - private HttpLoggingInterceptor loggingInterceptor; - - /* - * Constructor for ApiClient - */ - public ApiClient() { - httpClient = new OkHttpClient(); - - verifyingSsl = true; - - json = new JSON(this); - - /* - * Use RFC3339 format for date and datetime. - * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 - */ - this.dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - // Always use UTC as the default time zone when dealing with date (without time). - this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - initDatetimeFormat(); - - // Be lenient on datetime formats when parsing datetime from string. - // See parseDatetime. - this.lenientDatetimeFormat = true; - - // Set default User-Agent. - setUserAgent("Swagger-Codegen/1.0.0/java"); - - // Setup authentications (key: authentication name, value: authentication). - authentications = new HashMap(); - authentications.put("api_key", new ApiKeyAuth("header", "api_key")); - authentications.put("petstore_auth", new OAuth()); - // Prevent the authentications from being modified. - authentications = Collections.unmodifiableMap(authentications); - } - - /** - * Get base path - * - * @return Baes path - */ - public String getBasePath() { - return basePath; - } - - /** - * Set base path - * - * @param basePath Base path of the URL (e.g http://petstore.swagger.io/v2 - * @return An instance of OkHttpClient - */ - public ApiClient setBasePath(String basePath) { - this.basePath = basePath; - return this; - } - - /** - * Get HTTP client - * - * @return An instance of OkHttpClient - */ - public OkHttpClient getHttpClient() { - return httpClient; - } - - /** - * Set HTTP client - * - * @param httpClient An instance of OkHttpClient - * @return Api Client - */ - public ApiClient setHttpClient(OkHttpClient httpClient) { - this.httpClient = httpClient; - return this; - } - - /** - * Get JSON - * - * @return JSON object - */ - public JSON getJSON() { - return json; - } - - /** - * Set JSON - * - * @param json JSON object - * @return Api client - */ - public ApiClient setJSON(JSON json) { - this.json = json; - return this; - } - - /** - * True if isVerifyingSsl flag is on - * - * @return True if isVerifySsl flag is on - */ - public boolean isVerifyingSsl() { - return verifyingSsl; - } - - /** - * Configure whether to verify certificate and hostname when making https requests. - * Default to true. - * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. - * - * @param verifyingSsl True to verify TLS/SSL connection - * @return ApiClient - */ - public ApiClient setVerifyingSsl(boolean verifyingSsl) { - this.verifyingSsl = verifyingSsl; - applySslSettings(); - return this; - } - - /** - * Get SSL CA cert. - * - * @return Input stream to the SSL CA cert - */ - public InputStream getSslCaCert() { - return sslCaCert; - } - - /** - * Configure the CA certificate to be trusted when making https requests. - * Use null to reset to default. - * - * @param sslCaCert input stream for SSL CA cert - * @return ApiClient - */ - public ApiClient setSslCaCert(InputStream sslCaCert) { - this.sslCaCert = sslCaCert; - applySslSettings(); - return this; - } - - public DateFormat getDateFormat() { - return dateFormat; - } - - public ApiClient setDateFormat(DateFormat dateFormat) { - this.dateFormat = dateFormat; - this.dateLength = this.dateFormat.format(new Date()).length(); - return this; - } - - public DateFormat getDatetimeFormat() { - return datetimeFormat; - } - - public ApiClient setDatetimeFormat(DateFormat datetimeFormat) { - this.datetimeFormat = datetimeFormat; - return this; - } - - /** - * Whether to allow various ISO 8601 datetime formats when parsing a datetime string. - * @see #parseDatetime(String) - * @return True if lenientDatetimeFormat flag is set to true - */ - public boolean isLenientDatetimeFormat() { - return lenientDatetimeFormat; - } - - public ApiClient setLenientDatetimeFormat(boolean lenientDatetimeFormat) { - this.lenientDatetimeFormat = lenientDatetimeFormat; - return this; - } - - /** - * Parse the given date string into Date object. - * The default dateFormat supports these ISO 8601 date formats: - * 2015-08-16 - * 2015-8-16 - * @param str String to be parsed - * @return Date - */ - public Date parseDate(String str) { - if (str == null) - return null; - try { - return dateFormat.parse(str); - } catch (ParseException e) { - throw new RuntimeException(e); - } - } - - /** - * Parse the given datetime string into Date object. - * When lenientDatetimeFormat is enabled, the following ISO 8601 datetime formats are supported: - * 2015-08-16T08:20:05Z - * 2015-8-16T8:20:05Z - * 2015-08-16T08:20:05+00:00 - * 2015-08-16T08:20:05+0000 - * 2015-08-16T08:20:05.376Z - * 2015-08-16T08:20:05.376+00:00 - * 2015-08-16T08:20:05.376+00 - * Note: The 3-digit milli-seconds is optional. Time zone is required and can be in one of - * these formats: - * Z (same with +0000) - * +08:00 (same with +0800) - * -02 (same with -0200) - * -0200 - * @see ISO 8601 - * @param str Date time string to be parsed - * @return Date representation of the string - */ - public Date parseDatetime(String str) { - if (str == null) - return null; - - DateFormat format; - if (lenientDatetimeFormat) { - /* - * When lenientDatetimeFormat is enabled, normalize the date string - * into LENIENT_DATETIME_FORMAT to support various formats - * defined by ISO 8601. - */ - // normalize time zone - // trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000 - str = str.replaceAll("[zZ]\\z", "+0000"); - // remove colon in time zone: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000 - str = str.replaceAll("([+-]\\d{2}):(\\d{2})\\z", "$1$2"); - // expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000 - str = str.replaceAll("([+-]\\d{2})\\z", "$100"); - // add milliseconds when missing - // 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000 - str = str.replaceAll("(:\\d{1,2})([+-]\\d{4})\\z", "$1.000$2"); - format = new SimpleDateFormat(LENIENT_DATETIME_FORMAT); - } else { - format = this.datetimeFormat; - } - - try { - return format.parse(str); - } catch (ParseException e) { - throw new RuntimeException(e); - } - } - - /* - * Parse date or date time in string format into Date object. - * - * @param str Date time string to be parsed - * @return Date representation of the string - */ - public Date parseDateOrDatetime(String str) { - if (str == null) - return null; - else if (str.length() <= dateLength) - return parseDate(str); - else - return parseDatetime(str); - } - - /** - * Format the given Date object into string (Date format). - * - * @param date Date object - * @return Formatted date in string representation - */ - public String formatDate(Date date) { - return dateFormat.format(date); - } - - /** - * Format the given Date object into string (Datetime format). - * - * @param date Date object - * @return Formatted datetime in string representation - */ - public String formatDatetime(Date date) { - return datetimeFormat.format(date); - } - - /** - * Get authentications (key: authentication name, value: authentication). - * - * @return Map of authentication objects - */ - public Map getAuthentications() { - return authentications; - } - - /** - * Get authentication for the given name. - * - * @param authName The authentication name - * @return The authentication, null if not found - */ - public Authentication getAuthentication(String authName) { - return authentications.get(authName); - } - - /** - * Helper method to set username for the first HTTP basic authentication. - * - * @param username Username - */ - public void setUsername(String username) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setUsername(username); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set password for the first HTTP basic authentication. - * - * @param password Password - */ - public void setPassword(String password) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setPassword(password); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set API key value for the first API key authentication. - * - * @param apiKey API key - */ - public void setApiKey(String apiKey) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKey(apiKey); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set API key prefix for the first API key authentication. - * - * @param apiKeyPrefix API key prefix - */ - public void setApiKeyPrefix(String apiKeyPrefix) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set access token for the first OAuth2 authentication. - * - * @param accessToken Access token - */ - public void setAccessToken(String accessToken) { - for (Authentication auth : authentications.values()) { - if (auth instanceof OAuth) { - ((OAuth) auth).setAccessToken(accessToken); - return; - } - } - throw new RuntimeException("No OAuth2 authentication configured!"); - } - - /** - * Set the User-Agent header's value (by adding to the default header map). - * - * @param userAgent HTTP request's user agent - * @return ApiClient - */ - public ApiClient setUserAgent(String userAgent) { - addDefaultHeader("User-Agent", userAgent); - return this; - } - - /** - * Add a default header. - * - * @param key The header's key - * @param value The header's value - * @return ApiClient - */ - public ApiClient addDefaultHeader(String key, String value) { - defaultHeaderMap.put(key, value); - return this; - } - - /** - * @see setLenient - * - * @return True if lenientOnJson is enabled, false otherwise. - */ - public boolean isLenientOnJson() { - return lenientOnJson; - } - - /** - * Set LenientOnJson - * - * @param lenient True to enable lenientOnJson - * @return ApiClient - */ - public ApiClient setLenientOnJson(boolean lenient) { - this.lenientOnJson = lenient; - return this; - } - - /** - * Check that whether debugging is enabled for this API client. - * - * @return True if debugging is enabled, false otherwise. - */ - public boolean isDebugging() { - return debugging; - } - - /** - * Enable/disable debugging for this API client. - * - * @param debugging To enable (true) or disable (false) debugging - * @return ApiClient - */ - public ApiClient setDebugging(boolean debugging) { - if (debugging != this.debugging) { - if (debugging) { - loggingInterceptor = new HttpLoggingInterceptor(); - loggingInterceptor.setLevel(Level.BODY); - httpClient.interceptors().add(loggingInterceptor); - } else { - httpClient.interceptors().remove(loggingInterceptor); - loggingInterceptor = null; - } - } - this.debugging = debugging; - return this; - } - - /** - * The path of temporary folder used to store downloaded files from endpoints - * with file response. The default value is null, i.e. using - * the system's default tempopary folder. - * - * @see createTempFile - * @return Temporary folder path - */ - public String getTempFolderPath() { - return tempFolderPath; - } - - /** - * Set the tempoaray folder path (for downloading files) - * - * @param tempFolderPath Temporary folder path - * @return ApiClient - */ - public ApiClient setTempFolderPath(String tempFolderPath) { - this.tempFolderPath = tempFolderPath; - return this; - } - - /** - * Get connection timeout (in milliseconds). - * - * @return Timeout in milliseconds - */ - public int getConnectTimeout() { - return httpClient.getConnectTimeout(); - } - - /** - * Sets the connect timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * - * @param connectionTimeout connection timeout in milliseconds - * @return Api client - */ - public ApiClient setConnectTimeout(int connectionTimeout) { - httpClient.setConnectTimeout(connectionTimeout, TimeUnit.MILLISECONDS); - return this; - } - - /** - * Format the given parameter object into string. - * - * @param param Parameter - * @return String representation of the parameter - */ - public String parameterToString(Object param) { - if (param == null) { - return ""; - } else if (param instanceof Date) { - return formatDatetime((Date) param); - } else if (param instanceof Collection) { - StringBuilder b = new StringBuilder(); - for (Object o : (Collection)param) { - if (b.length() > 0) { - b.append(","); - } - b.append(String.valueOf(o)); - } - return b.toString(); - } else { - return String.valueOf(param); - } - } - - /** - * Format to {@code Pair} objects. - * - * @param collectionFormat collection format (e.g. csv, tsv) - * @param name Name - * @param value Value - * @return A list of Pair objects - */ - public List parameterToPairs(String collectionFormat, String name, Object value){ - List params = new ArrayList(); - - // preconditions - if (name == null || name.isEmpty() || value == null) return params; - - Collection valueCollection = null; - if (value instanceof Collection) { - valueCollection = (Collection) value; - } else { - params.add(new Pair(name, parameterToString(value))); - return params; - } - - if (valueCollection.isEmpty()){ - return params; - } - - // get the collection format - collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv - - // create the params based on the collection format - if (collectionFormat.equals("multi")) { - for (Object item : valueCollection) { - params.add(new Pair(name, parameterToString(item))); - } - - return params; - } - - String delimiter = ","; - - if (collectionFormat.equals("csv")) { - delimiter = ","; - } else if (collectionFormat.equals("ssv")) { - delimiter = " "; - } else if (collectionFormat.equals("tsv")) { - delimiter = "\t"; - } else if (collectionFormat.equals("pipes")) { - delimiter = "|"; - } - - StringBuilder sb = new StringBuilder() ; - for (Object item : valueCollection) { - sb.append(delimiter); - sb.append(parameterToString(item)); - } - - params.add(new Pair(name, sb.substring(1))); - - return params; - } - - /** - * Sanitize filename by removing path. - * e.g. ../../sun.gif becomes sun.gif - * - * @param filename The filename to be sanitized - * @return The sanitized filename - */ - public String sanitizeFilename(String filename) { - return filename.replaceAll(".*[/\\\\]", ""); - } - - /** - * Check if the given MIME is a JSON MIME. - * JSON MIME examples: - * application/json - * application/json; charset=UTF8 - * APPLICATION/JSON - * - * @param mime MIME (Multipurpose Internet Mail Extensions) - * @return True if the given MIME is JSON, false otherwise. - */ - public boolean isJsonMime(String mime) { - return mime != null && mime.matches("(?i)application\\/json(;.*)?"); - } - - /** - * Select the Accept header's value from the given accepts array: - * if JSON exists in the given array, use it; - * otherwise use all of them (joining into a string) - * - * @param accepts The accepts array to select from - * @return The Accept header to use. If the given array is empty, - * null will be returned (not to set the Accept header explicitly). - */ - public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) { - return null; - } - for (String accept : accepts) { - if (isJsonMime(accept)) { - return accept; - } - } - return StringUtil.join(accepts, ","); - } - - /** - * Select the Content-Type header's value from the given array: - * if JSON exists in the given array, use it; - * otherwise use the first one of the array. - * - * @param contentTypes The Content-Type array to select from - * @return The Content-Type header to use. If the given array is empty, - * JSON will be used. - */ - public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) { - return "application/json"; - } - for (String contentType : contentTypes) { - if (isJsonMime(contentType)) { - return contentType; - } - } - return contentTypes[0]; - } - - /** - * Escape the given string to be used as URL query value. - * - * @param str String to be escaped - * @return Escaped string - */ - public String escapeString(String str) { - try { - return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); - } catch (UnsupportedEncodingException e) { - return str; - } - } - - /** - * Deserialize response body to Java object, according to the return type and - * the Content-Type response header. - * - * @param Type - * @param response HTTP response - * @param returnType The type of the Java object - * @return The deserialized Java object - * @throws ApiException If fail to deserialize response body, i.e. cannot read response body - * or the Content-Type of the response is not supported. - */ - @SuppressWarnings("unchecked") - public T deserialize(Response response, Type returnType) throws ApiException { - if (response == null || returnType == null) { - return null; - } - - if ("byte[]".equals(returnType.toString())) { - // Handle binary response (byte array). - try { - return (T) response.body().bytes(); - } catch (IOException e) { - throw new ApiException(e); - } - } else if (returnType.equals(File.class)) { - // Handle file downloading. - return (T) downloadFileFromResponse(response); - } - - String respBody; - try { - if (response.body() != null) - respBody = response.body().string(); - else - respBody = null; - } catch (IOException e) { - throw new ApiException(e); - } - - if (respBody == null || "".equals(respBody)) { - return null; - } - - String contentType = response.headers().get("Content-Type"); - if (contentType == null) { - // ensuring a default content type - contentType = "application/json"; - } - if (isJsonMime(contentType)) { - return json.deserialize(respBody, returnType); - } else if (returnType.equals(String.class)) { - // Expecting string, return the raw response body. - return (T) respBody; - } else { - throw new ApiException( - "Content type \"" + contentType + "\" is not supported for type: " + returnType, - response.code(), - response.headers().toMultimap(), - respBody); - } - } - - /** - * Serialize the given Java object into request body according to the object's - * class and the request Content-Type. - * - * @param obj The Java object - * @param contentType The request Content-Type - * @return The serialized request body - * @throws ApiException If fail to serialize the given object - */ - public RequestBody serialize(Object obj, String contentType) throws ApiException { - if (obj instanceof byte[]) { - // Binary (byte array) body parameter support. - return RequestBody.create(MediaType.parse(contentType), (byte[]) obj); - } else if (obj instanceof File) { - // File body parameter support. - return RequestBody.create(MediaType.parse(contentType), (File) obj); - } else if (isJsonMime(contentType)) { - String content; - if (obj != null) { - content = json.serialize(obj); - } else { - content = null; - } - return RequestBody.create(MediaType.parse(contentType), content); - } else { - throw new ApiException("Content type \"" + contentType + "\" is not supported"); - } - } - - /** - * Download file from the given response. - * - * @param response An instance of the Response object - * @throws ApiException If fail to read file content from response and write to disk - * @return Downloaded file - */ - public File downloadFileFromResponse(Response response) throws ApiException { - try { - File file = prepareDownloadFile(response); - BufferedSink sink = Okio.buffer(Okio.sink(file)); - sink.writeAll(response.body().source()); - sink.close(); - return file; - } catch (IOException e) { - throw new ApiException(e); - } - } - - /** - * Prepare file for download - * - * @param response An instance of the Response object - * @throws IOException If fail to prepare file for download - * @return Prepared file for the download - */ - public File prepareDownloadFile(Response response) throws IOException { - String filename = null; - String contentDisposition = response.header("Content-Disposition"); - if (contentDisposition != null && !"".equals(contentDisposition)) { - // Get filename from the Content-Disposition header. - Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); - Matcher matcher = pattern.matcher(contentDisposition); - if (matcher.find()) { - filename = sanitizeFilename(matcher.group(1)); - } - } - - String prefix = null; - String suffix = null; - if (filename == null) { - prefix = "download-"; - suffix = ""; - } else { - int pos = filename.lastIndexOf("."); - if (pos == -1) { - prefix = filename + "-"; - } else { - prefix = filename.substring(0, pos) + "-"; - suffix = filename.substring(pos); - } - // File.createTempFile requires the prefix to be at least three characters long - if (prefix.length() < 3) - prefix = "download-"; - } - - if (tempFolderPath == null) - return File.createTempFile(prefix, suffix); - else - return File.createTempFile(prefix, suffix, new File(tempFolderPath)); - } - - /** - * {@link #execute(Call, Type)} - * - * @param Type - * @param call An instance of the Call object - * @throws ApiException If fail to execute the call - * @return ApiResponse<T> - */ - public ApiResponse execute(Call call) throws ApiException { - return execute(call, null); - } - - /** - * Execute HTTP call and deserialize the HTTP response body into the given return type. - * - * @param returnType The return type used to deserialize HTTP response body - * @param The return type corresponding to (same with) returnType - * @param call Call - * @return ApiResponse object containing response status, headers and - * data, which is a Java object deserialized from response body and would be null - * when returnType is null. - * @throws ApiException If fail to execute the call - */ - public ApiResponse execute(Call call, Type returnType) throws ApiException { - try { - Response response = call.execute(); - T data = handleResponse(response, returnType); - return new ApiResponse(response.code(), response.headers().toMultimap(), data); - } catch (IOException e) { - throw new ApiException(e); - } - } - - /** - * {@link #executeAsync(Call, Type, ApiCallback)} - * - * @param Type - * @param call An instance of the Call object - * @param callback ApiCallback<T> - */ - public void executeAsync(Call call, ApiCallback callback) { - executeAsync(call, null, callback); - } - - /** - * Execute HTTP call asynchronously. - * - * @see #execute(Call, Type) - * @param Type - * @param call The callback to be executed when the API call finishes - * @param returnType Return type - * @param callback ApiCallback - */ - @SuppressWarnings("unchecked") - public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { - call.enqueue(new Callback() { - @Override - public void onFailure(Request request, IOException e) { - callback.onFailure(new ApiException(e), 0, null); - } - - @Override - public void onResponse(Response response) throws IOException { - T result; - try { - result = (T) handleResponse(response, returnType); - } catch (ApiException e) { - callback.onFailure(e, response.code(), response.headers().toMultimap()); - return; - } - callback.onSuccess(result, response.code(), response.headers().toMultimap()); - } - }); - } - - /** - * Handle the given response, return the deserialized object when the response is successful. - * - * @param Type - * @param response Response - * @param returnType Return type - * @throws ApiException If the response has a unsuccessful status code or - * fail to deserialize the response body - * @return Type - */ - public T handleResponse(Response response, Type returnType) throws ApiException { - if (response.isSuccessful()) { - if (returnType == null || response.code() == 204) { - // returning null if the returnType is not defined, - // or the status code is 204 (No Content) - return null; - } else { - return deserialize(response, returnType); - } - } else { - String respBody = null; - if (response.body() != null) { - try { - respBody = response.body().string(); - } catch (IOException e) { - throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); - } - } - throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); - } - } - - /** - * Build HTTP call with the given options. - * - * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" - * @param queryParams The query parameters - * @param body The request body object - * @param headerParams The header parameters - * @param formParams The form parameters - * @param authNames The authentications to apply - * @param progressRequestListener Progress request listener - * @return The HTTP call - * @throws ApiException If fail to serialize the request body object - */ - public Call buildCall(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - updateParamsForAuth(authNames, queryParams, headerParams); - - final String url = buildUrl(path, queryParams); - final Request.Builder reqBuilder = new Request.Builder().url(url); - processHeaderParams(headerParams, reqBuilder); - - String contentType = (String) headerParams.get("Content-Type"); - // ensuring a default content type - if (contentType == null) { - contentType = "application/json"; - } - - RequestBody reqBody; - if (!HttpMethod.permitsRequestBody(method)) { - reqBody = null; - } else if ("application/x-www-form-urlencoded".equals(contentType)) { - reqBody = buildRequestBodyFormEncoding(formParams); - } else if ("multipart/form-data".equals(contentType)) { - reqBody = buildRequestBodyMultipart(formParams); - } else if (body == null) { - if ("DELETE".equals(method)) { - // allow calling DELETE without sending a request body - reqBody = null; - } else { - // use an empty request body (for POST, PUT and PATCH) - reqBody = RequestBody.create(MediaType.parse(contentType), ""); - } - } else { - reqBody = serialize(body, contentType); - } - - Request request = null; - - if(progressRequestListener != null && reqBody != null) { - ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener); - request = reqBuilder.method(method, progressRequestBody).build(); - } else { - request = reqBuilder.method(method, reqBody).build(); - } - - return httpClient.newCall(request); - } - - /** - * Build full URL by concatenating base path, the given sub path and query parameters. - * - * @param path The sub path - * @param queryParams The query parameters - * @return The full URL - */ - public String buildUrl(String path, List queryParams) { - final StringBuilder url = new StringBuilder(); - url.append(basePath).append(path); - - if (queryParams != null && !queryParams.isEmpty()) { - // support (constant) query string in `path`, e.g. "/posts?draft=1" - String prefix = path.contains("?") ? "&" : "?"; - for (Pair param : queryParams) { - if (param.getValue() != null) { - if (prefix != null) { - url.append(prefix); - prefix = null; - } else { - url.append("&"); - } - String value = parameterToString(param.getValue()); - url.append(escapeString(param.getName())).append("=").append(escapeString(value)); - } - } - } - - return url.toString(); - } - - /** - * Set header parameters to the request builder, including default headers. - * - * @param headerParams Header parameters in the ofrm of Map - * @param reqBuilder Reqeust.Builder - */ - public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { - for (Entry param : headerParams.entrySet()) { - reqBuilder.header(param.getKey(), parameterToString(param.getValue())); - } - for (Entry header : defaultHeaderMap.entrySet()) { - if (!headerParams.containsKey(header.getKey())) { - reqBuilder.header(header.getKey(), parameterToString(header.getValue())); - } - } - } - - /** - * Update query and header parameters based on authentication settings. - * - * @param authNames The authentications to apply - * @param queryParams List of query parameters - * @param headerParams Map of header parameters - */ - public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { - for (String authName : authNames) { - Authentication auth = authentications.get(authName); - if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); - auth.applyToParams(queryParams, headerParams); - } - } - - /** - * Build a form-encoding request body with the given form parameters. - * - * @param formParams Form parameters in the form of Map - * @return RequestBody - */ - public RequestBody buildRequestBodyFormEncoding(Map formParams) { - FormEncodingBuilder formBuilder = new FormEncodingBuilder(); - for (Entry param : formParams.entrySet()) { - formBuilder.add(param.getKey(), parameterToString(param.getValue())); - } - return formBuilder.build(); - } - - /** - * Build a multipart (file uploading) request body with the given form parameters, - * which could contain text fields and file fields. - * - * @param formParams Form parameters in the form of Map - * @return RequestBody - */ - public RequestBody buildRequestBodyMultipart(Map formParams) { - MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); - for (Entry param : formParams.entrySet()) { - if (param.getValue() instanceof File) { - File file = (File) param.getValue(); - Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\""); - MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); - mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file)); - } else { - Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\""); - mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue()))); - } - } - return mpBuilder.build(); - } - - /** - * Guess Content-Type header from the given file (defaults to "application/octet-stream"). - * - * @param file The given file - * @return The guessed Content-Type - */ - public String guessContentTypeFromFile(File file) { - String contentType = URLConnection.guessContentTypeFromName(file.getName()); - if (contentType == null) { - return "application/octet-stream"; - } else { - return contentType; - } - } - /** - * Initialize datetime format according to the current environment, e.g. Java 1.7 and Android. - */ - private void initDatetimeFormat() { - String formatWithTimeZone = null; - if (IS_ANDROID) { - if (ANDROID_SDK_VERSION >= 18) { - // The time zone format "ZZZZZ" is available since Android 4.3 (SDK version 18) - formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"; - } - } else if (JAVA_VERSION >= 1.7) { - // The time zone format "XXX" is available since Java 1.7 - formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; - } - if (formatWithTimeZone != null) { - this.datetimeFormat = new SimpleDateFormat(formatWithTimeZone); - // NOTE: Use the system's default time zone (mainly for datetime formatting). +public class ApiClient { + private Map defaultHeaderMap = new HashMap(); + private String basePath = "http://petstore.swagger.io/v2"; + private boolean debugging = false; + private int connectionTimeout = 0; + + private Client httpClient; + private ObjectMapper objectMapper; + + private Map authentications; + + private int statusCode; + private Map> responseHeaders; + + private DateFormat dateFormat; + + public ApiClient() { + objectMapper = new ObjectMapper(); + objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + objectMapper.registerModule(new JodaModule()); + objectMapper.setDateFormat(ApiClient.buildDefaultDateFormat()); + + dateFormat = ApiClient.buildDefaultDateFormat(); + + // Set default User-Agent. + setUserAgent("Swagger-Codegen/1.0.0/java"); + + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap(); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("petstore_auth", new OAuth()); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + + rebuildHttpClient(); + } + + public static DateFormat buildDefaultDateFormat() { + // Use RFC3339 format for date and datetime. + // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + // Use UTC as the default time zone. + dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + return dateFormat; + } + + /** + * Build the Client used to make HTTP requests with the latest settings, + * i.e. objectMapper and debugging. + * TODO: better to use the Builder Pattern? + */ + public ApiClient rebuildHttpClient() { + // Add the JSON serialization support to Jersey + JacksonJsonProvider jsonProvider = new JacksonJsonProvider(objectMapper); + DefaultClientConfig conf = new DefaultClientConfig(); + conf.getSingletons().add(jsonProvider); + Client client = Client.create(conf); + if (debugging) { + client.addFilter(new LoggingFilter()); + } + this.httpClient = client; + return this; + } + + /** + * Returns the current object mapper used for JSON serialization/deserialization. + *

+ * Note: If you make changes to the object mapper, remember to set it back via + * setObjectMapper in order to trigger HTTP client rebuilding. + *

+ */ + public ObjectMapper getObjectMapper() { + return objectMapper; + } + + public ApiClient setObjectMapper(ObjectMapper objectMapper) { + this.objectMapper = objectMapper; + // Need to rebuild the Client as it depends on object mapper. + rebuildHttpClient(); + return this; + } + + public Client getHttpClient() { + return httpClient; + } + + public ApiClient setHttpClient(Client httpClient) { + this.httpClient = httpClient; + return this; + } + + public String getBasePath() { + return basePath; + } + + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + /** + * Gets the status code of the previous request + */ + public int getStatusCode() { + return statusCode; + } + + /** + * Gets the response headers of the previous request + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + + /** + * Get authentications (key: authentication name, value: authentication). + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set access token for the first OAuth2 authentication. + */ + public void setAccessToken(String accessToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); + return; + } + } + throw new RuntimeException("No OAuth2 authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + */ + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + /** + * Check that whether debugging is enabled for this API client. + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + */ + public ApiClient setDebugging(boolean debugging) { + this.debugging = debugging; + // Need to rebuild the Client as it depends on the value of debugging. + rebuildHttpClient(); + return this; + } + + /** + * Connect timeout (in milliseconds). + */ + public int getConnectTimeout() { + return connectionTimeout; + } + + /** + * Set the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link Integer#MAX_VALUE}. + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + this.connectionTimeout = connectionTimeout; + httpClient.setConnectTimeout(connectionTimeout); + return this; + } + + /** + * Get the date format used to parse/format date parameters. + */ + public DateFormat getDateFormat() { + return dateFormat; + } + + /** + * Set the date format used to parse/format date parameters. + */ + public ApiClient setDateFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + // Also set the date format for model (de)serialization with Date properties. + this.objectMapper.setDateFormat((DateFormat) dateFormat.clone()); + // Need to rebuild the Client as objectMapper changes. + rebuildHttpClient(); + return this; + } + + /** + * Parse the given string into Date object. + */ + public Date parseDate(String str) { + try { + return dateFormat.parse(str); + } catch (java.text.ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Format the given Date object into string. + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } + + /** + * 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 to {@code Pair} objects. + */ + public List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + + // create the params based on the collection format + if (collectionFormat.equals("multi")) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); + } + + return params; + } + + String delimiter = ","; + + if (collectionFormat.equals("csv")) { + delimiter = ","; + } else if (collectionFormat.equals("ssv")) { + delimiter = " "; + } else if (collectionFormat.equals("tsv")) { + delimiter = "\t"; + } else if (collectionFormat.equals("pipes")) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + + return params; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + */ + public boolean isJsonMime(String mime) { + return mime != null && mime.matches("(?i)application\\/json(;.*)?"); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } + return contentTypes[0]; + } + + /** + * Escape the given string to be used as URL query value. + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Serialize the given Java object into string according the given + * Content-Type (only JSON is supported for now). + */ + 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 { - // Use a common format that works across all systems. - this.datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - // Always use the UTC time zone as we are using a constant trailing "Z" here. - this.datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - } - } - - /** - * Apply SSL related settings to httpClient according to the current values of - * verifyingSsl and sslCaCert. - */ - private void applySslSettings() { + 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 { + // We let Jersey attempt to serialize the body + return obj; + } + } + + /** + * Build full URL by concatenating base path, the given sub path and query parameters. + * + * @param path The sub path + * @param queryParams The query parameters + * @return The full URL + */ + private String buildUrl(String path, List queryParams) { + final StringBuilder url = new StringBuilder(); + url.append(basePath).append(path); + + if (queryParams != null && !queryParams.isEmpty()) { + // support (constant) query string in `path`, e.g. "/posts?draft=1" + String prefix = path.contains("?") ? "&" : "?"; + for (Pair param : queryParams) { + if (param.getValue() != null) { + if (prefix != null) { + url.append(prefix); + prefix = null; + } else { + url.append("&"); + } + String value = parameterToString(param.getValue()); + url.append(escapeString(param.getName())).append("=").append(escapeString(value)); + } + } + } + + return url.toString(); + } + + private ClientResponse getAPIResponse(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { + if (body != null && !formParams.isEmpty()) { + throw new ApiException(500, "Cannot have body and form params"); + } + + updateParamsForAuth(authNames, queryParams, headerParams); + + final String url = buildUrl(path, queryParams); + Builder builder; + if (accept == null) { + builder = httpClient.resource(url).getRequestBuilder(); + } else { + builder = httpClient.resource(url).accept(accept); + } + + for (String key : headerParams.keySet()) { + builder = builder.header(key, headerParams.get(key)); + } + for (String key : defaultHeaderMap.keySet()) { + if (!headerParams.containsKey(key)) { + builder = builder.header(key, defaultHeaderMap.get(key)); + } + } + + ClientResponse response = null; + + if ("GET".equals(method)) { + response = (ClientResponse) builder.get(ClientResponse.class); + } else if ("POST".equals(method)) { + response = builder.type(contentType).post(ClientResponse.class, serialize(body, contentType, formParams)); + } else if ("PUT".equals(method)) { + response = builder.type(contentType).put(ClientResponse.class, serialize(body, contentType, formParams)); + } else if ("DELETE".equals(method)) { + response = builder.type(contentType).delete(ClientResponse.class, serialize(body, contentType, formParams)); + } else if ("PATCH".equals(method)) { + response = builder.type(contentType).header("X-HTTP-Method-Override", "PATCH").post(ClientResponse.class, serialize(body, contentType, formParams)); + } + else { + throw new ApiException(500, "unknown method type " + method); + } + return response; + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @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 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 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, headerParams, formParams, accept, contentType, authNames); + + statusCode = response.getStatusInfo().getStatusCode(); + responseHeaders = response.getHeaders(); + + if(response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) { + return null; + } else if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { + if (returnType == null) + return null; + else + return response.getEntity(returnType); + } else { + String message = "error"; + String respBody = null; + if (response.hasEntity()) { try { - KeyManager[] keyManagers = null; - TrustManager[] trustManagers = null; - HostnameVerifier hostnameVerifier = null; - if (!verifyingSsl) { - TrustManager trustAll = new X509TrustManager() { - @Override - public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} - @Override - public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} - @Override - public X509Certificate[] getAcceptedIssuers() { return null; } - }; - SSLContext sslContext = SSLContext.getInstance("TLS"); - trustManagers = new TrustManager[]{ trustAll }; - hostnameVerifier = new HostnameVerifier() { - @Override - public boolean verify(String hostname, SSLSession session) { return true; } - }; - } else if (sslCaCert != null) { - char[] password = null; // Any password will work. - CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); - Collection certificates = certificateFactory.generateCertificates(sslCaCert); - if (certificates.isEmpty()) { - throw new IllegalArgumentException("expected non-empty set of trusted certificates"); - } - KeyStore caKeyStore = newEmptyKeyStore(password); - int index = 0; - for (Certificate certificate : certificates) { - String certificateAlias = "ca" + Integer.toString(index++); - caKeyStore.setCertificateEntry(certificateAlias, certificate); - } - TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - trustManagerFactory.init(caKeyStore); - trustManagers = trustManagerFactory.getTrustManagers(); - } - - if (keyManagers != null || trustManagers != null) { - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(keyManagers, trustManagers, new SecureRandom()); - httpClient.setSslSocketFactory(sslContext.getSocketFactory()); - } else { - httpClient.setSslSocketFactory(null); - } - httpClient.setHostnameVerifier(hostnameVerifier); - } catch (GeneralSecurityException e) { - throw new RuntimeException(e); - } - } - - private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { - try { - KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - keyStore.load(null, password); - return keyStore; - } catch (IOException e) { - throw new AssertionError(e); - } - } + respBody = response.getEntity(String.class); + message = respBody; + } catch (RuntimeException e) { + // e.printStackTrace(); + } + } + throw new ApiException( + response.getStatusInfo().getStatusCode(), + message, + response.getHeaders(), + respBody); + } + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + */ + private void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); + auth.applyToParams(queryParams, headerParams); + } + } + + /** + * Encode the given form parameters as request body. + */ + private String getXWWWFormUrlencodedParams(Map formParams) { + StringBuilder formParamBuilder = new StringBuilder(); + + for (Entry param : formParams.entrySet()) { + String valueStr = parameterToString(param.getValue()); + try { + formParamBuilder.append(URLEncoder.encode(param.getKey(), "utf8")) + .append("=") + .append(URLEncoder.encode(valueStr, "utf8")); + formParamBuilder.append("&"); + } catch (UnsupportedEncodingException e) { + // move on to next + } + } + + String encodedFormParams = formParamBuilder.toString(); + if (encodedFormParams.endsWith("&")) { + encodedFormParams = encodedFormParams.substring(0, encodedFormParams.length() - 1); + } + + return encodedFormParams; + } } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiResponse.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiResponse.java deleted file mode 100644 index d7dde1ee939..00000000000 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiResponse.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import java.util.List; -import java.util.Map; - -/** - * API response returned by API call. - * - * @param T The type of data that is deserialized from response body - */ -public class ApiResponse { - final private int statusCode; - final private Map> headers; - final private T data; - - /** - * @param statusCode The status code of HTTP response - * @param headers The headers of HTTP response - */ - public ApiResponse(int statusCode, Map> headers) { - this(statusCode, headers, null); - } - - /** - * @param statusCode The status code of HTTP response - * @param headers The headers of HTTP response - * @param data The object deserialized from response bod - */ - public ApiResponse(int statusCode, Map> headers, T data) { - this.statusCode = statusCode; - this.headers = headers; - this.data = data; - } - - public int getStatusCode() { - return statusCode; - } - - public Map> getHeaders() { - return headers; - } - - public T getData() { - return data; - } -} diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/JSON.java deleted file mode 100644 index 540611eab9d..00000000000 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/JSON.java +++ /dev/null @@ -1,237 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonNull; -import com.google.gson.JsonParseException; -import com.google.gson.JsonPrimitive; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; - -import java.io.IOException; -import java.io.StringReader; -import java.lang.reflect.Type; -import java.util.Date; - -import org.joda.time.DateTime; -import org.joda.time.LocalDate; -import org.joda.time.format.DateTimeFormatter; -import org.joda.time.format.ISODateTimeFormat; - -public class JSON { - private ApiClient apiClient; - private Gson gson; - - /** - * JSON constructor. - * - * @param apiClient An instance of ApiClient - */ - public JSON(ApiClient apiClient) { - this.apiClient = apiClient; - gson = new GsonBuilder() - .registerTypeAdapter(Date.class, new DateAdapter(apiClient)) - .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) - .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) - .create(); - } - - /** - * Get Gson. - * - * @return Gson - */ - public Gson getGson() { - return gson; - } - - /** - * Set Gson. - * - * @param gson Gson - */ - public void setGson(Gson gson) { - this.gson = gson; - } - - /** - * Serialize the given Java object into JSON string. - * - * @param obj Object - * @return String representation of the JSON - */ - public String serialize(Object obj) { - return gson.toJson(obj); - } - - /** - * Deserialize the given JSON string to Java object. - * - * @param Type - * @param body The JSON string - * @param returnType The type to deserialize inot - * @return The deserialized Java object - */ - @SuppressWarnings("unchecked") - public T deserialize(String body, Type returnType) { - try { - if (apiClient.isLenientOnJson()) { - JsonReader jsonReader = new JsonReader(new StringReader(body)); - // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) - jsonReader.setLenient(true); - return gson.fromJson(jsonReader, returnType); - } else { - return gson.fromJson(body, returnType); - } - } catch (JsonParseException e) { - // Fallback processing when failed to parse JSON form response body: - // return the response body string directly for the String return type; - // parse response body into date or datetime for the Date return type. - if (returnType.equals(String.class)) - return (T) body; - else if (returnType.equals(Date.class)) - return (T) apiClient.parseDateOrDatetime(body); - else throw(e); - } - } -} - -class DateAdapter implements JsonSerializer, JsonDeserializer { - private final ApiClient apiClient; - - /** - * Constructor for DateAdapter - * - * @param apiClient Api client - */ - public DateAdapter(ApiClient apiClient) { - super(); - this.apiClient = apiClient; - } - - /** - * Serialize - * - * @param src Date - * @param typeOfSrc Type - * @param context Json Serialization Context - * @return Json Element - */ - @Override - public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { - if (src == null) { - return JsonNull.INSTANCE; - } else { - return new JsonPrimitive(apiClient.formatDatetime(src)); - } - } - - /** - * Deserialize - * - * @param json Json element - * @param date Type - * @param typeOfSrc Type - * @param context Json Serialization Context - * @return Date - * @throw JsonParseException if fail to parse - */ - @Override - public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException { - String str = json.getAsJsonPrimitive().getAsString(); - try { - return apiClient.parseDateOrDatetime(str); - } catch (RuntimeException e) { - throw new JsonParseException(e); - } - } -} - -/** - * Gson TypeAdapter for Joda DateTime type - */ -class DateTimeTypeAdapter extends TypeAdapter { - - private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); - - @Override - public void write(JsonWriter out, DateTime date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - out.value(formatter.print(date)); - } - } - - @Override - public DateTime read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - return formatter.parseDateTime(date); - } - } -} - -/** - * Gson TypeAdapter for Joda LocalDate type - */ -class LocalDateTypeAdapter extends TypeAdapter { - - private final DateTimeFormatter formatter = ISODateTimeFormat.date(); - - @Override - public void write(JsonWriter out, LocalDate date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - out.value(formatter.print(date)); - } - } - - @Override - public LocalDate read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - return formatter.parseLocalDate(date); - } - } -} diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ProgressRequestBody.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ProgressRequestBody.java deleted file mode 100644 index d9ca742ecd2..00000000000 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ProgressRequestBody.java +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import com.squareup.okhttp.MediaType; -import com.squareup.okhttp.RequestBody; - -import java.io.IOException; - -import okio.Buffer; -import okio.BufferedSink; -import okio.ForwardingSink; -import okio.Okio; -import okio.Sink; - -public class ProgressRequestBody extends RequestBody { - - public interface ProgressRequestListener { - void onRequestProgress(long bytesWritten, long contentLength, boolean done); - } - - private final RequestBody requestBody; - - private final ProgressRequestListener progressListener; - - private BufferedSink bufferedSink; - - public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) { - this.requestBody = requestBody; - this.progressListener = progressListener; - } - - @Override - public MediaType contentType() { - return requestBody.contentType(); - } - - @Override - public long contentLength() throws IOException { - return requestBody.contentLength(); - } - - @Override - public void writeTo(BufferedSink sink) throws IOException { - if (bufferedSink == null) { - bufferedSink = Okio.buffer(sink(sink)); - } - - requestBody.writeTo(bufferedSink); - bufferedSink.flush(); - - } - - private Sink sink(Sink sink) { - return new ForwardingSink(sink) { - - long bytesWritten = 0L; - long contentLength = 0L; - - @Override - public void write(Buffer source, long byteCount) throws IOException { - super.write(source, byteCount); - if (contentLength == 0) { - contentLength = contentLength(); - } - - bytesWritten += byteCount; - progressListener.onRequestProgress(bytesWritten, contentLength, bytesWritten == contentLength); - } - }; - } -} diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ProgressResponseBody.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ProgressResponseBody.java deleted file mode 100644 index f8af685999d..00000000000 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ProgressResponseBody.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import com.squareup.okhttp.MediaType; -import com.squareup.okhttp.ResponseBody; - -import java.io.IOException; - -import okio.Buffer; -import okio.BufferedSource; -import okio.ForwardingSource; -import okio.Okio; -import okio.Source; - -public class ProgressResponseBody extends ResponseBody { - - public interface ProgressListener { - void update(long bytesRead, long contentLength, boolean done); - } - - private final ResponseBody responseBody; - private final ProgressListener progressListener; - private BufferedSource bufferedSource; - - public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) { - this.responseBody = responseBody; - this.progressListener = progressListener; - } - - @Override - public MediaType contentType() { - return responseBody.contentType(); - } - - @Override - public long contentLength() throws IOException { - return responseBody.contentLength(); - } - - @Override - public BufferedSource source() throws IOException { - if (bufferedSource == null) { - bufferedSource = Okio.buffer(source(responseBody.source())); - } - return bufferedSource; - } - - private Source source(Source source) { - return new ForwardingSource(source) { - long totalBytesRead = 0L; - - @Override - public long read(Buffer sink, long byteCount) throws IOException { - long bytesRead = super.read(sink, byteCount); - // read() returns the number of bytes read, or -1 if this source is exhausted. - totalBytesRead += bytesRead != -1 ? bytesRead : 0; - progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1); - return bytesRead; - } - }; - } -} - - diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java index 52dce361e2a..c772f9402da 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java @@ -22,332 +22,176 @@ * limitations under the License. */ - package io.swagger.client.api; -import io.swagger.client.ApiCallback; -import io.swagger.client.ApiClient; +import com.sun.jersey.api.client.GenericType; + import io.swagger.client.ApiException; -import io.swagger.client.ApiResponse; +import io.swagger.client.ApiClient; import io.swagger.client.Configuration; +import io.swagger.client.model.*; import io.swagger.client.Pair; -import io.swagger.client.ProgressRequestBody; -import io.swagger.client.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; import org.joda.time.LocalDate; import org.joda.time.DateTime; import java.math.BigDecimal; -import java.lang.reflect.Type; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -public class FakeApi { - private ApiClient apiClient; - - public FakeApi() { - this(Configuration.getDefaultApiClient()); - } - - public FakeApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for testEndpointParameters */ - private com.squareup.okhttp.Call testEndpointParametersCall(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'number' is set - if (number == null) { - throw new ApiException("Missing the required parameter 'number' when calling testEndpointParameters(Async)"); - } - - // verify the required parameter '_double' is set - if (_double == null) { - throw new ApiException("Missing the required parameter '_double' when calling testEndpointParameters(Async)"); - } - - // verify the required parameter 'string' is set - if (string == null) { - throw new ApiException("Missing the required parameter 'string' when calling testEndpointParameters(Async)"); - } - - // verify the required parameter '_byte' is set - if (_byte == null) { - throw new ApiException("Missing the required parameter '_byte' when calling testEndpointParameters(Async)"); - } - - - // create path and map variables - String localVarPath = "/fake".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (integer != null) - localVarFormParams.put("integer", integer); - if (int32 != null) - localVarFormParams.put("int32", int32); - if (int64 != null) - localVarFormParams.put("int64", int64); - if (number != null) - localVarFormParams.put("number", number); - if (_float != null) - localVarFormParams.put("float", _float); - if (_double != null) - localVarFormParams.put("double", _double); - if (string != null) - localVarFormParams.put("string", string); - if (_byte != null) - localVarFormParams.put("byte", _byte); - if (binary != null) - localVarFormParams.put("binary", binary); - if (date != null) - localVarFormParams.put("date", date); - if (dateTime != null) - localVarFormParams.put("dateTime", dateTime); - if (password != null) - localVarFormParams.put("password", password); - - final String[] localVarAccepts = { - "application/xml; charset=utf-8", "application/json; charset=utf-8" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/xml; charset=utf-8", "application/json; charset=utf-8" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * @param number None (required) - * @param _double None (required) - * @param string None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { - testEndpointParametersWithHttpInfo(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); - } - - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * @param number None (required) - * @param _double None (required) - * @param string None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { - com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password, null, null); - return apiClient.execute(call); - } - - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 (asynchronously) - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * @param number None (required) - * @param _double None (required) - * @param string None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call testEndpointParametersAsync(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for testEnumQueryParameters */ - private com.squareup.okhttp.Call testEnumQueryParametersCall(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - - // create path and map variables - String localVarPath = "/fake".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (enumQueryInteger != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_integer", enumQueryInteger)); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (enumQueryString != null) - localVarFormParams.put("enum_query_string", enumQueryString); - if (enumQueryDouble != null) - localVarFormParams.put("enum_query_double", enumQueryDouble); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/json" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); +public class FakeApi { + private ApiClient apiClient; + + public FakeApi() { + this(Configuration.getDefaultApiClient()); + } + + public FakeApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param string None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @throws ApiException if fails to make API call + */ + public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'number' is set + if (number == null) { + throw new ApiException(400, "Missing the required parameter 'number' when calling testEndpointParameters"); } - - /** - * To test enum query parameters - * - * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) - * @param enumQueryInteger Query parameter enum test (double) (optional) - * @param enumQueryDouble Query parameter enum test (double) (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void testEnumQueryParameters(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { - testEnumQueryParametersWithHttpInfo(enumQueryString, enumQueryInteger, enumQueryDouble); + + // verify the required parameter '_double' is set + if (_double == null) { + throw new ApiException(400, "Missing the required parameter '_double' when calling testEndpointParameters"); } - - /** - * To test enum query parameters - * - * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) - * @param enumQueryInteger Query parameter enum test (double) (optional) - * @param enumQueryDouble Query parameter enum test (double) (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse testEnumQueryParametersWithHttpInfo(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { - com.squareup.okhttp.Call call = testEnumQueryParametersCall(enumQueryString, enumQueryInteger, enumQueryDouble, null, null); - return apiClient.execute(call); + + // verify the required parameter 'string' is set + if (string == null) { + throw new ApiException(400, "Missing the required parameter 'string' when calling testEndpointParameters"); } - - /** - * To test enum query parameters (asynchronously) - * - * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) - * @param enumQueryInteger Query parameter enum test (double) (optional) - * @param enumQueryDouble Query parameter enum test (double) (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call testEnumQueryParametersAsync(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = testEnumQueryParametersCall(enumQueryString, enumQueryInteger, enumQueryDouble, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; + + // verify the required parameter '_byte' is set + if (_byte == null) { + throw new ApiException(400, "Missing the required parameter '_byte' when calling testEndpointParameters"); } + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + if (integer != null) + localVarFormParams.put("integer", integer); +if (int32 != null) + localVarFormParams.put("int32", int32); +if (int64 != null) + localVarFormParams.put("int64", int64); +if (number != null) + localVarFormParams.put("number", number); +if (_float != null) + localVarFormParams.put("float", _float); +if (_double != null) + localVarFormParams.put("double", _double); +if (string != null) + localVarFormParams.put("string", string); +if (_byte != null) + localVarFormParams.put("byte", _byte); +if (binary != null) + localVarFormParams.put("binary", binary); +if (date != null) + localVarFormParams.put("date", date); +if (dateTime != null) + localVarFormParams.put("dateTime", dateTime); +if (password != null) + localVarFormParams.put("password", password); + + final String[] localVarAccepts = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * To test enum query parameters + * + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @throws ApiException if fails to make API call + */ + public void testEnumQueryParameters(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_integer", enumQueryInteger)); + + + if (enumQueryString != null) + localVarFormParams.put("enum_query_string", enumQueryString); +if (enumQueryDouble != null) + localVarFormParams.put("enum_query_double", enumQueryDouble); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java index 2039a8842c1..c126283d2aa 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java @@ -22,914 +22,389 @@ * limitations under the License. */ - package io.swagger.client.api; -import io.swagger.client.ApiCallback; -import io.swagger.client.ApiClient; +import com.sun.jersey.api.client.GenericType; + import io.swagger.client.ApiException; -import io.swagger.client.ApiResponse; +import io.swagger.client.ApiClient; import io.swagger.client.Configuration; +import io.swagger.client.model.*; import io.swagger.client.Pair; -import io.swagger.client.ProgressRequestBody; -import io.swagger.client.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; import io.swagger.client.model.Pet; import java.io.File; import io.swagger.client.model.ModelApiResponse; -import java.lang.reflect.Type; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -public class PetApi { - private ApiClient apiClient; - - public PetApi() { - this(Configuration.getDefaultApiClient()); - } - public PetApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for addPet */ - private com.squareup.okhttp.Call addPetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling addPet(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/json", "application/xml" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void addPet(Pet body) throws ApiException { - addPetWithHttpInfo(body); - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse addPetWithHttpInfo(Pet body) throws ApiException { - com.squareup.okhttp.Call call = addPetCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Add a new pet to the store (asynchronously) - * - * @param body Pet object that needs to be added to the store (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call addPetAsync(Pet body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = addPetCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for deletePet */ - private com.squareup.okhttp.Call deletePetCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling deletePet(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - if (apiKey != null) - localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Deletes a pet - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void deletePet(Long petId, String apiKey) throws ApiException { - deletePetWithHttpInfo(petId, apiKey); - } - - /** - * Deletes a pet - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse deletePetWithHttpInfo(Long petId, String apiKey) throws ApiException { - com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, null, null); - return apiClient.execute(call); - } - - /** - * Deletes a pet (asynchronously) - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call deletePetAsync(Long petId, String apiKey, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for findPetsByStatus */ - private com.squareup.okhttp.Call findPetsByStatusCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'status' is set - if (status == null) { - throw new ApiException("Missing the required parameter 'status' when calling findPetsByStatus(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/findByStatus".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (status != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "status", status)); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Finds Pets by status - * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for filter (required) - * @return List<Pet> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public List findPetsByStatus(List status) throws ApiException { - ApiResponse> resp = findPetsByStatusWithHttpInfo(status); - return resp.getData(); - } - - /** - * Finds Pets by status - * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for filter (required) - * @return ApiResponse<List<Pet>> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse> findPetsByStatusWithHttpInfo(List status) throws ApiException { - com.squareup.okhttp.Call call = findPetsByStatusCall(status, null, null); - Type localVarReturnType = new TypeToken>(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Finds Pets by status (asynchronously) - * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for filter (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call findPetsByStatusAsync(List status, final ApiCallback> callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = findPetsByStatusCall(status, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken>(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for findPetsByTags */ - private com.squareup.okhttp.Call findPetsByTagsCall(List tags, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'tags' is set - if (tags == null) { - throw new ApiException("Missing the required parameter 'tags' when calling findPetsByTags(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/findByTags".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (tags != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "tags", tags)); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Finds Pets by tags - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by (required) - * @return List<Pet> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public List findPetsByTags(List tags) throws ApiException { - ApiResponse> resp = findPetsByTagsWithHttpInfo(tags); - return resp.getData(); - } - - /** - * Finds Pets by tags - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by (required) - * @return ApiResponse<List<Pet>> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse> findPetsByTagsWithHttpInfo(List tags) throws ApiException { - com.squareup.okhttp.Call call = findPetsByTagsCall(tags, null, null); - Type localVarReturnType = new TypeToken>(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Finds Pets by tags (asynchronously) - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call findPetsByTagsAsync(List tags, final ApiCallback> callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = findPetsByTagsCall(tags, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken>(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for getPetById */ - private com.squareup.okhttp.Call getPetByIdCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling getPetById(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "api_key" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Find pet by ID - * Returns a single pet - * @param petId ID of pet to return (required) - * @return Pet - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Pet getPetById(Long petId) throws ApiException { - ApiResponse resp = getPetByIdWithHttpInfo(petId); - return resp.getData(); - } - - /** - * Find pet by ID - * Returns a single pet - * @param petId ID of pet to return (required) - * @return ApiResponse<Pet> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse getPetByIdWithHttpInfo(Long petId) throws ApiException { - com.squareup.okhttp.Call call = getPetByIdCall(petId, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Find pet by ID (asynchronously) - * Returns a single pet - * @param petId ID of pet to return (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call getPetByIdAsync(Long petId, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = getPetByIdCall(petId, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for updatePet */ - private com.squareup.okhttp.Call updatePetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling updatePet(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/json", "application/xml" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void updatePet(Pet body) throws ApiException { - updatePetWithHttpInfo(body); - } - - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse updatePetWithHttpInfo(Pet body) throws ApiException { - com.squareup.okhttp.Call call = updatePetCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Update an existing pet (asynchronously) - * - * @param body Pet object that needs to be added to the store (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call updatePetAsync(Pet body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = updatePetCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for updatePetWithForm */ - private com.squareup.okhttp.Call updatePetWithFormCall(Long petId, String name, String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling updatePetWithForm(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (name != null) - localVarFormParams.put("name", name); - if (status != null) - localVarFormParams.put("status", status); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/x-www-form-urlencoded" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void updatePetWithForm(Long petId, String name, String status) throws ApiException { - updatePetWithFormWithHttpInfo(petId, name, status); - } - - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse updatePetWithFormWithHttpInfo(Long petId, String name, String status) throws ApiException { - com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, null, null); - return apiClient.execute(call); - } - - /** - * Updates a pet in the store with form data (asynchronously) - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call updatePetWithFormAsync(Long petId, String name, String status, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for uploadFile */ - private com.squareup.okhttp.Call uploadFileCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling uploadFile(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (additionalMetadata != null) - localVarFormParams.put("additionalMetadata", additionalMetadata); - if (file != null) - localVarFormParams.put("file", file); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "multipart/form-data" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * uploads an image - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @return ModelApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { - ApiResponse resp = uploadFileWithHttpInfo(petId, additionalMetadata, file); - return resp.getData(); - } - - /** - * uploads an image - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @return ApiResponse<ModelApiResponse> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file) throws ApiException { - com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * uploads an image (asynchronously) - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call uploadFileAsync(Long petId, String additionalMetadata, File file, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } +public class PetApi { + private ApiClient apiClient; + + public PetApi() { + this(Configuration.getDefaultApiClient()); + } + + public PetApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException if fails to make API call + */ + public void addPet(Pet body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling addPet"); + } + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @throws ApiException if fails to make API call + */ + public void deletePet(Long petId, String apiKey) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling deletePet"); + } + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + if (apiKey != null) + localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + + apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return List + * @throws ApiException if fails to make API call + */ + public List findPetsByStatus(List status) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'status' is set + if (status == null) { + throw new ApiException(400, "Missing the required parameter 'status' when calling findPetsByStatus"); + } + + // create path and map variables + String localVarPath = "/pet/findByStatus".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "status", status)); + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + GenericType> localVarReturnType = new GenericType>() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return List + * @throws ApiException if fails to make API call + */ + public List findPetsByTags(List tags) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'tags' is set + if (tags == null) { + throw new ApiException(400, "Missing the required parameter 'tags' when calling findPetsByTags"); + } + + // create path and map variables + String localVarPath = "/pet/findByTags".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "tags", tags)); + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + GenericType> localVarReturnType = new GenericType>() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return Pet + * @throws ApiException if fails to make API call + */ + public Pet getPetById(Long petId) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling getPetById"); + } + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "api_key" }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException if fails to make API call + */ + public void updatePet(Pet body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling updatePet"); + } + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + + apiClient.invokeAPI(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @throws ApiException if fails to make API call + */ + public void updatePetWithForm(Long petId, String name, String status) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling updatePetWithForm"); + } + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + if (name != null) + localVarFormParams.put("name", name); +if (status != null) + localVarFormParams.put("status", status); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/x-www-form-urlencoded" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ModelApiResponse + * @throws ApiException if fails to make API call + */ + public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling uploadFile"); + } + + // create path and map variables + String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + if (additionalMetadata != null) + localVarFormParams.put("additionalMetadata", additionalMetadata); +if (file != null) + localVarFormParams.put("file", file); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/StoreApi.java index 0768744c263..b30edd4f22f 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/StoreApi.java @@ -22,461 +22,201 @@ * limitations under the License. */ - package io.swagger.client.api; -import io.swagger.client.ApiCallback; -import io.swagger.client.ApiClient; +import com.sun.jersey.api.client.GenericType; + import io.swagger.client.ApiException; -import io.swagger.client.ApiResponse; +import io.swagger.client.ApiClient; import io.swagger.client.Configuration; +import io.swagger.client.model.*; import io.swagger.client.Pair; -import io.swagger.client.ProgressRequestBody; -import io.swagger.client.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; import io.swagger.client.model.Order; -import java.lang.reflect.Type; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -public class StoreApi { - private ApiClient apiClient; - - public StoreApi() { - this(Configuration.getDefaultApiClient()); - } - - public StoreApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for deleteOrder */ - private com.squareup.okhttp.Call deleteOrderCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException("Missing the required parameter 'orderId' when calling deleteOrder(Async)"); - } - - - // create path and map variables - String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void deleteOrder(String orderId) throws ApiException { - deleteOrderWithHttpInfo(orderId); - } - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse deleteOrderWithHttpInfo(String orderId) throws ApiException { - com.squareup.okhttp.Call call = deleteOrderCall(orderId, null, null); - return apiClient.execute(call); - } - - /** - * Delete purchase order by ID (asynchronously) - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call deleteOrderAsync(String orderId, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = deleteOrderCall(orderId, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for getInventory */ - private com.squareup.okhttp.Call getInventoryCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - - // create path and map variables - String localVarPath = "/store/inventory".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "api_key" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - * @return Map<String, Integer> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Map getInventory() throws ApiException { - ApiResponse> resp = getInventoryWithHttpInfo(); - return resp.getData(); - } - - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - * @return ApiResponse<Map<String, Integer>> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse> getInventoryWithHttpInfo() throws ApiException { - com.squareup.okhttp.Call call = getInventoryCall(null, null); - Type localVarReturnType = new TypeToken>(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Returns pet inventories by status (asynchronously) - * Returns a map of status codes to quantities - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call getInventoryAsync(final ApiCallback> callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = getInventoryCall(progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken>(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for getOrderById */ - private com.squareup.okhttp.Call getOrderByIdCall(Long orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException("Missing the required parameter 'orderId' when calling getOrderById(Async)"); - } - - - // create path and map variables - String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched (required) - * @return Order - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Order getOrderById(Long orderId) throws ApiException { - ApiResponse resp = getOrderByIdWithHttpInfo(orderId); - return resp.getData(); - } - - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched (required) - * @return ApiResponse<Order> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse getOrderByIdWithHttpInfo(Long orderId) throws ApiException { - com.squareup.okhttp.Call call = getOrderByIdCall(orderId, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Find purchase order by ID (asynchronously) - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call getOrderByIdAsync(Long orderId, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = getOrderByIdCall(orderId, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for placeOrder */ - private com.squareup.okhttp.Call placeOrderCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling placeOrder(Async)"); - } - - - // create path and map variables - String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet (required) - * @return Order - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Order placeOrder(Order body) throws ApiException { - ApiResponse resp = placeOrderWithHttpInfo(body); - return resp.getData(); - } - - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet (required) - * @return ApiResponse<Order> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse placeOrderWithHttpInfo(Order body) throws ApiException { - com.squareup.okhttp.Call call = placeOrderCall(body, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Place an order for a pet (asynchronously) - * - * @param body order placed for purchasing the pet (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call placeOrderAsync(Order body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = placeOrderCall(body, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } +public class StoreApi { + private ApiClient apiClient; + + public StoreApi() { + this(Configuration.getDefaultApiClient()); + } + + public StoreApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @throws ApiException if fails to make API call + */ + public void deleteOrder(String orderId) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder"); + } + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return Map + * @throws ApiException if fails to make API call + */ + public Map getInventory() throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/store/inventory".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "api_key" }; + + GenericType> localVarReturnType = new GenericType>() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @return Order + * @throws ApiException if fails to make API call + */ + public Order getOrderById(Long orderId) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById"); + } + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet (required) + * @return Order + * @throws ApiException if fails to make API call + */ + public Order placeOrder(Order body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling placeOrder"); + } + + // create path and map variables + String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/UserApi.java index 1c4fc3101a1..9d6a1bb12fd 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/UserApi.java @@ -22,886 +22,375 @@ * limitations under the License. */ - package io.swagger.client.api; -import io.swagger.client.ApiCallback; -import io.swagger.client.ApiClient; +import com.sun.jersey.api.client.GenericType; + import io.swagger.client.ApiException; -import io.swagger.client.ApiResponse; +import io.swagger.client.ApiClient; import io.swagger.client.Configuration; +import io.swagger.client.model.*; import io.swagger.client.Pair; -import io.swagger.client.ProgressRequestBody; -import io.swagger.client.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; import io.swagger.client.model.User; -import java.lang.reflect.Type; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -public class UserApi { - private ApiClient apiClient; - - public UserApi() { - this(Configuration.getDefaultApiClient()); - } - public UserApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for createUser */ - private com.squareup.okhttp.Call createUserCall(User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling createUser(Async)"); - } - - - // create path and map variables - String localVarPath = "/user".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void createUser(User body) throws ApiException { - createUserWithHttpInfo(body); - } - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse createUserWithHttpInfo(User body) throws ApiException { - com.squareup.okhttp.Call call = createUserCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Create user (asynchronously) - * This can only be done by the logged in user. - * @param body Created user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call createUserAsync(User body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = createUserCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for createUsersWithArrayInput */ - private com.squareup.okhttp.Call createUsersWithArrayInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling createUsersWithArrayInput(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/createWithArray".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void createUsersWithArrayInput(List body) throws ApiException { - createUsersWithArrayInputWithHttpInfo(body); - } - - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse createUsersWithArrayInputWithHttpInfo(List body) throws ApiException { - com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Creates list of users with given input array (asynchronously) - * - * @param body List of user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call createUsersWithArrayInputAsync(List body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for createUsersWithListInput */ - private com.squareup.okhttp.Call createUsersWithListInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling createUsersWithListInput(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void createUsersWithListInput(List body) throws ApiException { - createUsersWithListInputWithHttpInfo(body); - } - - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse createUsersWithListInputWithHttpInfo(List body) throws ApiException { - com.squareup.okhttp.Call call = createUsersWithListInputCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Creates list of users with given input array (asynchronously) - * - * @param body List of user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call createUsersWithListInputAsync(List body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = createUsersWithListInputCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for deleteUser */ - private com.squareup.okhttp.Call deleteUserCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling deleteUser(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void deleteUser(String username) throws ApiException { - deleteUserWithHttpInfo(username); - } - - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse deleteUserWithHttpInfo(String username) throws ApiException { - com.squareup.okhttp.Call call = deleteUserCall(username, null, null); - return apiClient.execute(call); - } - - /** - * Delete user (asynchronously) - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call deleteUserAsync(String username, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = deleteUserCall(username, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for getUserByName */ - private com.squareup.okhttp.Call getUserByNameCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling getUserByName(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return User - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public User getUserByName(String username) throws ApiException { - ApiResponse resp = getUserByNameWithHttpInfo(username); - return resp.getData(); - } - - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return ApiResponse<User> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse getUserByNameWithHttpInfo(String username) throws ApiException { - com.squareup.okhttp.Call call = getUserByNameCall(username, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Get user by user name (asynchronously) - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call getUserByNameAsync(String username, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = getUserByNameCall(username, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for loginUser */ - private com.squareup.okhttp.Call loginUserCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling loginUser(Async)"); - } - - // verify the required parameter 'password' is set - if (password == null) { - throw new ApiException("Missing the required parameter 'password' when calling loginUser(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/login".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (username != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("", "username", username)); - if (password != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("", "password", password)); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Logs user into the system - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @return String - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public String loginUser(String username, String password) throws ApiException { - ApiResponse resp = loginUserWithHttpInfo(username, password); - return resp.getData(); - } - - /** - * Logs user into the system - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @return ApiResponse<String> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse loginUserWithHttpInfo(String username, String password) throws ApiException { - com.squareup.okhttp.Call call = loginUserCall(username, password, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Logs user into the system (asynchronously) - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call loginUserAsync(String username, String password, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = loginUserCall(username, password, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for logoutUser */ - private com.squareup.okhttp.Call logoutUserCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - - // create path and map variables - String localVarPath = "/user/logout".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Logs out current logged in user session - * - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void logoutUser() throws ApiException { - logoutUserWithHttpInfo(); - } - - /** - * Logs out current logged in user session - * - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse logoutUserWithHttpInfo() throws ApiException { - com.squareup.okhttp.Call call = logoutUserCall(null, null); - return apiClient.execute(call); - } - - /** - * Logs out current logged in user session (asynchronously) - * - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call logoutUserAsync(final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = logoutUserCall(progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for updateUser */ - private com.squareup.okhttp.Call updateUserCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling updateUser(Async)"); - } - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling updateUser(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void updateUser(String username, User body) throws ApiException { - updateUserWithHttpInfo(username, body); - } - - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse updateUserWithHttpInfo(String username, User body) throws ApiException { - com.squareup.okhttp.Call call = updateUserCall(username, body, null, null); - return apiClient.execute(call); - } - - /** - * Updated user (asynchronously) - * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call updateUserAsync(String username, User body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = updateUserCall(username, body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } +public class UserApi { + private ApiClient apiClient; + + public UserApi() { + this(Configuration.getDefaultApiClient()); + } + + public UserApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object (required) + * @throws ApiException if fails to make API call + */ + public void createUser(User body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling createUser"); + } + + // create path and map variables + String localVarPath = "/user".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException if fails to make API call + */ + public void createUsersWithArrayInput(List body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling createUsersWithArrayInput"); + } + + // create path and map variables + String localVarPath = "/user/createWithArray".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException if fails to make API call + */ + public void createUsersWithListInput(List body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling createUsersWithListInput"); + } + + // create path and map variables + String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @throws ApiException if fails to make API call + */ + public void deleteUser(String username) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling deleteUser"); + } + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return User + * @throws ApiException if fails to make API call + */ + public User getUserByName(String username) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling getUserByName"); + } + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return String + * @throws ApiException if fails to make API call + */ + public String loginUser(String username, String password) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling loginUser"); + } + + // verify the required parameter 'password' is set + if (password == null) { + throw new ApiException(400, "Missing the required parameter 'password' when calling loginUser"); + } + + // create path and map variables + String localVarPath = "/user/login".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("", "username", username)); + localVarQueryParams.addAll(apiClient.parameterToPairs("", "password", password)); + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Logs out current logged in user session + * + * @throws ApiException if fails to make API call + */ + public void logoutUser() throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/user/logout".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @throws ApiException if fails to make API call + */ + public void updateUser(String username, User body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser"); + } + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling updateUser"); + } + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 4eb2300b69d..592648b2bba 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -27,40 +27,44 @@ import io.swagger.client.Pair; -import com.squareup.okhttp.Credentials; +import com.migcomponents.migbase64.Base64; import java.util.Map; import java.util.List; import java.io.UnsupportedEncodingException; + public class HttpBasicAuth implements Authentication { - private String username; - private String password; + private String username; + private String password; - public String getUsername() { - return username; - } + public String getUsername() { + return username; + } - public void setUsername(String username) { - this.username = username; - } + public void setUsername(String username) { + this.username = username; + } - public String getPassword() { - return password; - } + public String getPassword() { + return password; + } - public void setPassword(String password) { - this.password = password; - } + public void setPassword(String password) { + this.password = password; + } - @Override - public void applyToParams(List queryParams, Map headerParams) { - if (username == null && password == null) { - return; - } - headerParams.put("Authorization", Credentials.basic( - username == null ? "" : username, - password == null ? "" : password)); + @Override + public void applyToParams(List queryParams, Map headerParams) { + if (username == null && password == null) { + return; + } + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + try { + headerParams.put("Authorization", "Basic " + Base64.encodeToString(str.getBytes("UTF-8"), false)); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); } + } } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 1943e013fa1..1e2d40891a2 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; @@ -39,10 +39,10 @@ */ public class AdditionalPropertiesClass { - @SerializedName("map_property") + @JsonProperty("map_property") private Map mapProperty = new HashMap(); - @SerializedName("map_of_map_property") + @JsonProperty("map_of_map_property") private Map> mapOfMapProperty = new HashMap>(); public AdditionalPropertiesClass mapProperty(Map mapProperty) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Animal.java index ba3806dc875..3ed2c6d9660 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Animal.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,10 +36,10 @@ */ public class Animal { - @SerializedName("className") + @JsonProperty("className") private String className = null; - @SerializedName("color") + @JsonProperty("color") private String color = "red"; public Animal className(String className) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 5446c2c439b..4d0dc41ee70 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; @@ -39,7 +39,7 @@ */ public class ArrayOfArrayOfNumberOnly { - @SerializedName("ArrayArrayNumber") + @JsonProperty("ArrayArrayNumber") private List> arrayArrayNumber = new ArrayList>(); public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index c9257a5d3ee..bd3f05a2ad4 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; @@ -39,7 +39,7 @@ */ public class ArrayOfNumberOnly { - @SerializedName("ArrayNumber") + @JsonProperty("ArrayNumber") private List arrayNumber = new ArrayList(); public ArrayOfNumberOnly arrayNumber(List arrayNumber) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayTest.java index 8d58870bcdc..900b8375eb0 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayTest.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.ReadOnlyFirst; @@ -39,13 +39,13 @@ */ public class ArrayTest { - @SerializedName("array_of_string") + @JsonProperty("array_of_string") private List arrayOfString = new ArrayList(); - @SerializedName("array_array_of_integer") + @JsonProperty("array_array_of_integer") private List> arrayArrayOfInteger = new ArrayList>(); - @SerializedName("array_array_of_model") + @JsonProperty("array_array_of_model") private List> arrayArrayOfModel = new ArrayList>(); public ArrayTest arrayOfString(List arrayOfString) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Cat.java index 21ed0f4c26b..f39b159f0b4 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Cat.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -37,13 +37,13 @@ */ public class Cat extends Animal { - @SerializedName("className") + @JsonProperty("className") private String className = null; - @SerializedName("color") + @JsonProperty("color") private String color = "red"; - @SerializedName("declawed") + @JsonProperty("declawed") private Boolean declawed = null; public Cat className(String className) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Category.java index 2178a866f62..c9bbbf525c5 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Category.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,10 +36,10 @@ */ public class Category { - @SerializedName("id") + @JsonProperty("id") private Long id = null; - @SerializedName("name") + @JsonProperty("name") private String name = null; public Category id(Long id) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Dog.java index 4ba5804553f..dbcd1a7207b 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Dog.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -37,13 +37,13 @@ */ public class Dog extends Animal { - @SerializedName("className") + @JsonProperty("className") private String className = null; - @SerializedName("color") + @JsonProperty("color") private String color = "red"; - @SerializedName("breed") + @JsonProperty("breed") private String breed = null; public Dog className(String className) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumClass.java index 73484907229..4433dca5f48 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumClass.java @@ -26,7 +26,6 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; /** @@ -34,13 +33,10 @@ */ public enum EnumClass { - @SerializedName("_abc") _ABC("_abc"), - @SerializedName("-efg") _EFG("-efg"), - @SerializedName("(xyz)") _XYZ_("(xyz)"); private String value; diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumTest.java index 9aad1223215..de36ef40ed4 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumTest.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -40,10 +40,8 @@ public class EnumTest { * Gets or Sets enumString */ public enum EnumStringEnum { - @SerializedName("UPPER") UPPER("UPPER"), - @SerializedName("lower") LOWER("lower"); private String value; @@ -58,17 +56,15 @@ public String toString() { } } - @SerializedName("enum_string") + @JsonProperty("enum_string") private EnumStringEnum enumString = null; /** * Gets or Sets enumInteger */ public enum EnumIntegerEnum { - @SerializedName("1") NUMBER_1(1), - @SerializedName("-1") NUMBER_MINUS_1(-1); private Integer value; @@ -83,17 +79,15 @@ public String toString() { } } - @SerializedName("enum_integer") + @JsonProperty("enum_integer") private EnumIntegerEnum enumInteger = null; /** * Gets or Sets enumNumber */ public enum EnumNumberEnum { - @SerializedName("1.1") NUMBER_1_DOT_1(1.1), - @SerializedName("-1.2") NUMBER_MINUS_1_DOT_2(-1.2); private Double value; @@ -108,7 +102,7 @@ public String toString() { } } - @SerializedName("enum_number") + @JsonProperty("enum_number") private EnumNumberEnum enumNumber = null; public EnumTest enumString(EnumStringEnum enumString) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/FormatTest.java index 91109681509..9e17949ebc8 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/FormatTest.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; @@ -39,43 +39,43 @@ */ public class FormatTest { - @SerializedName("integer") + @JsonProperty("integer") private Integer integer = null; - @SerializedName("int32") + @JsonProperty("int32") private Integer int32 = null; - @SerializedName("int64") + @JsonProperty("int64") private Long int64 = null; - @SerializedName("number") + @JsonProperty("number") private BigDecimal number = null; - @SerializedName("float") + @JsonProperty("float") private Float _float = null; - @SerializedName("double") + @JsonProperty("double") private Double _double = null; - @SerializedName("string") + @JsonProperty("string") private String string = null; - @SerializedName("byte") + @JsonProperty("byte") private byte[] _byte = null; - @SerializedName("binary") + @JsonProperty("binary") private byte[] binary = null; - @SerializedName("date") + @JsonProperty("date") private LocalDate date = null; - @SerializedName("dateTime") + @JsonProperty("dateTime") private DateTime dateTime = null; - @SerializedName("uuid") + @JsonProperty("uuid") private String uuid = null; - @SerializedName("password") + @JsonProperty("password") private String password = null; public FormatTest integer(Integer integer) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java index d77fc7ac36b..a3d01218197 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,10 +36,10 @@ */ public class HasOnlyReadOnly { - @SerializedName("bar") + @JsonProperty("bar") private String bar = null; - @SerializedName("foo") + @JsonProperty("foo") private String foo = null; /** diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MapTest.java index 61bdb6b2c65..6c0fc91ac41 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MapTest.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; @@ -39,17 +39,15 @@ */ public class MapTest { - @SerializedName("map_map_of_string") + @JsonProperty("map_map_of_string") private Map> mapMapOfString = new HashMap>(); /** * Gets or Sets inner */ public enum InnerEnum { - @SerializedName("UPPER") UPPER("UPPER"), - @SerializedName("lower") LOWER("lower"); private String value; @@ -64,7 +62,7 @@ public String toString() { } } - @SerializedName("map_of_enum_string") + @JsonProperty("map_of_enum_string") private Map mapOfEnumString = new HashMap(); public MapTest mapMapOfString(Map> mapMapOfString) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 6e587b1bf97..c37d141f972 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -41,13 +41,13 @@ */ public class MixedPropertiesAndAdditionalPropertiesClass { - @SerializedName("uuid") + @JsonProperty("uuid") private String uuid = null; - @SerializedName("dateTime") + @JsonProperty("dateTime") private DateTime dateTime = null; - @SerializedName("map") + @JsonProperty("map") private Map map = new HashMap(); public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Model200Response.java index d8da58aca9c..3f4edf12daa 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Model200Response.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -37,10 +37,10 @@ @ApiModel(description = "Model for testing model name starting with number") public class Model200Response { - @SerializedName("name") + @JsonProperty("name") private Integer name = null; - @SerializedName("class") + @JsonProperty("class") private String PropertyClass = null; public Model200Response name(Integer name) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelApiResponse.java index 2a823298323..7b86d07a148 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,13 +36,13 @@ */ public class ModelApiResponse { - @SerializedName("code") + @JsonProperty("code") private Integer code = null; - @SerializedName("type") + @JsonProperty("type") private String type = null; - @SerializedName("message") + @JsonProperty("message") private String message = null; public ModelApiResponse code(Integer code) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelReturn.java index 024a9c0df1c..e8762f850db 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelReturn.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -37,7 +37,7 @@ @ApiModel(description = "Model for testing reserved words") public class ModelReturn { - @SerializedName("return") + @JsonProperty("return") private Integer _return = null; public ModelReturn _return(Integer _return) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Name.java index 318a2ddd50e..de446cdf30d 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Name.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -37,16 +37,16 @@ @ApiModel(description = "Model for testing model name same as property name") public class Name { - @SerializedName("name") + @JsonProperty("name") private Integer name = null; - @SerializedName("snake_case") + @JsonProperty("snake_case") private Integer snakeCase = null; - @SerializedName("property") + @JsonProperty("property") private String property = null; - @SerializedName("123Number") + @JsonProperty("123Number") private Integer _123Number = null; public Name name(Integer name) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/NumberOnly.java index 9b9ca048dfb..88c33f00f02 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/NumberOnly.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/NumberOnly.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; @@ -37,7 +37,7 @@ */ public class NumberOnly { - @SerializedName("JustNumber") + @JsonProperty("JustNumber") private BigDecimal justNumber = null; public NumberOnly justNumber(BigDecimal justNumber) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Order.java index 90cfd2f3892..ddebd7f8e48 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Order.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.joda.time.DateTime; @@ -37,29 +37,26 @@ */ public class Order { - @SerializedName("id") + @JsonProperty("id") private Long id = null; - @SerializedName("petId") + @JsonProperty("petId") private Long petId = null; - @SerializedName("quantity") + @JsonProperty("quantity") private Integer quantity = null; - @SerializedName("shipDate") + @JsonProperty("shipDate") private DateTime shipDate = null; /** * Order Status */ public enum StatusEnum { - @SerializedName("placed") PLACED("placed"), - @SerializedName("approved") APPROVED("approved"), - @SerializedName("delivered") DELIVERED("delivered"); private String value; @@ -74,10 +71,10 @@ public String toString() { } } - @SerializedName("status") + @JsonProperty("status") private StatusEnum status = null; - @SerializedName("complete") + @JsonProperty("complete") private Boolean complete = false; public Order id(Long id) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Pet.java index b80fdeaf923..b468ebf1237 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Pet.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Category; @@ -40,32 +40,29 @@ */ public class Pet { - @SerializedName("id") + @JsonProperty("id") private Long id = null; - @SerializedName("category") + @JsonProperty("category") private Category category = null; - @SerializedName("name") + @JsonProperty("name") private String name = null; - @SerializedName("photoUrls") + @JsonProperty("photoUrls") private List photoUrls = new ArrayList(); - @SerializedName("tags") + @JsonProperty("tags") private List tags = new ArrayList(); /** * pet status in the store */ public enum StatusEnum { - @SerializedName("available") AVAILABLE("available"), - @SerializedName("pending") PENDING("pending"), - @SerializedName("sold") SOLD("sold"); private String value; @@ -80,7 +77,7 @@ public String toString() { } } - @SerializedName("status") + @JsonProperty("status") private StatusEnum status = null; public Pet id(Long id) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index 13b729bb94d..7f56ef2ff35 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,10 +36,10 @@ */ public class ReadOnlyFirst { - @SerializedName("bar") + @JsonProperty("bar") private String bar = null; - @SerializedName("baz") + @JsonProperty("baz") private String baz = null; /** diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/SpecialModelName.java index b46b8367a01..bc4863f101a 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,7 +36,7 @@ */ public class SpecialModelName { - @SerializedName("$special[property.name]") + @JsonProperty("$special[property.name]") private Long specialPropertyName = null; public SpecialModelName specialPropertyName(Long specialPropertyName) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Tag.java index e56eb535d1e..f27e45ea2aa 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Tag.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,10 +36,10 @@ */ public class Tag { - @SerializedName("id") + @JsonProperty("id") private Long id = null; - @SerializedName("name") + @JsonProperty("name") private String name = null; public Tag id(Long id) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/User.java index 6c1ed6ceacc..7c0421fa09e 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/User.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,28 +36,28 @@ */ public class User { - @SerializedName("id") + @JsonProperty("id") private Long id = null; - @SerializedName("username") + @JsonProperty("username") private String username = null; - @SerializedName("firstName") + @JsonProperty("firstName") private String firstName = null; - @SerializedName("lastName") + @JsonProperty("lastName") private String lastName = null; - @SerializedName("email") + @JsonProperty("email") private String email = null; - @SerializedName("password") + @JsonProperty("password") private String password = null; - @SerializedName("phone") + @JsonProperty("phone") private String phone = null; - @SerializedName("userStatus") + @JsonProperty("userStatus") private Integer userStatus = null; public User id(Long id) { diff --git a/samples/client/petstore/java/jersey2-java8/build.gradle b/samples/client/petstore/java/jersey2-java8/build.gradle index 45cca63a19d..ece2fa55d57 100644 --- a/samples/client/petstore/java/jersey2-java8/build.gradle +++ b/samples/client/petstore/java/jersey2-java8/build.gradle @@ -32,8 +32,8 @@ if(hasProperty('target') && target == 'android') { targetSdkVersion 23 } compileOptions { - sourceCompatibility JavaVersion.VERSION_1_7 - targetCompatibility JavaVersion.VERSION_1_7 + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 } // Rename the aar correctly @@ -77,7 +77,6 @@ if(hasProperty('target') && target == 'android') { apply plugin: 'java' apply plugin: 'maven' - sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 @@ -93,10 +92,22 @@ if(hasProperty('target') && target == 'android') { } } +ext { + swagger_annotations_version = "1.5.8" + jackson_version = "2.7.5" + jersey_version = "2.22.2" + junit_version = "4.12" +} + dependencies { - compile 'io.swagger:swagger-annotations:1.5.8' - compile 'com.squareup.okhttp:okhttp:2.7.5' - compile 'com.squareup.okhttp:logging-interceptor:2.7.5' - compile 'com.google.code.gson:gson:2.6.2' - testCompile 'junit:junit:4.12' + compile "io.swagger:swagger-annotations:$swagger_annotations_version" + compile "org.glassfish.jersey.core:jersey-client:$jersey_version" + compile "org.glassfish.jersey.media:jersey-media-multipart:$jersey_version" + compile "org.glassfish.jersey.media:jersey-media-json-jackson:$jersey_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-jsr310:$jackson_version" + compile "com.brsanthu:migbase64:2.2" + testCompile "junit:junit:$junit_version" } diff --git a/samples/client/petstore/java/jersey2-java8/build.sbt b/samples/client/petstore/java/jersey2-java8/build.sbt index 45814b8a5cc..b187fb67ae2 100644 --- a/samples/client/petstore/java/jersey2-java8/build.sbt +++ b/samples/client/petstore/java/jersey2-java8/build.sbt @@ -10,9 +10,14 @@ lazy val root = (project in file(".")). resolvers += Resolver.mavenLocal, libraryDependencies ++= Seq( "io.swagger" % "swagger-annotations" % "1.5.8", - "com.squareup.okhttp" % "okhttp" % "2.7.5", - "com.squareup.okhttp" % "logging-interceptor" % "2.7.5", - "com.google.code.gson" % "gson" % "2.6.2", + "org.glassfish.jersey.core" % "jersey-client" % "2.22.2", + "org.glassfish.jersey.media" % "jersey-media-multipart" % "2.22.2", + "org.glassfish.jersey.media" % "jersey-media-json-jackson" % "2.22.2", + "com.fasterxml.jackson.core" % "jackson-core" % "2.7.5", + "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.5", + "com.fasterxml.jackson.core" % "jackson-databind" % "2.7.5", + "com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % "2.7.5", + "com.brsanthu" % "migbase64" % "2.2", "junit" % "junit" % "4.12" % "test", "com.novocode" % "junit-interface" % "0.10" % "test" ) diff --git a/samples/client/petstore/java/jersey2-java8/pom.xml b/samples/client/petstore/java/jersey2-java8/pom.xml index 9bf4ed63d67..d3327ef4b98 100644 --- a/samples/client/petstore/java/jersey2-java8/pom.xml +++ b/samples/client/petstore/java/jersey2-java8/pom.xml @@ -52,7 +52,7 @@ org.apache.maven.plugins maven-jar-plugin - 2.2 + 2.6 @@ -68,7 +68,6 @@ org.codehaus.mojo build-helper-maven-plugin - 1.10 add_sources @@ -96,6 +95,15 @@ + + org.apache.maven.plugins + maven-compiler-plugin + 2.5.1 + + 1.8 + 1.8 + + @@ -104,20 +112,51 @@ swagger-annotations ${swagger-core-version} + + + + org.glassfish.jersey.core + jersey-client + ${jersey-version} + + + org.glassfish.jersey.media + jersey-media-multipart + ${jersey-version} + - com.squareup.okhttp - okhttp - ${okhttp-version} + org.glassfish.jersey.media + jersey-media-json-jackson + ${jersey-version} + + - com.squareup.okhttp - logging-interceptor - ${okhttp-version} + com.fasterxml.jackson.core + jackson-core + ${jackson-version} - com.google.code.gson - gson - ${gson-version} + com.fasterxml.jackson.core + jackson-annotations + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-version} + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson-version} + + + + + com.brsanthu + migbase64 + 2.2 @@ -129,15 +168,10 @@ - 1.8 - ${java.version} - ${java.version} - 1.5.9 - 2.7.5 - 2.6.2 - 2.9.3 + 1.5.8 + 2.22.2 + 2.7.5 1.0.0 4.12 - UTF-8 diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiCallback.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiCallback.java deleted file mode 100644 index 3ca33cf8017..00000000000 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiCallback.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import java.io.IOException; - -import java.util.Map; -import java.util.List; - -/** - * Callback for asynchronous API call. - * - * @param The return type - */ -public interface ApiCallback { - /** - * This is called when the API call fails. - * - * @param e The exception causing the failure - * @param statusCode Status code of the response if available, otherwise it would be 0 - * @param responseHeaders Headers of the response if available, otherwise it would be null - */ - void onFailure(ApiException e, int statusCode, Map> responseHeaders); - - /** - * This is called when the API call succeeded. - * - * @param result The result deserialized from response - * @param statusCode Status code of the response - * @param responseHeaders Headers of the response - */ - void onSuccess(T result, int statusCode, Map> responseHeaders); - - /** - * This is called when the API upload processing. - * - * @param bytesWritten bytes Written - * @param contentLength content length of request body - * @param done write end - */ - void onUploadProgress(long bytesWritten, long contentLength, boolean done); - - /** - * This is called when the API downlond processing. - * - * @param bytesRead bytes Read - * @param contentLength content lenngth of the response - * @param done Read end - */ - void onDownloadProgress(long bytesRead, long contentLength, boolean done); -} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiClient.java index b7b04e3e4c5..047a47252f8 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiClient.java @@ -1,46 +1,28 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - package io.swagger.client; -import com.squareup.okhttp.Call; -import com.squareup.okhttp.Callback; -import com.squareup.okhttp.OkHttpClient; -import com.squareup.okhttp.Request; -import com.squareup.okhttp.Response; -import com.squareup.okhttp.RequestBody; -import com.squareup.okhttp.FormEncodingBuilder; -import com.squareup.okhttp.MultipartBuilder; -import com.squareup.okhttp.MediaType; -import com.squareup.okhttp.Headers; -import com.squareup.okhttp.internal.http.HttpMethod; -import com.squareup.okhttp.logging.HttpLoggingInterceptor; -import com.squareup.okhttp.logging.HttpLoggingInterceptor.Level; - -import java.lang.reflect.Type; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +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; + +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.client.ClientProperties; +import org.glassfish.jersey.filter.LoggingFilter; +import org.glassfish.jersey.jackson.JacksonFeature; +import org.glassfish.jersey.media.multipart.FormDataBodyPart; +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.MultiPart; +import org.glassfish.jersey.media.multipart.MultiPartFeature; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; import java.util.Collection; import java.util.Collections; import java.util.Map; @@ -50,1277 +32,667 @@ import java.util.ArrayList; import java.util.Date; import java.util.TimeZone; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import java.net.URLEncoder; -import java.net.URLConnection; import java.io.File; -import java.io.InputStream; -import java.io.IOException; import java.io.UnsupportedEncodingException; -import java.security.GeneralSecurityException; -import java.security.KeyStore; -import java.security.SecureRandom; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; - import java.text.DateFormat; import java.text.SimpleDateFormat; -import java.text.ParseException; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.KeyManager; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.X509TrustManager; - -import okio.BufferedSink; -import okio.Okio; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import io.swagger.client.auth.Authentication; import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; -public class ApiClient { - public static final double JAVA_VERSION; - public static final boolean IS_ANDROID; - public static final int ANDROID_SDK_VERSION; - - static { - JAVA_VERSION = Double.parseDouble(System.getProperty("java.specification.version")); - boolean isAndroid; - try { - Class.forName("android.app.Activity"); - isAndroid = true; - } catch (ClassNotFoundException e) { - isAndroid = false; - } - IS_ANDROID = isAndroid; - int sdkVersion = 0; - if (IS_ANDROID) { - try { - sdkVersion = Class.forName("android.os.Build$VERSION").getField("SDK_INT").getInt(null); - } catch (Exception e) { - try { - sdkVersion = Integer.parseInt((String) Class.forName("android.os.Build$VERSION").getField("SDK").get(null)); - } catch (Exception e2) { } - } - } - ANDROID_SDK_VERSION = sdkVersion; - } - - /** - * The datetime format to be used when lenientDatetimeFormat is enabled. - */ - public static final String LENIENT_DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; - - private String basePath = "http://petstore.swagger.io/v2"; - private boolean lenientOnJson = false; - private boolean debugging = false; - private Map defaultHeaderMap = new HashMap(); - private String tempFolderPath = null; - - private Map authentications; - - private DateFormat dateFormat; - private DateFormat datetimeFormat; - private boolean lenientDatetimeFormat; - private int dateLength; - - private InputStream sslCaCert; - private boolean verifyingSsl; - - private OkHttpClient httpClient; - private JSON json; - - private HttpLoggingInterceptor loggingInterceptor; - - /* - * Constructor for ApiClient - */ - public ApiClient() { - httpClient = new OkHttpClient(); - - verifyingSsl = true; - - json = new JSON(this); - - /* - * Use RFC3339 format for date and datetime. - * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 - */ - this.dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - // Always use UTC as the default time zone when dealing with date (without time). - this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - initDatetimeFormat(); - - // Be lenient on datetime formats when parsing datetime from string. - // See parseDatetime. - this.lenientDatetimeFormat = true; - - // Set default User-Agent. - setUserAgent("Swagger-Codegen/1.0.0/java"); - - // Setup authentications (key: authentication name, value: authentication). - authentications = new HashMap(); - authentications.put("api_key", new ApiKeyAuth("header", "api_key")); - authentications.put("petstore_auth", new OAuth()); - // Prevent the authentications from being modified. - authentications = Collections.unmodifiableMap(authentications); - } - - /** - * Get base path - * - * @return Baes path - */ - public String getBasePath() { - return basePath; - } - - /** - * Set base path - * - * @param basePath Base path of the URL (e.g http://petstore.swagger.io/v2 - * @return An instance of OkHttpClient - */ - public ApiClient setBasePath(String basePath) { - this.basePath = basePath; - return this; - } - - /** - * Get HTTP client - * - * @return An instance of OkHttpClient - */ - public OkHttpClient getHttpClient() { - return httpClient; - } - - /** - * Set HTTP client - * - * @param httpClient An instance of OkHttpClient - * @return Api Client - */ - public ApiClient setHttpClient(OkHttpClient httpClient) { - this.httpClient = httpClient; - return this; - } - - /** - * Get JSON - * - * @return JSON object - */ - public JSON getJSON() { - return json; - } - - /** - * Set JSON - * - * @param json JSON object - * @return Api client - */ - public ApiClient setJSON(JSON json) { - this.json = json; - return this; - } - - /** - * True if isVerifyingSsl flag is on - * - * @return True if isVerifySsl flag is on - */ - public boolean isVerifyingSsl() { - return verifyingSsl; - } - - /** - * Configure whether to verify certificate and hostname when making https requests. - * Default to true. - * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. - * - * @param verifyingSsl True to verify TLS/SSL connection - * @return ApiClient - */ - public ApiClient setVerifyingSsl(boolean verifyingSsl) { - this.verifyingSsl = verifyingSsl; - applySslSettings(); - return this; - } - - /** - * Get SSL CA cert. - * - * @return Input stream to the SSL CA cert - */ - public InputStream getSslCaCert() { - return sslCaCert; - } - - /** - * Configure the CA certificate to be trusted when making https requests. - * Use null to reset to default. - * - * @param sslCaCert input stream for SSL CA cert - * @return ApiClient - */ - public ApiClient setSslCaCert(InputStream sslCaCert) { - this.sslCaCert = sslCaCert; - applySslSettings(); - return this; - } - - public DateFormat getDateFormat() { - return dateFormat; - } - - public ApiClient setDateFormat(DateFormat dateFormat) { - this.dateFormat = dateFormat; - this.dateLength = this.dateFormat.format(new Date()).length(); - return this; - } - - public DateFormat getDatetimeFormat() { - return datetimeFormat; - } - - public ApiClient setDatetimeFormat(DateFormat datetimeFormat) { - this.datetimeFormat = datetimeFormat; - return this; - } - - /** - * Whether to allow various ISO 8601 datetime formats when parsing a datetime string. - * @see #parseDatetime(String) - * @return True if lenientDatetimeFormat flag is set to true - */ - public boolean isLenientDatetimeFormat() { - return lenientDatetimeFormat; - } - - public ApiClient setLenientDatetimeFormat(boolean lenientDatetimeFormat) { - this.lenientDatetimeFormat = lenientDatetimeFormat; - return this; - } - - /** - * Parse the given date string into Date object. - * The default dateFormat supports these ISO 8601 date formats: - * 2015-08-16 - * 2015-8-16 - * @param str String to be parsed - * @return Date - */ - public Date parseDate(String str) { - if (str == null) - return null; - try { - return dateFormat.parse(str); - } catch (ParseException e) { - throw new RuntimeException(e); - } - } - - /** - * Parse the given datetime string into Date object. - * When lenientDatetimeFormat is enabled, the following ISO 8601 datetime formats are supported: - * 2015-08-16T08:20:05Z - * 2015-8-16T8:20:05Z - * 2015-08-16T08:20:05+00:00 - * 2015-08-16T08:20:05+0000 - * 2015-08-16T08:20:05.376Z - * 2015-08-16T08:20:05.376+00:00 - * 2015-08-16T08:20:05.376+00 - * Note: The 3-digit milli-seconds is optional. Time zone is required and can be in one of - * these formats: - * Z (same with +0000) - * +08:00 (same with +0800) - * -02 (same with -0200) - * -0200 - * @see ISO 8601 - * @param str Date time string to be parsed - * @return Date representation of the string - */ - public Date parseDatetime(String str) { - if (str == null) - return null; - - DateFormat format; - if (lenientDatetimeFormat) { - /* - * When lenientDatetimeFormat is enabled, normalize the date string - * into LENIENT_DATETIME_FORMAT to support various formats - * defined by ISO 8601. - */ - // normalize time zone - // trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000 - str = str.replaceAll("[zZ]\\z", "+0000"); - // remove colon in time zone: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000 - str = str.replaceAll("([+-]\\d{2}):(\\d{2})\\z", "$1$2"); - // expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000 - str = str.replaceAll("([+-]\\d{2})\\z", "$100"); - // add milliseconds when missing - // 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000 - str = str.replaceAll("(:\\d{1,2})([+-]\\d{4})\\z", "$1.000$2"); - format = new SimpleDateFormat(LENIENT_DATETIME_FORMAT); - } else { - format = this.datetimeFormat; - } - - try { - return format.parse(str); - } catch (ParseException e) { - throw new RuntimeException(e); - } - } - - /* - * Parse date or date time in string format into Date object. - * - * @param str Date time string to be parsed - * @return Date representation of the string - */ - public Date parseDateOrDatetime(String str) { - if (str == null) - return null; - else if (str.length() <= dateLength) - return parseDate(str); - else - return parseDatetime(str); - } - - /** - * Format the given Date object into string (Date format). - * - * @param date Date object - * @return Formatted date in string representation - */ - public String formatDate(Date date) { - return dateFormat.format(date); - } - - /** - * Format the given Date object into string (Datetime format). - * - * @param date Date object - * @return Formatted datetime in string representation - */ - public String formatDatetime(Date date) { - return datetimeFormat.format(date); - } - - /** - * Get authentications (key: authentication name, value: authentication). - * - * @return Map of authentication objects - */ - public Map getAuthentications() { - return authentications; - } - - /** - * Get authentication for the given name. - * - * @param authName The authentication name - * @return The authentication, null if not found - */ - public Authentication getAuthentication(String authName) { - return authentications.get(authName); - } - - /** - * Helper method to set username for the first HTTP basic authentication. - * - * @param username Username - */ - public void setUsername(String username) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setUsername(username); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set password for the first HTTP basic authentication. - * - * @param password Password - */ - public void setPassword(String password) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setPassword(password); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set API key value for the first API key authentication. - * - * @param apiKey API key - */ - public void setApiKey(String apiKey) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKey(apiKey); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set API key prefix for the first API key authentication. - * - * @param apiKeyPrefix API key prefix - */ - public void setApiKeyPrefix(String apiKeyPrefix) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set access token for the first OAuth2 authentication. - * - * @param accessToken Access token - */ - public void setAccessToken(String accessToken) { - for (Authentication auth : authentications.values()) { - if (auth instanceof OAuth) { - ((OAuth) auth).setAccessToken(accessToken); - return; - } - } - throw new RuntimeException("No OAuth2 authentication configured!"); - } - - /** - * Set the User-Agent header's value (by adding to the default header map). - * - * @param userAgent HTTP request's user agent - * @return ApiClient - */ - public ApiClient setUserAgent(String userAgent) { - addDefaultHeader("User-Agent", userAgent); - return this; - } - - /** - * Add a default header. - * - * @param key The header's key - * @param value The header's value - * @return ApiClient - */ - public ApiClient addDefaultHeader(String key, String value) { - defaultHeaderMap.put(key, value); - return this; - } - - /** - * @see setLenient - * - * @return True if lenientOnJson is enabled, false otherwise. - */ - public boolean isLenientOnJson() { - return lenientOnJson; - } - - /** - * Set LenientOnJson - * - * @param lenient True to enable lenientOnJson - * @return ApiClient - */ - public ApiClient setLenientOnJson(boolean lenient) { - this.lenientOnJson = lenient; - return this; - } - - /** - * Check that whether debugging is enabled for this API client. - * - * @return True if debugging is enabled, false otherwise. - */ - public boolean isDebugging() { - return debugging; - } - - /** - * Enable/disable debugging for this API client. - * - * @param debugging To enable (true) or disable (false) debugging - * @return ApiClient - */ - public ApiClient setDebugging(boolean debugging) { - if (debugging != this.debugging) { - if (debugging) { - loggingInterceptor = new HttpLoggingInterceptor(); - loggingInterceptor.setLevel(Level.BODY); - httpClient.interceptors().add(loggingInterceptor); - } else { - httpClient.interceptors().remove(loggingInterceptor); - loggingInterceptor = null; - } - } - this.debugging = debugging; - return this; - } - - /** - * The path of temporary folder used to store downloaded files from endpoints - * with file response. The default value is null, i.e. using - * the system's default tempopary folder. - * - * @see createTempFile - * @return Temporary folder path - */ - public String getTempFolderPath() { - return tempFolderPath; - } - - /** - * Set the tempoaray folder path (for downloading files) - * - * @param tempFolderPath Temporary folder path - * @return ApiClient - */ - public ApiClient setTempFolderPath(String tempFolderPath) { - this.tempFolderPath = tempFolderPath; - return this; - } - - /** - * Get connection timeout (in milliseconds). - * - * @return Timeout in milliseconds - */ - public int getConnectTimeout() { - return httpClient.getConnectTimeout(); - } - - /** - * Sets the connect timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * - * @param connectionTimeout connection timeout in milliseconds - * @return Api client - */ - public ApiClient setConnectTimeout(int connectionTimeout) { - httpClient.setConnectTimeout(connectionTimeout, TimeUnit.MILLISECONDS); - return this; - } - - /** - * Format the given parameter object into string. - * - * @param param Parameter - * @return String representation of the parameter - */ - public String parameterToString(Object param) { - if (param == null) { - return ""; - } else if (param instanceof Date) { - return formatDatetime((Date) param); - } else if (param instanceof Collection) { - StringBuilder b = new StringBuilder(); - for (Object o : (Collection)param) { - if (b.length() > 0) { - b.append(","); - } - b.append(String.valueOf(o)); - } - return b.toString(); - } else { - return String.valueOf(param); - } - } - - /** - * Format to {@code Pair} objects. - * - * @param collectionFormat collection format (e.g. csv, tsv) - * @param name Name - * @param value Value - * @return A list of Pair objects - */ - public List parameterToPairs(String collectionFormat, String name, Object value){ - List params = new ArrayList(); - - // preconditions - if (name == null || name.isEmpty() || value == null) return params; - - Collection valueCollection = null; - if (value instanceof Collection) { - valueCollection = (Collection) value; - } else { - params.add(new Pair(name, parameterToString(value))); - return params; - } - - if (valueCollection.isEmpty()){ - return params; - } - - // get the collection format - collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv - - // create the params based on the collection format - if (collectionFormat.equals("multi")) { - for (Object item : valueCollection) { - params.add(new Pair(name, parameterToString(item))); - } - - return params; - } - - String delimiter = ","; - - if (collectionFormat.equals("csv")) { - delimiter = ","; - } else if (collectionFormat.equals("ssv")) { - delimiter = " "; - } else if (collectionFormat.equals("tsv")) { - delimiter = "\t"; - } else if (collectionFormat.equals("pipes")) { - delimiter = "|"; - } - - StringBuilder sb = new StringBuilder() ; - for (Object item : valueCollection) { - sb.append(delimiter); - sb.append(parameterToString(item)); - } - - params.add(new Pair(name, sb.substring(1))); - - return params; - } - - /** - * Sanitize filename by removing path. - * e.g. ../../sun.gif becomes sun.gif - * - * @param filename The filename to be sanitized - * @return The sanitized filename - */ - public String sanitizeFilename(String filename) { - return filename.replaceAll(".*[/\\\\]", ""); - } - - /** - * Check if the given MIME is a JSON MIME. - * JSON MIME examples: - * application/json - * application/json; charset=UTF8 - * APPLICATION/JSON - * - * @param mime MIME (Multipurpose Internet Mail Extensions) - * @return True if the given MIME is JSON, false otherwise. - */ - public boolean isJsonMime(String mime) { - return mime != null && mime.matches("(?i)application\\/json(;.*)?"); - } - - /** - * Select the Accept header's value from the given accepts array: - * if JSON exists in the given array, use it; - * otherwise use all of them (joining into a string) - * - * @param accepts The accepts array to select from - * @return The Accept header to use. If the given array is empty, - * null will be returned (not to set the Accept header explicitly). - */ - public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) { - return null; - } - for (String accept : accepts) { - if (isJsonMime(accept)) { - return accept; - } - } - return StringUtil.join(accepts, ","); - } - - /** - * Select the Content-Type header's value from the given array: - * if JSON exists in the given array, use it; - * otherwise use the first one of the array. - * - * @param contentTypes The Content-Type array to select from - * @return The Content-Type header to use. If the given array is empty, - * JSON will be used. - */ - public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) { - return "application/json"; - } - for (String contentType : contentTypes) { - if (isJsonMime(contentType)) { - return contentType; - } - } - return contentTypes[0]; - } - - /** - * Escape the given string to be used as URL query value. - * - * @param str String to be escaped - * @return Escaped string - */ - public String escapeString(String str) { - try { - return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); - } catch (UnsupportedEncodingException e) { - return str; - } - } - - /** - * Deserialize response body to Java object, according to the return type and - * the Content-Type response header. - * - * @param Type - * @param response HTTP response - * @param returnType The type of the Java object - * @return The deserialized Java object - * @throws ApiException If fail to deserialize response body, i.e. cannot read response body - * or the Content-Type of the response is not supported. - */ - @SuppressWarnings("unchecked") - public T deserialize(Response response, Type returnType) throws ApiException { - if (response == null || returnType == null) { - return null; - } - - if ("byte[]".equals(returnType.toString())) { - // Handle binary response (byte array). - try { - return (T) response.body().bytes(); - } catch (IOException e) { - throw new ApiException(e); - } - } else if (returnType.equals(File.class)) { - // Handle file downloading. - return (T) downloadFileFromResponse(response); - } - - String respBody; - try { - if (response.body() != null) - respBody = response.body().string(); - else - respBody = null; - } catch (IOException e) { - throw new ApiException(e); - } - - if (respBody == null || "".equals(respBody)) { - return null; - } - String contentType = response.headers().get("Content-Type"); - if (contentType == null) { - // ensuring a default content type - contentType = "application/json"; - } - if (isJsonMime(contentType)) { - return json.deserialize(respBody, returnType); - } else if (returnType.equals(String.class)) { - // Expecting string, return the raw response body. - return (T) respBody; - } else { - throw new ApiException( - "Content type \"" + contentType + "\" is not supported for type: " + returnType, - response.code(), - response.headers().toMultimap(), - respBody); - } - } - - /** - * Serialize the given Java object into request body according to the object's - * class and the request Content-Type. - * - * @param obj The Java object - * @param contentType The request Content-Type - * @return The serialized request body - * @throws ApiException If fail to serialize the given object - */ - public RequestBody serialize(Object obj, String contentType) throws ApiException { - if (obj instanceof byte[]) { - // Binary (byte array) body parameter support. - return RequestBody.create(MediaType.parse(contentType), (byte[]) obj); - } else if (obj instanceof File) { - // File body parameter support. - return RequestBody.create(MediaType.parse(contentType), (File) obj); - } else if (isJsonMime(contentType)) { - String content; - if (obj != null) { - content = json.serialize(obj); - } else { - content = null; - } - return RequestBody.create(MediaType.parse(contentType), content); - } else { - throw new ApiException("Content type \"" + contentType + "\" is not supported"); - } - } - - /** - * Download file from the given response. - * - * @param response An instance of the Response object - * @throws ApiException If fail to read file content from response and write to disk - * @return Downloaded file - */ - public File downloadFileFromResponse(Response response) throws ApiException { - try { - File file = prepareDownloadFile(response); - BufferedSink sink = Okio.buffer(Okio.sink(file)); - sink.writeAll(response.body().source()); - sink.close(); - return file; - } catch (IOException e) { - throw new ApiException(e); - } - } - - /** - * Prepare file for download - * - * @param response An instance of the Response object - * @throws IOException If fail to prepare file for download - * @return Prepared file for the download - */ - public File prepareDownloadFile(Response response) throws IOException { - String filename = null; - String contentDisposition = response.header("Content-Disposition"); - if (contentDisposition != null && !"".equals(contentDisposition)) { - // Get filename from the Content-Disposition header. - Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); - Matcher matcher = pattern.matcher(contentDisposition); - if (matcher.find()) { - filename = sanitizeFilename(matcher.group(1)); - } - } - - String prefix = null; - String suffix = null; - if (filename == null) { - prefix = "download-"; - suffix = ""; - } else { - int pos = filename.lastIndexOf("."); - if (pos == -1) { - prefix = filename + "-"; - } else { - prefix = filename.substring(0, pos) + "-"; - suffix = filename.substring(pos); - } - // File.createTempFile requires the prefix to be at least three characters long - if (prefix.length() < 3) - prefix = "download-"; - } - - if (tempFolderPath == null) - return File.createTempFile(prefix, suffix); - else - return File.createTempFile(prefix, suffix, new File(tempFolderPath)); - } - - /** - * {@link #execute(Call, Type)} - * - * @param Type - * @param call An instance of the Call object - * @throws ApiException If fail to execute the call - * @return ApiResponse<T> - */ - public ApiResponse execute(Call call) throws ApiException { - return execute(call, null); - } - - /** - * Execute HTTP call and deserialize the HTTP response body into the given return type. - * - * @param returnType The return type used to deserialize HTTP response body - * @param The return type corresponding to (same with) returnType - * @param call Call - * @return ApiResponse object containing response status, headers and - * data, which is a Java object deserialized from response body and would be null - * when returnType is null. - * @throws ApiException If fail to execute the call - */ - public ApiResponse execute(Call call, Type returnType) throws ApiException { - try { - Response response = call.execute(); - T data = handleResponse(response, returnType); - return new ApiResponse(response.code(), response.headers().toMultimap(), data); - } catch (IOException e) { - throw new ApiException(e); - } - } - - /** - * {@link #executeAsync(Call, Type, ApiCallback)} - * - * @param Type - * @param call An instance of the Call object - * @param callback ApiCallback<T> - */ - public void executeAsync(Call call, ApiCallback callback) { - executeAsync(call, null, callback); - } - - /** - * Execute HTTP call asynchronously. - * - * @see #execute(Call, Type) - * @param Type - * @param call The callback to be executed when the API call finishes - * @param returnType Return type - * @param callback ApiCallback - */ - @SuppressWarnings("unchecked") - public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { - call.enqueue(new Callback() { - @Override - public void onFailure(Request request, IOException e) { - callback.onFailure(new ApiException(e), 0, null); - } - - @Override - public void onResponse(Response response) throws IOException { - T result; - try { - result = (T) handleResponse(response, returnType); - } catch (ApiException e) { - callback.onFailure(e, response.code(), response.headers().toMultimap()); - return; - } - callback.onSuccess(result, response.code(), response.headers().toMultimap()); - } - }); - } - - /** - * Handle the given response, return the deserialized object when the response is successful. - * - * @param Type - * @param response Response - * @param returnType Return type - * @throws ApiException If the response has a unsuccessful status code or - * fail to deserialize the response body - * @return Type - */ - public T handleResponse(Response response, Type returnType) throws ApiException { - if (response.isSuccessful()) { - if (returnType == null || response.code() == 204) { - // returning null if the returnType is not defined, - // or the status code is 204 (No Content) - return null; - } else { - return deserialize(response, returnType); - } - } else { - String respBody = null; - if (response.body() != null) { - try { - respBody = response.body().string(); - } catch (IOException e) { - throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); - } - } - throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); - } - } - - /** - * Build HTTP call with the given options. - * - * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" - * @param queryParams The query parameters - * @param body The request body object - * @param headerParams The header parameters - * @param formParams The form parameters - * @param authNames The authentications to apply - * @param progressRequestListener Progress request listener - * @return The HTTP call - * @throws ApiException If fail to serialize the request body object - */ - public Call buildCall(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - updateParamsForAuth(authNames, queryParams, headerParams); - - final String url = buildUrl(path, queryParams); - final Request.Builder reqBuilder = new Request.Builder().url(url); - processHeaderParams(headerParams, reqBuilder); - - String contentType = (String) headerParams.get("Content-Type"); - // ensuring a default content type - if (contentType == null) { - contentType = "application/json"; - } - - RequestBody reqBody; - if (!HttpMethod.permitsRequestBody(method)) { - reqBody = null; - } else if ("application/x-www-form-urlencoded".equals(contentType)) { - reqBody = buildRequestBodyFormEncoding(formParams); - } else if ("multipart/form-data".equals(contentType)) { - reqBody = buildRequestBodyMultipart(formParams); - } else if (body == null) { - if ("DELETE".equals(method)) { - // allow calling DELETE without sending a request body - reqBody = null; - } else { - // use an empty request body (for POST, PUT and PATCH) - reqBody = RequestBody.create(MediaType.parse(contentType), ""); - } - } else { - reqBody = serialize(body, contentType); - } - - Request request = null; - - if(progressRequestListener != null && reqBody != null) { - ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener); - request = reqBuilder.method(method, progressRequestBody).build(); - } else { - request = reqBuilder.method(method, reqBody).build(); - } - - return httpClient.newCall(request); - } - - /** - * Build full URL by concatenating base path, the given sub path and query parameters. - * - * @param path The sub path - * @param queryParams The query parameters - * @return The full URL - */ - public String buildUrl(String path, List queryParams) { - final StringBuilder url = new StringBuilder(); - url.append(basePath).append(path); - - if (queryParams != null && !queryParams.isEmpty()) { - // support (constant) query string in `path`, e.g. "/posts?draft=1" - String prefix = path.contains("?") ? "&" : "?"; - for (Pair param : queryParams) { - if (param.getValue() != null) { - if (prefix != null) { - url.append(prefix); - prefix = null; - } else { - url.append("&"); - } - String value = parameterToString(param.getValue()); - url.append(escapeString(param.getName())).append("=").append(escapeString(value)); - } - } - } - - return url.toString(); - } - - /** - * Set header parameters to the request builder, including default headers. - * - * @param headerParams Header parameters in the ofrm of Map - * @param reqBuilder Reqeust.Builder - */ - public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { - for (Entry param : headerParams.entrySet()) { - reqBuilder.header(param.getKey(), parameterToString(param.getValue())); - } - for (Entry header : defaultHeaderMap.entrySet()) { - if (!headerParams.containsKey(header.getKey())) { - reqBuilder.header(header.getKey(), parameterToString(header.getValue())); - } - } - } - - /** - * Update query and header parameters based on authentication settings. - * - * @param authNames The authentications to apply - * @param queryParams List of query parameters - * @param headerParams Map of header parameters - */ - public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { - for (String authName : authNames) { - Authentication auth = authentications.get(authName); - if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); - auth.applyToParams(queryParams, headerParams); - } - } - - /** - * Build a form-encoding request body with the given form parameters. - * - * @param formParams Form parameters in the form of Map - * @return RequestBody - */ - public RequestBody buildRequestBodyFormEncoding(Map formParams) { - FormEncodingBuilder formBuilder = new FormEncodingBuilder(); - for (Entry param : formParams.entrySet()) { - formBuilder.add(param.getKey(), parameterToString(param.getValue())); - } - return formBuilder.build(); - } - - /** - * Build a multipart (file uploading) request body with the given form parameters, - * which could contain text fields and file fields. - * - * @param formParams Form parameters in the form of Map - * @return RequestBody - */ - public RequestBody buildRequestBodyMultipart(Map formParams) { - MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); - for (Entry param : formParams.entrySet()) { - if (param.getValue() instanceof File) { - File file = (File) param.getValue(); - Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\""); - MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); - mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file)); - } else { - Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\""); - mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue()))); - } - } - return mpBuilder.build(); - } - - /** - * Guess Content-Type header from the given file (defaults to "application/octet-stream"). - * - * @param file The given file - * @return The guessed Content-Type - */ - public String guessContentTypeFromFile(File file) { - String contentType = URLConnection.guessContentTypeFromName(file.getName()); - if (contentType == null) { - return "application/octet-stream"; - } else { - return contentType; - } - } - - /** - * Initialize datetime format according to the current environment, e.g. Java 1.7 and Android. - */ - private void initDatetimeFormat() { - String formatWithTimeZone = null; - if (IS_ANDROID) { - if (ANDROID_SDK_VERSION >= 18) { - // The time zone format "ZZZZZ" is available since Android 4.3 (SDK version 18) - formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"; - } - } else if (JAVA_VERSION >= 1.7) { - // The time zone format "XXX" is available since Java 1.7 - formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; - } - if (formatWithTimeZone != null) { - this.datetimeFormat = new SimpleDateFormat(formatWithTimeZone); - // NOTE: Use the system's default time zone (mainly for datetime formatting). +public class ApiClient { + private Map defaultHeaderMap = new HashMap(); + private String basePath = "http://petstore.swagger.io/v2"; + private boolean debugging = false; + private int connectionTimeout = 0; + + private Client httpClient; + private JSON json; + private String tempFolderPath = null; + + private Map authentications; + + private int statusCode; + private Map> responseHeaders; + + private DateFormat dateFormat; + + public ApiClient() { + json = new JSON(); + httpClient = buildHttpClient(debugging); + + // Use RFC3339 format for date and datetime. + // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + + // Use UTC as the default time zone. + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + + this.json.setDateFormat((DateFormat) dateFormat.clone()); + + // Set default User-Agent. + setUserAgent("Swagger-Codegen/1.0.0/java"); + + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap(); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("petstore_auth", new OAuth()); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + /** + * Gets the JSON instance to do JSON serialization and deserialization. + */ + public JSON getJSON() { + return json; + } + + public Client getHttpClient() { + return httpClient; + } + + public ApiClient setHttpClient(Client httpClient) { + this.httpClient = httpClient; + return this; + } + + public String getBasePath() { + return basePath; + } + + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + /** + * Gets the status code of the previous request + */ + public int getStatusCode() { + return statusCode; + } + + /** + * Gets the response headers of the previous request + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + + /** + * Get authentications (key: authentication name, value: authentication). + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set access token for the first OAuth2 authentication. + */ + public void setAccessToken(String accessToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); + return; + } + } + throw new RuntimeException("No OAuth2 authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + */ + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + /** + * Check that whether debugging is enabled for this API client. + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + */ + public ApiClient setDebugging(boolean debugging) { + this.debugging = debugging; + // Rebuild HTTP Client according to the new "debugging" value. + this.httpClient = buildHttpClient(debugging); + return this; + } + + /** + * The path of temporary folder used to store downloaded files from endpoints + * with file response. The default value is null, i.e. using + * the system's default tempopary folder. + * + * @see https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createTempFile(java.lang.String,%20java.lang.String,%20java.io.File) + */ + public String getTempFolderPath() { + return tempFolderPath; + } + + public ApiClient setTempFolderPath(String tempFolderPath) { + this.tempFolderPath = tempFolderPath; + return this; + } + + /** + * Connect timeout (in milliseconds). + */ + public int getConnectTimeout() { + return connectionTimeout; + } + + /** + * Set the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link Integer#MAX_VALUE}. + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + this.connectionTimeout = connectionTimeout; + httpClient.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout); + return this; + } + + /** + * Get the date format used to parse/format date parameters. + */ + public DateFormat getDateFormat() { + return dateFormat; + } + + /** + * Set the date format used to parse/format date parameters. + */ + 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()); + return this; + } + + /** + * Parse the given string into Date object. + */ + public Date parseDate(String str) { + try { + return dateFormat.parse(str); + } catch (java.text.ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Format the given Date object into string. + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } + + /** + * 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 to {@code Pair} objects. + */ + public List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + + // create the params based on the collection format + if (collectionFormat.equals("multi")) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); + } + + return params; + } + + String delimiter = ","; + + if (collectionFormat.equals("csv")) { + delimiter = ","; + } else if (collectionFormat.equals("ssv")) { + delimiter = " "; + } else if (collectionFormat.equals("tsv")) { + delimiter = "\t"; + } else if (collectionFormat.equals("pipes")) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + + return params; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + */ + public boolean isJsonMime(String mime) { + return mime != null && mime.matches("(?i)application\\/json(;.*)?"); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } + return contentTypes[0]; + } + + /** + * Escape the given string to be used as URL query value. + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Serialize the given Java object into string entity according the given + * Content-Type (only JSON is supported for now). + */ + 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 { - // Use a common format that works across all systems. - this.datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - // Always use the UTC time zone as we are using a constant trailing "Z" here. - this.datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - } - } - - /** - * Apply SSL related settings to httpClient according to the current values of - * verifyingSsl and sslCaCert. - */ - private void applySslSettings() { + 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 { + // 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, GenericType returnType) throws ApiException { + // Handle file downloading. + if (returnType.equals(File.class)) { + @SuppressWarnings("unchecked") + T file = (T) downloadFileFromResponse(response); + return file; + } + + String contentType = null; + List contentTypes = response.getHeaders().get("Content-Type"); + if (contentTypes != null && !contentTypes.isEmpty()) + contentType = String.valueOf(contentTypes.get(0)); + if (contentType == null) + throw new ApiException(500, "missing Content-Type in response"); + + return response.readEntity(returnType); + } + + /** + * Download file from the given response. + * @throws ApiException If fail to read file content from response and write to disk + */ + public File downloadFileFromResponse(Response response) throws ApiException { + try { + File file = prepareDownloadFile(response); + Files.copy(response.readEntity(InputStream.class), file.toPath()); + return file; + } catch (IOException e) { + throw new ApiException(e); + } + } + + public File prepareDownloadFile(Response response) throws IOException { + String filename = null; + String contentDisposition = (String) response.getHeaders().getFirst("Content-Disposition"); + if (contentDisposition != null && !"".equals(contentDisposition)) { + // Get filename from the Content-Disposition header. + Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); + Matcher matcher = pattern.matcher(contentDisposition); + if (matcher.find()) + filename = matcher.group(1); + } + + String prefix = null; + String suffix = null; + if (filename == null) { + prefix = "download-"; + suffix = ""; + } else { + int pos = filename.lastIndexOf("."); + if (pos == -1) { + prefix = filename + "-"; + } else { + prefix = filename.substring(0, pos) + "-"; + suffix = filename.substring(pos); + } + // File.createTempFile requires the prefix to be at least three characters long + if (prefix.length() < 3) + prefix = "download-"; + } + + if (tempFolderPath == null) + return File.createTempFile(prefix, suffix); + else + return File.createTempFile(prefix, suffix, new File(tempFolderPath)); + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @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 + * @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 + * @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, GenericType returnType) throws ApiException { + updateParamsForAuth(authNames, queryParams, headerParams); + + // Not using `.target(this.basePath).path(path)` below, + // to support (constant) query string in `path`, e.g. "/posts?draft=1" + WebTarget target = httpClient.target(this.basePath + path); + + if (queryParams != null) { + for (Pair queryParam : queryParams) { + if (queryParam.getValue() != null) { + target = target.queryParam(queryParam.getName(), queryParam.getValue()); + } + } + } + + Invocation.Builder invocationBuilder = target.request().accept(accept); + + for (String key : headerParams.keySet()) { + String value = headerParams.get(key); + if (value != null) { + invocationBuilder = invocationBuilder.header(key, value); + } + } + + for (String key : defaultHeaderMap.keySet()) { + if (!headerParams.containsKey(key)) { + String value = defaultHeaderMap.get(key); + if (value != null) { + invocationBuilder = invocationBuilder.header(key, value); + } + } + } + + Entity entity = serialize(body, formParams, contentType); + + Response response = null; + + if ("GET".equals(method)) { + response = invocationBuilder.get(); + } else if ("POST".equals(method)) { + response = invocationBuilder.post(entity); + } else if ("PUT".equals(method)) { + response = invocationBuilder.put(entity); + } else if ("DELETE".equals(method)) { + response = invocationBuilder.delete(); + } else { + throw new ApiException(500, "unknown method type " + method); + } + + statusCode = response.getStatusInfo().getStatusCode(); + responseHeaders = buildResponseHeaders(response); + + if (response.getStatus() == Status.NO_CONTENT.getStatusCode()) { + return null; + } else if (response.getStatusInfo().getFamily().equals(Status.Family.SUCCESSFUL)) { + if (returnType == null) + return null; + else + return deserialize(response, returnType); + } else { + String message = "error"; + String respBody = null; + if (response.hasEntity()) { try { - KeyManager[] keyManagers = null; - TrustManager[] trustManagers = null; - HostnameVerifier hostnameVerifier = null; - if (!verifyingSsl) { - TrustManager trustAll = new X509TrustManager() { - @Override - public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} - @Override - public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} - @Override - public X509Certificate[] getAcceptedIssuers() { return null; } - }; - SSLContext sslContext = SSLContext.getInstance("TLS"); - trustManagers = new TrustManager[]{ trustAll }; - hostnameVerifier = new HostnameVerifier() { - @Override - public boolean verify(String hostname, SSLSession session) { return true; } - }; - } else if (sslCaCert != null) { - char[] password = null; // Any password will work. - CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); - Collection certificates = certificateFactory.generateCertificates(sslCaCert); - if (certificates.isEmpty()) { - throw new IllegalArgumentException("expected non-empty set of trusted certificates"); - } - KeyStore caKeyStore = newEmptyKeyStore(password); - int index = 0; - for (Certificate certificate : certificates) { - String certificateAlias = "ca" + Integer.toString(index++); - caKeyStore.setCertificateEntry(certificateAlias, certificate); - } - TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - trustManagerFactory.init(caKeyStore); - trustManagers = trustManagerFactory.getTrustManagers(); - } - - if (keyManagers != null || trustManagers != null) { - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(keyManagers, trustManagers, new SecureRandom()); - httpClient.setSslSocketFactory(sslContext.getSocketFactory()); - } else { - httpClient.setSslSocketFactory(null); - } - httpClient.setHostnameVerifier(hostnameVerifier); - } catch (GeneralSecurityException e) { - throw new RuntimeException(e); - } - } - - private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { - try { - KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - keyStore.load(null, password); - return keyStore; - } catch (IOException e) { - throw new AssertionError(e); - } - } + respBody = String.valueOf(response.readEntity(String.class)); + message = respBody; + } catch (RuntimeException e) { + // e.printStackTrace(); + } + } + throw new ApiException( + response.getStatus(), + message, + buildResponseHeaders(response), + respBody); + } + } + + /** + * Build the Client used to make HTTP requests. + */ + private Client buildHttpClient(boolean debugging) { + final ClientConfig clientConfig = new ClientConfig(); + clientConfig.register(MultiPartFeature.class); + clientConfig.register(json); + clientConfig.register(JacksonFeature.class); + if (debugging) { + clientConfig.register(LoggingFilter.class); + } + return ClientBuilder.newClient(clientConfig); + } + + private Map> buildResponseHeaders(Response response) { + Map> responseHeaders = new HashMap>(); + for (Entry> entry: response.getHeaders().entrySet()) { + List values = entry.getValue(); + List headers = new ArrayList(); + for (Object o : values) { + headers.add(String.valueOf(o)); + } + responseHeaders.put(entry.getKey(), headers); + } + return responseHeaders; + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + */ + private void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); + auth.applyToParams(queryParams, headerParams); + } + } } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiResponse.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiResponse.java deleted file mode 100644 index d7dde1ee939..00000000000 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiResponse.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import java.util.List; -import java.util.Map; - -/** - * API response returned by API call. - * - * @param T The type of data that is deserialized from response body - */ -public class ApiResponse { - final private int statusCode; - final private Map> headers; - final private T data; - - /** - * @param statusCode The status code of HTTP response - * @param headers The headers of HTTP response - */ - public ApiResponse(int statusCode, Map> headers) { - this(statusCode, headers, null); - } - - /** - * @param statusCode The status code of HTTP response - * @param headers The headers of HTTP response - * @param data The object deserialized from response bod - */ - public ApiResponse(int statusCode, Map> headers, T data) { - this.statusCode = statusCode; - this.headers = headers; - this.data = data; - } - - public int getStatusCode() { - return statusCode; - } - - public Map> getHeaders() { - return headers; - } - - public T getData() { - return data; - } -} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/JSON.java index 11bdce59abf..d0feb432d99 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/JSON.java @@ -1,240 +1,36 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - package io.swagger.client; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonNull; -import com.google.gson.JsonParseException; -import com.google.gson.JsonPrimitive; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; - -import java.io.IOException; -import java.io.StringReader; -import java.lang.reflect.Type; -import java.util.Date; - -import java.time.LocalDate; -import java.time.OffsetDateTime; -import java.time.format.DateTimeFormatter; - -public class JSON { - private ApiClient apiClient; - private Gson gson; +import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.datatype.jsr310.*; - /** - * JSON constructor. - * - * @param apiClient An instance of ApiClient - */ - public JSON(ApiClient apiClient) { - this.apiClient = apiClient; - gson = new GsonBuilder() - .registerTypeAdapter(Date.class, new DateAdapter(apiClient)) - .registerTypeAdapter(OffsetDateTime.class, new OffsetDateTimeTypeAdapter()) - .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) - .create(); - } - - /** - * Get Gson. - * - * @return Gson - */ - public Gson getGson() { - return gson; - } - - /** - * Set Gson. - * - * @param gson Gson - */ - public void setGson(Gson gson) { - this.gson = gson; - } - - /** - * Serialize the given Java object into JSON string. - * - * @param obj Object - * @return String representation of the JSON - */ - public String serialize(Object obj) { - return gson.toJson(obj); - } - - /** - * Deserialize the given JSON string to Java object. - * - * @param Type - * @param body The JSON string - * @param returnType The type to deserialize inot - * @return The deserialized Java object - */ - @SuppressWarnings("unchecked") - public T deserialize(String body, Type returnType) { - try { - if (apiClient.isLenientOnJson()) { - JsonReader jsonReader = new JsonReader(new StringReader(body)); - // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) - jsonReader.setLenient(true); - return gson.fromJson(jsonReader, returnType); - } else { - return gson.fromJson(body, returnType); - } - } catch (JsonParseException e) { - // Fallback processing when failed to parse JSON form response body: - // return the response body string directly for the String return type; - // parse response body into date or datetime for the Date return type. - if (returnType.equals(String.class)) - return (T) body; - else if (returnType.equals(Date.class)) - return (T) apiClient.parseDateOrDatetime(body); - else throw(e); - } - } -} +import java.text.DateFormat; -class DateAdapter implements JsonSerializer, JsonDeserializer { - private final ApiClient apiClient; +import javax.ws.rs.ext.ContextResolver; - /** - * Constructor for DateAdapter - * - * @param apiClient Api client - */ - public DateAdapter(ApiClient apiClient) { - super(); - this.apiClient = apiClient; - } - - /** - * Serialize - * - * @param src Date - * @param typeOfSrc Type - * @param context Json Serialization Context - * @return Json Element - */ - @Override - public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { - if (src == null) { - return JsonNull.INSTANCE; - } else { - return new JsonPrimitive(apiClient.formatDatetime(src)); - } - } - - /** - * Deserialize - * - * @param json Json element - * @param date Type - * @param typeOfSrc Type - * @param context Json Serialization Context - * @return Date - * @throw JsonParseException if fail to parse - */ - @Override - public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException { - String str = json.getAsJsonPrimitive().getAsString(); - try { - return apiClient.parseDateOrDatetime(str); - } catch (RuntimeException e) { - throw new JsonParseException(e); - } - } -} - -/** - * Gson TypeAdapter for jsr310 OffsetDateTime type - */ -class OffsetDateTimeTypeAdapter extends TypeAdapter { - - private final DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME; - - @Override - public void write(JsonWriter out, OffsetDateTime date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - out.value(formatter.format(date)); - } - } - - @Override - public OffsetDateTime read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - if (date.endsWith("+0000")) { - date = date.substring(0, date.length()-5) + "Z"; - } - - return OffsetDateTime.parse(date, formatter); - } - } -} -/** - * Gson TypeAdapter for jsr310 LocalDate type - */ -class LocalDateTypeAdapter extends TypeAdapter { +public class JSON implements ContextResolver { + private ObjectMapper mapper; - private final DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE; + 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 JavaTimeModule()); + } - @Override - public void write(JsonWriter out, LocalDate date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - out.value(formatter.format(date)); - } - } + /** + * Set the date format for JSON (de)serialization with Date properties. + */ + public void setDateFormat(DateFormat dateFormat) { + mapper.setDateFormat(dateFormat); + } - @Override - public LocalDate read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - return LocalDate.parse(date, formatter); - } - } + @Override + public ObjectMapper getContext(Class type) { + return mapper; + } } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ProgressRequestBody.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ProgressRequestBody.java deleted file mode 100644 index d9ca742ecd2..00000000000 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ProgressRequestBody.java +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import com.squareup.okhttp.MediaType; -import com.squareup.okhttp.RequestBody; - -import java.io.IOException; - -import okio.Buffer; -import okio.BufferedSink; -import okio.ForwardingSink; -import okio.Okio; -import okio.Sink; - -public class ProgressRequestBody extends RequestBody { - - public interface ProgressRequestListener { - void onRequestProgress(long bytesWritten, long contentLength, boolean done); - } - - private final RequestBody requestBody; - - private final ProgressRequestListener progressListener; - - private BufferedSink bufferedSink; - - public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) { - this.requestBody = requestBody; - this.progressListener = progressListener; - } - - @Override - public MediaType contentType() { - return requestBody.contentType(); - } - - @Override - public long contentLength() throws IOException { - return requestBody.contentLength(); - } - - @Override - public void writeTo(BufferedSink sink) throws IOException { - if (bufferedSink == null) { - bufferedSink = Okio.buffer(sink(sink)); - } - - requestBody.writeTo(bufferedSink); - bufferedSink.flush(); - - } - - private Sink sink(Sink sink) { - return new ForwardingSink(sink) { - - long bytesWritten = 0L; - long contentLength = 0L; - - @Override - public void write(Buffer source, long byteCount) throws IOException { - super.write(source, byteCount); - if (contentLength == 0) { - contentLength = contentLength(); - } - - bytesWritten += byteCount; - progressListener.onRequestProgress(bytesWritten, contentLength, bytesWritten == contentLength); - } - }; - } -} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ProgressResponseBody.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ProgressResponseBody.java deleted file mode 100644 index f8af685999d..00000000000 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ProgressResponseBody.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import com.squareup.okhttp.MediaType; -import com.squareup.okhttp.ResponseBody; - -import java.io.IOException; - -import okio.Buffer; -import okio.BufferedSource; -import okio.ForwardingSource; -import okio.Okio; -import okio.Source; - -public class ProgressResponseBody extends ResponseBody { - - public interface ProgressListener { - void update(long bytesRead, long contentLength, boolean done); - } - - private final ResponseBody responseBody; - private final ProgressListener progressListener; - private BufferedSource bufferedSource; - - public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) { - this.responseBody = responseBody; - this.progressListener = progressListener; - } - - @Override - public MediaType contentType() { - return responseBody.contentType(); - } - - @Override - public long contentLength() throws IOException { - return responseBody.contentLength(); - } - - @Override - public BufferedSource source() throws IOException { - if (bufferedSource == null) { - bufferedSource = Okio.buffer(source(responseBody.source())); - } - return bufferedSource; - } - - private Source source(Source source) { - return new ForwardingSource(source) { - long totalBytesRead = 0L; - - @Override - public long read(Buffer sink, long byteCount) throws IOException { - long bytesRead = super.read(sink, byteCount); - // read() returns the number of bytes read, or -1 if this source is exhausted. - totalBytesRead += bytesRead != -1 ? bytesRead : 0; - progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1); - return bytesRead; - } - }; - } -} - - diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/FakeApi.java index 5935c42e1c3..5bb6afe51b8 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/FakeApi.java @@ -1,353 +1,171 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - package io.swagger.client.api; -import io.swagger.client.ApiCallback; -import io.swagger.client.ApiClient; import io.swagger.client.ApiException; -import io.swagger.client.ApiResponse; +import io.swagger.client.ApiClient; import io.swagger.client.Configuration; import io.swagger.client.Pair; -import io.swagger.client.ProgressRequestBody; -import io.swagger.client.ProgressResponseBody; -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; +import javax.ws.rs.core.GenericType; import java.time.LocalDate; import java.time.OffsetDateTime; import java.math.BigDecimal; -import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -public class FakeApi { - private ApiClient apiClient; - public FakeApi() { - this(Configuration.getDefaultApiClient()); - } - - public FakeApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for testEndpointParameters */ - private com.squareup.okhttp.Call testEndpointParametersCall(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'number' is set - if (number == null) { - throw new ApiException("Missing the required parameter 'number' when calling testEndpointParameters(Async)"); - } - - // verify the required parameter '_double' is set - if (_double == null) { - throw new ApiException("Missing the required parameter '_double' when calling testEndpointParameters(Async)"); - } - - // verify the required parameter 'string' is set - if (string == null) { - throw new ApiException("Missing the required parameter 'string' when calling testEndpointParameters(Async)"); - } - - // verify the required parameter '_byte' is set - if (_byte == null) { - throw new ApiException("Missing the required parameter '_byte' when calling testEndpointParameters(Async)"); - } - - - // create path and map variables - String localVarPath = "/fake".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (integer != null) - localVarFormParams.put("integer", integer); - if (int32 != null) - localVarFormParams.put("int32", int32); - if (int64 != null) - localVarFormParams.put("int64", int64); - if (number != null) - localVarFormParams.put("number", number); - if (_float != null) - localVarFormParams.put("float", _float); - if (_double != null) - localVarFormParams.put("double", _double); - if (string != null) - localVarFormParams.put("string", string); - if (_byte != null) - localVarFormParams.put("byte", _byte); - if (binary != null) - localVarFormParams.put("binary", binary); - if (date != null) - localVarFormParams.put("date", date); - if (dateTime != null) - localVarFormParams.put("dateTime", dateTime); - if (password != null) - localVarFormParams.put("password", password); - - final String[] localVarAccepts = { - "application/xml; charset=utf-8", "application/json; charset=utf-8" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/xml; charset=utf-8", "application/json; charset=utf-8" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * @param number None (required) - * @param _double None (required) - * @param string None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password) throws ApiException { - testEndpointParametersWithHttpInfo(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); - } - - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * @param number None (required) - * @param _double None (required) - * @param string None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password) throws ApiException { - com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password, null, null); - return apiClient.execute(call); - } - - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 (asynchronously) - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * @param number None (required) - * @param _double None (required) - * @param string None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call testEndpointParametersAsync(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for testEnumQueryParameters */ - private com.squareup.okhttp.Call testEnumQueryParametersCall(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - - // create path and map variables - String localVarPath = "/fake".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (enumQueryInteger != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_integer", enumQueryInteger)); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (enumQueryString != null) - localVarFormParams.put("enum_query_string", enumQueryString); - if (enumQueryDouble != null) - localVarFormParams.put("enum_query_double", enumQueryDouble); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/json" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); +public class FakeApi { + private ApiClient apiClient; + + public FakeApi() { + this(Configuration.getDefaultApiClient()); + } + + public FakeApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param string None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @throws ApiException if fails to make API call + */ + public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'number' is set + if (number == null) { + throw new ApiException(400, "Missing the required parameter 'number' when calling testEndpointParameters"); } - - /** - * To test enum query parameters - * - * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) - * @param enumQueryInteger Query parameter enum test (double) (optional) - * @param enumQueryDouble Query parameter enum test (double) (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void testEnumQueryParameters(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { - testEnumQueryParametersWithHttpInfo(enumQueryString, enumQueryInteger, enumQueryDouble); + + // verify the required parameter '_double' is set + if (_double == null) { + throw new ApiException(400, "Missing the required parameter '_double' when calling testEndpointParameters"); } - - /** - * To test enum query parameters - * - * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) - * @param enumQueryInteger Query parameter enum test (double) (optional) - * @param enumQueryDouble Query parameter enum test (double) (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse testEnumQueryParametersWithHttpInfo(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { - com.squareup.okhttp.Call call = testEnumQueryParametersCall(enumQueryString, enumQueryInteger, enumQueryDouble, null, null); - return apiClient.execute(call); + + // verify the required parameter 'string' is set + if (string == null) { + throw new ApiException(400, "Missing the required parameter 'string' when calling testEndpointParameters"); } - - /** - * To test enum query parameters (asynchronously) - * - * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) - * @param enumQueryInteger Query parameter enum test (double) (optional) - * @param enumQueryDouble Query parameter enum test (double) (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call testEnumQueryParametersAsync(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = testEnumQueryParametersCall(enumQueryString, enumQueryInteger, enumQueryDouble, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; + + // verify the required parameter '_byte' is set + if (_byte == null) { + throw new ApiException(400, "Missing the required parameter '_byte' when calling testEndpointParameters"); } + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + if (integer != null) + localVarFormParams.put("integer", integer); +if (int32 != null) + localVarFormParams.put("int32", int32); +if (int64 != null) + localVarFormParams.put("int64", int64); +if (number != null) + localVarFormParams.put("number", number); +if (_float != null) + localVarFormParams.put("float", _float); +if (_double != null) + localVarFormParams.put("double", _double); +if (string != null) + localVarFormParams.put("string", string); +if (_byte != null) + localVarFormParams.put("byte", _byte); +if (binary != null) + localVarFormParams.put("binary", binary); +if (date != null) + localVarFormParams.put("date", date); +if (dateTime != null) + localVarFormParams.put("dateTime", dateTime); +if (password != null) + localVarFormParams.put("password", password); + + final String[] localVarAccepts = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * To test enum query parameters + * + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @throws ApiException if fails to make API call + */ + public void testEnumQueryParameters(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_integer", enumQueryInteger)); + + + if (enumQueryString != null) + localVarFormParams.put("enum_query_string", enumQueryString); +if (enumQueryDouble != null) + localVarFormParams.put("enum_query_double", enumQueryDouble); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/PetApi.java index 2039a8842c1..ab85c4ac394 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/PetApi.java @@ -1,935 +1,384 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - package io.swagger.client.api; -import io.swagger.client.ApiCallback; -import io.swagger.client.ApiClient; import io.swagger.client.ApiException; -import io.swagger.client.ApiResponse; +import io.swagger.client.ApiClient; import io.swagger.client.Configuration; import io.swagger.client.Pair; -import io.swagger.client.ProgressRequestBody; -import io.swagger.client.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; -import java.io.IOException; +import javax.ws.rs.core.GenericType; import io.swagger.client.model.Pet; import java.io.File; import io.swagger.client.model.ModelApiResponse; -import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -public class PetApi { - private ApiClient apiClient; - - public PetApi() { - this(Configuration.getDefaultApiClient()); - } - - public PetApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for addPet */ - private com.squareup.okhttp.Call addPetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling addPet(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/json", "application/xml" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void addPet(Pet body) throws ApiException { - addPetWithHttpInfo(body); - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse addPetWithHttpInfo(Pet body) throws ApiException { - com.squareup.okhttp.Call call = addPetCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Add a new pet to the store (asynchronously) - * - * @param body Pet object that needs to be added to the store (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call addPetAsync(Pet body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = addPetCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for deletePet */ - private com.squareup.okhttp.Call deletePetCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling deletePet(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - if (apiKey != null) - localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Deletes a pet - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void deletePet(Long petId, String apiKey) throws ApiException { - deletePetWithHttpInfo(petId, apiKey); - } - - /** - * Deletes a pet - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse deletePetWithHttpInfo(Long petId, String apiKey) throws ApiException { - com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, null, null); - return apiClient.execute(call); - } - - /** - * Deletes a pet (asynchronously) - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call deletePetAsync(Long petId, String apiKey, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for findPetsByStatus */ - private com.squareup.okhttp.Call findPetsByStatusCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'status' is set - if (status == null) { - throw new ApiException("Missing the required parameter 'status' when calling findPetsByStatus(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/findByStatus".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (status != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "status", status)); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Finds Pets by status - * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for filter (required) - * @return List<Pet> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public List findPetsByStatus(List status) throws ApiException { - ApiResponse> resp = findPetsByStatusWithHttpInfo(status); - return resp.getData(); - } - /** - * Finds Pets by status - * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for filter (required) - * @return ApiResponse<List<Pet>> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse> findPetsByStatusWithHttpInfo(List status) throws ApiException { - com.squareup.okhttp.Call call = findPetsByStatusCall(status, null, null); - Type localVarReturnType = new TypeToken>(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Finds Pets by status (asynchronously) - * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for filter (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call findPetsByStatusAsync(List status, final ApiCallback> callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = findPetsByStatusCall(status, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken>(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for findPetsByTags */ - private com.squareup.okhttp.Call findPetsByTagsCall(List tags, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'tags' is set - if (tags == null) { - throw new ApiException("Missing the required parameter 'tags' when calling findPetsByTags(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/findByTags".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (tags != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "tags", tags)); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Finds Pets by tags - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by (required) - * @return List<Pet> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public List findPetsByTags(List tags) throws ApiException { - ApiResponse> resp = findPetsByTagsWithHttpInfo(tags); - return resp.getData(); - } - - /** - * Finds Pets by tags - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by (required) - * @return ApiResponse<List<Pet>> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse> findPetsByTagsWithHttpInfo(List tags) throws ApiException { - com.squareup.okhttp.Call call = findPetsByTagsCall(tags, null, null); - Type localVarReturnType = new TypeToken>(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Finds Pets by tags (asynchronously) - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call findPetsByTagsAsync(List tags, final ApiCallback> callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = findPetsByTagsCall(tags, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken>(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for getPetById */ - private com.squareup.okhttp.Call getPetByIdCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling getPetById(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "api_key" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Find pet by ID - * Returns a single pet - * @param petId ID of pet to return (required) - * @return Pet - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Pet getPetById(Long petId) throws ApiException { - ApiResponse resp = getPetByIdWithHttpInfo(petId); - return resp.getData(); - } - - /** - * Find pet by ID - * Returns a single pet - * @param petId ID of pet to return (required) - * @return ApiResponse<Pet> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse getPetByIdWithHttpInfo(Long petId) throws ApiException { - com.squareup.okhttp.Call call = getPetByIdCall(petId, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Find pet by ID (asynchronously) - * Returns a single pet - * @param petId ID of pet to return (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call getPetByIdAsync(Long petId, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = getPetByIdCall(petId, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for updatePet */ - private com.squareup.okhttp.Call updatePetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling updatePet(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/json", "application/xml" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void updatePet(Pet body) throws ApiException { - updatePetWithHttpInfo(body); - } - - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse updatePetWithHttpInfo(Pet body) throws ApiException { - com.squareup.okhttp.Call call = updatePetCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Update an existing pet (asynchronously) - * - * @param body Pet object that needs to be added to the store (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call updatePetAsync(Pet body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = updatePetCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for updatePetWithForm */ - private com.squareup.okhttp.Call updatePetWithFormCall(Long petId, String name, String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling updatePetWithForm(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (name != null) - localVarFormParams.put("name", name); - if (status != null) - localVarFormParams.put("status", status); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/x-www-form-urlencoded" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void updatePetWithForm(Long petId, String name, String status) throws ApiException { - updatePetWithFormWithHttpInfo(petId, name, status); - } - - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse updatePetWithFormWithHttpInfo(Long petId, String name, String status) throws ApiException { - com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, null, null); - return apiClient.execute(call); - } - - /** - * Updates a pet in the store with form data (asynchronously) - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call updatePetWithFormAsync(Long petId, String name, String status, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for uploadFile */ - private com.squareup.okhttp.Call uploadFileCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling uploadFile(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (additionalMetadata != null) - localVarFormParams.put("additionalMetadata", additionalMetadata); - if (file != null) - localVarFormParams.put("file", file); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "multipart/form-data" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * uploads an image - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @return ModelApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { - ApiResponse resp = uploadFileWithHttpInfo(petId, additionalMetadata, file); - return resp.getData(); - } - - /** - * uploads an image - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @return ApiResponse<ModelApiResponse> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file) throws ApiException { - com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * uploads an image (asynchronously) - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call uploadFileAsync(Long petId, String additionalMetadata, File file, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } +public class PetApi { + private ApiClient apiClient; + + public PetApi() { + this(Configuration.getDefaultApiClient()); + } + + public PetApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException if fails to make API call + */ + public void addPet(Pet body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling addPet"); + } + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @throws ApiException if fails to make API call + */ + public void deletePet(Long petId, String apiKey) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling deletePet"); + } + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + if (apiKey != null) + localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + + apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return List + * @throws ApiException if fails to make API call + */ + public List findPetsByStatus(List status) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'status' is set + if (status == null) { + throw new ApiException(400, "Missing the required parameter 'status' when calling findPetsByStatus"); + } + + // create path and map variables + String localVarPath = "/pet/findByStatus".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "status", status)); + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + GenericType> localVarReturnType = new GenericType>() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return List + * @throws ApiException if fails to make API call + */ + public List findPetsByTags(List tags) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'tags' is set + if (tags == null) { + throw new ApiException(400, "Missing the required parameter 'tags' when calling findPetsByTags"); + } + + // create path and map variables + String localVarPath = "/pet/findByTags".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "tags", tags)); + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + GenericType> localVarReturnType = new GenericType>() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return Pet + * @throws ApiException if fails to make API call + */ + public Pet getPetById(Long petId) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling getPetById"); + } + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "api_key" }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException if fails to make API call + */ + public void updatePet(Pet body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling updatePet"); + } + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + + apiClient.invokeAPI(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @throws ApiException if fails to make API call + */ + public void updatePetWithForm(Long petId, String name, String status) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling updatePetWithForm"); + } + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + if (name != null) + localVarFormParams.put("name", name); +if (status != null) + localVarFormParams.put("status", status); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/x-www-form-urlencoded" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ModelApiResponse + * @throws ApiException if fails to make API call + */ + public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling uploadFile"); + } + + // create path and map variables + String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + if (additionalMetadata != null) + localVarFormParams.put("additionalMetadata", additionalMetadata); +if (file != null) + localVarFormParams.put("file", file); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/StoreApi.java index 0768744c263..c0c9a166ad7 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/StoreApi.java @@ -1,482 +1,196 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - package io.swagger.client.api; -import io.swagger.client.ApiCallback; -import io.swagger.client.ApiClient; import io.swagger.client.ApiException; -import io.swagger.client.ApiResponse; +import io.swagger.client.ApiClient; import io.swagger.client.Configuration; import io.swagger.client.Pair; -import io.swagger.client.ProgressRequestBody; -import io.swagger.client.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; -import java.io.IOException; +import javax.ws.rs.core.GenericType; import io.swagger.client.model.Order; -import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -public class StoreApi { - private ApiClient apiClient; - - public StoreApi() { - this(Configuration.getDefaultApiClient()); - } - - public StoreApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - /* Build call for deleteOrder */ - private com.squareup.okhttp.Call deleteOrderCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException("Missing the required parameter 'orderId' when calling deleteOrder(Async)"); - } - - - // create path and map variables - String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void deleteOrder(String orderId) throws ApiException { - deleteOrderWithHttpInfo(orderId); - } - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse deleteOrderWithHttpInfo(String orderId) throws ApiException { - com.squareup.okhttp.Call call = deleteOrderCall(orderId, null, null); - return apiClient.execute(call); - } - - /** - * Delete purchase order by ID (asynchronously) - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call deleteOrderAsync(String orderId, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = deleteOrderCall(orderId, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for getInventory */ - private com.squareup.okhttp.Call getInventoryCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - - // create path and map variables - String localVarPath = "/store/inventory".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "api_key" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - * @return Map<String, Integer> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Map getInventory() throws ApiException { - ApiResponse> resp = getInventoryWithHttpInfo(); - return resp.getData(); - } - - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - * @return ApiResponse<Map<String, Integer>> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse> getInventoryWithHttpInfo() throws ApiException { - com.squareup.okhttp.Call call = getInventoryCall(null, null); - Type localVarReturnType = new TypeToken>(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Returns pet inventories by status (asynchronously) - * Returns a map of status codes to quantities - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call getInventoryAsync(final ApiCallback> callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = getInventoryCall(progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken>(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for getOrderById */ - private com.squareup.okhttp.Call getOrderByIdCall(Long orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException("Missing the required parameter 'orderId' when calling getOrderById(Async)"); - } - - - // create path and map variables - String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched (required) - * @return Order - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Order getOrderById(Long orderId) throws ApiException { - ApiResponse resp = getOrderByIdWithHttpInfo(orderId); - return resp.getData(); - } - - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched (required) - * @return ApiResponse<Order> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse getOrderByIdWithHttpInfo(Long orderId) throws ApiException { - com.squareup.okhttp.Call call = getOrderByIdCall(orderId, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Find purchase order by ID (asynchronously) - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call getOrderByIdAsync(Long orderId, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = getOrderByIdCall(orderId, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for placeOrder */ - private com.squareup.okhttp.Call placeOrderCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling placeOrder(Async)"); - } - - - // create path and map variables - String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet (required) - * @return Order - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Order placeOrder(Order body) throws ApiException { - ApiResponse resp = placeOrderWithHttpInfo(body); - return resp.getData(); - } - - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet (required) - * @return ApiResponse<Order> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse placeOrderWithHttpInfo(Order body) throws ApiException { - com.squareup.okhttp.Call call = placeOrderCall(body, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Place an order for a pet (asynchronously) - * - * @param body order placed for purchasing the pet (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call placeOrderAsync(Order body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = placeOrderCall(body, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } +public class StoreApi { + private ApiClient apiClient; + + public StoreApi() { + this(Configuration.getDefaultApiClient()); + } + + public StoreApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @throws ApiException if fails to make API call + */ + public void deleteOrder(String orderId) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder"); + } + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return Map + * @throws ApiException if fails to make API call + */ + public Map getInventory() throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/store/inventory".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "api_key" }; + + GenericType> localVarReturnType = new GenericType>() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @return Order + * @throws ApiException if fails to make API call + */ + public Order getOrderById(Long orderId) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById"); + } + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet (required) + * @return Order + * @throws ApiException if fails to make API call + */ + public Order placeOrder(Order body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling placeOrder"); + } + + // create path and map variables + String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/UserApi.java index 1c4fc3101a1..7602f4e2ba9 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/UserApi.java @@ -1,907 +1,370 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - package io.swagger.client.api; -import io.swagger.client.ApiCallback; -import io.swagger.client.ApiClient; import io.swagger.client.ApiException; -import io.swagger.client.ApiResponse; +import io.swagger.client.ApiClient; import io.swagger.client.Configuration; import io.swagger.client.Pair; -import io.swagger.client.ProgressRequestBody; -import io.swagger.client.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; -import java.io.IOException; +import javax.ws.rs.core.GenericType; import io.swagger.client.model.User; -import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -public class UserApi { - private ApiClient apiClient; - - public UserApi() { - this(Configuration.getDefaultApiClient()); - } - - public UserApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for createUser */ - private com.squareup.okhttp.Call createUserCall(User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling createUser(Async)"); - } - - - // create path and map variables - String localVarPath = "/user".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void createUser(User body) throws ApiException { - createUserWithHttpInfo(body); - } - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse createUserWithHttpInfo(User body) throws ApiException { - com.squareup.okhttp.Call call = createUserCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Create user (asynchronously) - * This can only be done by the logged in user. - * @param body Created user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call createUserAsync(User body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = createUserCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for createUsersWithArrayInput */ - private com.squareup.okhttp.Call createUsersWithArrayInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling createUsersWithArrayInput(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/createWithArray".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void createUsersWithArrayInput(List body) throws ApiException { - createUsersWithArrayInputWithHttpInfo(body); - } - - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse createUsersWithArrayInputWithHttpInfo(List body) throws ApiException { - com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Creates list of users with given input array (asynchronously) - * - * @param body List of user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call createUsersWithArrayInputAsync(List body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for createUsersWithListInput */ - private com.squareup.okhttp.Call createUsersWithListInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling createUsersWithListInput(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void createUsersWithListInput(List body) throws ApiException { - createUsersWithListInputWithHttpInfo(body); - } - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse createUsersWithListInputWithHttpInfo(List body) throws ApiException { - com.squareup.okhttp.Call call = createUsersWithListInputCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Creates list of users with given input array (asynchronously) - * - * @param body List of user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call createUsersWithListInputAsync(List body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = createUsersWithListInputCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for deleteUser */ - private com.squareup.okhttp.Call deleteUserCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling deleteUser(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void deleteUser(String username) throws ApiException { - deleteUserWithHttpInfo(username); - } - - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse deleteUserWithHttpInfo(String username) throws ApiException { - com.squareup.okhttp.Call call = deleteUserCall(username, null, null); - return apiClient.execute(call); - } - - /** - * Delete user (asynchronously) - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call deleteUserAsync(String username, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = deleteUserCall(username, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for getUserByName */ - private com.squareup.okhttp.Call getUserByNameCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling getUserByName(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return User - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public User getUserByName(String username) throws ApiException { - ApiResponse resp = getUserByNameWithHttpInfo(username); - return resp.getData(); - } - - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return ApiResponse<User> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse getUserByNameWithHttpInfo(String username) throws ApiException { - com.squareup.okhttp.Call call = getUserByNameCall(username, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Get user by user name (asynchronously) - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call getUserByNameAsync(String username, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = getUserByNameCall(username, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for loginUser */ - private com.squareup.okhttp.Call loginUserCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling loginUser(Async)"); - } - - // verify the required parameter 'password' is set - if (password == null) { - throw new ApiException("Missing the required parameter 'password' when calling loginUser(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/login".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (username != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("", "username", username)); - if (password != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("", "password", password)); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Logs user into the system - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @return String - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public String loginUser(String username, String password) throws ApiException { - ApiResponse resp = loginUserWithHttpInfo(username, password); - return resp.getData(); - } - - /** - * Logs user into the system - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @return ApiResponse<String> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse loginUserWithHttpInfo(String username, String password) throws ApiException { - com.squareup.okhttp.Call call = loginUserCall(username, password, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Logs user into the system (asynchronously) - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call loginUserAsync(String username, String password, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = loginUserCall(username, password, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for logoutUser */ - private com.squareup.okhttp.Call logoutUserCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - - // create path and map variables - String localVarPath = "/user/logout".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Logs out current logged in user session - * - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void logoutUser() throws ApiException { - logoutUserWithHttpInfo(); - } - - /** - * Logs out current logged in user session - * - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse logoutUserWithHttpInfo() throws ApiException { - com.squareup.okhttp.Call call = logoutUserCall(null, null); - return apiClient.execute(call); - } - - /** - * Logs out current logged in user session (asynchronously) - * - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call logoutUserAsync(final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = logoutUserCall(progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for updateUser */ - private com.squareup.okhttp.Call updateUserCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling updateUser(Async)"); - } - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling updateUser(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void updateUser(String username, User body) throws ApiException { - updateUserWithHttpInfo(username, body); - } - - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse updateUserWithHttpInfo(String username, User body) throws ApiException { - com.squareup.okhttp.Call call = updateUserCall(username, body, null, null); - return apiClient.execute(call); - } - - /** - * Updated user (asynchronously) - * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call updateUserAsync(String username, User body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = updateUserCall(username, body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } +public class UserApi { + private ApiClient apiClient; + + public UserApi() { + this(Configuration.getDefaultApiClient()); + } + + public UserApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object (required) + * @throws ApiException if fails to make API call + */ + public void createUser(User body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling createUser"); + } + + // create path and map variables + String localVarPath = "/user".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException if fails to make API call + */ + public void createUsersWithArrayInput(List body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling createUsersWithArrayInput"); + } + + // create path and map variables + String localVarPath = "/user/createWithArray".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException if fails to make API call + */ + public void createUsersWithListInput(List body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling createUsersWithListInput"); + } + + // create path and map variables + String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @throws ApiException if fails to make API call + */ + public void deleteUser(String username) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling deleteUser"); + } + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return User + * @throws ApiException if fails to make API call + */ + public User getUserByName(String username) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling getUserByName"); + } + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return String + * @throws ApiException if fails to make API call + */ + public String loginUser(String username, String password) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling loginUser"); + } + + // verify the required parameter 'password' is set + if (password == null) { + throw new ApiException(400, "Missing the required parameter 'password' when calling loginUser"); + } + + // create path and map variables + String localVarPath = "/user/login".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("", "username", username)); + localVarQueryParams.addAll(apiClient.parameterToPairs("", "password", password)); + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Logs out current logged in user session + * + * @throws ApiException if fails to make API call + */ + public void logoutUser() throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/user/logout".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @throws ApiException if fails to make API call + */ + public void updateUser(String username, User body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser"); + } + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling updateUser"); + } + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 4eb2300b69d..592648b2bba 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -27,40 +27,44 @@ import io.swagger.client.Pair; -import com.squareup.okhttp.Credentials; +import com.migcomponents.migbase64.Base64; import java.util.Map; import java.util.List; import java.io.UnsupportedEncodingException; + public class HttpBasicAuth implements Authentication { - private String username; - private String password; + private String username; + private String password; - public String getUsername() { - return username; - } + public String getUsername() { + return username; + } - public void setUsername(String username) { - this.username = username; - } + public void setUsername(String username) { + this.username = username; + } - public String getPassword() { - return password; - } + public String getPassword() { + return password; + } - public void setPassword(String password) { - this.password = password; - } + public void setPassword(String password) { + this.password = password; + } - @Override - public void applyToParams(List queryParams, Map headerParams) { - if (username == null && password == null) { - return; - } - headerParams.put("Authorization", Credentials.basic( - username == null ? "" : username, - password == null ? "" : password)); + @Override + public void applyToParams(List queryParams, Map headerParams) { + if (username == null && password == null) { + return; + } + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + try { + headerParams.put("Authorization", "Basic " + Base64.encodeToString(str.getBytes("UTF-8"), false)); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); } + } } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 1943e013fa1..1e2d40891a2 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; @@ -39,10 +39,10 @@ */ public class AdditionalPropertiesClass { - @SerializedName("map_property") + @JsonProperty("map_property") private Map mapProperty = new HashMap(); - @SerializedName("map_of_map_property") + @JsonProperty("map_of_map_property") private Map> mapOfMapProperty = new HashMap>(); public AdditionalPropertiesClass mapProperty(Map mapProperty) { diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Animal.java index ba3806dc875..3ed2c6d9660 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Animal.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,10 +36,10 @@ */ public class Animal { - @SerializedName("className") + @JsonProperty("className") private String className = null; - @SerializedName("color") + @JsonProperty("color") private String color = "red"; public Animal className(String className) { diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 5446c2c439b..4d0dc41ee70 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; @@ -39,7 +39,7 @@ */ public class ArrayOfArrayOfNumberOnly { - @SerializedName("ArrayArrayNumber") + @JsonProperty("ArrayArrayNumber") private List> arrayArrayNumber = new ArrayList>(); public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index c9257a5d3ee..bd3f05a2ad4 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; @@ -39,7 +39,7 @@ */ public class ArrayOfNumberOnly { - @SerializedName("ArrayNumber") + @JsonProperty("ArrayNumber") private List arrayNumber = new ArrayList(); public ArrayOfNumberOnly arrayNumber(List arrayNumber) { diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayTest.java index 8d58870bcdc..900b8375eb0 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayTest.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.ReadOnlyFirst; @@ -39,13 +39,13 @@ */ public class ArrayTest { - @SerializedName("array_of_string") + @JsonProperty("array_of_string") private List arrayOfString = new ArrayList(); - @SerializedName("array_array_of_integer") + @JsonProperty("array_array_of_integer") private List> arrayArrayOfInteger = new ArrayList>(); - @SerializedName("array_array_of_model") + @JsonProperty("array_array_of_model") private List> arrayArrayOfModel = new ArrayList>(); public ArrayTest arrayOfString(List arrayOfString) { diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Cat.java index 21ed0f4c26b..f39b159f0b4 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Cat.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -37,13 +37,13 @@ */ public class Cat extends Animal { - @SerializedName("className") + @JsonProperty("className") private String className = null; - @SerializedName("color") + @JsonProperty("color") private String color = "red"; - @SerializedName("declawed") + @JsonProperty("declawed") private Boolean declawed = null; public Cat className(String className) { diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Category.java index 2178a866f62..c9bbbf525c5 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Category.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,10 +36,10 @@ */ public class Category { - @SerializedName("id") + @JsonProperty("id") private Long id = null; - @SerializedName("name") + @JsonProperty("name") private String name = null; public Category id(Long id) { diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Dog.java index 4ba5804553f..dbcd1a7207b 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Dog.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -37,13 +37,13 @@ */ public class Dog extends Animal { - @SerializedName("className") + @JsonProperty("className") private String className = null; - @SerializedName("color") + @JsonProperty("color") private String color = "red"; - @SerializedName("breed") + @JsonProperty("breed") private String breed = null; public Dog className(String className) { diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumClass.java index 73484907229..4433dca5f48 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumClass.java @@ -26,7 +26,6 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; /** @@ -34,13 +33,10 @@ */ public enum EnumClass { - @SerializedName("_abc") _ABC("_abc"), - @SerializedName("-efg") _EFG("-efg"), - @SerializedName("(xyz)") _XYZ_("(xyz)"); private String value; diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumTest.java index 9aad1223215..de36ef40ed4 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumTest.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -40,10 +40,8 @@ public class EnumTest { * Gets or Sets enumString */ public enum EnumStringEnum { - @SerializedName("UPPER") UPPER("UPPER"), - @SerializedName("lower") LOWER("lower"); private String value; @@ -58,17 +56,15 @@ public String toString() { } } - @SerializedName("enum_string") + @JsonProperty("enum_string") private EnumStringEnum enumString = null; /** * Gets or Sets enumInteger */ public enum EnumIntegerEnum { - @SerializedName("1") NUMBER_1(1), - @SerializedName("-1") NUMBER_MINUS_1(-1); private Integer value; @@ -83,17 +79,15 @@ public String toString() { } } - @SerializedName("enum_integer") + @JsonProperty("enum_integer") private EnumIntegerEnum enumInteger = null; /** * Gets or Sets enumNumber */ public enum EnumNumberEnum { - @SerializedName("1.1") NUMBER_1_DOT_1(1.1), - @SerializedName("-1.2") NUMBER_MINUS_1_DOT_2(-1.2); private Double value; @@ -108,7 +102,7 @@ public String toString() { } } - @SerializedName("enum_number") + @JsonProperty("enum_number") private EnumNumberEnum enumNumber = null; public EnumTest enumString(EnumStringEnum enumString) { diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/FormatTest.java index 4f7b82a92a1..4b49129ea84 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/FormatTest.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; @@ -39,43 +39,43 @@ */ public class FormatTest { - @SerializedName("integer") + @JsonProperty("integer") private Integer integer = null; - @SerializedName("int32") + @JsonProperty("int32") private Integer int32 = null; - @SerializedName("int64") + @JsonProperty("int64") private Long int64 = null; - @SerializedName("number") + @JsonProperty("number") private BigDecimal number = null; - @SerializedName("float") + @JsonProperty("float") private Float _float = null; - @SerializedName("double") + @JsonProperty("double") private Double _double = null; - @SerializedName("string") + @JsonProperty("string") private String string = null; - @SerializedName("byte") + @JsonProperty("byte") private byte[] _byte = null; - @SerializedName("binary") + @JsonProperty("binary") private byte[] binary = null; - @SerializedName("date") + @JsonProperty("date") private LocalDate date = null; - @SerializedName("dateTime") + @JsonProperty("dateTime") private OffsetDateTime dateTime = null; - @SerializedName("uuid") + @JsonProperty("uuid") private String uuid = null; - @SerializedName("password") + @JsonProperty("password") private String password = null; public FormatTest integer(Integer integer) { diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java index d77fc7ac36b..a3d01218197 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,10 +36,10 @@ */ public class HasOnlyReadOnly { - @SerializedName("bar") + @JsonProperty("bar") private String bar = null; - @SerializedName("foo") + @JsonProperty("foo") private String foo = null; /** diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MapTest.java index 61bdb6b2c65..6c0fc91ac41 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MapTest.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; @@ -39,17 +39,15 @@ */ public class MapTest { - @SerializedName("map_map_of_string") + @JsonProperty("map_map_of_string") private Map> mapMapOfString = new HashMap>(); /** * Gets or Sets inner */ public enum InnerEnum { - @SerializedName("UPPER") UPPER("UPPER"), - @SerializedName("lower") LOWER("lower"); private String value; @@ -64,7 +62,7 @@ public String toString() { } } - @SerializedName("map_of_enum_string") + @JsonProperty("map_of_enum_string") private Map mapOfEnumString = new HashMap(); public MapTest mapMapOfString(Map> mapMapOfString) { diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 2eefddfc9a1..8e72ca437b9 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -41,13 +41,13 @@ */ public class MixedPropertiesAndAdditionalPropertiesClass { - @SerializedName("uuid") + @JsonProperty("uuid") private String uuid = null; - @SerializedName("dateTime") + @JsonProperty("dateTime") private OffsetDateTime dateTime = null; - @SerializedName("map") + @JsonProperty("map") private Map map = new HashMap(); public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Model200Response.java index d8da58aca9c..3f4edf12daa 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Model200Response.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -37,10 +37,10 @@ @ApiModel(description = "Model for testing model name starting with number") public class Model200Response { - @SerializedName("name") + @JsonProperty("name") private Integer name = null; - @SerializedName("class") + @JsonProperty("class") private String PropertyClass = null; public Model200Response name(Integer name) { diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelApiResponse.java index 2a823298323..7b86d07a148 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,13 +36,13 @@ */ public class ModelApiResponse { - @SerializedName("code") + @JsonProperty("code") private Integer code = null; - @SerializedName("type") + @JsonProperty("type") private String type = null; - @SerializedName("message") + @JsonProperty("message") private String message = null; public ModelApiResponse code(Integer code) { diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelReturn.java index 024a9c0df1c..e8762f850db 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelReturn.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -37,7 +37,7 @@ @ApiModel(description = "Model for testing reserved words") public class ModelReturn { - @SerializedName("return") + @JsonProperty("return") private Integer _return = null; public ModelReturn _return(Integer _return) { diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Name.java index 318a2ddd50e..de446cdf30d 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Name.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -37,16 +37,16 @@ @ApiModel(description = "Model for testing model name same as property name") public class Name { - @SerializedName("name") + @JsonProperty("name") private Integer name = null; - @SerializedName("snake_case") + @JsonProperty("snake_case") private Integer snakeCase = null; - @SerializedName("property") + @JsonProperty("property") private String property = null; - @SerializedName("123Number") + @JsonProperty("123Number") private Integer _123Number = null; public Name name(Integer name) { diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/NumberOnly.java index 9b9ca048dfb..88c33f00f02 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/NumberOnly.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/NumberOnly.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; @@ -37,7 +37,7 @@ */ public class NumberOnly { - @SerializedName("JustNumber") + @JsonProperty("JustNumber") private BigDecimal justNumber = null; public NumberOnly justNumber(BigDecimal justNumber) { diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Order.java index eaf4397c4bf..1e7fc88dc38 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Order.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.time.OffsetDateTime; @@ -37,29 +37,26 @@ */ public class Order { - @SerializedName("id") + @JsonProperty("id") private Long id = null; - @SerializedName("petId") + @JsonProperty("petId") private Long petId = null; - @SerializedName("quantity") + @JsonProperty("quantity") private Integer quantity = null; - @SerializedName("shipDate") + @JsonProperty("shipDate") private OffsetDateTime shipDate = null; /** * Order Status */ public enum StatusEnum { - @SerializedName("placed") PLACED("placed"), - @SerializedName("approved") APPROVED("approved"), - @SerializedName("delivered") DELIVERED("delivered"); private String value; @@ -74,10 +71,10 @@ public String toString() { } } - @SerializedName("status") + @JsonProperty("status") private StatusEnum status = null; - @SerializedName("complete") + @JsonProperty("complete") private Boolean complete = false; public Order id(Long id) { diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Pet.java index b80fdeaf923..b468ebf1237 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Pet.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Category; @@ -40,32 +40,29 @@ */ public class Pet { - @SerializedName("id") + @JsonProperty("id") private Long id = null; - @SerializedName("category") + @JsonProperty("category") private Category category = null; - @SerializedName("name") + @JsonProperty("name") private String name = null; - @SerializedName("photoUrls") + @JsonProperty("photoUrls") private List photoUrls = new ArrayList(); - @SerializedName("tags") + @JsonProperty("tags") private List tags = new ArrayList(); /** * pet status in the store */ public enum StatusEnum { - @SerializedName("available") AVAILABLE("available"), - @SerializedName("pending") PENDING("pending"), - @SerializedName("sold") SOLD("sold"); private String value; @@ -80,7 +77,7 @@ public String toString() { } } - @SerializedName("status") + @JsonProperty("status") private StatusEnum status = null; public Pet id(Long id) { diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index 13b729bb94d..7f56ef2ff35 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,10 +36,10 @@ */ public class ReadOnlyFirst { - @SerializedName("bar") + @JsonProperty("bar") private String bar = null; - @SerializedName("baz") + @JsonProperty("baz") private String baz = null; /** diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/SpecialModelName.java index b46b8367a01..bc4863f101a 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,7 +36,7 @@ */ public class SpecialModelName { - @SerializedName("$special[property.name]") + @JsonProperty("$special[property.name]") private Long specialPropertyName = null; public SpecialModelName specialPropertyName(Long specialPropertyName) { diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Tag.java index e56eb535d1e..f27e45ea2aa 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Tag.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,10 +36,10 @@ */ public class Tag { - @SerializedName("id") + @JsonProperty("id") private Long id = null; - @SerializedName("name") + @JsonProperty("name") private String name = null; public Tag id(Long id) { diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/User.java index 6c1ed6ceacc..7c0421fa09e 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/User.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,28 +36,28 @@ */ public class User { - @SerializedName("id") + @JsonProperty("id") private Long id = null; - @SerializedName("username") + @JsonProperty("username") private String username = null; - @SerializedName("firstName") + @JsonProperty("firstName") private String firstName = null; - @SerializedName("lastName") + @JsonProperty("lastName") private String lastName = null; - @SerializedName("email") + @JsonProperty("email") private String email = null; - @SerializedName("password") + @JsonProperty("password") private String password = null; - @SerializedName("phone") + @JsonProperty("phone") private String phone = null; - @SerializedName("userStatus") + @JsonProperty("userStatus") private Integer userStatus = null; public User id(Long id) { diff --git a/samples/client/petstore/java/jersey2/build.gradle b/samples/client/petstore/java/jersey2/build.gradle index 9dfa55f2f89..067c81e1645 100644 --- a/samples/client/petstore/java/jersey2/build.gradle +++ b/samples/client/petstore/java/jersey2/build.gradle @@ -77,7 +77,6 @@ if(hasProperty('target') && target == 'android') { apply plugin: 'java' apply plugin: 'maven' - sourceCompatibility = JavaVersion.VERSION_1_7 targetCompatibility = JavaVersion.VERSION_1_7 @@ -93,11 +92,24 @@ if(hasProperty('target') && target == 'android') { } } +ext { + swagger_annotations_version = "1.5.8" + jackson_version = "2.7.5" + jersey_version = "2.22.2" + jodatime_version = "2.9.4" + junit_version = "4.12" +} + dependencies { - compile 'io.swagger:swagger-annotations:1.5.8' - compile 'com.squareup.okhttp:okhttp:2.7.5' - compile 'com.squareup.okhttp:logging-interceptor:2.7.5' - compile 'com.google.code.gson:gson:2.6.2' - compile 'joda-time:joda-time:2.9.3' - testCompile 'junit:junit:4.12' + compile "io.swagger:swagger-annotations:$swagger_annotations_version" + compile "org.glassfish.jersey.core:jersey-client:$jersey_version" + compile "org.glassfish.jersey.media:jersey-media-multipart:$jersey_version" + compile "org.glassfish.jersey.media:jersey-media-json-jackson:$jersey_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:$jackson_version" + 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/jersey2/build.sbt b/samples/client/petstore/java/jersey2/build.sbt index c192efc1d42..555b44f16db 100644 --- a/samples/client/petstore/java/jersey2/build.sbt +++ b/samples/client/petstore/java/jersey2/build.sbt @@ -10,10 +10,15 @@ lazy val root = (project in file(".")). resolvers += Resolver.mavenLocal, libraryDependencies ++= Seq( "io.swagger" % "swagger-annotations" % "1.5.8", - "com.squareup.okhttp" % "okhttp" % "2.7.5", - "com.squareup.okhttp" % "logging-interceptor" % "2.7.5", - "com.google.code.gson" % "gson" % "2.6.2", - "joda-time" % "joda-time" % "2.9.3" % "compile", + "org.glassfish.jersey.core" % "jersey-client" % "2.22.2", + "org.glassfish.jersey.media" % "jersey-media-multipart" % "2.22.2", + "org.glassfish.jersey.media" % "jersey-media-json-jackson" % "2.22.2", + "com.fasterxml.jackson.core" % "jackson-core" % "2.7.5", + "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.5", + "com.fasterxml.jackson.core" % "jackson-databind" % "2.7.5", + "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.7.5", + "joda-time" % "joda-time" % "2.9.4", + "com.brsanthu" % "migbase64" % "2.2", "junit" % "junit" % "4.12" % "test", "com.novocode" % "junit-interface" % "0.10" % "test" ) diff --git a/samples/client/petstore/java/jersey2/pom.xml b/samples/client/petstore/java/jersey2/pom.xml index 43699a74d4e..0026cda2c47 100644 --- a/samples/client/petstore/java/jersey2/pom.xml +++ b/samples/client/petstore/java/jersey2/pom.xml @@ -52,7 +52,7 @@ org.apache.maven.plugins maven-jar-plugin - 2.2 + 2.6 @@ -68,7 +68,6 @@ org.codehaus.mojo build-helper-maven-plugin - 1.10 add_sources @@ -96,6 +95,15 @@ + + org.apache.maven.plugins + maven-compiler-plugin + 2.5.1 + + 1.7 + 1.7 + + @@ -104,20 +112,44 @@ swagger-annotations ${swagger-core-version} + + + + org.glassfish.jersey.core + jersey-client + ${jersey-version} + + + org.glassfish.jersey.media + jersey-media-multipart + ${jersey-version} + - com.squareup.okhttp - okhttp - ${okhttp-version} + org.glassfish.jersey.media + jersey-media-json-jackson + ${jersey-version} + + - com.squareup.okhttp - logging-interceptor - ${okhttp-version} + com.fasterxml.jackson.core + jackson-core + ${jackson-version} - com.google.code.gson - gson - ${gson-version} + com.fasterxml.jackson.core + jackson-annotations + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-version} + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + ${jackson-version} joda-time @@ -125,6 +157,13 @@ ${jodatime-version} + + + com.brsanthu + migbase64 + 2.2 + + junit @@ -134,15 +173,11 @@ - 1.7 - ${java.version} - ${java.version} - 1.5.9 - 2.7.5 - 2.6.2 - 2.9.3 + 1.5.8 + 2.22.2 + 2.7.5 + 2.9.4 1.0.0 4.12 - UTF-8 diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiCallback.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiCallback.java deleted file mode 100644 index 3ca33cf8017..00000000000 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiCallback.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import java.io.IOException; - -import java.util.Map; -import java.util.List; - -/** - * Callback for asynchronous API call. - * - * @param The return type - */ -public interface ApiCallback { - /** - * This is called when the API call fails. - * - * @param e The exception causing the failure - * @param statusCode Status code of the response if available, otherwise it would be 0 - * @param responseHeaders Headers of the response if available, otherwise it would be null - */ - void onFailure(ApiException e, int statusCode, Map> responseHeaders); - - /** - * This is called when the API call succeeded. - * - * @param result The result deserialized from response - * @param statusCode Status code of the response - * @param responseHeaders Headers of the response - */ - void onSuccess(T result, int statusCode, Map> responseHeaders); - - /** - * This is called when the API upload processing. - * - * @param bytesWritten bytes Written - * @param contentLength content length of request body - * @param done write end - */ - void onUploadProgress(long bytesWritten, long contentLength, boolean done); - - /** - * This is called when the API downlond processing. - * - * @param bytesRead bytes Read - * @param contentLength content lenngth of the response - * @param done Read end - */ - void onDownloadProgress(long bytesRead, long contentLength, boolean done); -} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java index b7b04e3e4c5..047a47252f8 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 @@ -1,46 +1,28 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - package io.swagger.client; -import com.squareup.okhttp.Call; -import com.squareup.okhttp.Callback; -import com.squareup.okhttp.OkHttpClient; -import com.squareup.okhttp.Request; -import com.squareup.okhttp.Response; -import com.squareup.okhttp.RequestBody; -import com.squareup.okhttp.FormEncodingBuilder; -import com.squareup.okhttp.MultipartBuilder; -import com.squareup.okhttp.MediaType; -import com.squareup.okhttp.Headers; -import com.squareup.okhttp.internal.http.HttpMethod; -import com.squareup.okhttp.logging.HttpLoggingInterceptor; -import com.squareup.okhttp.logging.HttpLoggingInterceptor.Level; - -import java.lang.reflect.Type; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +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; + +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.client.ClientProperties; +import org.glassfish.jersey.filter.LoggingFilter; +import org.glassfish.jersey.jackson.JacksonFeature; +import org.glassfish.jersey.media.multipart.FormDataBodyPart; +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.MultiPart; +import org.glassfish.jersey.media.multipart.MultiPartFeature; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; import java.util.Collection; import java.util.Collections; import java.util.Map; @@ -50,1277 +32,667 @@ import java.util.ArrayList; import java.util.Date; import java.util.TimeZone; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import java.net.URLEncoder; -import java.net.URLConnection; import java.io.File; -import java.io.InputStream; -import java.io.IOException; import java.io.UnsupportedEncodingException; -import java.security.GeneralSecurityException; -import java.security.KeyStore; -import java.security.SecureRandom; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; - import java.text.DateFormat; import java.text.SimpleDateFormat; -import java.text.ParseException; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.KeyManager; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.X509TrustManager; - -import okio.BufferedSink; -import okio.Okio; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import io.swagger.client.auth.Authentication; import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; -public class ApiClient { - public static final double JAVA_VERSION; - public static final boolean IS_ANDROID; - public static final int ANDROID_SDK_VERSION; - - static { - JAVA_VERSION = Double.parseDouble(System.getProperty("java.specification.version")); - boolean isAndroid; - try { - Class.forName("android.app.Activity"); - isAndroid = true; - } catch (ClassNotFoundException e) { - isAndroid = false; - } - IS_ANDROID = isAndroid; - int sdkVersion = 0; - if (IS_ANDROID) { - try { - sdkVersion = Class.forName("android.os.Build$VERSION").getField("SDK_INT").getInt(null); - } catch (Exception e) { - try { - sdkVersion = Integer.parseInt((String) Class.forName("android.os.Build$VERSION").getField("SDK").get(null)); - } catch (Exception e2) { } - } - } - ANDROID_SDK_VERSION = sdkVersion; - } - - /** - * The datetime format to be used when lenientDatetimeFormat is enabled. - */ - public static final String LENIENT_DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; - - private String basePath = "http://petstore.swagger.io/v2"; - private boolean lenientOnJson = false; - private boolean debugging = false; - private Map defaultHeaderMap = new HashMap(); - private String tempFolderPath = null; - - private Map authentications; - - private DateFormat dateFormat; - private DateFormat datetimeFormat; - private boolean lenientDatetimeFormat; - private int dateLength; - - private InputStream sslCaCert; - private boolean verifyingSsl; - - private OkHttpClient httpClient; - private JSON json; - - private HttpLoggingInterceptor loggingInterceptor; - - /* - * Constructor for ApiClient - */ - public ApiClient() { - httpClient = new OkHttpClient(); - - verifyingSsl = true; - - json = new JSON(this); - - /* - * Use RFC3339 format for date and datetime. - * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 - */ - this.dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - // Always use UTC as the default time zone when dealing with date (without time). - this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - initDatetimeFormat(); - - // Be lenient on datetime formats when parsing datetime from string. - // See parseDatetime. - this.lenientDatetimeFormat = true; - - // Set default User-Agent. - setUserAgent("Swagger-Codegen/1.0.0/java"); - - // Setup authentications (key: authentication name, value: authentication). - authentications = new HashMap(); - authentications.put("api_key", new ApiKeyAuth("header", "api_key")); - authentications.put("petstore_auth", new OAuth()); - // Prevent the authentications from being modified. - authentications = Collections.unmodifiableMap(authentications); - } - - /** - * Get base path - * - * @return Baes path - */ - public String getBasePath() { - return basePath; - } - - /** - * Set base path - * - * @param basePath Base path of the URL (e.g http://petstore.swagger.io/v2 - * @return An instance of OkHttpClient - */ - public ApiClient setBasePath(String basePath) { - this.basePath = basePath; - return this; - } - - /** - * Get HTTP client - * - * @return An instance of OkHttpClient - */ - public OkHttpClient getHttpClient() { - return httpClient; - } - - /** - * Set HTTP client - * - * @param httpClient An instance of OkHttpClient - * @return Api Client - */ - public ApiClient setHttpClient(OkHttpClient httpClient) { - this.httpClient = httpClient; - return this; - } - - /** - * Get JSON - * - * @return JSON object - */ - public JSON getJSON() { - return json; - } - - /** - * Set JSON - * - * @param json JSON object - * @return Api client - */ - public ApiClient setJSON(JSON json) { - this.json = json; - return this; - } - - /** - * True if isVerifyingSsl flag is on - * - * @return True if isVerifySsl flag is on - */ - public boolean isVerifyingSsl() { - return verifyingSsl; - } - - /** - * Configure whether to verify certificate and hostname when making https requests. - * Default to true. - * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. - * - * @param verifyingSsl True to verify TLS/SSL connection - * @return ApiClient - */ - public ApiClient setVerifyingSsl(boolean verifyingSsl) { - this.verifyingSsl = verifyingSsl; - applySslSettings(); - return this; - } - - /** - * Get SSL CA cert. - * - * @return Input stream to the SSL CA cert - */ - public InputStream getSslCaCert() { - return sslCaCert; - } - - /** - * Configure the CA certificate to be trusted when making https requests. - * Use null to reset to default. - * - * @param sslCaCert input stream for SSL CA cert - * @return ApiClient - */ - public ApiClient setSslCaCert(InputStream sslCaCert) { - this.sslCaCert = sslCaCert; - applySslSettings(); - return this; - } - - public DateFormat getDateFormat() { - return dateFormat; - } - - public ApiClient setDateFormat(DateFormat dateFormat) { - this.dateFormat = dateFormat; - this.dateLength = this.dateFormat.format(new Date()).length(); - return this; - } - - public DateFormat getDatetimeFormat() { - return datetimeFormat; - } - - public ApiClient setDatetimeFormat(DateFormat datetimeFormat) { - this.datetimeFormat = datetimeFormat; - return this; - } - - /** - * Whether to allow various ISO 8601 datetime formats when parsing a datetime string. - * @see #parseDatetime(String) - * @return True if lenientDatetimeFormat flag is set to true - */ - public boolean isLenientDatetimeFormat() { - return lenientDatetimeFormat; - } - - public ApiClient setLenientDatetimeFormat(boolean lenientDatetimeFormat) { - this.lenientDatetimeFormat = lenientDatetimeFormat; - return this; - } - - /** - * Parse the given date string into Date object. - * The default dateFormat supports these ISO 8601 date formats: - * 2015-08-16 - * 2015-8-16 - * @param str String to be parsed - * @return Date - */ - public Date parseDate(String str) { - if (str == null) - return null; - try { - return dateFormat.parse(str); - } catch (ParseException e) { - throw new RuntimeException(e); - } - } - - /** - * Parse the given datetime string into Date object. - * When lenientDatetimeFormat is enabled, the following ISO 8601 datetime formats are supported: - * 2015-08-16T08:20:05Z - * 2015-8-16T8:20:05Z - * 2015-08-16T08:20:05+00:00 - * 2015-08-16T08:20:05+0000 - * 2015-08-16T08:20:05.376Z - * 2015-08-16T08:20:05.376+00:00 - * 2015-08-16T08:20:05.376+00 - * Note: The 3-digit milli-seconds is optional. Time zone is required and can be in one of - * these formats: - * Z (same with +0000) - * +08:00 (same with +0800) - * -02 (same with -0200) - * -0200 - * @see ISO 8601 - * @param str Date time string to be parsed - * @return Date representation of the string - */ - public Date parseDatetime(String str) { - if (str == null) - return null; - - DateFormat format; - if (lenientDatetimeFormat) { - /* - * When lenientDatetimeFormat is enabled, normalize the date string - * into LENIENT_DATETIME_FORMAT to support various formats - * defined by ISO 8601. - */ - // normalize time zone - // trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000 - str = str.replaceAll("[zZ]\\z", "+0000"); - // remove colon in time zone: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000 - str = str.replaceAll("([+-]\\d{2}):(\\d{2})\\z", "$1$2"); - // expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000 - str = str.replaceAll("([+-]\\d{2})\\z", "$100"); - // add milliseconds when missing - // 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000 - str = str.replaceAll("(:\\d{1,2})([+-]\\d{4})\\z", "$1.000$2"); - format = new SimpleDateFormat(LENIENT_DATETIME_FORMAT); - } else { - format = this.datetimeFormat; - } - - try { - return format.parse(str); - } catch (ParseException e) { - throw new RuntimeException(e); - } - } - - /* - * Parse date or date time in string format into Date object. - * - * @param str Date time string to be parsed - * @return Date representation of the string - */ - public Date parseDateOrDatetime(String str) { - if (str == null) - return null; - else if (str.length() <= dateLength) - return parseDate(str); - else - return parseDatetime(str); - } - - /** - * Format the given Date object into string (Date format). - * - * @param date Date object - * @return Formatted date in string representation - */ - public String formatDate(Date date) { - return dateFormat.format(date); - } - - /** - * Format the given Date object into string (Datetime format). - * - * @param date Date object - * @return Formatted datetime in string representation - */ - public String formatDatetime(Date date) { - return datetimeFormat.format(date); - } - - /** - * Get authentications (key: authentication name, value: authentication). - * - * @return Map of authentication objects - */ - public Map getAuthentications() { - return authentications; - } - - /** - * Get authentication for the given name. - * - * @param authName The authentication name - * @return The authentication, null if not found - */ - public Authentication getAuthentication(String authName) { - return authentications.get(authName); - } - - /** - * Helper method to set username for the first HTTP basic authentication. - * - * @param username Username - */ - public void setUsername(String username) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setUsername(username); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set password for the first HTTP basic authentication. - * - * @param password Password - */ - public void setPassword(String password) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setPassword(password); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set API key value for the first API key authentication. - * - * @param apiKey API key - */ - public void setApiKey(String apiKey) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKey(apiKey); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set API key prefix for the first API key authentication. - * - * @param apiKeyPrefix API key prefix - */ - public void setApiKeyPrefix(String apiKeyPrefix) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set access token for the first OAuth2 authentication. - * - * @param accessToken Access token - */ - public void setAccessToken(String accessToken) { - for (Authentication auth : authentications.values()) { - if (auth instanceof OAuth) { - ((OAuth) auth).setAccessToken(accessToken); - return; - } - } - throw new RuntimeException("No OAuth2 authentication configured!"); - } - - /** - * Set the User-Agent header's value (by adding to the default header map). - * - * @param userAgent HTTP request's user agent - * @return ApiClient - */ - public ApiClient setUserAgent(String userAgent) { - addDefaultHeader("User-Agent", userAgent); - return this; - } - - /** - * Add a default header. - * - * @param key The header's key - * @param value The header's value - * @return ApiClient - */ - public ApiClient addDefaultHeader(String key, String value) { - defaultHeaderMap.put(key, value); - return this; - } - - /** - * @see setLenient - * - * @return True if lenientOnJson is enabled, false otherwise. - */ - public boolean isLenientOnJson() { - return lenientOnJson; - } - - /** - * Set LenientOnJson - * - * @param lenient True to enable lenientOnJson - * @return ApiClient - */ - public ApiClient setLenientOnJson(boolean lenient) { - this.lenientOnJson = lenient; - return this; - } - - /** - * Check that whether debugging is enabled for this API client. - * - * @return True if debugging is enabled, false otherwise. - */ - public boolean isDebugging() { - return debugging; - } - - /** - * Enable/disable debugging for this API client. - * - * @param debugging To enable (true) or disable (false) debugging - * @return ApiClient - */ - public ApiClient setDebugging(boolean debugging) { - if (debugging != this.debugging) { - if (debugging) { - loggingInterceptor = new HttpLoggingInterceptor(); - loggingInterceptor.setLevel(Level.BODY); - httpClient.interceptors().add(loggingInterceptor); - } else { - httpClient.interceptors().remove(loggingInterceptor); - loggingInterceptor = null; - } - } - this.debugging = debugging; - return this; - } - - /** - * The path of temporary folder used to store downloaded files from endpoints - * with file response. The default value is null, i.e. using - * the system's default tempopary folder. - * - * @see createTempFile - * @return Temporary folder path - */ - public String getTempFolderPath() { - return tempFolderPath; - } - - /** - * Set the tempoaray folder path (for downloading files) - * - * @param tempFolderPath Temporary folder path - * @return ApiClient - */ - public ApiClient setTempFolderPath(String tempFolderPath) { - this.tempFolderPath = tempFolderPath; - return this; - } - - /** - * Get connection timeout (in milliseconds). - * - * @return Timeout in milliseconds - */ - public int getConnectTimeout() { - return httpClient.getConnectTimeout(); - } - - /** - * Sets the connect timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * - * @param connectionTimeout connection timeout in milliseconds - * @return Api client - */ - public ApiClient setConnectTimeout(int connectionTimeout) { - httpClient.setConnectTimeout(connectionTimeout, TimeUnit.MILLISECONDS); - return this; - } - - /** - * Format the given parameter object into string. - * - * @param param Parameter - * @return String representation of the parameter - */ - public String parameterToString(Object param) { - if (param == null) { - return ""; - } else if (param instanceof Date) { - return formatDatetime((Date) param); - } else if (param instanceof Collection) { - StringBuilder b = new StringBuilder(); - for (Object o : (Collection)param) { - if (b.length() > 0) { - b.append(","); - } - b.append(String.valueOf(o)); - } - return b.toString(); - } else { - return String.valueOf(param); - } - } - - /** - * Format to {@code Pair} objects. - * - * @param collectionFormat collection format (e.g. csv, tsv) - * @param name Name - * @param value Value - * @return A list of Pair objects - */ - public List parameterToPairs(String collectionFormat, String name, Object value){ - List params = new ArrayList(); - - // preconditions - if (name == null || name.isEmpty() || value == null) return params; - - Collection valueCollection = null; - if (value instanceof Collection) { - valueCollection = (Collection) value; - } else { - params.add(new Pair(name, parameterToString(value))); - return params; - } - - if (valueCollection.isEmpty()){ - return params; - } - - // get the collection format - collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv - - // create the params based on the collection format - if (collectionFormat.equals("multi")) { - for (Object item : valueCollection) { - params.add(new Pair(name, parameterToString(item))); - } - - return params; - } - - String delimiter = ","; - - if (collectionFormat.equals("csv")) { - delimiter = ","; - } else if (collectionFormat.equals("ssv")) { - delimiter = " "; - } else if (collectionFormat.equals("tsv")) { - delimiter = "\t"; - } else if (collectionFormat.equals("pipes")) { - delimiter = "|"; - } - - StringBuilder sb = new StringBuilder() ; - for (Object item : valueCollection) { - sb.append(delimiter); - sb.append(parameterToString(item)); - } - - params.add(new Pair(name, sb.substring(1))); - - return params; - } - - /** - * Sanitize filename by removing path. - * e.g. ../../sun.gif becomes sun.gif - * - * @param filename The filename to be sanitized - * @return The sanitized filename - */ - public String sanitizeFilename(String filename) { - return filename.replaceAll(".*[/\\\\]", ""); - } - - /** - * Check if the given MIME is a JSON MIME. - * JSON MIME examples: - * application/json - * application/json; charset=UTF8 - * APPLICATION/JSON - * - * @param mime MIME (Multipurpose Internet Mail Extensions) - * @return True if the given MIME is JSON, false otherwise. - */ - public boolean isJsonMime(String mime) { - return mime != null && mime.matches("(?i)application\\/json(;.*)?"); - } - - /** - * Select the Accept header's value from the given accepts array: - * if JSON exists in the given array, use it; - * otherwise use all of them (joining into a string) - * - * @param accepts The accepts array to select from - * @return The Accept header to use. If the given array is empty, - * null will be returned (not to set the Accept header explicitly). - */ - public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) { - return null; - } - for (String accept : accepts) { - if (isJsonMime(accept)) { - return accept; - } - } - return StringUtil.join(accepts, ","); - } - - /** - * Select the Content-Type header's value from the given array: - * if JSON exists in the given array, use it; - * otherwise use the first one of the array. - * - * @param contentTypes The Content-Type array to select from - * @return The Content-Type header to use. If the given array is empty, - * JSON will be used. - */ - public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) { - return "application/json"; - } - for (String contentType : contentTypes) { - if (isJsonMime(contentType)) { - return contentType; - } - } - return contentTypes[0]; - } - - /** - * Escape the given string to be used as URL query value. - * - * @param str String to be escaped - * @return Escaped string - */ - public String escapeString(String str) { - try { - return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); - } catch (UnsupportedEncodingException e) { - return str; - } - } - - /** - * Deserialize response body to Java object, according to the return type and - * the Content-Type response header. - * - * @param Type - * @param response HTTP response - * @param returnType The type of the Java object - * @return The deserialized Java object - * @throws ApiException If fail to deserialize response body, i.e. cannot read response body - * or the Content-Type of the response is not supported. - */ - @SuppressWarnings("unchecked") - public T deserialize(Response response, Type returnType) throws ApiException { - if (response == null || returnType == null) { - return null; - } - - if ("byte[]".equals(returnType.toString())) { - // Handle binary response (byte array). - try { - return (T) response.body().bytes(); - } catch (IOException e) { - throw new ApiException(e); - } - } else if (returnType.equals(File.class)) { - // Handle file downloading. - return (T) downloadFileFromResponse(response); - } - - String respBody; - try { - if (response.body() != null) - respBody = response.body().string(); - else - respBody = null; - } catch (IOException e) { - throw new ApiException(e); - } - - if (respBody == null || "".equals(respBody)) { - return null; - } - String contentType = response.headers().get("Content-Type"); - if (contentType == null) { - // ensuring a default content type - contentType = "application/json"; - } - if (isJsonMime(contentType)) { - return json.deserialize(respBody, returnType); - } else if (returnType.equals(String.class)) { - // Expecting string, return the raw response body. - return (T) respBody; - } else { - throw new ApiException( - "Content type \"" + contentType + "\" is not supported for type: " + returnType, - response.code(), - response.headers().toMultimap(), - respBody); - } - } - - /** - * Serialize the given Java object into request body according to the object's - * class and the request Content-Type. - * - * @param obj The Java object - * @param contentType The request Content-Type - * @return The serialized request body - * @throws ApiException If fail to serialize the given object - */ - public RequestBody serialize(Object obj, String contentType) throws ApiException { - if (obj instanceof byte[]) { - // Binary (byte array) body parameter support. - return RequestBody.create(MediaType.parse(contentType), (byte[]) obj); - } else if (obj instanceof File) { - // File body parameter support. - return RequestBody.create(MediaType.parse(contentType), (File) obj); - } else if (isJsonMime(contentType)) { - String content; - if (obj != null) { - content = json.serialize(obj); - } else { - content = null; - } - return RequestBody.create(MediaType.parse(contentType), content); - } else { - throw new ApiException("Content type \"" + contentType + "\" is not supported"); - } - } - - /** - * Download file from the given response. - * - * @param response An instance of the Response object - * @throws ApiException If fail to read file content from response and write to disk - * @return Downloaded file - */ - public File downloadFileFromResponse(Response response) throws ApiException { - try { - File file = prepareDownloadFile(response); - BufferedSink sink = Okio.buffer(Okio.sink(file)); - sink.writeAll(response.body().source()); - sink.close(); - return file; - } catch (IOException e) { - throw new ApiException(e); - } - } - - /** - * Prepare file for download - * - * @param response An instance of the Response object - * @throws IOException If fail to prepare file for download - * @return Prepared file for the download - */ - public File prepareDownloadFile(Response response) throws IOException { - String filename = null; - String contentDisposition = response.header("Content-Disposition"); - if (contentDisposition != null && !"".equals(contentDisposition)) { - // Get filename from the Content-Disposition header. - Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); - Matcher matcher = pattern.matcher(contentDisposition); - if (matcher.find()) { - filename = sanitizeFilename(matcher.group(1)); - } - } - - String prefix = null; - String suffix = null; - if (filename == null) { - prefix = "download-"; - suffix = ""; - } else { - int pos = filename.lastIndexOf("."); - if (pos == -1) { - prefix = filename + "-"; - } else { - prefix = filename.substring(0, pos) + "-"; - suffix = filename.substring(pos); - } - // File.createTempFile requires the prefix to be at least three characters long - if (prefix.length() < 3) - prefix = "download-"; - } - - if (tempFolderPath == null) - return File.createTempFile(prefix, suffix); - else - return File.createTempFile(prefix, suffix, new File(tempFolderPath)); - } - - /** - * {@link #execute(Call, Type)} - * - * @param Type - * @param call An instance of the Call object - * @throws ApiException If fail to execute the call - * @return ApiResponse<T> - */ - public ApiResponse execute(Call call) throws ApiException { - return execute(call, null); - } - - /** - * Execute HTTP call and deserialize the HTTP response body into the given return type. - * - * @param returnType The return type used to deserialize HTTP response body - * @param The return type corresponding to (same with) returnType - * @param call Call - * @return ApiResponse object containing response status, headers and - * data, which is a Java object deserialized from response body and would be null - * when returnType is null. - * @throws ApiException If fail to execute the call - */ - public ApiResponse execute(Call call, Type returnType) throws ApiException { - try { - Response response = call.execute(); - T data = handleResponse(response, returnType); - return new ApiResponse(response.code(), response.headers().toMultimap(), data); - } catch (IOException e) { - throw new ApiException(e); - } - } - - /** - * {@link #executeAsync(Call, Type, ApiCallback)} - * - * @param Type - * @param call An instance of the Call object - * @param callback ApiCallback<T> - */ - public void executeAsync(Call call, ApiCallback callback) { - executeAsync(call, null, callback); - } - - /** - * Execute HTTP call asynchronously. - * - * @see #execute(Call, Type) - * @param Type - * @param call The callback to be executed when the API call finishes - * @param returnType Return type - * @param callback ApiCallback - */ - @SuppressWarnings("unchecked") - public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { - call.enqueue(new Callback() { - @Override - public void onFailure(Request request, IOException e) { - callback.onFailure(new ApiException(e), 0, null); - } - - @Override - public void onResponse(Response response) throws IOException { - T result; - try { - result = (T) handleResponse(response, returnType); - } catch (ApiException e) { - callback.onFailure(e, response.code(), response.headers().toMultimap()); - return; - } - callback.onSuccess(result, response.code(), response.headers().toMultimap()); - } - }); - } - - /** - * Handle the given response, return the deserialized object when the response is successful. - * - * @param Type - * @param response Response - * @param returnType Return type - * @throws ApiException If the response has a unsuccessful status code or - * fail to deserialize the response body - * @return Type - */ - public T handleResponse(Response response, Type returnType) throws ApiException { - if (response.isSuccessful()) { - if (returnType == null || response.code() == 204) { - // returning null if the returnType is not defined, - // or the status code is 204 (No Content) - return null; - } else { - return deserialize(response, returnType); - } - } else { - String respBody = null; - if (response.body() != null) { - try { - respBody = response.body().string(); - } catch (IOException e) { - throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); - } - } - throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); - } - } - - /** - * Build HTTP call with the given options. - * - * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" - * @param queryParams The query parameters - * @param body The request body object - * @param headerParams The header parameters - * @param formParams The form parameters - * @param authNames The authentications to apply - * @param progressRequestListener Progress request listener - * @return The HTTP call - * @throws ApiException If fail to serialize the request body object - */ - public Call buildCall(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - updateParamsForAuth(authNames, queryParams, headerParams); - - final String url = buildUrl(path, queryParams); - final Request.Builder reqBuilder = new Request.Builder().url(url); - processHeaderParams(headerParams, reqBuilder); - - String contentType = (String) headerParams.get("Content-Type"); - // ensuring a default content type - if (contentType == null) { - contentType = "application/json"; - } - - RequestBody reqBody; - if (!HttpMethod.permitsRequestBody(method)) { - reqBody = null; - } else if ("application/x-www-form-urlencoded".equals(contentType)) { - reqBody = buildRequestBodyFormEncoding(formParams); - } else if ("multipart/form-data".equals(contentType)) { - reqBody = buildRequestBodyMultipart(formParams); - } else if (body == null) { - if ("DELETE".equals(method)) { - // allow calling DELETE without sending a request body - reqBody = null; - } else { - // use an empty request body (for POST, PUT and PATCH) - reqBody = RequestBody.create(MediaType.parse(contentType), ""); - } - } else { - reqBody = serialize(body, contentType); - } - - Request request = null; - - if(progressRequestListener != null && reqBody != null) { - ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener); - request = reqBuilder.method(method, progressRequestBody).build(); - } else { - request = reqBuilder.method(method, reqBody).build(); - } - - return httpClient.newCall(request); - } - - /** - * Build full URL by concatenating base path, the given sub path and query parameters. - * - * @param path The sub path - * @param queryParams The query parameters - * @return The full URL - */ - public String buildUrl(String path, List queryParams) { - final StringBuilder url = new StringBuilder(); - url.append(basePath).append(path); - - if (queryParams != null && !queryParams.isEmpty()) { - // support (constant) query string in `path`, e.g. "/posts?draft=1" - String prefix = path.contains("?") ? "&" : "?"; - for (Pair param : queryParams) { - if (param.getValue() != null) { - if (prefix != null) { - url.append(prefix); - prefix = null; - } else { - url.append("&"); - } - String value = parameterToString(param.getValue()); - url.append(escapeString(param.getName())).append("=").append(escapeString(value)); - } - } - } - - return url.toString(); - } - - /** - * Set header parameters to the request builder, including default headers. - * - * @param headerParams Header parameters in the ofrm of Map - * @param reqBuilder Reqeust.Builder - */ - public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { - for (Entry param : headerParams.entrySet()) { - reqBuilder.header(param.getKey(), parameterToString(param.getValue())); - } - for (Entry header : defaultHeaderMap.entrySet()) { - if (!headerParams.containsKey(header.getKey())) { - reqBuilder.header(header.getKey(), parameterToString(header.getValue())); - } - } - } - - /** - * Update query and header parameters based on authentication settings. - * - * @param authNames The authentications to apply - * @param queryParams List of query parameters - * @param headerParams Map of header parameters - */ - public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { - for (String authName : authNames) { - Authentication auth = authentications.get(authName); - if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); - auth.applyToParams(queryParams, headerParams); - } - } - - /** - * Build a form-encoding request body with the given form parameters. - * - * @param formParams Form parameters in the form of Map - * @return RequestBody - */ - public RequestBody buildRequestBodyFormEncoding(Map formParams) { - FormEncodingBuilder formBuilder = new FormEncodingBuilder(); - for (Entry param : formParams.entrySet()) { - formBuilder.add(param.getKey(), parameterToString(param.getValue())); - } - return formBuilder.build(); - } - - /** - * Build a multipart (file uploading) request body with the given form parameters, - * which could contain text fields and file fields. - * - * @param formParams Form parameters in the form of Map - * @return RequestBody - */ - public RequestBody buildRequestBodyMultipart(Map formParams) { - MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); - for (Entry param : formParams.entrySet()) { - if (param.getValue() instanceof File) { - File file = (File) param.getValue(); - Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\""); - MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); - mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file)); - } else { - Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\""); - mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue()))); - } - } - return mpBuilder.build(); - } - - /** - * Guess Content-Type header from the given file (defaults to "application/octet-stream"). - * - * @param file The given file - * @return The guessed Content-Type - */ - public String guessContentTypeFromFile(File file) { - String contentType = URLConnection.guessContentTypeFromName(file.getName()); - if (contentType == null) { - return "application/octet-stream"; - } else { - return contentType; - } - } - - /** - * Initialize datetime format according to the current environment, e.g. Java 1.7 and Android. - */ - private void initDatetimeFormat() { - String formatWithTimeZone = null; - if (IS_ANDROID) { - if (ANDROID_SDK_VERSION >= 18) { - // The time zone format "ZZZZZ" is available since Android 4.3 (SDK version 18) - formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"; - } - } else if (JAVA_VERSION >= 1.7) { - // The time zone format "XXX" is available since Java 1.7 - formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; - } - if (formatWithTimeZone != null) { - this.datetimeFormat = new SimpleDateFormat(formatWithTimeZone); - // NOTE: Use the system's default time zone (mainly for datetime formatting). +public class ApiClient { + private Map defaultHeaderMap = new HashMap(); + private String basePath = "http://petstore.swagger.io/v2"; + private boolean debugging = false; + private int connectionTimeout = 0; + + private Client httpClient; + private JSON json; + private String tempFolderPath = null; + + private Map authentications; + + private int statusCode; + private Map> responseHeaders; + + private DateFormat dateFormat; + + public ApiClient() { + json = new JSON(); + httpClient = buildHttpClient(debugging); + + // Use RFC3339 format for date and datetime. + // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + + // Use UTC as the default time zone. + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + + this.json.setDateFormat((DateFormat) dateFormat.clone()); + + // Set default User-Agent. + setUserAgent("Swagger-Codegen/1.0.0/java"); + + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap(); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("petstore_auth", new OAuth()); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + /** + * Gets the JSON instance to do JSON serialization and deserialization. + */ + public JSON getJSON() { + return json; + } + + public Client getHttpClient() { + return httpClient; + } + + public ApiClient setHttpClient(Client httpClient) { + this.httpClient = httpClient; + return this; + } + + public String getBasePath() { + return basePath; + } + + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + /** + * Gets the status code of the previous request + */ + public int getStatusCode() { + return statusCode; + } + + /** + * Gets the response headers of the previous request + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + + /** + * Get authentications (key: authentication name, value: authentication). + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set access token for the first OAuth2 authentication. + */ + public void setAccessToken(String accessToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); + return; + } + } + throw new RuntimeException("No OAuth2 authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + */ + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + /** + * Check that whether debugging is enabled for this API client. + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + */ + public ApiClient setDebugging(boolean debugging) { + this.debugging = debugging; + // Rebuild HTTP Client according to the new "debugging" value. + this.httpClient = buildHttpClient(debugging); + return this; + } + + /** + * The path of temporary folder used to store downloaded files from endpoints + * with file response. The default value is null, i.e. using + * the system's default tempopary folder. + * + * @see https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createTempFile(java.lang.String,%20java.lang.String,%20java.io.File) + */ + public String getTempFolderPath() { + return tempFolderPath; + } + + public ApiClient setTempFolderPath(String tempFolderPath) { + this.tempFolderPath = tempFolderPath; + return this; + } + + /** + * Connect timeout (in milliseconds). + */ + public int getConnectTimeout() { + return connectionTimeout; + } + + /** + * Set the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link Integer#MAX_VALUE}. + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + this.connectionTimeout = connectionTimeout; + httpClient.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout); + return this; + } + + /** + * Get the date format used to parse/format date parameters. + */ + public DateFormat getDateFormat() { + return dateFormat; + } + + /** + * Set the date format used to parse/format date parameters. + */ + 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()); + return this; + } + + /** + * Parse the given string into Date object. + */ + public Date parseDate(String str) { + try { + return dateFormat.parse(str); + } catch (java.text.ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Format the given Date object into string. + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } + + /** + * 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 to {@code Pair} objects. + */ + public List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + + // create the params based on the collection format + if (collectionFormat.equals("multi")) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); + } + + return params; + } + + String delimiter = ","; + + if (collectionFormat.equals("csv")) { + delimiter = ","; + } else if (collectionFormat.equals("ssv")) { + delimiter = " "; + } else if (collectionFormat.equals("tsv")) { + delimiter = "\t"; + } else if (collectionFormat.equals("pipes")) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + + return params; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + */ + public boolean isJsonMime(String mime) { + return mime != null && mime.matches("(?i)application\\/json(;.*)?"); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } + return contentTypes[0]; + } + + /** + * Escape the given string to be used as URL query value. + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Serialize the given Java object into string entity according the given + * Content-Type (only JSON is supported for now). + */ + 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 { - // Use a common format that works across all systems. - this.datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - // Always use the UTC time zone as we are using a constant trailing "Z" here. - this.datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - } - } - - /** - * Apply SSL related settings to httpClient according to the current values of - * verifyingSsl and sslCaCert. - */ - private void applySslSettings() { + 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 { + // 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, GenericType returnType) throws ApiException { + // Handle file downloading. + if (returnType.equals(File.class)) { + @SuppressWarnings("unchecked") + T file = (T) downloadFileFromResponse(response); + return file; + } + + String contentType = null; + List contentTypes = response.getHeaders().get("Content-Type"); + if (contentTypes != null && !contentTypes.isEmpty()) + contentType = String.valueOf(contentTypes.get(0)); + if (contentType == null) + throw new ApiException(500, "missing Content-Type in response"); + + return response.readEntity(returnType); + } + + /** + * Download file from the given response. + * @throws ApiException If fail to read file content from response and write to disk + */ + public File downloadFileFromResponse(Response response) throws ApiException { + try { + File file = prepareDownloadFile(response); + Files.copy(response.readEntity(InputStream.class), file.toPath()); + return file; + } catch (IOException e) { + throw new ApiException(e); + } + } + + public File prepareDownloadFile(Response response) throws IOException { + String filename = null; + String contentDisposition = (String) response.getHeaders().getFirst("Content-Disposition"); + if (contentDisposition != null && !"".equals(contentDisposition)) { + // Get filename from the Content-Disposition header. + Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); + Matcher matcher = pattern.matcher(contentDisposition); + if (matcher.find()) + filename = matcher.group(1); + } + + String prefix = null; + String suffix = null; + if (filename == null) { + prefix = "download-"; + suffix = ""; + } else { + int pos = filename.lastIndexOf("."); + if (pos == -1) { + prefix = filename + "-"; + } else { + prefix = filename.substring(0, pos) + "-"; + suffix = filename.substring(pos); + } + // File.createTempFile requires the prefix to be at least three characters long + if (prefix.length() < 3) + prefix = "download-"; + } + + if (tempFolderPath == null) + return File.createTempFile(prefix, suffix); + else + return File.createTempFile(prefix, suffix, new File(tempFolderPath)); + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @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 + * @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 + * @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, GenericType returnType) throws ApiException { + updateParamsForAuth(authNames, queryParams, headerParams); + + // Not using `.target(this.basePath).path(path)` below, + // to support (constant) query string in `path`, e.g. "/posts?draft=1" + WebTarget target = httpClient.target(this.basePath + path); + + if (queryParams != null) { + for (Pair queryParam : queryParams) { + if (queryParam.getValue() != null) { + target = target.queryParam(queryParam.getName(), queryParam.getValue()); + } + } + } + + Invocation.Builder invocationBuilder = target.request().accept(accept); + + for (String key : headerParams.keySet()) { + String value = headerParams.get(key); + if (value != null) { + invocationBuilder = invocationBuilder.header(key, value); + } + } + + for (String key : defaultHeaderMap.keySet()) { + if (!headerParams.containsKey(key)) { + String value = defaultHeaderMap.get(key); + if (value != null) { + invocationBuilder = invocationBuilder.header(key, value); + } + } + } + + Entity entity = serialize(body, formParams, contentType); + + Response response = null; + + if ("GET".equals(method)) { + response = invocationBuilder.get(); + } else if ("POST".equals(method)) { + response = invocationBuilder.post(entity); + } else if ("PUT".equals(method)) { + response = invocationBuilder.put(entity); + } else if ("DELETE".equals(method)) { + response = invocationBuilder.delete(); + } else { + throw new ApiException(500, "unknown method type " + method); + } + + statusCode = response.getStatusInfo().getStatusCode(); + responseHeaders = buildResponseHeaders(response); + + if (response.getStatus() == Status.NO_CONTENT.getStatusCode()) { + return null; + } else if (response.getStatusInfo().getFamily().equals(Status.Family.SUCCESSFUL)) { + if (returnType == null) + return null; + else + return deserialize(response, returnType); + } else { + String message = "error"; + String respBody = null; + if (response.hasEntity()) { try { - KeyManager[] keyManagers = null; - TrustManager[] trustManagers = null; - HostnameVerifier hostnameVerifier = null; - if (!verifyingSsl) { - TrustManager trustAll = new X509TrustManager() { - @Override - public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} - @Override - public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} - @Override - public X509Certificate[] getAcceptedIssuers() { return null; } - }; - SSLContext sslContext = SSLContext.getInstance("TLS"); - trustManagers = new TrustManager[]{ trustAll }; - hostnameVerifier = new HostnameVerifier() { - @Override - public boolean verify(String hostname, SSLSession session) { return true; } - }; - } else if (sslCaCert != null) { - char[] password = null; // Any password will work. - CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); - Collection certificates = certificateFactory.generateCertificates(sslCaCert); - if (certificates.isEmpty()) { - throw new IllegalArgumentException("expected non-empty set of trusted certificates"); - } - KeyStore caKeyStore = newEmptyKeyStore(password); - int index = 0; - for (Certificate certificate : certificates) { - String certificateAlias = "ca" + Integer.toString(index++); - caKeyStore.setCertificateEntry(certificateAlias, certificate); - } - TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - trustManagerFactory.init(caKeyStore); - trustManagers = trustManagerFactory.getTrustManagers(); - } - - if (keyManagers != null || trustManagers != null) { - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(keyManagers, trustManagers, new SecureRandom()); - httpClient.setSslSocketFactory(sslContext.getSocketFactory()); - } else { - httpClient.setSslSocketFactory(null); - } - httpClient.setHostnameVerifier(hostnameVerifier); - } catch (GeneralSecurityException e) { - throw new RuntimeException(e); - } - } - - private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { - try { - KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - keyStore.load(null, password); - return keyStore; - } catch (IOException e) { - throw new AssertionError(e); - } - } + respBody = String.valueOf(response.readEntity(String.class)); + message = respBody; + } catch (RuntimeException e) { + // e.printStackTrace(); + } + } + throw new ApiException( + response.getStatus(), + message, + buildResponseHeaders(response), + respBody); + } + } + + /** + * Build the Client used to make HTTP requests. + */ + private Client buildHttpClient(boolean debugging) { + final ClientConfig clientConfig = new ClientConfig(); + clientConfig.register(MultiPartFeature.class); + clientConfig.register(json); + clientConfig.register(JacksonFeature.class); + if (debugging) { + clientConfig.register(LoggingFilter.class); + } + return ClientBuilder.newClient(clientConfig); + } + + private Map> buildResponseHeaders(Response response) { + Map> responseHeaders = new HashMap>(); + for (Entry> entry: response.getHeaders().entrySet()) { + List values = entry.getValue(); + List headers = new ArrayList(); + for (Object o : values) { + headers.add(String.valueOf(o)); + } + responseHeaders.put(entry.getKey(), headers); + } + return responseHeaders; + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + */ + private void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); + auth.applyToParams(queryParams, headerParams); + } + } } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiResponse.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiResponse.java deleted file mode 100644 index d7dde1ee939..00000000000 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiResponse.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import java.util.List; -import java.util.Map; - -/** - * API response returned by API call. - * - * @param T The type of data that is deserialized from response body - */ -public class ApiResponse { - final private int statusCode; - final private Map> headers; - final private T data; - - /** - * @param statusCode The status code of HTTP response - * @param headers The headers of HTTP response - */ - public ApiResponse(int statusCode, Map> headers) { - this(statusCode, headers, null); - } - - /** - * @param statusCode The status code of HTTP response - * @param headers The headers of HTTP response - * @param data The object deserialized from response bod - */ - public ApiResponse(int statusCode, Map> headers, T data) { - this.statusCode = statusCode; - this.headers = headers; - this.data = data; - } - - public int getStatusCode() { - return statusCode; - } - - public Map> getHeaders() { - return headers; - } - - public T getData() { - return data; - } -} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java index 540611eab9d..d6f725b2caa 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java @@ -1,237 +1,36 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - package io.swagger.client; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonNull; -import com.google.gson.JsonParseException; -import com.google.gson.JsonPrimitive; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; - -import java.io.IOException; -import java.io.StringReader; -import java.lang.reflect.Type; -import java.util.Date; - -import org.joda.time.DateTime; -import org.joda.time.LocalDate; -import org.joda.time.format.DateTimeFormatter; -import org.joda.time.format.ISODateTimeFormat; - -public class JSON { - private ApiClient apiClient; - private Gson gson; - - /** - * JSON constructor. - * - * @param apiClient An instance of ApiClient - */ - public JSON(ApiClient apiClient) { - this.apiClient = apiClient; - gson = new GsonBuilder() - .registerTypeAdapter(Date.class, new DateAdapter(apiClient)) - .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) - .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) - .create(); - } - - /** - * Get Gson. - * - * @return Gson - */ - public Gson getGson() { - return gson; - } - - /** - * Set Gson. - * - * @param gson Gson - */ - public void setGson(Gson gson) { - this.gson = gson; - } - - /** - * Serialize the given Java object into JSON string. - * - * @param obj Object - * @return String representation of the JSON - */ - public String serialize(Object obj) { - return gson.toJson(obj); - } +import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.datatype.joda.*; - /** - * Deserialize the given JSON string to Java object. - * - * @param Type - * @param body The JSON string - * @param returnType The type to deserialize inot - * @return The deserialized Java object - */ - @SuppressWarnings("unchecked") - public T deserialize(String body, Type returnType) { - try { - if (apiClient.isLenientOnJson()) { - JsonReader jsonReader = new JsonReader(new StringReader(body)); - // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) - jsonReader.setLenient(true); - return gson.fromJson(jsonReader, returnType); - } else { - return gson.fromJson(body, returnType); - } - } catch (JsonParseException e) { - // Fallback processing when failed to parse JSON form response body: - // return the response body string directly for the String return type; - // parse response body into date or datetime for the Date return type. - if (returnType.equals(String.class)) - return (T) body; - else if (returnType.equals(Date.class)) - return (T) apiClient.parseDateOrDatetime(body); - else throw(e); - } - } -} - -class DateAdapter implements JsonSerializer, JsonDeserializer { - private final ApiClient apiClient; - - /** - * Constructor for DateAdapter - * - * @param apiClient Api client - */ - public DateAdapter(ApiClient apiClient) { - super(); - this.apiClient = apiClient; - } +import java.text.DateFormat; - /** - * Serialize - * - * @param src Date - * @param typeOfSrc Type - * @param context Json Serialization Context - * @return Json Element - */ - @Override - public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { - if (src == null) { - return JsonNull.INSTANCE; - } else { - return new JsonPrimitive(apiClient.formatDatetime(src)); - } - } - - /** - * Deserialize - * - * @param json Json element - * @param date Type - * @param typeOfSrc Type - * @param context Json Serialization Context - * @return Date - * @throw JsonParseException if fail to parse - */ - @Override - public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException { - String str = json.getAsJsonPrimitive().getAsString(); - try { - return apiClient.parseDateOrDatetime(str); - } catch (RuntimeException e) { - throw new JsonParseException(e); - } - } -} +import javax.ws.rs.ext.ContextResolver; -/** - * Gson TypeAdapter for Joda DateTime type - */ -class DateTimeTypeAdapter extends TypeAdapter { - - private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); - - @Override - public void write(JsonWriter out, DateTime date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - out.value(formatter.print(date)); - } - } - - @Override - public DateTime read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - return formatter.parseDateTime(date); - } - } -} -/** - * Gson TypeAdapter for Joda LocalDate type - */ -class LocalDateTypeAdapter extends TypeAdapter { +public class JSON implements ContextResolver { + private ObjectMapper mapper; - private final DateTimeFormatter formatter = ISODateTimeFormat.date(); + 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()); + } - @Override - public void write(JsonWriter out, LocalDate date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - out.value(formatter.print(date)); - } - } + /** + * Set the date format for JSON (de)serialization with Date properties. + */ + public void setDateFormat(DateFormat dateFormat) { + mapper.setDateFormat(dateFormat); + } - @Override - public LocalDate read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - return formatter.parseLocalDate(date); - } - } + @Override + public ObjectMapper getContext(Class type) { + return mapper; + } } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ProgressRequestBody.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ProgressRequestBody.java deleted file mode 100644 index d9ca742ecd2..00000000000 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ProgressRequestBody.java +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import com.squareup.okhttp.MediaType; -import com.squareup.okhttp.RequestBody; - -import java.io.IOException; - -import okio.Buffer; -import okio.BufferedSink; -import okio.ForwardingSink; -import okio.Okio; -import okio.Sink; - -public class ProgressRequestBody extends RequestBody { - - public interface ProgressRequestListener { - void onRequestProgress(long bytesWritten, long contentLength, boolean done); - } - - private final RequestBody requestBody; - - private final ProgressRequestListener progressListener; - - private BufferedSink bufferedSink; - - public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) { - this.requestBody = requestBody; - this.progressListener = progressListener; - } - - @Override - public MediaType contentType() { - return requestBody.contentType(); - } - - @Override - public long contentLength() throws IOException { - return requestBody.contentLength(); - } - - @Override - public void writeTo(BufferedSink sink) throws IOException { - if (bufferedSink == null) { - bufferedSink = Okio.buffer(sink(sink)); - } - - requestBody.writeTo(bufferedSink); - bufferedSink.flush(); - - } - - private Sink sink(Sink sink) { - return new ForwardingSink(sink) { - - long bytesWritten = 0L; - long contentLength = 0L; - - @Override - public void write(Buffer source, long byteCount) throws IOException { - super.write(source, byteCount); - if (contentLength == 0) { - contentLength = contentLength(); - } - - bytesWritten += byteCount; - progressListener.onRequestProgress(bytesWritten, contentLength, bytesWritten == contentLength); - } - }; - } -} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ProgressResponseBody.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ProgressResponseBody.java deleted file mode 100644 index f8af685999d..00000000000 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ProgressResponseBody.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import com.squareup.okhttp.MediaType; -import com.squareup.okhttp.ResponseBody; - -import java.io.IOException; - -import okio.Buffer; -import okio.BufferedSource; -import okio.ForwardingSource; -import okio.Okio; -import okio.Source; - -public class ProgressResponseBody extends ResponseBody { - - public interface ProgressListener { - void update(long bytesRead, long contentLength, boolean done); - } - - private final ResponseBody responseBody; - private final ProgressListener progressListener; - private BufferedSource bufferedSource; - - public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) { - this.responseBody = responseBody; - this.progressListener = progressListener; - } - - @Override - public MediaType contentType() { - return responseBody.contentType(); - } - - @Override - public long contentLength() throws IOException { - return responseBody.contentLength(); - } - - @Override - public BufferedSource source() throws IOException { - if (bufferedSource == null) { - bufferedSource = Okio.buffer(source(responseBody.source())); - } - return bufferedSource; - } - - private Source source(Source source) { - return new ForwardingSource(source) { - long totalBytesRead = 0L; - - @Override - public long read(Buffer sink, long byteCount) throws IOException { - long bytesRead = super.read(sink, byteCount); - // read() returns the number of bytes read, or -1 if this source is exhausted. - totalBytesRead += bytesRead != -1 ? bytesRead : 0; - progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1); - return bytesRead; - } - }; - } -} - - diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java index 52dce361e2a..547417bfa55 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java @@ -1,353 +1,171 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - package io.swagger.client.api; -import io.swagger.client.ApiCallback; -import io.swagger.client.ApiClient; import io.swagger.client.ApiException; -import io.swagger.client.ApiResponse; +import io.swagger.client.ApiClient; import io.swagger.client.Configuration; import io.swagger.client.Pair; -import io.swagger.client.ProgressRequestBody; -import io.swagger.client.ProgressResponseBody; -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; +import javax.ws.rs.core.GenericType; import org.joda.time.LocalDate; import org.joda.time.DateTime; import java.math.BigDecimal; -import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -public class FakeApi { - private ApiClient apiClient; - public FakeApi() { - this(Configuration.getDefaultApiClient()); - } - - public FakeApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for testEndpointParameters */ - private com.squareup.okhttp.Call testEndpointParametersCall(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'number' is set - if (number == null) { - throw new ApiException("Missing the required parameter 'number' when calling testEndpointParameters(Async)"); - } - - // verify the required parameter '_double' is set - if (_double == null) { - throw new ApiException("Missing the required parameter '_double' when calling testEndpointParameters(Async)"); - } - - // verify the required parameter 'string' is set - if (string == null) { - throw new ApiException("Missing the required parameter 'string' when calling testEndpointParameters(Async)"); - } - - // verify the required parameter '_byte' is set - if (_byte == null) { - throw new ApiException("Missing the required parameter '_byte' when calling testEndpointParameters(Async)"); - } - - - // create path and map variables - String localVarPath = "/fake".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (integer != null) - localVarFormParams.put("integer", integer); - if (int32 != null) - localVarFormParams.put("int32", int32); - if (int64 != null) - localVarFormParams.put("int64", int64); - if (number != null) - localVarFormParams.put("number", number); - if (_float != null) - localVarFormParams.put("float", _float); - if (_double != null) - localVarFormParams.put("double", _double); - if (string != null) - localVarFormParams.put("string", string); - if (_byte != null) - localVarFormParams.put("byte", _byte); - if (binary != null) - localVarFormParams.put("binary", binary); - if (date != null) - localVarFormParams.put("date", date); - if (dateTime != null) - localVarFormParams.put("dateTime", dateTime); - if (password != null) - localVarFormParams.put("password", password); - - final String[] localVarAccepts = { - "application/xml; charset=utf-8", "application/json; charset=utf-8" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/xml; charset=utf-8", "application/json; charset=utf-8" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * @param number None (required) - * @param _double None (required) - * @param string None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { - testEndpointParametersWithHttpInfo(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); - } - - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * @param number None (required) - * @param _double None (required) - * @param string None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { - com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password, null, null); - return apiClient.execute(call); - } - - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 (asynchronously) - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * @param number None (required) - * @param _double None (required) - * @param string None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call testEndpointParametersAsync(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for testEnumQueryParameters */ - private com.squareup.okhttp.Call testEnumQueryParametersCall(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - - // create path and map variables - String localVarPath = "/fake".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (enumQueryInteger != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_integer", enumQueryInteger)); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (enumQueryString != null) - localVarFormParams.put("enum_query_string", enumQueryString); - if (enumQueryDouble != null) - localVarFormParams.put("enum_query_double", enumQueryDouble); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/json" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); +public class FakeApi { + private ApiClient apiClient; + + public FakeApi() { + this(Configuration.getDefaultApiClient()); + } + + public FakeApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param string None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @throws ApiException if fails to make API call + */ + public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'number' is set + if (number == null) { + throw new ApiException(400, "Missing the required parameter 'number' when calling testEndpointParameters"); } - - /** - * To test enum query parameters - * - * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) - * @param enumQueryInteger Query parameter enum test (double) (optional) - * @param enumQueryDouble Query parameter enum test (double) (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void testEnumQueryParameters(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { - testEnumQueryParametersWithHttpInfo(enumQueryString, enumQueryInteger, enumQueryDouble); + + // verify the required parameter '_double' is set + if (_double == null) { + throw new ApiException(400, "Missing the required parameter '_double' when calling testEndpointParameters"); } - - /** - * To test enum query parameters - * - * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) - * @param enumQueryInteger Query parameter enum test (double) (optional) - * @param enumQueryDouble Query parameter enum test (double) (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse testEnumQueryParametersWithHttpInfo(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { - com.squareup.okhttp.Call call = testEnumQueryParametersCall(enumQueryString, enumQueryInteger, enumQueryDouble, null, null); - return apiClient.execute(call); + + // verify the required parameter 'string' is set + if (string == null) { + throw new ApiException(400, "Missing the required parameter 'string' when calling testEndpointParameters"); } - - /** - * To test enum query parameters (asynchronously) - * - * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) - * @param enumQueryInteger Query parameter enum test (double) (optional) - * @param enumQueryDouble Query parameter enum test (double) (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call testEnumQueryParametersAsync(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = testEnumQueryParametersCall(enumQueryString, enumQueryInteger, enumQueryDouble, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; + + // verify the required parameter '_byte' is set + if (_byte == null) { + throw new ApiException(400, "Missing the required parameter '_byte' when calling testEndpointParameters"); } + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + if (integer != null) + localVarFormParams.put("integer", integer); +if (int32 != null) + localVarFormParams.put("int32", int32); +if (int64 != null) + localVarFormParams.put("int64", int64); +if (number != null) + localVarFormParams.put("number", number); +if (_float != null) + localVarFormParams.put("float", _float); +if (_double != null) + localVarFormParams.put("double", _double); +if (string != null) + localVarFormParams.put("string", string); +if (_byte != null) + localVarFormParams.put("byte", _byte); +if (binary != null) + localVarFormParams.put("binary", binary); +if (date != null) + localVarFormParams.put("date", date); +if (dateTime != null) + localVarFormParams.put("dateTime", dateTime); +if (password != null) + localVarFormParams.put("password", password); + + final String[] localVarAccepts = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * To test enum query parameters + * + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @throws ApiException if fails to make API call + */ + public void testEnumQueryParameters(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_integer", enumQueryInteger)); + + + if (enumQueryString != null) + localVarFormParams.put("enum_query_string", enumQueryString); +if (enumQueryDouble != null) + localVarFormParams.put("enum_query_double", enumQueryDouble); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } } 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 2039a8842c1..ab85c4ac394 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java @@ -1,935 +1,384 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - package io.swagger.client.api; -import io.swagger.client.ApiCallback; -import io.swagger.client.ApiClient; import io.swagger.client.ApiException; -import io.swagger.client.ApiResponse; +import io.swagger.client.ApiClient; import io.swagger.client.Configuration; import io.swagger.client.Pair; -import io.swagger.client.ProgressRequestBody; -import io.swagger.client.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; -import java.io.IOException; +import javax.ws.rs.core.GenericType; import io.swagger.client.model.Pet; import java.io.File; import io.swagger.client.model.ModelApiResponse; -import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -public class PetApi { - private ApiClient apiClient; - - public PetApi() { - this(Configuration.getDefaultApiClient()); - } - - public PetApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for addPet */ - private com.squareup.okhttp.Call addPetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling addPet(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/json", "application/xml" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void addPet(Pet body) throws ApiException { - addPetWithHttpInfo(body); - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse addPetWithHttpInfo(Pet body) throws ApiException { - com.squareup.okhttp.Call call = addPetCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Add a new pet to the store (asynchronously) - * - * @param body Pet object that needs to be added to the store (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call addPetAsync(Pet body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = addPetCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for deletePet */ - private com.squareup.okhttp.Call deletePetCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling deletePet(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - if (apiKey != null) - localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Deletes a pet - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void deletePet(Long petId, String apiKey) throws ApiException { - deletePetWithHttpInfo(petId, apiKey); - } - - /** - * Deletes a pet - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse deletePetWithHttpInfo(Long petId, String apiKey) throws ApiException { - com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, null, null); - return apiClient.execute(call); - } - - /** - * Deletes a pet (asynchronously) - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call deletePetAsync(Long petId, String apiKey, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for findPetsByStatus */ - private com.squareup.okhttp.Call findPetsByStatusCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'status' is set - if (status == null) { - throw new ApiException("Missing the required parameter 'status' when calling findPetsByStatus(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/findByStatus".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (status != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "status", status)); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Finds Pets by status - * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for filter (required) - * @return List<Pet> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public List findPetsByStatus(List status) throws ApiException { - ApiResponse> resp = findPetsByStatusWithHttpInfo(status); - return resp.getData(); - } - /** - * Finds Pets by status - * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for filter (required) - * @return ApiResponse<List<Pet>> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse> findPetsByStatusWithHttpInfo(List status) throws ApiException { - com.squareup.okhttp.Call call = findPetsByStatusCall(status, null, null); - Type localVarReturnType = new TypeToken>(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Finds Pets by status (asynchronously) - * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for filter (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call findPetsByStatusAsync(List status, final ApiCallback> callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = findPetsByStatusCall(status, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken>(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for findPetsByTags */ - private com.squareup.okhttp.Call findPetsByTagsCall(List tags, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'tags' is set - if (tags == null) { - throw new ApiException("Missing the required parameter 'tags' when calling findPetsByTags(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/findByTags".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (tags != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "tags", tags)); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Finds Pets by tags - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by (required) - * @return List<Pet> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public List findPetsByTags(List tags) throws ApiException { - ApiResponse> resp = findPetsByTagsWithHttpInfo(tags); - return resp.getData(); - } - - /** - * Finds Pets by tags - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by (required) - * @return ApiResponse<List<Pet>> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse> findPetsByTagsWithHttpInfo(List tags) throws ApiException { - com.squareup.okhttp.Call call = findPetsByTagsCall(tags, null, null); - Type localVarReturnType = new TypeToken>(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Finds Pets by tags (asynchronously) - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call findPetsByTagsAsync(List tags, final ApiCallback> callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = findPetsByTagsCall(tags, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken>(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for getPetById */ - private com.squareup.okhttp.Call getPetByIdCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling getPetById(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "api_key" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Find pet by ID - * Returns a single pet - * @param petId ID of pet to return (required) - * @return Pet - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Pet getPetById(Long petId) throws ApiException { - ApiResponse resp = getPetByIdWithHttpInfo(petId); - return resp.getData(); - } - - /** - * Find pet by ID - * Returns a single pet - * @param petId ID of pet to return (required) - * @return ApiResponse<Pet> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse getPetByIdWithHttpInfo(Long petId) throws ApiException { - com.squareup.okhttp.Call call = getPetByIdCall(petId, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Find pet by ID (asynchronously) - * Returns a single pet - * @param petId ID of pet to return (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call getPetByIdAsync(Long petId, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = getPetByIdCall(petId, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for updatePet */ - private com.squareup.okhttp.Call updatePetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling updatePet(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/json", "application/xml" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void updatePet(Pet body) throws ApiException { - updatePetWithHttpInfo(body); - } - - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse updatePetWithHttpInfo(Pet body) throws ApiException { - com.squareup.okhttp.Call call = updatePetCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Update an existing pet (asynchronously) - * - * @param body Pet object that needs to be added to the store (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call updatePetAsync(Pet body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = updatePetCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for updatePetWithForm */ - private com.squareup.okhttp.Call updatePetWithFormCall(Long petId, String name, String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling updatePetWithForm(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (name != null) - localVarFormParams.put("name", name); - if (status != null) - localVarFormParams.put("status", status); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/x-www-form-urlencoded" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void updatePetWithForm(Long petId, String name, String status) throws ApiException { - updatePetWithFormWithHttpInfo(petId, name, status); - } - - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse updatePetWithFormWithHttpInfo(Long petId, String name, String status) throws ApiException { - com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, null, null); - return apiClient.execute(call); - } - - /** - * Updates a pet in the store with form data (asynchronously) - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call updatePetWithFormAsync(Long petId, String name, String status, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for uploadFile */ - private com.squareup.okhttp.Call uploadFileCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling uploadFile(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (additionalMetadata != null) - localVarFormParams.put("additionalMetadata", additionalMetadata); - if (file != null) - localVarFormParams.put("file", file); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "multipart/form-data" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * uploads an image - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @return ModelApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { - ApiResponse resp = uploadFileWithHttpInfo(petId, additionalMetadata, file); - return resp.getData(); - } - - /** - * uploads an image - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @return ApiResponse<ModelApiResponse> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file) throws ApiException { - com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * uploads an image (asynchronously) - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call uploadFileAsync(Long petId, String additionalMetadata, File file, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } +public class PetApi { + private ApiClient apiClient; + + public PetApi() { + this(Configuration.getDefaultApiClient()); + } + + public PetApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException if fails to make API call + */ + public void addPet(Pet body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling addPet"); + } + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @throws ApiException if fails to make API call + */ + public void deletePet(Long petId, String apiKey) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling deletePet"); + } + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + if (apiKey != null) + localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + + apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return List + * @throws ApiException if fails to make API call + */ + public List findPetsByStatus(List status) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'status' is set + if (status == null) { + throw new ApiException(400, "Missing the required parameter 'status' when calling findPetsByStatus"); + } + + // create path and map variables + String localVarPath = "/pet/findByStatus".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "status", status)); + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + GenericType> localVarReturnType = new GenericType>() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return List + * @throws ApiException if fails to make API call + */ + public List findPetsByTags(List tags) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'tags' is set + if (tags == null) { + throw new ApiException(400, "Missing the required parameter 'tags' when calling findPetsByTags"); + } + + // create path and map variables + String localVarPath = "/pet/findByTags".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "tags", tags)); + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + GenericType> localVarReturnType = new GenericType>() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return Pet + * @throws ApiException if fails to make API call + */ + public Pet getPetById(Long petId) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling getPetById"); + } + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "api_key" }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException if fails to make API call + */ + public void updatePet(Pet body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling updatePet"); + } + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + + apiClient.invokeAPI(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @throws ApiException if fails to make API call + */ + public void updatePetWithForm(Long petId, String name, String status) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling updatePetWithForm"); + } + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + if (name != null) + localVarFormParams.put("name", name); +if (status != null) + localVarFormParams.put("status", status); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/x-www-form-urlencoded" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ModelApiResponse + * @throws ApiException if fails to make API call + */ + public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling uploadFile"); + } + + // create path and map variables + String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + if (additionalMetadata != null) + localVarFormParams.put("additionalMetadata", additionalMetadata); +if (file != null) + localVarFormParams.put("file", file); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } } 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 0768744c263..c0c9a166ad7 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java @@ -1,482 +1,196 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - package io.swagger.client.api; -import io.swagger.client.ApiCallback; -import io.swagger.client.ApiClient; import io.swagger.client.ApiException; -import io.swagger.client.ApiResponse; +import io.swagger.client.ApiClient; import io.swagger.client.Configuration; import io.swagger.client.Pair; -import io.swagger.client.ProgressRequestBody; -import io.swagger.client.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; -import java.io.IOException; +import javax.ws.rs.core.GenericType; import io.swagger.client.model.Order; -import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -public class StoreApi { - private ApiClient apiClient; - - public StoreApi() { - this(Configuration.getDefaultApiClient()); - } - - public StoreApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - /* Build call for deleteOrder */ - private com.squareup.okhttp.Call deleteOrderCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException("Missing the required parameter 'orderId' when calling deleteOrder(Async)"); - } - - - // create path and map variables - String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void deleteOrder(String orderId) throws ApiException { - deleteOrderWithHttpInfo(orderId); - } - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse deleteOrderWithHttpInfo(String orderId) throws ApiException { - com.squareup.okhttp.Call call = deleteOrderCall(orderId, null, null); - return apiClient.execute(call); - } - - /** - * Delete purchase order by ID (asynchronously) - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call deleteOrderAsync(String orderId, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = deleteOrderCall(orderId, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for getInventory */ - private com.squareup.okhttp.Call getInventoryCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - - // create path and map variables - String localVarPath = "/store/inventory".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "api_key" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - * @return Map<String, Integer> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Map getInventory() throws ApiException { - ApiResponse> resp = getInventoryWithHttpInfo(); - return resp.getData(); - } - - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - * @return ApiResponse<Map<String, Integer>> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse> getInventoryWithHttpInfo() throws ApiException { - com.squareup.okhttp.Call call = getInventoryCall(null, null); - Type localVarReturnType = new TypeToken>(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Returns pet inventories by status (asynchronously) - * Returns a map of status codes to quantities - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call getInventoryAsync(final ApiCallback> callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = getInventoryCall(progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken>(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for getOrderById */ - private com.squareup.okhttp.Call getOrderByIdCall(Long orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException("Missing the required parameter 'orderId' when calling getOrderById(Async)"); - } - - - // create path and map variables - String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched (required) - * @return Order - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Order getOrderById(Long orderId) throws ApiException { - ApiResponse resp = getOrderByIdWithHttpInfo(orderId); - return resp.getData(); - } - - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched (required) - * @return ApiResponse<Order> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse getOrderByIdWithHttpInfo(Long orderId) throws ApiException { - com.squareup.okhttp.Call call = getOrderByIdCall(orderId, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Find purchase order by ID (asynchronously) - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call getOrderByIdAsync(Long orderId, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = getOrderByIdCall(orderId, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for placeOrder */ - private com.squareup.okhttp.Call placeOrderCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling placeOrder(Async)"); - } - - - // create path and map variables - String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet (required) - * @return Order - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Order placeOrder(Order body) throws ApiException { - ApiResponse resp = placeOrderWithHttpInfo(body); - return resp.getData(); - } - - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet (required) - * @return ApiResponse<Order> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse placeOrderWithHttpInfo(Order body) throws ApiException { - com.squareup.okhttp.Call call = placeOrderCall(body, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Place an order for a pet (asynchronously) - * - * @param body order placed for purchasing the pet (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call placeOrderAsync(Order body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = placeOrderCall(body, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } +public class StoreApi { + private ApiClient apiClient; + + public StoreApi() { + this(Configuration.getDefaultApiClient()); + } + + public StoreApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @throws ApiException if fails to make API call + */ + public void deleteOrder(String orderId) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder"); + } + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return Map + * @throws ApiException if fails to make API call + */ + public Map getInventory() throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/store/inventory".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "api_key" }; + + GenericType> localVarReturnType = new GenericType>() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @return Order + * @throws ApiException if fails to make API call + */ + public Order getOrderById(Long orderId) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById"); + } + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet (required) + * @return Order + * @throws ApiException if fails to make API call + */ + public Order placeOrder(Order body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling placeOrder"); + } + + // create path and map variables + String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } } 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 1c4fc3101a1..7602f4e2ba9 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java @@ -1,907 +1,370 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - package io.swagger.client.api; -import io.swagger.client.ApiCallback; -import io.swagger.client.ApiClient; import io.swagger.client.ApiException; -import io.swagger.client.ApiResponse; +import io.swagger.client.ApiClient; import io.swagger.client.Configuration; import io.swagger.client.Pair; -import io.swagger.client.ProgressRequestBody; -import io.swagger.client.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; -import java.io.IOException; +import javax.ws.rs.core.GenericType; import io.swagger.client.model.User; -import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -public class UserApi { - private ApiClient apiClient; - - public UserApi() { - this(Configuration.getDefaultApiClient()); - } - - public UserApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for createUser */ - private com.squareup.okhttp.Call createUserCall(User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling createUser(Async)"); - } - - - // create path and map variables - String localVarPath = "/user".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void createUser(User body) throws ApiException { - createUserWithHttpInfo(body); - } - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse createUserWithHttpInfo(User body) throws ApiException { - com.squareup.okhttp.Call call = createUserCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Create user (asynchronously) - * This can only be done by the logged in user. - * @param body Created user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call createUserAsync(User body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = createUserCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for createUsersWithArrayInput */ - private com.squareup.okhttp.Call createUsersWithArrayInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling createUsersWithArrayInput(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/createWithArray".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void createUsersWithArrayInput(List body) throws ApiException { - createUsersWithArrayInputWithHttpInfo(body); - } - - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse createUsersWithArrayInputWithHttpInfo(List body) throws ApiException { - com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Creates list of users with given input array (asynchronously) - * - * @param body List of user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call createUsersWithArrayInputAsync(List body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for createUsersWithListInput */ - private com.squareup.okhttp.Call createUsersWithListInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling createUsersWithListInput(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void createUsersWithListInput(List body) throws ApiException { - createUsersWithListInputWithHttpInfo(body); - } - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse createUsersWithListInputWithHttpInfo(List body) throws ApiException { - com.squareup.okhttp.Call call = createUsersWithListInputCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Creates list of users with given input array (asynchronously) - * - * @param body List of user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call createUsersWithListInputAsync(List body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = createUsersWithListInputCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for deleteUser */ - private com.squareup.okhttp.Call deleteUserCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling deleteUser(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void deleteUser(String username) throws ApiException { - deleteUserWithHttpInfo(username); - } - - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse deleteUserWithHttpInfo(String username) throws ApiException { - com.squareup.okhttp.Call call = deleteUserCall(username, null, null); - return apiClient.execute(call); - } - - /** - * Delete user (asynchronously) - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call deleteUserAsync(String username, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = deleteUserCall(username, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for getUserByName */ - private com.squareup.okhttp.Call getUserByNameCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling getUserByName(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return User - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public User getUserByName(String username) throws ApiException { - ApiResponse resp = getUserByNameWithHttpInfo(username); - return resp.getData(); - } - - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return ApiResponse<User> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse getUserByNameWithHttpInfo(String username) throws ApiException { - com.squareup.okhttp.Call call = getUserByNameCall(username, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Get user by user name (asynchronously) - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call getUserByNameAsync(String username, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = getUserByNameCall(username, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for loginUser */ - private com.squareup.okhttp.Call loginUserCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling loginUser(Async)"); - } - - // verify the required parameter 'password' is set - if (password == null) { - throw new ApiException("Missing the required parameter 'password' when calling loginUser(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/login".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (username != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("", "username", username)); - if (password != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("", "password", password)); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Logs user into the system - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @return String - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public String loginUser(String username, String password) throws ApiException { - ApiResponse resp = loginUserWithHttpInfo(username, password); - return resp.getData(); - } - - /** - * Logs user into the system - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @return ApiResponse<String> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse loginUserWithHttpInfo(String username, String password) throws ApiException { - com.squareup.okhttp.Call call = loginUserCall(username, password, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Logs user into the system (asynchronously) - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call loginUserAsync(String username, String password, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = loginUserCall(username, password, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for logoutUser */ - private com.squareup.okhttp.Call logoutUserCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - - // create path and map variables - String localVarPath = "/user/logout".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Logs out current logged in user session - * - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void logoutUser() throws ApiException { - logoutUserWithHttpInfo(); - } - - /** - * Logs out current logged in user session - * - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse logoutUserWithHttpInfo() throws ApiException { - com.squareup.okhttp.Call call = logoutUserCall(null, null); - return apiClient.execute(call); - } - - /** - * Logs out current logged in user session (asynchronously) - * - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call logoutUserAsync(final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = logoutUserCall(progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for updateUser */ - private com.squareup.okhttp.Call updateUserCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling updateUser(Async)"); - } - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling updateUser(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void updateUser(String username, User body) throws ApiException { - updateUserWithHttpInfo(username, body); - } - - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse updateUserWithHttpInfo(String username, User body) throws ApiException { - com.squareup.okhttp.Call call = updateUserCall(username, body, null, null); - return apiClient.execute(call); - } - - /** - * Updated user (asynchronously) - * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call updateUserAsync(String username, User body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = updateUserCall(username, body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } +public class UserApi { + private ApiClient apiClient; + + public UserApi() { + this(Configuration.getDefaultApiClient()); + } + + public UserApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object (required) + * @throws ApiException if fails to make API call + */ + public void createUser(User body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling createUser"); + } + + // create path and map variables + String localVarPath = "/user".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException if fails to make API call + */ + public void createUsersWithArrayInput(List body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling createUsersWithArrayInput"); + } + + // create path and map variables + String localVarPath = "/user/createWithArray".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException if fails to make API call + */ + public void createUsersWithListInput(List body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling createUsersWithListInput"); + } + + // create path and map variables + String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @throws ApiException if fails to make API call + */ + public void deleteUser(String username) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling deleteUser"); + } + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return User + * @throws ApiException if fails to make API call + */ + public User getUserByName(String username) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling getUserByName"); + } + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return String + * @throws ApiException if fails to make API call + */ + public String loginUser(String username, String password) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling loginUser"); + } + + // verify the required parameter 'password' is set + if (password == null) { + throw new ApiException(400, "Missing the required parameter 'password' when calling loginUser"); + } + + // create path and map variables + String localVarPath = "/user/login".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("", "username", username)); + localVarQueryParams.addAll(apiClient.parameterToPairs("", "password", password)); + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Logs out current logged in user session + * + * @throws ApiException if fails to make API call + */ + public void logoutUser() throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/user/logout".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @throws ApiException if fails to make API call + */ + public void updateUser(String username, User body) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser"); + } + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling updateUser"); + } + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 4eb2300b69d..592648b2bba 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -27,40 +27,44 @@ import io.swagger.client.Pair; -import com.squareup.okhttp.Credentials; +import com.migcomponents.migbase64.Base64; import java.util.Map; import java.util.List; import java.io.UnsupportedEncodingException; + public class HttpBasicAuth implements Authentication { - private String username; - private String password; + private String username; + private String password; - public String getUsername() { - return username; - } + public String getUsername() { + return username; + } - public void setUsername(String username) { - this.username = username; - } + public void setUsername(String username) { + this.username = username; + } - public String getPassword() { - return password; - } + public String getPassword() { + return password; + } - public void setPassword(String password) { - this.password = password; - } + public void setPassword(String password) { + this.password = password; + } - @Override - public void applyToParams(List queryParams, Map headerParams) { - if (username == null && password == null) { - return; - } - headerParams.put("Authorization", Credentials.basic( - username == null ? "" : username, - password == null ? "" : password)); + @Override + public void applyToParams(List queryParams, Map headerParams) { + if (username == null && password == null) { + return; + } + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + try { + headerParams.put("Authorization", "Basic " + Base64.encodeToString(str.getBytes("UTF-8"), false)); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); } + } } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 1943e013fa1..1e2d40891a2 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; @@ -39,10 +39,10 @@ */ public class AdditionalPropertiesClass { - @SerializedName("map_property") + @JsonProperty("map_property") private Map mapProperty = new HashMap(); - @SerializedName("map_of_map_property") + @JsonProperty("map_of_map_property") private Map> mapOfMapProperty = new HashMap>(); public AdditionalPropertiesClass mapProperty(Map mapProperty) { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java index ba3806dc875..3ed2c6d9660 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,10 +36,10 @@ */ public class Animal { - @SerializedName("className") + @JsonProperty("className") private String className = null; - @SerializedName("color") + @JsonProperty("color") private String color = "red"; public Animal className(String className) { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 5446c2c439b..4d0dc41ee70 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; @@ -39,7 +39,7 @@ */ public class ArrayOfArrayOfNumberOnly { - @SerializedName("ArrayArrayNumber") + @JsonProperty("ArrayArrayNumber") private List> arrayArrayNumber = new ArrayList>(); public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index c9257a5d3ee..bd3f05a2ad4 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; @@ -39,7 +39,7 @@ */ public class ArrayOfNumberOnly { - @SerializedName("ArrayNumber") + @JsonProperty("ArrayNumber") private List arrayNumber = new ArrayList(); public ArrayOfNumberOnly arrayNumber(List arrayNumber) { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayTest.java index 8d58870bcdc..900b8375eb0 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayTest.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.ReadOnlyFirst; @@ -39,13 +39,13 @@ */ public class ArrayTest { - @SerializedName("array_of_string") + @JsonProperty("array_of_string") private List arrayOfString = new ArrayList(); - @SerializedName("array_array_of_integer") + @JsonProperty("array_array_of_integer") private List> arrayArrayOfInteger = new ArrayList>(); - @SerializedName("array_array_of_model") + @JsonProperty("array_array_of_model") private List> arrayArrayOfModel = new ArrayList>(); public ArrayTest arrayOfString(List arrayOfString) { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Cat.java index 21ed0f4c26b..f39b159f0b4 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Cat.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -37,13 +37,13 @@ */ public class Cat extends Animal { - @SerializedName("className") + @JsonProperty("className") private String className = null; - @SerializedName("color") + @JsonProperty("color") private String color = "red"; - @SerializedName("declawed") + @JsonProperty("declawed") private Boolean declawed = null; public Cat className(String className) { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java index 2178a866f62..c9bbbf525c5 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,10 +36,10 @@ */ public class Category { - @SerializedName("id") + @JsonProperty("id") private Long id = null; - @SerializedName("name") + @JsonProperty("name") private String name = null; public Category id(Long id) { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Dog.java index 4ba5804553f..dbcd1a7207b 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Dog.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -37,13 +37,13 @@ */ public class Dog extends Animal { - @SerializedName("className") + @JsonProperty("className") private String className = null; - @SerializedName("color") + @JsonProperty("color") private String color = "red"; - @SerializedName("breed") + @JsonProperty("breed") private String breed = null; public Dog className(String className) { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumClass.java index 73484907229..4433dca5f48 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumClass.java @@ -26,7 +26,6 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; /** @@ -34,13 +33,10 @@ */ public enum EnumClass { - @SerializedName("_abc") _ABC("_abc"), - @SerializedName("-efg") _EFG("-efg"), - @SerializedName("(xyz)") _XYZ_("(xyz)"); private String value; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java index 9aad1223215..de36ef40ed4 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -40,10 +40,8 @@ public class EnumTest { * Gets or Sets enumString */ public enum EnumStringEnum { - @SerializedName("UPPER") UPPER("UPPER"), - @SerializedName("lower") LOWER("lower"); private String value; @@ -58,17 +56,15 @@ public String toString() { } } - @SerializedName("enum_string") + @JsonProperty("enum_string") private EnumStringEnum enumString = null; /** * Gets or Sets enumInteger */ public enum EnumIntegerEnum { - @SerializedName("1") NUMBER_1(1), - @SerializedName("-1") NUMBER_MINUS_1(-1); private Integer value; @@ -83,17 +79,15 @@ public String toString() { } } - @SerializedName("enum_integer") + @JsonProperty("enum_integer") private EnumIntegerEnum enumInteger = null; /** * Gets or Sets enumNumber */ public enum EnumNumberEnum { - @SerializedName("1.1") NUMBER_1_DOT_1(1.1), - @SerializedName("-1.2") NUMBER_MINUS_1_DOT_2(-1.2); private Double value; @@ -108,7 +102,7 @@ public String toString() { } } - @SerializedName("enum_number") + @JsonProperty("enum_number") private EnumNumberEnum enumNumber = null; public EnumTest enumString(EnumStringEnum enumString) { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/FormatTest.java index 91109681509..9e17949ebc8 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/FormatTest.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; @@ -39,43 +39,43 @@ */ public class FormatTest { - @SerializedName("integer") + @JsonProperty("integer") private Integer integer = null; - @SerializedName("int32") + @JsonProperty("int32") private Integer int32 = null; - @SerializedName("int64") + @JsonProperty("int64") private Long int64 = null; - @SerializedName("number") + @JsonProperty("number") private BigDecimal number = null; - @SerializedName("float") + @JsonProperty("float") private Float _float = null; - @SerializedName("double") + @JsonProperty("double") private Double _double = null; - @SerializedName("string") + @JsonProperty("string") private String string = null; - @SerializedName("byte") + @JsonProperty("byte") private byte[] _byte = null; - @SerializedName("binary") + @JsonProperty("binary") private byte[] binary = null; - @SerializedName("date") + @JsonProperty("date") private LocalDate date = null; - @SerializedName("dateTime") + @JsonProperty("dateTime") private DateTime dateTime = null; - @SerializedName("uuid") + @JsonProperty("uuid") private String uuid = null; - @SerializedName("password") + @JsonProperty("password") private String password = null; public FormatTest integer(Integer integer) { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java index d77fc7ac36b..a3d01218197 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,10 +36,10 @@ */ public class HasOnlyReadOnly { - @SerializedName("bar") + @JsonProperty("bar") private String bar = null; - @SerializedName("foo") + @JsonProperty("foo") private String foo = null; /** diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MapTest.java index 61bdb6b2c65..6c0fc91ac41 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MapTest.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; @@ -39,17 +39,15 @@ */ public class MapTest { - @SerializedName("map_map_of_string") + @JsonProperty("map_map_of_string") private Map> mapMapOfString = new HashMap>(); /** * Gets or Sets inner */ public enum InnerEnum { - @SerializedName("UPPER") UPPER("UPPER"), - @SerializedName("lower") LOWER("lower"); private String value; @@ -64,7 +62,7 @@ public String toString() { } } - @SerializedName("map_of_enum_string") + @JsonProperty("map_of_enum_string") private Map mapOfEnumString = new HashMap(); public MapTest mapMapOfString(Map> mapMapOfString) { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 6e587b1bf97..c37d141f972 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -41,13 +41,13 @@ */ public class MixedPropertiesAndAdditionalPropertiesClass { - @SerializedName("uuid") + @JsonProperty("uuid") private String uuid = null; - @SerializedName("dateTime") + @JsonProperty("dateTime") private DateTime dateTime = null; - @SerializedName("map") + @JsonProperty("map") private Map map = new HashMap(); public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Model200Response.java index d8da58aca9c..3f4edf12daa 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Model200Response.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -37,10 +37,10 @@ @ApiModel(description = "Model for testing model name starting with number") public class Model200Response { - @SerializedName("name") + @JsonProperty("name") private Integer name = null; - @SerializedName("class") + @JsonProperty("class") private String PropertyClass = null; public Model200Response name(Integer name) { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelApiResponse.java index 2a823298323..7b86d07a148 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,13 +36,13 @@ */ public class ModelApiResponse { - @SerializedName("code") + @JsonProperty("code") private Integer code = null; - @SerializedName("type") + @JsonProperty("type") private String type = null; - @SerializedName("message") + @JsonProperty("message") private String message = null; public ModelApiResponse code(Integer code) { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelReturn.java index 024a9c0df1c..e8762f850db 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelReturn.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -37,7 +37,7 @@ @ApiModel(description = "Model for testing reserved words") public class ModelReturn { - @SerializedName("return") + @JsonProperty("return") private Integer _return = null; public ModelReturn _return(Integer _return) { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Name.java index 318a2ddd50e..de446cdf30d 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Name.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -37,16 +37,16 @@ @ApiModel(description = "Model for testing model name same as property name") public class Name { - @SerializedName("name") + @JsonProperty("name") private Integer name = null; - @SerializedName("snake_case") + @JsonProperty("snake_case") private Integer snakeCase = null; - @SerializedName("property") + @JsonProperty("property") private String property = null; - @SerializedName("123Number") + @JsonProperty("123Number") private Integer _123Number = null; public Name name(Integer name) { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/NumberOnly.java index 9b9ca048dfb..88c33f00f02 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/NumberOnly.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/NumberOnly.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; @@ -37,7 +37,7 @@ */ public class NumberOnly { - @SerializedName("JustNumber") + @JsonProperty("JustNumber") private BigDecimal justNumber = null; public NumberOnly justNumber(BigDecimal justNumber) { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java index 90cfd2f3892..ddebd7f8e48 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.joda.time.DateTime; @@ -37,29 +37,26 @@ */ public class Order { - @SerializedName("id") + @JsonProperty("id") private Long id = null; - @SerializedName("petId") + @JsonProperty("petId") private Long petId = null; - @SerializedName("quantity") + @JsonProperty("quantity") private Integer quantity = null; - @SerializedName("shipDate") + @JsonProperty("shipDate") private DateTime shipDate = null; /** * Order Status */ public enum StatusEnum { - @SerializedName("placed") PLACED("placed"), - @SerializedName("approved") APPROVED("approved"), - @SerializedName("delivered") DELIVERED("delivered"); private String value; @@ -74,10 +71,10 @@ public String toString() { } } - @SerializedName("status") + @JsonProperty("status") private StatusEnum status = null; - @SerializedName("complete") + @JsonProperty("complete") private Boolean complete = false; public Order id(Long id) { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java index b80fdeaf923..b468ebf1237 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Category; @@ -40,32 +40,29 @@ */ public class Pet { - @SerializedName("id") + @JsonProperty("id") private Long id = null; - @SerializedName("category") + @JsonProperty("category") private Category category = null; - @SerializedName("name") + @JsonProperty("name") private String name = null; - @SerializedName("photoUrls") + @JsonProperty("photoUrls") private List photoUrls = new ArrayList(); - @SerializedName("tags") + @JsonProperty("tags") private List tags = new ArrayList(); /** * pet status in the store */ public enum StatusEnum { - @SerializedName("available") AVAILABLE("available"), - @SerializedName("pending") PENDING("pending"), - @SerializedName("sold") SOLD("sold"); private String value; @@ -80,7 +77,7 @@ public String toString() { } } - @SerializedName("status") + @JsonProperty("status") private StatusEnum status = null; public Pet id(Long id) { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index 13b729bb94d..7f56ef2ff35 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,10 +36,10 @@ */ public class ReadOnlyFirst { - @SerializedName("bar") + @JsonProperty("bar") private String bar = null; - @SerializedName("baz") + @JsonProperty("baz") private String baz = null; /** diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/SpecialModelName.java index b46b8367a01..bc4863f101a 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,7 +36,7 @@ */ public class SpecialModelName { - @SerializedName("$special[property.name]") + @JsonProperty("$special[property.name]") private Long specialPropertyName = null; public SpecialModelName specialPropertyName(Long specialPropertyName) { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java index e56eb535d1e..f27e45ea2aa 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,10 +36,10 @@ */ public class Tag { - @SerializedName("id") + @JsonProperty("id") private Long id = null; - @SerializedName("name") + @JsonProperty("name") private String name = null; public Tag id(Long id) { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java index 6c1ed6ceacc..7c0421fa09e 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.google.gson.annotations.SerializedName; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,28 +36,28 @@ */ public class User { - @SerializedName("id") + @JsonProperty("id") private Long id = null; - @SerializedName("username") + @JsonProperty("username") private String username = null; - @SerializedName("firstName") + @JsonProperty("firstName") private String firstName = null; - @SerializedName("lastName") + @JsonProperty("lastName") private String lastName = null; - @SerializedName("email") + @JsonProperty("email") private String email = null; - @SerializedName("password") + @JsonProperty("password") private String password = null; - @SerializedName("phone") + @JsonProperty("phone") private String phone = null; - @SerializedName("userStatus") + @JsonProperty("userStatus") private Integer userStatus = null; public User id(Long id) { diff --git a/samples/client/petstore/java/retrofit/build.gradle b/samples/client/petstore/java/retrofit/build.gradle index 172055c892e..401b362d172 100644 --- a/samples/client/petstore/java/retrofit/build.gradle +++ b/samples/client/petstore/java/retrofit/build.gradle @@ -23,7 +23,7 @@ if(hasProperty('target') && target == 'android') { apply plugin: 'com.android.library' apply plugin: 'com.github.dcendents.android-maven' - + android { compileSdkVersion 23 buildToolsVersion '23.0.2' @@ -35,7 +35,7 @@ if(hasProperty('target') && target == 'android') { sourceCompatibility JavaVersion.VERSION_1_7 targetCompatibility JavaVersion.VERSION_1_7 } - + // Rename the aar correctly libraryVariants.all { variant -> variant.outputs.each { output -> @@ -51,7 +51,7 @@ if(hasProperty('target') && target == 'android') { provided 'javax.annotation:jsr250-api:1.0' } } - + afterEvaluate { android.libraryVariants.all { variant -> def task = project.tasks.create "jar${variant.name.capitalize()}", Jar @@ -63,12 +63,12 @@ if(hasProperty('target') && target == 'android') { artifacts.add('archives', task); } } - + task sourcesJar(type: Jar) { from android.sourceSets.main.java.srcDirs classifier = 'sources' } - + artifacts { archives sourcesJar } @@ -77,27 +77,36 @@ if(hasProperty('target') && target == 'android') { apply plugin: 'java' apply plugin: 'maven' - + sourceCompatibility = JavaVersion.VERSION_1_7 targetCompatibility = JavaVersion.VERSION_1_7 - + install { repositories.mavenInstaller { pom.artifactId = 'swagger-petstore-retrofit' } } - + task execute(type:JavaExec) { main = System.getProperty('mainClass') classpath = sourceSets.main.runtimeClasspath } } +ext { + okhttp_version = "2.7.5" + oltu_version = "1.0.1" + retrofit_version = "1.9.0" + swagger_annotations_version = "1.5.8" + junit_version = "4.12" + jodatime_version = "2.9.3" +} + dependencies { - compile 'io.swagger:swagger-annotations:1.5.8' - compile 'com.squareup.okhttp:okhttp:2.7.5' - compile 'com.squareup.okhttp:logging-interceptor:2.7.5' - compile 'com.google.code.gson:gson:2.6.2' - compile 'joda-time:joda-time:2.9.3' - testCompile 'junit:junit:4.12' + compile "com.squareup.okhttp:okhttp:$okhttp_version" + compile "com.squareup.retrofit:retrofit:$retrofit_version" + compile "io.swagger:swagger-annotations:$swagger_annotations_version" + compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version" + compile "joda-time:joda-time:$jodatime_version" + testCompile "junit:junit:$junit_version" } diff --git a/samples/client/petstore/java/retrofit/build.sbt b/samples/client/petstore/java/retrofit/build.sbt index f665bcc952a..629c85c2bf3 100644 --- a/samples/client/petstore/java/retrofit/build.sbt +++ b/samples/client/petstore/java/retrofit/build.sbt @@ -9,10 +9,10 @@ lazy val root = (project in file(".")). publishArtifact in (Compile, packageDoc) := false, resolvers += Resolver.mavenLocal, libraryDependencies ++= Seq( - "io.swagger" % "swagger-annotations" % "1.5.8", - "com.squareup.okhttp" % "okhttp" % "2.7.5", - "com.squareup.okhttp" % "logging-interceptor" % "2.7.5", - "com.google.code.gson" % "gson" % "2.6.2", + "com.squareup.okhttp" % "okhttp" % "2.7.5" % "compile", + "com.squareup.retrofit" % "retrofit" % "1.9.0" % "compile", + "io.swagger" % "swagger-annotations" % "1.5.8" % "compile", + "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", "joda-time" % "joda-time" % "2.9.3" % "compile", "junit" % "junit" % "4.12" % "test", "com.novocode" % "junit-interface" % "0.10" % "test" diff --git a/samples/client/petstore/java/retrofit/pom.xml b/samples/client/petstore/java/retrofit/pom.xml index 0791f9f10ad..ee6ce62988f 100644 --- a/samples/client/petstore/java/retrofit/pom.xml +++ b/samples/client/petstore/java/retrofit/pom.xml @@ -68,7 +68,6 @@ org.codehaus.mojo build-helper-maven-plugin - 1.10 add_sources @@ -96,6 +95,15 @@ + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.7 + 1.7 + + @@ -105,25 +113,25 @@ ${swagger-core-version} - com.squareup.okhttp - okhttp - ${okhttp-version} + com.squareup.retrofit + retrofit + ${retrofit-version} + org.apache.oltu.oauth2 + org.apache.oltu.oauth2.client + ${oltu-version} + + com.squareup.okhttp - logging-interceptor + okhttp ${okhttp-version} - - com.google.code.gson - gson - ${gson-version} - joda-time joda-time ${jodatime-version} - + @@ -134,15 +142,12 @@ - 1.7 - ${java.version} - ${java.version} - 1.5.9 + 1.5.8 + 1.9.0 2.7.5 - 2.6.2 2.9.3 + 1.0.1 1.0.0 4.12 - UTF-8 diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiCallback.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiCallback.java deleted file mode 100644 index 3ca33cf8017..00000000000 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiCallback.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import java.io.IOException; - -import java.util.Map; -import java.util.List; - -/** - * Callback for asynchronous API call. - * - * @param The return type - */ -public interface ApiCallback { - /** - * This is called when the API call fails. - * - * @param e The exception causing the failure - * @param statusCode Status code of the response if available, otherwise it would be 0 - * @param responseHeaders Headers of the response if available, otherwise it would be null - */ - void onFailure(ApiException e, int statusCode, Map> responseHeaders); - - /** - * This is called when the API call succeeded. - * - * @param result The result deserialized from response - * @param statusCode Status code of the response - * @param responseHeaders Headers of the response - */ - void onSuccess(T result, int statusCode, Map> responseHeaders); - - /** - * This is called when the API upload processing. - * - * @param bytesWritten bytes Written - * @param contentLength content length of request body - * @param done write end - */ - void onUploadProgress(long bytesWritten, long contentLength, boolean done); - - /** - * This is called when the API downlond processing. - * - * @param bytesRead bytes Read - * @param contentLength content lenngth of the response - * @param done Read end - */ - void onDownloadProgress(long bytesRead, long contentLength, boolean done); -} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java index b7b04e3e4c5..08cfb4b3751 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java @@ -1,1326 +1,407 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - package io.swagger.client; -import com.squareup.okhttp.Call; -import com.squareup.okhttp.Callback; -import com.squareup.okhttp.OkHttpClient; -import com.squareup.okhttp.Request; -import com.squareup.okhttp.Response; -import com.squareup.okhttp.RequestBody; -import com.squareup.okhttp.FormEncodingBuilder; -import com.squareup.okhttp.MultipartBuilder; -import com.squareup.okhttp.MediaType; -import com.squareup.okhttp.Headers; -import com.squareup.okhttp.internal.http.HttpMethod; -import com.squareup.okhttp.logging.HttpLoggingInterceptor; -import com.squareup.okhttp.logging.HttpLoggingInterceptor.Level; - +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; import java.lang.reflect.Type; - -import java.util.Collection; -import java.util.Collections; +import java.util.LinkedHashMap; import java.util.Map; -import java.util.Map.Entry; -import java.util.HashMap; -import java.util.List; -import java.util.ArrayList; -import java.util.Date; -import java.util.TimeZone; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.net.URLEncoder; -import java.net.URLConnection; - -import java.io.File; -import java.io.InputStream; -import java.io.IOException; -import java.io.UnsupportedEncodingException; - -import java.security.GeneralSecurityException; -import java.security.KeyStore; -import java.security.SecureRandom; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.text.ParseException; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.KeyManager; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.X509TrustManager; - -import okio.BufferedSink; -import okio.Okio; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; + +import retrofit.RestAdapter; +import retrofit.client.OkClient; +import retrofit.converter.ConversionException; +import retrofit.converter.Converter; +import retrofit.converter.GsonConverter; +import retrofit.mime.TypedByteArray; +import retrofit.mime.TypedInput; +import retrofit.mime.TypedOutput; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.squareup.okhttp.Interceptor; +import com.squareup.okhttp.OkHttpClient; -import io.swagger.client.auth.Authentication; import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; +import io.swagger.client.auth.OAuth.AccessTokenListener; +import io.swagger.client.auth.OAuthFlow; -public class ApiClient { - public static final double JAVA_VERSION; - public static final boolean IS_ANDROID; - public static final int ANDROID_SDK_VERSION; - - static { - JAVA_VERSION = Double.parseDouble(System.getProperty("java.specification.version")); - boolean isAndroid; - try { - Class.forName("android.app.Activity"); - isAndroid = true; - } catch (ClassNotFoundException e) { - isAndroid = false; - } - IS_ANDROID = isAndroid; - int sdkVersion = 0; - if (IS_ANDROID) { - try { - sdkVersion = Class.forName("android.os.Build$VERSION").getField("SDK_INT").getInt(null); - } catch (Exception e) { - try { - sdkVersion = Integer.parseInt((String) Class.forName("android.os.Build$VERSION").getField("SDK").get(null)); - } catch (Exception e2) { } - } - } - ANDROID_SDK_VERSION = sdkVersion; - } - - /** - * The datetime format to be used when lenientDatetimeFormat is enabled. - */ - public static final String LENIENT_DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; - - private String basePath = "http://petstore.swagger.io/v2"; - private boolean lenientOnJson = false; - private boolean debugging = false; - private Map defaultHeaderMap = new HashMap(); - private String tempFolderPath = null; - - private Map authentications; - - private DateFormat dateFormat; - private DateFormat datetimeFormat; - private boolean lenientDatetimeFormat; - private int dateLength; - - private InputStream sslCaCert; - private boolean verifyingSsl; - private OkHttpClient httpClient; - private JSON json; +public class ApiClient { - private HttpLoggingInterceptor loggingInterceptor; + private Map apiAuthorizations; + private OkHttpClient okClient; + private RestAdapter.Builder adapterBuilder; - /* - * Constructor for ApiClient - */ public ApiClient() { - httpClient = new OkHttpClient(); - - verifyingSsl = true; - - json = new JSON(this); - - /* - * Use RFC3339 format for date and datetime. - * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 - */ - this.dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - // Always use UTC as the default time zone when dealing with date (without time). - this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - initDatetimeFormat(); - - // Be lenient on datetime formats when parsing datetime from string. - // See parseDatetime. - this.lenientDatetimeFormat = true; - - // Set default User-Agent. - setUserAgent("Swagger-Codegen/1.0.0/java"); - - // Setup authentications (key: authentication name, value: authentication). - authentications = new HashMap(); - authentications.put("api_key", new ApiKeyAuth("header", "api_key")); - authentications.put("petstore_auth", new OAuth()); - // Prevent the authentications from being modified. - authentications = Collections.unmodifiableMap(authentications); - } - - /** - * Get base path - * - * @return Baes path - */ - public String getBasePath() { - return basePath; - } - - /** - * Set base path - * - * @param basePath Base path of the URL (e.g http://petstore.swagger.io/v2 - * @return An instance of OkHttpClient - */ - public ApiClient setBasePath(String basePath) { - this.basePath = basePath; - return this; - } - - /** - * Get HTTP client - * - * @return An instance of OkHttpClient - */ - public OkHttpClient getHttpClient() { - return httpClient; - } - - /** - * Set HTTP client - * - * @param httpClient An instance of OkHttpClient - * @return Api Client - */ - public ApiClient setHttpClient(OkHttpClient httpClient) { - this.httpClient = httpClient; - return this; - } - - /** - * Get JSON - * - * @return JSON object - */ - public JSON getJSON() { - return json; - } - - /** - * Set JSON - * - * @param json JSON object - * @return Api client - */ - public ApiClient setJSON(JSON json) { - this.json = json; - return this; - } - - /** - * True if isVerifyingSsl flag is on - * - * @return True if isVerifySsl flag is on - */ - public boolean isVerifyingSsl() { - return verifyingSsl; - } - - /** - * Configure whether to verify certificate and hostname when making https requests. - * Default to true. - * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. - * - * @param verifyingSsl True to verify TLS/SSL connection - * @return ApiClient - */ - public ApiClient setVerifyingSsl(boolean verifyingSsl) { - this.verifyingSsl = verifyingSsl; - applySslSettings(); - return this; - } - - /** - * Get SSL CA cert. - * - * @return Input stream to the SSL CA cert - */ - public InputStream getSslCaCert() { - return sslCaCert; - } - - /** - * Configure the CA certificate to be trusted when making https requests. - * Use null to reset to default. - * - * @param sslCaCert input stream for SSL CA cert - * @return ApiClient - */ - public ApiClient setSslCaCert(InputStream sslCaCert) { - this.sslCaCert = sslCaCert; - applySslSettings(); - return this; - } - - public DateFormat getDateFormat() { - return dateFormat; - } - - public ApiClient setDateFormat(DateFormat dateFormat) { - this.dateFormat = dateFormat; - this.dateLength = this.dateFormat.format(new Date()).length(); - return this; - } - - public DateFormat getDatetimeFormat() { - return datetimeFormat; - } - - public ApiClient setDatetimeFormat(DateFormat datetimeFormat) { - this.datetimeFormat = datetimeFormat; - return this; + apiAuthorizations = new LinkedHashMap(); + createDefaultAdapter(); + } + + public ApiClient(String[] authNames) { + this(); + for(String authName : authNames) { + Interceptor auth; + if (authName == "api_key") { + auth = new ApiKeyAuth("header", "api_key"); + } else if (authName == "petstore_auth") { + auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); + } else { + throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); + } + addAuthorization(authName, auth); + } } /** - * Whether to allow various ISO 8601 datetime formats when parsing a datetime string. - * @see #parseDatetime(String) - * @return True if lenientDatetimeFormat flag is set to true + * Basic constructor for single auth name + * @param authName */ - public boolean isLenientDatetimeFormat() { - return lenientDatetimeFormat; - } - - public ApiClient setLenientDatetimeFormat(boolean lenientDatetimeFormat) { - this.lenientDatetimeFormat = lenientDatetimeFormat; - return this; + public ApiClient(String authName) { + this(new String[]{authName}); } /** - * Parse the given date string into Date object. - * The default dateFormat supports these ISO 8601 date formats: - * 2015-08-16 - * 2015-8-16 - * @param str String to be parsed - * @return Date + * Helper constructor for single api key + * @param authName + * @param apiKey */ - public Date parseDate(String str) { - if (str == null) - return null; - try { - return dateFormat.parse(str); - } catch (ParseException e) { - throw new RuntimeException(e); - } + public ApiClient(String authName, String apiKey) { + this(authName); + this.setApiKey(apiKey); } /** - * Parse the given datetime string into Date object. - * When lenientDatetimeFormat is enabled, the following ISO 8601 datetime formats are supported: - * 2015-08-16T08:20:05Z - * 2015-8-16T8:20:05Z - * 2015-08-16T08:20:05+00:00 - * 2015-08-16T08:20:05+0000 - * 2015-08-16T08:20:05.376Z - * 2015-08-16T08:20:05.376+00:00 - * 2015-08-16T08:20:05.376+00 - * Note: The 3-digit milli-seconds is optional. Time zone is required and can be in one of - * these formats: - * Z (same with +0000) - * +08:00 (same with +0800) - * -02 (same with -0200) - * -0200 - * @see ISO 8601 - * @param str Date time string to be parsed - * @return Date representation of the string - */ - public Date parseDatetime(String str) { - if (str == null) - return null; - - DateFormat format; - if (lenientDatetimeFormat) { - /* - * When lenientDatetimeFormat is enabled, normalize the date string - * into LENIENT_DATETIME_FORMAT to support various formats - * defined by ISO 8601. - */ - // normalize time zone - // trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000 - str = str.replaceAll("[zZ]\\z", "+0000"); - // remove colon in time zone: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000 - str = str.replaceAll("([+-]\\d{2}):(\\d{2})\\z", "$1$2"); - // expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000 - str = str.replaceAll("([+-]\\d{2})\\z", "$100"); - // add milliseconds when missing - // 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000 - str = str.replaceAll("(:\\d{1,2})([+-]\\d{4})\\z", "$1.000$2"); - format = new SimpleDateFormat(LENIENT_DATETIME_FORMAT); - } else { - format = this.datetimeFormat; - } - - try { - return format.parse(str); - } catch (ParseException e) { - throw new RuntimeException(e); - } - } - - /* - * Parse date or date time in string format into Date object. - * - * @param str Date time string to be parsed - * @return Date representation of the string + * Helper constructor for single basic auth or password oauth2 + * @param authName + * @param username + * @param password */ - public Date parseDateOrDatetime(String str) { - if (str == null) - return null; - else if (str.length() <= dateLength) - return parseDate(str); - else - return parseDatetime(str); + public ApiClient(String authName, String username, String password) { + this(authName); + this.setCredentials(username, password); } /** - * Format the given Date object into string (Date format). - * - * @param date Date object - * @return Formatted date in string representation + * Helper constructor for single password oauth2 + * @param authName + * @param clientId + * @param secret + * @param username + * @param password */ - public String formatDate(Date date) { - return dateFormat.format(date); + public ApiClient(String authName, String clientId, String secret, String username, String password) { + this(authName); + this.getTokenEndPoint() + .setClientId(clientId) + .setClientSecret(secret) + .setUsername(username) + .setPassword(password); } + + public void createDefaultAdapter() { + Gson gson = new GsonBuilder() + .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") + .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) + .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) + .create(); - /** - * Format the given Date object into string (Datetime format). - * - * @param date Date object - * @return Formatted datetime in string representation - */ - public String formatDatetime(Date date) { - return datetimeFormat.format(date); - } + okClient = new OkHttpClient(); - /** - * Get authentications (key: authentication name, value: authentication). - * - * @return Map of authentication objects - */ - public Map getAuthentications() { - return authentications; + adapterBuilder = new RestAdapter + .Builder() + .setEndpoint("http://petstore.swagger.io/v2") + .setClient(new OkClient(okClient)) + .setConverter(new GsonConverterWrapper(gson)); } - /** - * Get authentication for the given name. - * - * @param authName The authentication name - * @return The authentication, null if not found - */ - public Authentication getAuthentication(String authName) { - return authentications.get(authName); + public S createService(Class serviceClass) { + return adapterBuilder.build().create(serviceClass); + } /** - * Helper method to set username for the first HTTP basic authentication. - * - * @param username Username + * Helper method to configure the first api key found + * @param apiKey */ - public void setUsername(String username) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setUsername(username); + private void setApiKey(String apiKey) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof ApiKeyAuth) { + ApiKeyAuth keyAuth = (ApiKeyAuth) apiAuthorization; + keyAuth.setApiKey(apiKey); return; } } - throw new RuntimeException("No HTTP basic authentication configured!"); } /** - * Helper method to set password for the first HTTP basic authentication. - * - * @param password Password + * Helper method to configure the username/password for basic auth or password oauth + * @param username + * @param password */ - public void setPassword(String password) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setPassword(password); + private void setCredentials(String username, String password) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof HttpBasicAuth) { + HttpBasicAuth basicAuth = (HttpBasicAuth) apiAuthorization; + basicAuth.setCredentials(username, password); + return; + } + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.getTokenRequestBuilder().setUsername(username).setPassword(password); return; } } - throw new RuntimeException("No HTTP basic authentication configured!"); } /** - * Helper method to set API key value for the first API key authentication. - * - * @param apiKey API key + * Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one) + * @return */ - public void setApiKey(String apiKey) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKey(apiKey); - return; + public TokenRequestBuilder getTokenEndPoint() { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + return oauth.getTokenRequestBuilder(); } } - throw new RuntimeException("No API key authentication configured!"); + return null; } /** - * Helper method to set API key prefix for the first API key authentication. - * - * @param apiKeyPrefix API key prefix + * Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one) + * @return */ - public void setApiKeyPrefix(String apiKeyPrefix) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); - return; + public AuthenticationRequestBuilder getAuthorizationEndPoint() { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + return oauth.getAuthenticationRequestBuilder(); } } - throw new RuntimeException("No API key authentication configured!"); + return null; } /** - * Helper method to set access token for the first OAuth2 authentication. - * - * @param accessToken Access token + * Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one) + * @param accessToken */ public void setAccessToken(String accessToken) { - for (Authentication auth : authentications.values()) { - if (auth instanceof OAuth) { - ((OAuth) auth).setAccessToken(accessToken); + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.setAccessToken(accessToken); return; } } - throw new RuntimeException("No OAuth2 authentication configured!"); - } - - /** - * Set the User-Agent header's value (by adding to the default header map). - * - * @param userAgent HTTP request's user agent - * @return ApiClient - */ - public ApiClient setUserAgent(String userAgent) { - addDefaultHeader("User-Agent", userAgent); - return this; - } - - /** - * Add a default header. - * - * @param key The header's key - * @param value The header's value - * @return ApiClient - */ - public ApiClient addDefaultHeader(String key, String value) { - defaultHeaderMap.put(key, value); - return this; - } - - /** - * @see setLenient - * - * @return True if lenientOnJson is enabled, false otherwise. - */ - public boolean isLenientOnJson() { - return lenientOnJson; - } - - /** - * Set LenientOnJson - * - * @param lenient True to enable lenientOnJson - * @return ApiClient - */ - public ApiClient setLenientOnJson(boolean lenient) { - this.lenientOnJson = lenient; - return this; - } - - /** - * Check that whether debugging is enabled for this API client. - * - * @return True if debugging is enabled, false otherwise. - */ - public boolean isDebugging() { - return debugging; } - - /** - * Enable/disable debugging for this API client. - * - * @param debugging To enable (true) or disable (false) debugging - * @return ApiClient - */ - public ApiClient setDebugging(boolean debugging) { - if (debugging != this.debugging) { - if (debugging) { - loggingInterceptor = new HttpLoggingInterceptor(); - loggingInterceptor.setLevel(Level.BODY); - httpClient.interceptors().add(loggingInterceptor); - } else { - httpClient.interceptors().remove(loggingInterceptor); - loggingInterceptor = null; + + /** + * Helper method to configure the oauth accessCode/implicit flow parameters + * @param clientId + * @param clientSecret + * @param redirectURI + */ + public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.getTokenRequestBuilder() + .setClientId(clientId) + .setClientSecret(clientSecret) + .setRedirectURI(redirectURI); + oauth.getAuthenticationRequestBuilder() + .setClientId(clientId) + .setRedirectURI(redirectURI); + return; } } - this.debugging = debugging; - return this; } - - /** - * The path of temporary folder used to store downloaded files from endpoints - * with file response. The default value is null, i.e. using - * the system's default tempopary folder. - * - * @see createTempFile - * @return Temporary folder path - */ - public String getTempFolderPath() { - return tempFolderPath; - } - + /** - * Set the tempoaray folder path (for downloading files) - * - * @param tempFolderPath Temporary folder path - * @return ApiClient + * Configures a listener which is notified when a new access token is received. + * @param accessTokenListener */ - public ApiClient setTempFolderPath(String tempFolderPath) { - this.tempFolderPath = tempFolderPath; - return this; - } - - /** - * Get connection timeout (in milliseconds). - * - * @return Timeout in milliseconds - */ - public int getConnectTimeout() { - return httpClient.getConnectTimeout(); - } - - /** - * Sets the connect timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * - * @param connectionTimeout connection timeout in milliseconds - * @return Api client - */ - public ApiClient setConnectTimeout(int connectionTimeout) { - httpClient.setConnectTimeout(connectionTimeout, TimeUnit.MILLISECONDS); - return this; - } - - /** - * Format the given parameter object into string. - * - * @param param Parameter - * @return String representation of the parameter - */ - public String parameterToString(Object param) { - if (param == null) { - return ""; - } else if (param instanceof Date) { - return formatDatetime((Date) param); - } else if (param instanceof Collection) { - StringBuilder b = new StringBuilder(); - for (Object o : (Collection)param) { - if (b.length() > 0) { - b.append(","); - } - b.append(String.valueOf(o)); + public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.registerAccessTokenListener(accessTokenListener); + return; } - return b.toString(); - } else { - return String.valueOf(param); } } /** - * Format to {@code Pair} objects. - * - * @param collectionFormat collection format (e.g. csv, tsv) - * @param name Name - * @param value Value - * @return A list of Pair objects + * Adds an authorization to be used by the client + * @param authName + * @param authorization */ - public List parameterToPairs(String collectionFormat, String name, Object value){ - List params = new ArrayList(); - - // preconditions - if (name == null || name.isEmpty() || value == null) return params; - - Collection valueCollection = null; - if (value instanceof Collection) { - valueCollection = (Collection) value; - } else { - params.add(new Pair(name, parameterToString(value))); - return params; - } - - if (valueCollection.isEmpty()){ - return params; + public void addAuthorization(String authName, Interceptor authorization) { + if (apiAuthorizations.containsKey(authName)) { + throw new RuntimeException("auth name \"" + authName + "\" already in api authorizations"); } - - // get the collection format - collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv - - // create the params based on the collection format - if (collectionFormat.equals("multi")) { - for (Object item : valueCollection) { - params.add(new Pair(name, parameterToString(item))); - } - - return params; - } - - String delimiter = ","; - - if (collectionFormat.equals("csv")) { - delimiter = ","; - } else if (collectionFormat.equals("ssv")) { - delimiter = " "; - } else if (collectionFormat.equals("tsv")) { - delimiter = "\t"; - } else if (collectionFormat.equals("pipes")) { - delimiter = "|"; - } - - StringBuilder sb = new StringBuilder() ; - for (Object item : valueCollection) { - sb.append(delimiter); - sb.append(parameterToString(item)); - } - - params.add(new Pair(name, sb.substring(1))); - - return params; + apiAuthorizations.put(authName, authorization); + okClient.interceptors().add(authorization); } - /** - * Sanitize filename by removing path. - * e.g. ../../sun.gif becomes sun.gif - * - * @param filename The filename to be sanitized - * @return The sanitized filename - */ - public String sanitizeFilename(String filename) { - return filename.replaceAll(".*[/\\\\]", ""); + public Map getApiAuthorizations() { + return apiAuthorizations; } - /** - * Check if the given MIME is a JSON MIME. - * JSON MIME examples: - * application/json - * application/json; charset=UTF8 - * APPLICATION/JSON - * - * @param mime MIME (Multipurpose Internet Mail Extensions) - * @return True if the given MIME is JSON, false otherwise. - */ - public boolean isJsonMime(String mime) { - return mime != null && mime.matches("(?i)application\\/json(;.*)?"); + public void setApiAuthorizations(Map apiAuthorizations) { + this.apiAuthorizations = apiAuthorizations; } - /** - * Select the Accept header's value from the given accepts array: - * if JSON exists in the given array, use it; - * otherwise use all of them (joining into a string) - * - * @param accepts The accepts array to select from - * @return The Accept header to use. If the given array is empty, - * null will be returned (not to set the Accept header explicitly). - */ - public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) { - return null; - } - for (String accept : accepts) { - if (isJsonMime(accept)) { - return accept; - } - } - return StringUtil.join(accepts, ","); + public RestAdapter.Builder getAdapterBuilder() { + return adapterBuilder; } - /** - * Select the Content-Type header's value from the given array: - * if JSON exists in the given array, use it; - * otherwise use the first one of the array. - * - * @param contentTypes The Content-Type array to select from - * @return The Content-Type header to use. If the given array is empty, - * JSON will be used. - */ - public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) { - return "application/json"; - } - for (String contentType : contentTypes) { - if (isJsonMime(contentType)) { - return contentType; - } - } - return contentTypes[0]; + public void setAdapterBuilder(RestAdapter.Builder adapterBuilder) { + this.adapterBuilder = adapterBuilder; } - /** - * Escape the given string to be used as URL query value. - * - * @param str String to be escaped - * @return Escaped string - */ - public String escapeString(String str) { - try { - return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); - } catch (UnsupportedEncodingException e) { - return str; - } + public OkHttpClient getOkClient() { + return okClient; } - - /** - * Deserialize response body to Java object, according to the return type and - * the Content-Type response header. - * - * @param Type - * @param response HTTP response - * @param returnType The type of the Java object - * @return The deserialized Java object - * @throws ApiException If fail to deserialize response body, i.e. cannot read response body - * or the Content-Type of the response is not supported. - */ - @SuppressWarnings("unchecked") - public T deserialize(Response response, Type returnType) throws ApiException { - if (response == null || returnType == null) { - return null; - } - - if ("byte[]".equals(returnType.toString())) { - // Handle binary response (byte array). - try { - return (T) response.body().bytes(); - } catch (IOException e) { - throw new ApiException(e); - } - } else if (returnType.equals(File.class)) { - // Handle file downloading. - return (T) downloadFileFromResponse(response); - } - - String respBody; - try { - if (response.body() != null) - respBody = response.body().string(); - else - respBody = null; - } catch (IOException e) { - throw new ApiException(e); - } - - if (respBody == null || "".equals(respBody)) { - return null; - } - - String contentType = response.headers().get("Content-Type"); - if (contentType == null) { - // ensuring a default content type - contentType = "application/json"; - } - if (isJsonMime(contentType)) { - return json.deserialize(respBody, returnType); - } else if (returnType.equals(String.class)) { - // Expecting string, return the raw response body. - return (T) respBody; - } else { - throw new ApiException( - "Content type \"" + contentType + "\" is not supported for type: " + returnType, - response.code(), - response.headers().toMultimap(), - respBody); + + public void addAuthsToOkClient(OkHttpClient okClient) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + okClient.interceptors().add(apiAuthorization); } } /** - * Serialize the given Java object into request body according to the object's - * class and the request Content-Type. - * - * @param obj The Java object - * @param contentType The request Content-Type - * @return The serialized request body - * @throws ApiException If fail to serialize the given object + * Clones the okClient given in parameter, adds the auth interceptors and uses it to configure the RestAdapter + * @param okClient */ - public RequestBody serialize(Object obj, String contentType) throws ApiException { - if (obj instanceof byte[]) { - // Binary (byte array) body parameter support. - return RequestBody.create(MediaType.parse(contentType), (byte[]) obj); - } else if (obj instanceof File) { - // File body parameter support. - return RequestBody.create(MediaType.parse(contentType), (File) obj); - } else if (isJsonMime(contentType)) { - String content; - if (obj != null) { - content = json.serialize(obj); - } else { - content = null; - } - return RequestBody.create(MediaType.parse(contentType), content); - } else { - throw new ApiException("Content type \"" + contentType + "\" is not supported"); - } + public void configureFromOkclient(OkHttpClient okClient) { + OkHttpClient clone = okClient.clone(); + addAuthsToOkClient(clone); + adapterBuilder.setClient(new OkClient(clone)); } +} - /** - * Download file from the given response. - * - * @param response An instance of the Response object - * @throws ApiException If fail to read file content from response and write to disk - * @return Downloaded file - */ - public File downloadFileFromResponse(Response response) throws ApiException { - try { - File file = prepareDownloadFile(response); - BufferedSink sink = Okio.buffer(Okio.sink(file)); - sink.writeAll(response.body().source()); - sink.close(); - return file; - } catch (IOException e) { - throw new ApiException(e); - } - } +/** + * This wrapper is to take care of this case: + * when the deserialization fails due to JsonParseException and the + * expected type is String, then just return the body string. + */ +class GsonConverterWrapper implements Converter { + private GsonConverter converter; - /** - * Prepare file for download - * - * @param response An instance of the Response object - * @throws IOException If fail to prepare file for download - * @return Prepared file for the download - */ - public File prepareDownloadFile(Response response) throws IOException { - String filename = null; - String contentDisposition = response.header("Content-Disposition"); - if (contentDisposition != null && !"".equals(contentDisposition)) { - // Get filename from the Content-Disposition header. - Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); - Matcher matcher = pattern.matcher(contentDisposition); - if (matcher.find()) { - filename = sanitizeFilename(matcher.group(1)); - } - } + public GsonConverterWrapper(Gson gson) { + converter = new GsonConverter(gson); + } - String prefix = null; - String suffix = null; - if (filename == null) { - prefix = "download-"; - suffix = ""; - } else { - int pos = filename.lastIndexOf("."); - if (pos == -1) { - prefix = filename + "-"; + @Override public Object fromBody(TypedInput body, Type type) throws ConversionException { + byte[] bodyBytes = readInBytes(body); + TypedByteArray newBody = new TypedByteArray(body.mimeType(), bodyBytes); + try { + return converter.fromBody(newBody, type); + } catch (ConversionException e) { + if (e.getCause() instanceof JsonParseException && type.equals(String.class)) { + return new String(bodyBytes); } else { - prefix = filename.substring(0, pos) + "-"; - suffix = filename.substring(pos); + throw e; } - // File.createTempFile requires the prefix to be at least three characters long - if (prefix.length() < 3) - prefix = "download-"; } - - if (tempFolderPath == null) - return File.createTempFile(prefix, suffix); - else - return File.createTempFile(prefix, suffix, new File(tempFolderPath)); } - /** - * {@link #execute(Call, Type)} - * - * @param Type - * @param call An instance of the Call object - * @throws ApiException If fail to execute the call - * @return ApiResponse<T> - */ - public ApiResponse execute(Call call) throws ApiException { - return execute(call, null); + @Override public TypedOutput toBody(Object object) { + return converter.toBody(object); } - /** - * Execute HTTP call and deserialize the HTTP response body into the given return type. - * - * @param returnType The return type used to deserialize HTTP response body - * @param The return type corresponding to (same with) returnType - * @param call Call - * @return ApiResponse object containing response status, headers and - * data, which is a Java object deserialized from response body and would be null - * when returnType is null. - * @throws ApiException If fail to execute the call - */ - public ApiResponse execute(Call call, Type returnType) throws ApiException { + private byte[] readInBytes(TypedInput body) throws ConversionException { + InputStream in = null; try { - Response response = call.execute(); - T data = handleResponse(response, returnType); - return new ApiResponse(response.code(), response.headers().toMultimap(), data); + in = body.in(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + byte[] buffer = new byte[0xFFFF]; + for (int len; (len = in.read(buffer)) != -1;) + os.write(buffer, 0, len); + os.flush(); + return os.toByteArray(); } catch (IOException e) { - throw new ApiException(e); - } - } - - /** - * {@link #executeAsync(Call, Type, ApiCallback)} - * - * @param Type - * @param call An instance of the Call object - * @param callback ApiCallback<T> - */ - public void executeAsync(Call call, ApiCallback callback) { - executeAsync(call, null, callback); - } - - /** - * Execute HTTP call asynchronously. - * - * @see #execute(Call, Type) - * @param Type - * @param call The callback to be executed when the API call finishes - * @param returnType Return type - * @param callback ApiCallback - */ - @SuppressWarnings("unchecked") - public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { - call.enqueue(new Callback() { - @Override - public void onFailure(Request request, IOException e) { - callback.onFailure(new ApiException(e), 0, null); - } - - @Override - public void onResponse(Response response) throws IOException { - T result; + throw new ConversionException(e); + } finally { + if (in != null) { try { - result = (T) handleResponse(response, returnType); - } catch (ApiException e) { - callback.onFailure(e, response.code(), response.headers().toMultimap()); - return; + in.close(); + } catch (IOException ignored) { } - callback.onSuccess(result, response.code(), response.headers().toMultimap()); } - }); - } - - /** - * Handle the given response, return the deserialized object when the response is successful. - * - * @param Type - * @param response Response - * @param returnType Return type - * @throws ApiException If the response has a unsuccessful status code or - * fail to deserialize the response body - * @return Type - */ - public T handleResponse(Response response, Type returnType) throws ApiException { - if (response.isSuccessful()) { - if (returnType == null || response.code() == 204) { - // returning null if the returnType is not defined, - // or the status code is 204 (No Content) - return null; - } else { - return deserialize(response, returnType); - } - } else { - String respBody = null; - if (response.body() != null) { - try { - respBody = response.body().string(); - } catch (IOException e) { - throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); - } - } - throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); } - } - /** - * Build HTTP call with the given options. - * - * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" - * @param queryParams The query parameters - * @param body The request body object - * @param headerParams The header parameters - * @param formParams The form parameters - * @param authNames The authentications to apply - * @param progressRequestListener Progress request listener - * @return The HTTP call - * @throws ApiException If fail to serialize the request body object - */ - public Call buildCall(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - updateParamsForAuth(authNames, queryParams, headerParams); - - final String url = buildUrl(path, queryParams); - final Request.Builder reqBuilder = new Request.Builder().url(url); - processHeaderParams(headerParams, reqBuilder); - - String contentType = (String) headerParams.get("Content-Type"); - // ensuring a default content type - if (contentType == null) { - contentType = "application/json"; - } - - RequestBody reqBody; - if (!HttpMethod.permitsRequestBody(method)) { - reqBody = null; - } else if ("application/x-www-form-urlencoded".equals(contentType)) { - reqBody = buildRequestBodyFormEncoding(formParams); - } else if ("multipart/form-data".equals(contentType)) { - reqBody = buildRequestBodyMultipart(formParams); - } else if (body == null) { - if ("DELETE".equals(method)) { - // allow calling DELETE without sending a request body - reqBody = null; - } else { - // use an empty request body (for POST, PUT and PATCH) - reqBody = RequestBody.create(MediaType.parse(contentType), ""); - } - } else { - reqBody = serialize(body, contentType); - } - - Request request = null; - - if(progressRequestListener != null && reqBody != null) { - ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener); - request = reqBuilder.method(method, progressRequestBody).build(); - } else { - request = reqBuilder.method(method, reqBody).build(); - } - - return httpClient.newCall(request); } +} - /** - * Build full URL by concatenating base path, the given sub path and query parameters. - * - * @param path The sub path - * @param queryParams The query parameters - * @return The full URL - */ - public String buildUrl(String path, List queryParams) { - final StringBuilder url = new StringBuilder(); - url.append(basePath).append(path); - - if (queryParams != null && !queryParams.isEmpty()) { - // support (constant) query string in `path`, e.g. "/posts?draft=1" - String prefix = path.contains("?") ? "&" : "?"; - for (Pair param : queryParams) { - if (param.getValue() != null) { - if (prefix != null) { - url.append(prefix); - prefix = null; - } else { - url.append("&"); - } - String value = parameterToString(param.getValue()); - url.append(escapeString(param.getName())).append("=").append(escapeString(value)); - } - } - } - - return url.toString(); - } +/** + * Gson TypeAdapter for Joda DateTime type + */ +class DateTimeTypeAdapter extends TypeAdapter { - /** - * Set header parameters to the request builder, including default headers. - * - * @param headerParams Header parameters in the ofrm of Map - * @param reqBuilder Reqeust.Builder - */ - public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { - for (Entry param : headerParams.entrySet()) { - reqBuilder.header(param.getKey(), parameterToString(param.getValue())); - } - for (Entry header : defaultHeaderMap.entrySet()) { - if (!headerParams.containsKey(header.getKey())) { - reqBuilder.header(header.getKey(), parameterToString(header.getValue())); - } - } - } + private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); - /** - * Update query and header parameters based on authentication settings. - * - * @param authNames The authentications to apply - * @param queryParams List of query parameters - * @param headerParams Map of header parameters - */ - public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { - for (String authName : authNames) { - Authentication auth = authentications.get(authName); - if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); - auth.applyToParams(queryParams, headerParams); + @Override + public void write(JsonWriter out, DateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); } } - /** - * Build a form-encoding request body with the given form parameters. - * - * @param formParams Form parameters in the form of Map - * @return RequestBody - */ - public RequestBody buildRequestBodyFormEncoding(Map formParams) { - FormEncodingBuilder formBuilder = new FormEncodingBuilder(); - for (Entry param : formParams.entrySet()) { - formBuilder.add(param.getKey(), parameterToString(param.getValue())); + @Override + public DateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseDateTime(date); } - return formBuilder.build(); } +} - /** - * Build a multipart (file uploading) request body with the given form parameters, - * which could contain text fields and file fields. - * - * @param formParams Form parameters in the form of Map - * @return RequestBody - */ - public RequestBody buildRequestBodyMultipart(Map formParams) { - MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); - for (Entry param : formParams.entrySet()) { - if (param.getValue() instanceof File) { - File file = (File) param.getValue(); - Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\""); - MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); - mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file)); - } else { - Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\""); - mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue()))); - } - } - return mpBuilder.build(); - } +/** + * Gson TypeAdapter for Joda DateTime type + */ +class LocalDateTypeAdapter extends TypeAdapter { - /** - * Guess Content-Type header from the given file (defaults to "application/octet-stream"). - * - * @param file The given file - * @return The guessed Content-Type - */ - public String guessContentTypeFromFile(File file) { - String contentType = URLConnection.guessContentTypeFromName(file.getName()); - if (contentType == null) { - return "application/octet-stream"; - } else { - return contentType; - } - } + private final DateTimeFormatter formatter = ISODateTimeFormat.date(); - /** - * Initialize datetime format according to the current environment, e.g. Java 1.7 and Android. - */ - private void initDatetimeFormat() { - String formatWithTimeZone = null; - if (IS_ANDROID) { - if (ANDROID_SDK_VERSION >= 18) { - // The time zone format "ZZZZZ" is available since Android 4.3 (SDK version 18) - formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"; - } - } else if (JAVA_VERSION >= 1.7) { - // The time zone format "XXX" is available since Java 1.7 - formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; - } - if (formatWithTimeZone != null) { - this.datetimeFormat = new SimpleDateFormat(formatWithTimeZone); - // NOTE: Use the system's default time zone (mainly for datetime formatting). + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); } else { - // Use a common format that works across all systems. - this.datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - // Always use the UTC time zone as we are using a constant trailing "Z" here. - this.datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - } - } - - /** - * Apply SSL related settings to httpClient according to the current values of - * verifyingSsl and sslCaCert. - */ - private void applySslSettings() { - try { - KeyManager[] keyManagers = null; - TrustManager[] trustManagers = null; - HostnameVerifier hostnameVerifier = null; - if (!verifyingSsl) { - TrustManager trustAll = new X509TrustManager() { - @Override - public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} - @Override - public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} - @Override - public X509Certificate[] getAcceptedIssuers() { return null; } - }; - SSLContext sslContext = SSLContext.getInstance("TLS"); - trustManagers = new TrustManager[]{ trustAll }; - hostnameVerifier = new HostnameVerifier() { - @Override - public boolean verify(String hostname, SSLSession session) { return true; } - }; - } else if (sslCaCert != null) { - char[] password = null; // Any password will work. - CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); - Collection certificates = certificateFactory.generateCertificates(sslCaCert); - if (certificates.isEmpty()) { - throw new IllegalArgumentException("expected non-empty set of trusted certificates"); - } - KeyStore caKeyStore = newEmptyKeyStore(password); - int index = 0; - for (Certificate certificate : certificates) { - String certificateAlias = "ca" + Integer.toString(index++); - caKeyStore.setCertificateEntry(certificateAlias, certificate); - } - TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - trustManagerFactory.init(caKeyStore); - trustManagers = trustManagerFactory.getTrustManagers(); - } - - if (keyManagers != null || trustManagers != null) { - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(keyManagers, trustManagers, new SecureRandom()); - httpClient.setSslSocketFactory(sslContext.getSocketFactory()); - } else { - httpClient.setSslSocketFactory(null); - } - httpClient.setHostnameVerifier(hostnameVerifier); - } catch (GeneralSecurityException e) { - throw new RuntimeException(e); + out.value(formatter.print(date)); } } - private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { - try { - KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - keyStore.load(null, password); - return keyStore; - } catch (IOException e) { - throw new AssertionError(e); + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseLocalDate(date); } } } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiException.java deleted file mode 100644 index 3bed001f002..00000000000 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiException.java +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import java.util.Map; -import java.util.List; - - -public class ApiException extends Exception { - private int code = 0; - private Map> responseHeaders = null; - private String responseBody = null; - - public ApiException() {} - - public ApiException(Throwable throwable) { - super(throwable); - } - - public ApiException(String message) { - super(message); - } - - public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { - super(message, throwable); - this.code = code; - this.responseHeaders = responseHeaders; - this.responseBody = responseBody; - } - - public ApiException(String message, int code, Map> responseHeaders, String responseBody) { - this(message, (Throwable) null, code, responseHeaders, responseBody); - } - - public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { - this(message, throwable, code, responseHeaders, null); - } - - public ApiException(int code, Map> responseHeaders, String responseBody) { - this((String) null, (Throwable) null, code, responseHeaders, responseBody); - } - - public ApiException(int code, String message) { - super(message); - this.code = code; - } - - public ApiException(int code, String message, Map> responseHeaders, String responseBody) { - this(code, message); - this.responseHeaders = responseHeaders; - this.responseBody = responseBody; - } - - /** - * Get the HTTP status code. - * - * @return HTTP status code - */ - public int getCode() { - return code; - } - - /** - * Get the HTTP response headers. - * - * @return A map of list of string - */ - public Map> getResponseHeaders() { - return responseHeaders; - } - - /** - * Get the HTTP response body. - * - * @return Response body in the form of string - */ - public String getResponseBody() { - return responseBody; - } -} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiResponse.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiResponse.java deleted file mode 100644 index d7dde1ee939..00000000000 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiResponse.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import java.util.List; -import java.util.Map; - -/** - * API response returned by API call. - * - * @param T The type of data that is deserialized from response body - */ -public class ApiResponse { - final private int statusCode; - final private Map> headers; - final private T data; - - /** - * @param statusCode The status code of HTTP response - * @param headers The headers of HTTP response - */ - public ApiResponse(int statusCode, Map> headers) { - this(statusCode, headers, null); - } - - /** - * @param statusCode The status code of HTTP response - * @param headers The headers of HTTP response - * @param data The object deserialized from response bod - */ - public ApiResponse(int statusCode, Map> headers, T data) { - this.statusCode = statusCode; - this.headers = headers; - this.data = data; - } - - public int getStatusCode() { - return statusCode; - } - - public Map> getHeaders() { - return headers; - } - - public T getData() { - return data; - } -} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/CollectionFormats.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/CollectionFormats.java new file mode 100644 index 00000000000..c3cf5257514 --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/CollectionFormats.java @@ -0,0 +1,95 @@ +package io.swagger.client; + +import java.util.Arrays; +import java.util.List; + +public class CollectionFormats { + + public static class CSVParams { + + protected List params; + + public CSVParams() { + } + + public CSVParams(List params) { + this.params = params; + } + + public CSVParams(String... params) { + this.params = Arrays.asList(params); + } + + public List getParams() { + return params; + } + + public void setParams(List params) { + this.params = params; + } + + @Override + public String toString() { + return StringUtil.join(params.toArray(new String[0]), ","); + } + + } + + public static class SSVParams extends CSVParams { + + public SSVParams() { + } + + public SSVParams(List params) { + super(params); + } + + public SSVParams(String... params) { + super(params); + } + + @Override + public String toString() { + return StringUtil.join(params.toArray(new String[0]), " "); + } + } + + public static class TSVParams extends CSVParams { + + public TSVParams() { + } + + public TSVParams(List params) { + super(params); + } + + public TSVParams(String... params) { + super(params); + } + + @Override + public String toString() { + return StringUtil.join( params.toArray(new String[0]), "\t"); + } + } + + public static class PIPESParams extends CSVParams { + + public PIPESParams() { + } + + public PIPESParams(List params) { + super(params); + } + + public PIPESParams(String... params) { + super(params); + } + + @Override + public String toString() { + return StringUtil.join(params.toArray(new String[0]), "|"); + } + } + +} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/Configuration.java deleted file mode 100644 index 5191b9b73c6..00000000000 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/Configuration.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - - -public class Configuration { - private static ApiClient defaultApiClient = new ApiClient(); - - /** - * Get the default API client, which would be used when creating API - * instances without providing an API client. - * - * @return Default API client - */ - public static ApiClient getDefaultApiClient() { - return defaultApiClient; - } - - /** - * Set the default API client, which would be used when creating API - * instances without providing an API client. - * - * @param apiClient API client - */ - public static void setDefaultApiClient(ApiClient apiClient) { - defaultApiClient = apiClient; - } -} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/JSON.java deleted file mode 100644 index 540611eab9d..00000000000 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/JSON.java +++ /dev/null @@ -1,237 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonNull; -import com.google.gson.JsonParseException; -import com.google.gson.JsonPrimitive; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; - -import java.io.IOException; -import java.io.StringReader; -import java.lang.reflect.Type; -import java.util.Date; - -import org.joda.time.DateTime; -import org.joda.time.LocalDate; -import org.joda.time.format.DateTimeFormatter; -import org.joda.time.format.ISODateTimeFormat; - -public class JSON { - private ApiClient apiClient; - private Gson gson; - - /** - * JSON constructor. - * - * @param apiClient An instance of ApiClient - */ - public JSON(ApiClient apiClient) { - this.apiClient = apiClient; - gson = new GsonBuilder() - .registerTypeAdapter(Date.class, new DateAdapter(apiClient)) - .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) - .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) - .create(); - } - - /** - * Get Gson. - * - * @return Gson - */ - public Gson getGson() { - return gson; - } - - /** - * Set Gson. - * - * @param gson Gson - */ - public void setGson(Gson gson) { - this.gson = gson; - } - - /** - * Serialize the given Java object into JSON string. - * - * @param obj Object - * @return String representation of the JSON - */ - public String serialize(Object obj) { - return gson.toJson(obj); - } - - /** - * Deserialize the given JSON string to Java object. - * - * @param Type - * @param body The JSON string - * @param returnType The type to deserialize inot - * @return The deserialized Java object - */ - @SuppressWarnings("unchecked") - public T deserialize(String body, Type returnType) { - try { - if (apiClient.isLenientOnJson()) { - JsonReader jsonReader = new JsonReader(new StringReader(body)); - // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) - jsonReader.setLenient(true); - return gson.fromJson(jsonReader, returnType); - } else { - return gson.fromJson(body, returnType); - } - } catch (JsonParseException e) { - // Fallback processing when failed to parse JSON form response body: - // return the response body string directly for the String return type; - // parse response body into date or datetime for the Date return type. - if (returnType.equals(String.class)) - return (T) body; - else if (returnType.equals(Date.class)) - return (T) apiClient.parseDateOrDatetime(body); - else throw(e); - } - } -} - -class DateAdapter implements JsonSerializer, JsonDeserializer { - private final ApiClient apiClient; - - /** - * Constructor for DateAdapter - * - * @param apiClient Api client - */ - public DateAdapter(ApiClient apiClient) { - super(); - this.apiClient = apiClient; - } - - /** - * Serialize - * - * @param src Date - * @param typeOfSrc Type - * @param context Json Serialization Context - * @return Json Element - */ - @Override - public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { - if (src == null) { - return JsonNull.INSTANCE; - } else { - return new JsonPrimitive(apiClient.formatDatetime(src)); - } - } - - /** - * Deserialize - * - * @param json Json element - * @param date Type - * @param typeOfSrc Type - * @param context Json Serialization Context - * @return Date - * @throw JsonParseException if fail to parse - */ - @Override - public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException { - String str = json.getAsJsonPrimitive().getAsString(); - try { - return apiClient.parseDateOrDatetime(str); - } catch (RuntimeException e) { - throw new JsonParseException(e); - } - } -} - -/** - * Gson TypeAdapter for Joda DateTime type - */ -class DateTimeTypeAdapter extends TypeAdapter { - - private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); - - @Override - public void write(JsonWriter out, DateTime date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - out.value(formatter.print(date)); - } - } - - @Override - public DateTime read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - return formatter.parseDateTime(date); - } - } -} - -/** - * Gson TypeAdapter for Joda LocalDate type - */ -class LocalDateTypeAdapter extends TypeAdapter { - - private final DateTimeFormatter formatter = ISODateTimeFormat.date(); - - @Override - public void write(JsonWriter out, LocalDate date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - out.value(formatter.print(date)); - } - } - - @Override - public LocalDate read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - return formatter.parseLocalDate(date); - } - } -} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/Pair.java deleted file mode 100644 index 15b247eea93..00000000000 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/Pair.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - - -public class Pair { - private String name = ""; - private String value = ""; - - public Pair (String name, String value) { - setName(name); - setValue(value); - } - - private void setName(String name) { - if (!isValidString(name)) return; - - this.name = name; - } - - private void setValue(String value) { - if (!isValidString(value)) return; - - this.value = value; - } - - public String getName() { - return this.name; - } - - public String getValue() { - return this.value; - } - - private boolean isValidString(String arg) { - if (arg == null) return false; - if (arg.trim().isEmpty()) return false; - - return true; - } -} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ProgressRequestBody.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ProgressRequestBody.java deleted file mode 100644 index d9ca742ecd2..00000000000 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ProgressRequestBody.java +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import com.squareup.okhttp.MediaType; -import com.squareup.okhttp.RequestBody; - -import java.io.IOException; - -import okio.Buffer; -import okio.BufferedSink; -import okio.ForwardingSink; -import okio.Okio; -import okio.Sink; - -public class ProgressRequestBody extends RequestBody { - - public interface ProgressRequestListener { - void onRequestProgress(long bytesWritten, long contentLength, boolean done); - } - - private final RequestBody requestBody; - - private final ProgressRequestListener progressListener; - - private BufferedSink bufferedSink; - - public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) { - this.requestBody = requestBody; - this.progressListener = progressListener; - } - - @Override - public MediaType contentType() { - return requestBody.contentType(); - } - - @Override - public long contentLength() throws IOException { - return requestBody.contentLength(); - } - - @Override - public void writeTo(BufferedSink sink) throws IOException { - if (bufferedSink == null) { - bufferedSink = Okio.buffer(sink(sink)); - } - - requestBody.writeTo(bufferedSink); - bufferedSink.flush(); - - } - - private Sink sink(Sink sink) { - return new ForwardingSink(sink) { - - long bytesWritten = 0L; - long contentLength = 0L; - - @Override - public void write(Buffer source, long byteCount) throws IOException { - super.write(source, byteCount); - if (contentLength == 0) { - contentLength = contentLength(); - } - - bytesWritten += byteCount; - progressListener.onRequestProgress(bytesWritten, contentLength, bytesWritten == contentLength); - } - }; - } -} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ProgressResponseBody.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ProgressResponseBody.java deleted file mode 100644 index f8af685999d..00000000000 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ProgressResponseBody.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import com.squareup.okhttp.MediaType; -import com.squareup.okhttp.ResponseBody; - -import java.io.IOException; - -import okio.Buffer; -import okio.BufferedSource; -import okio.ForwardingSource; -import okio.Okio; -import okio.Source; - -public class ProgressResponseBody extends ResponseBody { - - public interface ProgressListener { - void update(long bytesRead, long contentLength, boolean done); - } - - private final ResponseBody responseBody; - private final ProgressListener progressListener; - private BufferedSource bufferedSource; - - public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) { - this.responseBody = responseBody; - this.progressListener = progressListener; - } - - @Override - public MediaType contentType() { - return responseBody.contentType(); - } - - @Override - public long contentLength() throws IOException { - return responseBody.contentLength(); - } - - @Override - public BufferedSource source() throws IOException { - if (bufferedSource == null) { - bufferedSource = Okio.buffer(source(responseBody.source())); - } - return bufferedSource; - } - - private Source source(Source source) { - return new ForwardingSource(source) { - long totalBytesRead = 0L; - - @Override - public long read(Buffer sink, long byteCount) throws IOException { - long bytesRead = super.read(sink, byteCount); - // read() returns the number of bytes read, or -1 if this source is exhausted. - totalBytesRead += bytesRead != -1 ? bytesRead : 0; - progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1); - return bytesRead; - } - }; - } -} - - diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java index 52dce361e2a..b1d2d056bb9 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java @@ -1,353 +1,99 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - package io.swagger.client.api; -import io.swagger.client.ApiCallback; -import io.swagger.client.ApiClient; -import io.swagger.client.ApiException; -import io.swagger.client.ApiResponse; -import io.swagger.client.Configuration; -import io.swagger.client.Pair; -import io.swagger.client.ProgressRequestBody; -import io.swagger.client.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; +import io.swagger.client.CollectionFormats.*; -import java.io.IOException; +import retrofit.Callback; +import retrofit.http.*; +import retrofit.mime.*; import org.joda.time.LocalDate; import org.joda.time.DateTime; import java.math.BigDecimal; -import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -public class FakeApi { - private ApiClient apiClient; - - public FakeApi() { - this(Configuration.getDefaultApiClient()); - } - - public FakeApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for testEndpointParameters */ - private com.squareup.okhttp.Call testEndpointParametersCall(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'number' is set - if (number == null) { - throw new ApiException("Missing the required parameter 'number' when calling testEndpointParameters(Async)"); - } - - // verify the required parameter '_double' is set - if (_double == null) { - throw new ApiException("Missing the required parameter '_double' when calling testEndpointParameters(Async)"); - } - - // verify the required parameter 'string' is set - if (string == null) { - throw new ApiException("Missing the required parameter 'string' when calling testEndpointParameters(Async)"); - } - - // verify the required parameter '_byte' is set - if (_byte == null) { - throw new ApiException("Missing the required parameter '_byte' when calling testEndpointParameters(Async)"); - } - - - // create path and map variables - String localVarPath = "/fake".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (integer != null) - localVarFormParams.put("integer", integer); - if (int32 != null) - localVarFormParams.put("int32", int32); - if (int64 != null) - localVarFormParams.put("int64", int64); - if (number != null) - localVarFormParams.put("number", number); - if (_float != null) - localVarFormParams.put("float", _float); - if (_double != null) - localVarFormParams.put("double", _double); - if (string != null) - localVarFormParams.put("string", string); - if (_byte != null) - localVarFormParams.put("byte", _byte); - if (binary != null) - localVarFormParams.put("binary", binary); - if (date != null) - localVarFormParams.put("date", date); - if (dateTime != null) - localVarFormParams.put("dateTime", dateTime); - if (password != null) - localVarFormParams.put("password", password); - - final String[] localVarAccepts = { - "application/xml; charset=utf-8", "application/json; charset=utf-8" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/xml; charset=utf-8", "application/json; charset=utf-8" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * @param number None (required) - * @param _double None (required) - * @param string None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { - testEndpointParametersWithHttpInfo(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); - } - - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * @param number None (required) - * @param _double None (required) - * @param string None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { - com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password, null, null); - return apiClient.execute(call); - } - - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 (asynchronously) - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * @param number None (required) - * @param _double None (required) - * @param string None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call testEndpointParametersAsync(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for testEnumQueryParameters */ - private com.squareup.okhttp.Call testEnumQueryParametersCall(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - - // create path and map variables - String localVarPath = "/fake".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (enumQueryInteger != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_integer", enumQueryInteger)); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (enumQueryString != null) - localVarFormParams.put("enum_query_string", enumQueryString); - if (enumQueryDouble != null) - localVarFormParams.put("enum_query_double", enumQueryDouble); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/json" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * To test enum query parameters - * - * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) - * @param enumQueryInteger Query parameter enum test (double) (optional) - * @param enumQueryDouble Query parameter enum test (double) (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void testEnumQueryParameters(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { - testEnumQueryParametersWithHttpInfo(enumQueryString, enumQueryInteger, enumQueryDouble); - } - - /** - * To test enum query parameters - * - * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) - * @param enumQueryInteger Query parameter enum test (double) (optional) - * @param enumQueryDouble Query parameter enum test (double) (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse testEnumQueryParametersWithHttpInfo(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { - com.squareup.okhttp.Call call = testEnumQueryParametersCall(enumQueryString, enumQueryInteger, enumQueryDouble, null, null); - return apiClient.execute(call); - } - - /** - * To test enum query parameters (asynchronously) - * - * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) - * @param enumQueryInteger Query parameter enum test (double) (optional) - * @param enumQueryDouble Query parameter enum test (double) (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call testEnumQueryParametersAsync(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = testEnumQueryParametersCall(enumQueryString, enumQueryInteger, enumQueryDouble, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } +public interface FakeApi { + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Sync method + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param string None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @return Void + */ + + @FormUrlEncoded + @POST("/fake") + Void testEndpointParameters( + @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password + ); + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Async method + * @param number None (required) + * @param _double None (required) + * @param string None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @param cb callback method + * @return void + */ + + @FormUrlEncoded + @POST("/fake") + void testEndpointParameters( + @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password, Callback cb + ); + /** + * To test enum query parameters + * Sync method + * + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @return Void + */ + + @FormUrlEncoded + @GET("/fake") + Void testEnumQueryParameters( + @Field("enum_query_string") String enumQueryString, @Query("enum_query_integer") BigDecimal enumQueryInteger, @Field("enum_query_double") Double enumQueryDouble + ); + + /** + * To test enum query parameters + * Async method + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @param cb callback method + * @return void + */ + + @FormUrlEncoded + @GET("/fake") + void testEnumQueryParameters( + @Field("enum_query_string") String enumQueryString, @Query("enum_query_integer") BigDecimal enumQueryInteger, @Field("enum_query_double") Double enumQueryDouble, Callback cb + ); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java index 2039a8842c1..66ed6aea981 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java @@ -1,935 +1,233 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - package io.swagger.client.api; -import io.swagger.client.ApiCallback; -import io.swagger.client.ApiClient; -import io.swagger.client.ApiException; -import io.swagger.client.ApiResponse; -import io.swagger.client.Configuration; -import io.swagger.client.Pair; -import io.swagger.client.ProgressRequestBody; -import io.swagger.client.ProgressResponseBody; +import io.swagger.client.CollectionFormats.*; -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; +import retrofit.Callback; +import retrofit.http.*; +import retrofit.mime.*; import io.swagger.client.model.Pet; import java.io.File; import io.swagger.client.model.ModelApiResponse; -import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -public class PetApi { - private ApiClient apiClient; - - public PetApi() { - this(Configuration.getDefaultApiClient()); - } - - public PetApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for addPet */ - private com.squareup.okhttp.Call addPetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling addPet(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/json", "application/xml" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void addPet(Pet body) throws ApiException { - addPetWithHttpInfo(body); - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse addPetWithHttpInfo(Pet body) throws ApiException { - com.squareup.okhttp.Call call = addPetCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Add a new pet to the store (asynchronously) - * - * @param body Pet object that needs to be added to the store (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call addPetAsync(Pet body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = addPetCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for deletePet */ - private com.squareup.okhttp.Call deletePetCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling deletePet(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - if (apiKey != null) - localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Deletes a pet - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void deletePet(Long petId, String apiKey) throws ApiException { - deletePetWithHttpInfo(petId, apiKey); - } - - /** - * Deletes a pet - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse deletePetWithHttpInfo(Long petId, String apiKey) throws ApiException { - com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, null, null); - return apiClient.execute(call); - } - - /** - * Deletes a pet (asynchronously) - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call deletePetAsync(Long petId, String apiKey, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for findPetsByStatus */ - private com.squareup.okhttp.Call findPetsByStatusCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'status' is set - if (status == null) { - throw new ApiException("Missing the required parameter 'status' when calling findPetsByStatus(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/findByStatus".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (status != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "status", status)); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Finds Pets by status - * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for filter (required) - * @return List<Pet> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public List findPetsByStatus(List status) throws ApiException { - ApiResponse> resp = findPetsByStatusWithHttpInfo(status); - return resp.getData(); - } - - /** - * Finds Pets by status - * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for filter (required) - * @return ApiResponse<List<Pet>> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse> findPetsByStatusWithHttpInfo(List status) throws ApiException { - com.squareup.okhttp.Call call = findPetsByStatusCall(status, null, null); - Type localVarReturnType = new TypeToken>(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Finds Pets by status (asynchronously) - * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for filter (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call findPetsByStatusAsync(List status, final ApiCallback> callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = findPetsByStatusCall(status, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken>(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for findPetsByTags */ - private com.squareup.okhttp.Call findPetsByTagsCall(List tags, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'tags' is set - if (tags == null) { - throw new ApiException("Missing the required parameter 'tags' when calling findPetsByTags(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/findByTags".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (tags != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "tags", tags)); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Finds Pets by tags - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by (required) - * @return List<Pet> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public List findPetsByTags(List tags) throws ApiException { - ApiResponse> resp = findPetsByTagsWithHttpInfo(tags); - return resp.getData(); - } - - /** - * Finds Pets by tags - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by (required) - * @return ApiResponse<List<Pet>> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse> findPetsByTagsWithHttpInfo(List tags) throws ApiException { - com.squareup.okhttp.Call call = findPetsByTagsCall(tags, null, null); - Type localVarReturnType = new TypeToken>(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Finds Pets by tags (asynchronously) - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call findPetsByTagsAsync(List tags, final ApiCallback> callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = findPetsByTagsCall(tags, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken>(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for getPetById */ - private com.squareup.okhttp.Call getPetByIdCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling getPetById(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "api_key" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Find pet by ID - * Returns a single pet - * @param petId ID of pet to return (required) - * @return Pet - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Pet getPetById(Long petId) throws ApiException { - ApiResponse resp = getPetByIdWithHttpInfo(petId); - return resp.getData(); - } - - /** - * Find pet by ID - * Returns a single pet - * @param petId ID of pet to return (required) - * @return ApiResponse<Pet> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse getPetByIdWithHttpInfo(Long petId) throws ApiException { - com.squareup.okhttp.Call call = getPetByIdCall(petId, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Find pet by ID (asynchronously) - * Returns a single pet - * @param petId ID of pet to return (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call getPetByIdAsync(Long petId, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = getPetByIdCall(petId, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for updatePet */ - private com.squareup.okhttp.Call updatePetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling updatePet(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/json", "application/xml" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void updatePet(Pet body) throws ApiException { - updatePetWithHttpInfo(body); - } - - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse updatePetWithHttpInfo(Pet body) throws ApiException { - com.squareup.okhttp.Call call = updatePetCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Update an existing pet (asynchronously) - * - * @param body Pet object that needs to be added to the store (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call updatePetAsync(Pet body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = updatePetCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for updatePetWithForm */ - private com.squareup.okhttp.Call updatePetWithFormCall(Long petId, String name, String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling updatePetWithForm(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (name != null) - localVarFormParams.put("name", name); - if (status != null) - localVarFormParams.put("status", status); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/x-www-form-urlencoded" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void updatePetWithForm(Long petId, String name, String status) throws ApiException { - updatePetWithFormWithHttpInfo(petId, name, status); - } - - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse updatePetWithFormWithHttpInfo(Long petId, String name, String status) throws ApiException { - com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, null, null); - return apiClient.execute(call); - } - - /** - * Updates a pet in the store with form data (asynchronously) - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call updatePetWithFormAsync(Long petId, String name, String status, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for uploadFile */ - private com.squareup.okhttp.Call uploadFileCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling uploadFile(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (additionalMetadata != null) - localVarFormParams.put("additionalMetadata", additionalMetadata); - if (file != null) - localVarFormParams.put("file", file); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "multipart/form-data" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * uploads an image - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @return ModelApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { - ApiResponse resp = uploadFileWithHttpInfo(petId, additionalMetadata, file); - return resp.getData(); - } - - /** - * uploads an image - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @return ApiResponse<ModelApiResponse> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file) throws ApiException { - com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * uploads an image (asynchronously) - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call uploadFileAsync(Long petId, String additionalMetadata, File file, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } +public interface PetApi { + /** + * Add a new pet to the store + * Sync method + * + * @param body Pet object that needs to be added to the store (required) + * @return Void + */ + + @POST("/pet") + Void addPet( + @Body Pet body + ); + + /** + * Add a new pet to the store + * Async method + * @param body Pet object that needs to be added to the store (required) + * @param cb callback method + * @return void + */ + + @POST("/pet") + void addPet( + @Body Pet body, Callback cb + ); + /** + * Deletes a pet + * Sync method + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @return Void + */ + + @DELETE("/pet/{petId}") + Void deletePet( + @Path("petId") Long petId, @Header("api_key") String apiKey + ); + + /** + * Deletes a pet + * Async method + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @param cb callback method + * @return void + */ + + @DELETE("/pet/{petId}") + void deletePet( + @Path("petId") Long petId, @Header("api_key") String apiKey, Callback cb + ); + /** + * Finds Pets by status + * Sync method + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return List + */ + + @GET("/pet/findByStatus") + List findPetsByStatus( + @Query("status") CSVParams status + ); + + /** + * Finds Pets by status + * Async method + * @param status Status values that need to be considered for filter (required) + * @param cb callback method + * @return void + */ + + @GET("/pet/findByStatus") + void findPetsByStatus( + @Query("status") CSVParams status, Callback> cb + ); + /** + * Finds Pets by tags + * Sync method + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return List + */ + + @GET("/pet/findByTags") + List findPetsByTags( + @Query("tags") CSVParams tags + ); + + /** + * Finds Pets by tags + * Async method + * @param tags Tags to filter by (required) + * @param cb callback method + * @return void + */ + + @GET("/pet/findByTags") + void findPetsByTags( + @Query("tags") CSVParams tags, Callback> cb + ); + /** + * Find pet by ID + * Sync method + * Returns a single pet + * @param petId ID of pet to return (required) + * @return Pet + */ + + @GET("/pet/{petId}") + Pet getPetById( + @Path("petId") Long petId + ); + + /** + * Find pet by ID + * Async method + * @param petId ID of pet to return (required) + * @param cb callback method + * @return void + */ + + @GET("/pet/{petId}") + void getPetById( + @Path("petId") Long petId, Callback cb + ); + /** + * Update an existing pet + * Sync method + * + * @param body Pet object that needs to be added to the store (required) + * @return Void + */ + + @PUT("/pet") + Void updatePet( + @Body Pet body + ); + + /** + * Update an existing pet + * Async method + * @param body Pet object that needs to be added to the store (required) + * @param cb callback method + * @return void + */ + + @PUT("/pet") + void updatePet( + @Body Pet body, Callback cb + ); + /** + * Updates a pet in the store with form data + * Sync method + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @return Void + */ + + @FormUrlEncoded + @POST("/pet/{petId}") + Void updatePetWithForm( + @Path("petId") Long petId, @Field("name") String name, @Field("status") String status + ); + + /** + * Updates a pet in the store with form data + * Async method + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @param cb callback method + * @return void + */ + + @FormUrlEncoded + @POST("/pet/{petId}") + void updatePetWithForm( + @Path("petId") Long petId, @Field("name") String name, @Field("status") String status, Callback cb + ); + /** + * uploads an image + * Sync method + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ModelApiResponse + */ + + @Multipart + @POST("/pet/{petId}/uploadImage") + ModelApiResponse uploadFile( + @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file") TypedFile file + ); + + /** + * uploads an image + * Async method + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @param cb callback method + * @return void + */ + + @Multipart + @POST("/pet/{petId}/uploadImage") + void uploadFile( + @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file") TypedFile file, Callback cb + ); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java index 0768744c263..def4aa2efc7 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java @@ -1,482 +1,114 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - package io.swagger.client.api; -import io.swagger.client.ApiCallback; -import io.swagger.client.ApiClient; -import io.swagger.client.ApiException; -import io.swagger.client.ApiResponse; -import io.swagger.client.Configuration; -import io.swagger.client.Pair; -import io.swagger.client.ProgressRequestBody; -import io.swagger.client.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; +import io.swagger.client.CollectionFormats.*; -import java.io.IOException; +import retrofit.Callback; +import retrofit.http.*; +import retrofit.mime.*; import io.swagger.client.model.Order; -import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -public class StoreApi { - private ApiClient apiClient; - - public StoreApi() { - this(Configuration.getDefaultApiClient()); - } - - public StoreApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for deleteOrder */ - private com.squareup.okhttp.Call deleteOrderCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException("Missing the required parameter 'orderId' when calling deleteOrder(Async)"); - } - - - // create path and map variables - String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void deleteOrder(String orderId) throws ApiException { - deleteOrderWithHttpInfo(orderId); - } - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse deleteOrderWithHttpInfo(String orderId) throws ApiException { - com.squareup.okhttp.Call call = deleteOrderCall(orderId, null, null); - return apiClient.execute(call); - } - - /** - * Delete purchase order by ID (asynchronously) - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call deleteOrderAsync(String orderId, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = deleteOrderCall(orderId, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for getInventory */ - private com.squareup.okhttp.Call getInventoryCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - - // create path and map variables - String localVarPath = "/store/inventory".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "api_key" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - * @return Map<String, Integer> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Map getInventory() throws ApiException { - ApiResponse> resp = getInventoryWithHttpInfo(); - return resp.getData(); - } - - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - * @return ApiResponse<Map<String, Integer>> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse> getInventoryWithHttpInfo() throws ApiException { - com.squareup.okhttp.Call call = getInventoryCall(null, null); - Type localVarReturnType = new TypeToken>(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Returns pet inventories by status (asynchronously) - * Returns a map of status codes to quantities - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call getInventoryAsync(final ApiCallback> callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = getInventoryCall(progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken>(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for getOrderById */ - private com.squareup.okhttp.Call getOrderByIdCall(Long orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException("Missing the required parameter 'orderId' when calling getOrderById(Async)"); - } - - - // create path and map variables - String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched (required) - * @return Order - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Order getOrderById(Long orderId) throws ApiException { - ApiResponse resp = getOrderByIdWithHttpInfo(orderId); - return resp.getData(); - } - - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched (required) - * @return ApiResponse<Order> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse getOrderByIdWithHttpInfo(Long orderId) throws ApiException { - com.squareup.okhttp.Call call = getOrderByIdCall(orderId, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Find purchase order by ID (asynchronously) - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call getOrderByIdAsync(Long orderId, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = getOrderByIdCall(orderId, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for placeOrder */ - private com.squareup.okhttp.Call placeOrderCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling placeOrder(Async)"); - } - - - // create path and map variables - String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet (required) - * @return Order - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Order placeOrder(Order body) throws ApiException { - ApiResponse resp = placeOrderWithHttpInfo(body); - return resp.getData(); - } - - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet (required) - * @return ApiResponse<Order> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse placeOrderWithHttpInfo(Order body) throws ApiException { - com.squareup.okhttp.Call call = placeOrderCall(body, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Place an order for a pet (asynchronously) - * - * @param body order placed for purchasing the pet (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call placeOrderAsync(Order body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = placeOrderCall(body, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } +public interface StoreApi { + /** + * Delete purchase order by ID + * Sync method + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @return Void + */ + + @DELETE("/store/order/{orderId}") + Void deleteOrder( + @Path("orderId") String orderId + ); + + /** + * Delete purchase order by ID + * Async method + * @param orderId ID of the order that needs to be deleted (required) + * @param cb callback method + * @return void + */ + + @DELETE("/store/order/{orderId}") + void deleteOrder( + @Path("orderId") String orderId, Callback cb + ); + /** + * Returns pet inventories by status + * Sync method + * Returns a map of status codes to quantities + * @return Map + */ + + @GET("/store/inventory") + Map getInventory(); + + + /** + * Returns pet inventories by status + * Async method + * @param cb callback method + * @return void + */ + + @GET("/store/inventory") + void getInventory( + Callback> cb + ); + /** + * Find purchase order by ID + * Sync method + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @return Order + */ + + @GET("/store/order/{orderId}") + Order getOrderById( + @Path("orderId") Long orderId + ); + + /** + * Find purchase order by ID + * Async method + * @param orderId ID of pet that needs to be fetched (required) + * @param cb callback method + * @return void + */ + + @GET("/store/order/{orderId}") + void getOrderById( + @Path("orderId") Long orderId, Callback cb + ); + /** + * Place an order for a pet + * Sync method + * + * @param body order placed for purchasing the pet (required) + * @return Order + */ + + @POST("/store/order") + Order placeOrder( + @Body Order body + ); + + /** + * Place an order for a pet + * Async method + * @param body order placed for purchasing the pet (required) + * @param cb callback method + * @return void + */ + + @POST("/store/order") + void placeOrder( + @Body Order body, Callback cb + ); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java index 1c4fc3101a1..8c3380d07d4 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java @@ -1,907 +1,218 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - package io.swagger.client.api; -import io.swagger.client.ApiCallback; -import io.swagger.client.ApiClient; -import io.swagger.client.ApiException; -import io.swagger.client.ApiResponse; -import io.swagger.client.Configuration; -import io.swagger.client.Pair; -import io.swagger.client.ProgressRequestBody; -import io.swagger.client.ProgressResponseBody; +import io.swagger.client.CollectionFormats.*; -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; +import retrofit.Callback; +import retrofit.http.*; +import retrofit.mime.*; import io.swagger.client.model.User; -import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -public class UserApi { - private ApiClient apiClient; - - public UserApi() { - this(Configuration.getDefaultApiClient()); - } - - public UserApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for createUser */ - private com.squareup.okhttp.Call createUserCall(User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling createUser(Async)"); - } - - - // create path and map variables - String localVarPath = "/user".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void createUser(User body) throws ApiException { - createUserWithHttpInfo(body); - } - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse createUserWithHttpInfo(User body) throws ApiException { - com.squareup.okhttp.Call call = createUserCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Create user (asynchronously) - * This can only be done by the logged in user. - * @param body Created user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call createUserAsync(User body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = createUserCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for createUsersWithArrayInput */ - private com.squareup.okhttp.Call createUsersWithArrayInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling createUsersWithArrayInput(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/createWithArray".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void createUsersWithArrayInput(List body) throws ApiException { - createUsersWithArrayInputWithHttpInfo(body); - } - - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse createUsersWithArrayInputWithHttpInfo(List body) throws ApiException { - com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Creates list of users with given input array (asynchronously) - * - * @param body List of user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call createUsersWithArrayInputAsync(List body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for createUsersWithListInput */ - private com.squareup.okhttp.Call createUsersWithListInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling createUsersWithListInput(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void createUsersWithListInput(List body) throws ApiException { - createUsersWithListInputWithHttpInfo(body); - } - - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse createUsersWithListInputWithHttpInfo(List body) throws ApiException { - com.squareup.okhttp.Call call = createUsersWithListInputCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Creates list of users with given input array (asynchronously) - * - * @param body List of user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call createUsersWithListInputAsync(List body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = createUsersWithListInputCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for deleteUser */ - private com.squareup.okhttp.Call deleteUserCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling deleteUser(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void deleteUser(String username) throws ApiException { - deleteUserWithHttpInfo(username); - } - - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse deleteUserWithHttpInfo(String username) throws ApiException { - com.squareup.okhttp.Call call = deleteUserCall(username, null, null); - return apiClient.execute(call); - } - - /** - * Delete user (asynchronously) - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call deleteUserAsync(String username, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = deleteUserCall(username, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for getUserByName */ - private com.squareup.okhttp.Call getUserByNameCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling getUserByName(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return User - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public User getUserByName(String username) throws ApiException { - ApiResponse resp = getUserByNameWithHttpInfo(username); - return resp.getData(); - } - - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return ApiResponse<User> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse getUserByNameWithHttpInfo(String username) throws ApiException { - com.squareup.okhttp.Call call = getUserByNameCall(username, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Get user by user name (asynchronously) - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call getUserByNameAsync(String username, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = getUserByNameCall(username, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for loginUser */ - private com.squareup.okhttp.Call loginUserCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling loginUser(Async)"); - } - - // verify the required parameter 'password' is set - if (password == null) { - throw new ApiException("Missing the required parameter 'password' when calling loginUser(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/login".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (username != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("", "username", username)); - if (password != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("", "password", password)); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Logs user into the system - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @return String - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public String loginUser(String username, String password) throws ApiException { - ApiResponse resp = loginUserWithHttpInfo(username, password); - return resp.getData(); - } - - /** - * Logs user into the system - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @return ApiResponse<String> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse loginUserWithHttpInfo(String username, String password) throws ApiException { - com.squareup.okhttp.Call call = loginUserCall(username, password, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Logs user into the system (asynchronously) - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call loginUserAsync(String username, String password, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = loginUserCall(username, password, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for logoutUser */ - private com.squareup.okhttp.Call logoutUserCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - - // create path and map variables - String localVarPath = "/user/logout".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Logs out current logged in user session - * - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void logoutUser() throws ApiException { - logoutUserWithHttpInfo(); - } - - /** - * Logs out current logged in user session - * - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse logoutUserWithHttpInfo() throws ApiException { - com.squareup.okhttp.Call call = logoutUserCall(null, null); - return apiClient.execute(call); - } - - /** - * Logs out current logged in user session (asynchronously) - * - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call logoutUserAsync(final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = logoutUserCall(progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for updateUser */ - private com.squareup.okhttp.Call updateUserCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling updateUser(Async)"); - } - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling updateUser(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void updateUser(String username, User body) throws ApiException { - updateUserWithHttpInfo(username, body); - } - - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse updateUserWithHttpInfo(String username, User body) throws ApiException { - com.squareup.okhttp.Call call = updateUserCall(username, body, null, null); - return apiClient.execute(call); - } - - /** - * Updated user (asynchronously) - * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call updateUserAsync(String username, User body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = updateUserCall(username, body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } +public interface UserApi { + /** + * Create user + * Sync method + * This can only be done by the logged in user. + * @param body Created user object (required) + * @return Void + */ + + @POST("/user") + Void createUser( + @Body User body + ); + + /** + * Create user + * Async method + * @param body Created user object (required) + * @param cb callback method + * @return void + */ + + @POST("/user") + void createUser( + @Body User body, Callback cb + ); + /** + * Creates list of users with given input array + * Sync method + * + * @param body List of user object (required) + * @return Void + */ + + @POST("/user/createWithArray") + Void createUsersWithArrayInput( + @Body List body + ); + + /** + * Creates list of users with given input array + * Async method + * @param body List of user object (required) + * @param cb callback method + * @return void + */ + + @POST("/user/createWithArray") + void createUsersWithArrayInput( + @Body List body, Callback cb + ); + /** + * Creates list of users with given input array + * Sync method + * + * @param body List of user object (required) + * @return Void + */ + + @POST("/user/createWithList") + Void createUsersWithListInput( + @Body List body + ); + + /** + * Creates list of users with given input array + * Async method + * @param body List of user object (required) + * @param cb callback method + * @return void + */ + + @POST("/user/createWithList") + void createUsersWithListInput( + @Body List body, Callback cb + ); + /** + * Delete user + * Sync method + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @return Void + */ + + @DELETE("/user/{username}") + Void deleteUser( + @Path("username") String username + ); + + /** + * Delete user + * Async method + * @param username The name that needs to be deleted (required) + * @param cb callback method + * @return void + */ + + @DELETE("/user/{username}") + void deleteUser( + @Path("username") String username, Callback cb + ); + /** + * Get user by user name + * Sync method + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return User + */ + + @GET("/user/{username}") + User getUserByName( + @Path("username") String username + ); + + /** + * Get user by user name + * Async method + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @param cb callback method + * @return void + */ + + @GET("/user/{username}") + void getUserByName( + @Path("username") String username, Callback cb + ); + /** + * Logs user into the system + * Sync method + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return String + */ + + @GET("/user/login") + String loginUser( + @Query("username") String username, @Query("password") String password + ); + + /** + * Logs user into the system + * Async method + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @param cb callback method + * @return void + */ + + @GET("/user/login") + void loginUser( + @Query("username") String username, @Query("password") String password, Callback cb + ); + /** + * Logs out current logged in user session + * Sync method + * + * @return Void + */ + + @GET("/user/logout") + Void logoutUser(); + + + /** + * Logs out current logged in user session + * Async method + * @param cb callback method + * @return void + */ + + @GET("/user/logout") + void logoutUser( + Callback cb + ); + /** + * Updated user + * Sync method + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @return Void + */ + + @PUT("/user/{username}") + Void updateUser( + @Path("username") String username, @Body User body + ); + + /** + * Updated user + * Async method + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @param cb callback method + * @return void + */ + + @PUT("/user/{username}") + void updateUser( + @Path("username") String username, @Body User body, Callback cb + ); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index a125fff5f24..59d01238796 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -1,87 +1,68 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - package io.swagger.client.auth; -import io.swagger.client.Pair; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; -import java.util.Map; -import java.util.List; +import com.squareup.okhttp.Interceptor; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Response; +public class ApiKeyAuth implements Interceptor { + private final String location; + private final String paramName; -public class ApiKeyAuth implements Authentication { - private final String location; - private final String paramName; + private String apiKey; - private String apiKey; - private String apiKeyPrefix; + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } - public ApiKeyAuth(String location, String paramName) { - this.location = location; - this.paramName = paramName; - } + public String getLocation() { + return location; + } - public String getLocation() { - return location; - } + public String getParamName() { + return paramName; + } - public String getParamName() { - return paramName; - } + public String getApiKey() { + return apiKey; + } - public String getApiKey() { - return apiKey; - } + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } - public void setApiKey(String apiKey) { - this.apiKey = apiKey; - } + @Override + public Response intercept(Chain chain) throws IOException { + String paramValue; + Request request = chain.request(); - public String getApiKeyPrefix() { - return apiKeyPrefix; - } + if (location == "query") { + String newQuery = request.uri().getQuery(); + paramValue = paramName + "=" + apiKey; + if (newQuery == null) { + newQuery = paramValue; + } else { + newQuery += "&" + paramValue; + } - public void setApiKeyPrefix(String apiKeyPrefix) { - this.apiKeyPrefix = apiKeyPrefix; - } + URI newUri; + try { + newUri = new URI(request.uri().getScheme(), request.uri().getAuthority(), + request.uri().getPath(), newQuery, request.uri().getFragment()); + } catch (URISyntaxException e) { + throw new IOException(e); + } - @Override - public void applyToParams(List queryParams, Map headerParams) { - if (apiKey == null) { - return; - } - String value; - if (apiKeyPrefix != null) { - value = apiKeyPrefix + " " + apiKey; - } else { - value = apiKey; - } - if (location == "query") { - queryParams.add(new Pair(paramName, value)); - } else if (location == "header") { - headerParams.put(paramName, value); + request = request.newBuilder().url(newUri.toURL()).build(); + } else if (location == "header") { + request = request.newBuilder() + .addHeader(paramName, apiKey) + .build(); + } + return chain.proceed(request); } - } -} +} \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/Authentication.java deleted file mode 100644 index 221a7d9dd1f..00000000000 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/Authentication.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client.auth; - -import io.swagger.client.Pair; - -import java.util.Map; -import java.util.List; - -public interface Authentication { - /** - * Apply authentication settings to header and query params. - * - * @param queryParams List of query parameters - * @param headerParams Map of header parameters - */ - void applyToParams(List queryParams, Map headerParams); -} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 4eb2300b69d..cb7c617767b 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -1,43 +1,17 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - package io.swagger.client.auth; -import io.swagger.client.Pair; +import java.io.IOException; import com.squareup.okhttp.Credentials; +import com.squareup.okhttp.Interceptor; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Response; -import java.util.Map; -import java.util.List; +public class HttpBasicAuth implements Interceptor { -import java.io.UnsupportedEncodingException; - -public class HttpBasicAuth implements Authentication { private String username; private String password; - + public String getUsername() { return username; } @@ -54,13 +28,22 @@ public void setPassword(String password) { this.password = password; } + public void setCredentials(String username, String password) { + this.username = username; + this.password = password; + } + @Override - public void applyToParams(List queryParams, Map headerParams) { - if (username == null && password == null) { - return; + public Response intercept(Chain chain) throws IOException { + Request request = chain.request(); + + // If the request already have an authorization (eg. Basic auth), do nothing + if (request.header("Authorization") == null) { + String credentials = Credentials.basic(username, password); + request = request.newBuilder() + .addHeader("Authorization", credentials) + .build(); } - headerParams.put("Authorization", Credentials.basic( - username == null ? "" : username, - password == null ? "" : password)); + return chain.proceed(request); } } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuth.java index 14521f6ed7e..b725e019aff 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuth.java @@ -1,51 +1,176 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - package io.swagger.client.auth; -import io.swagger.client.Pair; +import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; +import static java.net.HttpURLConnection.HTTP_FORBIDDEN; +import java.io.IOException; import java.util.Map; -import java.util.List; +import org.apache.oltu.oauth2.client.OAuthClient; +import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; +import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse; +import org.apache.oltu.oauth2.common.exception.OAuthProblemException; +import org.apache.oltu.oauth2.common.exception.OAuthSystemException; +import org.apache.oltu.oauth2.common.message.types.GrantType; +import org.apache.oltu.oauth2.common.token.BasicOAuthToken; + +import com.squareup.okhttp.Interceptor; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Request.Builder; +import com.squareup.okhttp.Response; + +public class OAuth implements Interceptor { + + public interface AccessTokenListener { + public void notify(BasicOAuthToken token); + } + + private volatile String accessToken; + private OAuthClient oauthClient; + + private TokenRequestBuilder tokenRequestBuilder; + private AuthenticationRequestBuilder authenticationRequestBuilder; + + private AccessTokenListener accessTokenListener; + + public OAuth( OkHttpClient client, TokenRequestBuilder requestBuilder ) { + this.oauthClient = new OAuthClient(new OAuthOkHttpClient(client)); + this.tokenRequestBuilder = requestBuilder; + } + + public OAuth(TokenRequestBuilder requestBuilder ) { + this(new OkHttpClient(), requestBuilder); + } + + public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { + this(OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes)); + setFlow(flow); + authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl); + } + + public void setFlow(OAuthFlow flow) { + switch(flow) { + case accessCode: + case implicit: + tokenRequestBuilder.setGrantType(GrantType.AUTHORIZATION_CODE); + break; + case password: + tokenRequestBuilder.setGrantType(GrantType.PASSWORD); + break; + case application: + tokenRequestBuilder.setGrantType(GrantType.CLIENT_CREDENTIALS); + break; + default: + break; + } + } + + @Override + public Response intercept(Chain chain) + throws IOException { -public class OAuth implements Authentication { - private String accessToken; + Request request = chain.request(); - public String getAccessToken() { - return accessToken; - } + // If the request already have an authorization (eg. Basic auth), do nothing + if (request.header("Authorization") != null) { + return chain.proceed(request); + } - public void setAccessToken(String accessToken) { - this.accessToken = accessToken; - } + // If first time, get the token + OAuthClientRequest oAuthRequest; + if (getAccessToken() == null) { + updateAccessToken(null); + } - @Override - public void applyToParams(List queryParams, Map headerParams) { - if (accessToken != null) { - headerParams.put("Authorization", "Bearer " + accessToken); + if (getAccessToken() != null) { + // Build the request + Builder rb = request.newBuilder(); + + String requestAccessToken = new String(getAccessToken()); + try { + oAuthRequest = new OAuthBearerClientRequest(request.urlString()) + .setAccessToken(requestAccessToken) + .buildHeaderMessage(); + } catch (OAuthSystemException e) { + throw new IOException(e); + } + + for ( Map.Entry header : oAuthRequest.getHeaders().entrySet() ) { + rb.addHeader(header.getKey(), header.getValue()); + } + rb.url( oAuthRequest.getLocationUri()); + + //Execute the request + Response response = chain.proceed(rb.build()); + + // 401 most likely indicates that access token has expired. + // Time to refresh and resend the request + if ( response != null && (response.code() == HTTP_UNAUTHORIZED | response.code() == HTTP_FORBIDDEN) ) { + if (updateAccessToken(requestAccessToken)) { + return intercept( chain ); + } + } + return response; + } else { + return chain.proceed(chain.request()); + } } - } + + /* + * Returns true if the access token has been updated + */ + public synchronized boolean updateAccessToken(String requestAccessToken) throws IOException { + if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) { + try { + OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(this.tokenRequestBuilder.buildBodyMessage()); + if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) { + setAccessToken(accessTokenResponse.getAccessToken()); + if (accessTokenListener != null) { + accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); + } + return getAccessToken().equals(requestAccessToken); + } else { + return false; + } + } catch (OAuthSystemException e) { + throw new IOException(e); + } catch (OAuthProblemException e) { + throw new IOException(e); + } + } + return true; + } + + public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { + this.accessTokenListener = accessTokenListener; + } + + public synchronized String getAccessToken() { + return accessToken; + } + + public synchronized void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + public TokenRequestBuilder getTokenRequestBuilder() { + return tokenRequestBuilder; + } + + public void setTokenRequestBuilder(TokenRequestBuilder tokenRequestBuilder) { + this.tokenRequestBuilder = tokenRequestBuilder; + } + + public AuthenticationRequestBuilder getAuthenticationRequestBuilder() { + return authenticationRequestBuilder; + } + + public void setAuthenticationRequestBuilder(AuthenticationRequestBuilder authenticationRequestBuilder) { + this.authenticationRequestBuilder = authenticationRequestBuilder; + } + } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java new file mode 100644 index 00000000000..c872901ba24 --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java @@ -0,0 +1,69 @@ +package io.swagger.client.auth; + +import java.io.IOException; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.oltu.oauth2.client.HttpClient; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest; +import org.apache.oltu.oauth2.client.response.OAuthClientResponse; +import org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory; +import org.apache.oltu.oauth2.common.exception.OAuthProblemException; +import org.apache.oltu.oauth2.common.exception.OAuthSystemException; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.RequestBody; +import com.squareup.okhttp.Response; + + +public class OAuthOkHttpClient implements HttpClient { + + private OkHttpClient client; + + public OAuthOkHttpClient() { + this.client = new OkHttpClient(); + } + + public OAuthOkHttpClient(OkHttpClient client) { + this.client = client; + } + + public T execute(OAuthClientRequest request, Map headers, + String requestMethod, Class responseClass) + throws OAuthSystemException, OAuthProblemException { + + MediaType mediaType = MediaType.parse("application/json"); + Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri()); + + if(headers != null) { + for (Entry entry : headers.entrySet()) { + if (entry.getKey().equalsIgnoreCase("Content-Type")) { + mediaType = MediaType.parse(entry.getValue()); + } else { + requestBuilder.addHeader(entry.getKey(), entry.getValue()); + } + } + } + + RequestBody body = request.getBody() != null ? RequestBody.create(mediaType, request.getBody()) : null; + requestBuilder.method(requestMethod, body); + + try { + Response response = client.newCall(requestBuilder.build()).execute(); + return OAuthClientResponseFactory.createCustomResponse( + response.body().string(), + response.body().contentType().toString(), + response.code(), + responseClass); + } catch (IOException e) { + throw new OAuthSystemException(e); + } + } + + public void shutdown() { + // Nothing to do here + } + +} diff --git a/samples/client/petstore/java/retrofit2/docs/FakeApi.md b/samples/client/petstore/java/retrofit2/docs/FakeApi.md index 21a4db7c377..decba432a56 100644 --- a/samples/client/petstore/java/retrofit2/docs/FakeApi.md +++ b/samples/client/petstore/java/retrofit2/docs/FakeApi.md @@ -4,13 +4,13 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -[**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters +[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** fake | To test enum query parameters # **testEndpointParameters** -> testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) +> Void testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -37,7 +37,8 @@ LocalDate date = new LocalDate(); // LocalDate | None DateTime dateTime = new DateTime(); // DateTime | None String password = "password_example"; // String | None try { - apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + Void result = apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling FakeApi#testEndpointParameters"); e.printStackTrace(); @@ -63,7 +64,7 @@ Name | Type | Description | Notes ### Return type -null (empty response body) +[**Void**](.md) ### Authorization @@ -76,7 +77,7 @@ No authorization required # **testEnumQueryParameters** -> testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble) +> Void testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble) To test enum query parameters @@ -92,7 +93,8 @@ String enumQueryString = "-efg"; // String | Query parameter enum test (string) BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | Query parameter enum test (double) Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) try { - apiInstance.testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); + Void result = apiInstance.testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); + System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling FakeApi#testEnumQueryParameters"); e.printStackTrace(); @@ -109,7 +111,7 @@ Name | Type | Description | Notes ### Return type -null (empty response body) +[**Void**](.md) ### Authorization diff --git a/samples/client/petstore/java/retrofit2/docs/PetApi.md b/samples/client/petstore/java/retrofit2/docs/PetApi.md index e0314e20e51..40ea199b153 100644 --- a/samples/client/petstore/java/retrofit2/docs/PetApi.md +++ b/samples/client/petstore/java/retrofit2/docs/PetApi.md @@ -4,19 +4,19 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store -[**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet -[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status -[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags -[**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID -[**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet -[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data -[**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image +[**addPet**](PetApi.md#addPet) | **POST** pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletePet) | **DELETE** pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getPetById) | **GET** pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatePet) | **PUT** pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadFile) | **POST** pet/{petId}/uploadImage | uploads an image # **addPet** -> addPet(body) +> Void addPet(body) Add a new pet to the store @@ -40,7 +40,8 @@ petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); PetApi apiInstance = new PetApi(); Pet body = new Pet(); // Pet | Pet object that needs to be added to the store try { - apiInstance.addPet(body); + Void result = apiInstance.addPet(body); + System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling PetApi#addPet"); e.printStackTrace(); @@ -55,7 +56,7 @@ Name | Type | Description | Notes ### Return type -null (empty response body) +[**Void**](.md) ### Authorization @@ -68,7 +69,7 @@ null (empty response body) # **deletePet** -> deletePet(petId, apiKey) +> Void deletePet(petId, apiKey) Deletes a pet @@ -93,7 +94,8 @@ PetApi apiInstance = new PetApi(); Long petId = 789L; // Long | Pet id to delete String apiKey = "apiKey_example"; // String | try { - apiInstance.deletePet(petId, apiKey); + Void result = apiInstance.deletePet(petId, apiKey); + System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling PetApi#deletePet"); e.printStackTrace(); @@ -109,7 +111,7 @@ Name | Type | Description | Notes ### Return type -null (empty response body) +[**Void**](.md) ### Authorization @@ -283,7 +285,7 @@ Name | Type | Description | Notes # **updatePet** -> updatePet(body) +> Void updatePet(body) Update an existing pet @@ -307,7 +309,8 @@ petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); PetApi apiInstance = new PetApi(); Pet body = new Pet(); // Pet | Pet object that needs to be added to the store try { - apiInstance.updatePet(body); + Void result = apiInstance.updatePet(body); + System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling PetApi#updatePet"); e.printStackTrace(); @@ -322,7 +325,7 @@ Name | Type | Description | Notes ### Return type -null (empty response body) +[**Void**](.md) ### Authorization @@ -335,7 +338,7 @@ null (empty response body) # **updatePetWithForm** -> updatePetWithForm(petId, name, status) +> Void updatePetWithForm(petId, name, status) Updates a pet in the store with form data @@ -361,7 +364,8 @@ Long petId = 789L; // Long | ID of pet that needs to be updated String name = "name_example"; // String | Updated name of the pet String status = "status_example"; // String | Updated status of the pet try { - apiInstance.updatePetWithForm(petId, name, status); + Void result = apiInstance.updatePetWithForm(petId, name, status); + System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling PetApi#updatePetWithForm"); e.printStackTrace(); @@ -378,7 +382,7 @@ Name | Type | Description | Notes ### Return type -null (empty response body) +[**Void**](.md) ### Authorization diff --git a/samples/client/petstore/java/retrofit2/docs/StoreApi.md b/samples/client/petstore/java/retrofit2/docs/StoreApi.md index 0b30791725a..30e3c11d440 100644 --- a/samples/client/petstore/java/retrofit2/docs/StoreApi.md +++ b/samples/client/petstore/java/retrofit2/docs/StoreApi.md @@ -4,15 +4,15 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID -[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status -[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID -[**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** store/order/{orderId} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** store/order/{orderId} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** store/order | Place an order for a pet # **deleteOrder** -> deleteOrder(orderId) +> Void deleteOrder(orderId) Delete purchase order by ID @@ -28,7 +28,8 @@ For valid response try integer IDs with value < 1000. Anything above 1000 or StoreApi apiInstance = new StoreApi(); String orderId = "orderId_example"; // String | ID of the order that needs to be deleted try { - apiInstance.deleteOrder(orderId); + Void result = apiInstance.deleteOrder(orderId); + System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling StoreApi#deleteOrder"); e.printStackTrace(); @@ -43,7 +44,7 @@ Name | Type | Description | Notes ### Return type -null (empty response body) +[**Void**](.md) ### Authorization diff --git a/samples/client/petstore/java/retrofit2/docs/UserApi.md b/samples/client/petstore/java/retrofit2/docs/UserApi.md index 8cdc15992ee..b0a0149a50a 100644 --- a/samples/client/petstore/java/retrofit2/docs/UserApi.md +++ b/samples/client/petstore/java/retrofit2/docs/UserApi.md @@ -4,19 +4,19 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**createUser**](UserApi.md#createUser) | **POST** /user | Create user -[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array -[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array -[**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user -[**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name -[**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system -[**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session -[**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user +[**createUser**](UserApi.md#createUser) | **POST** user | Create user +[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteUser) | **DELETE** user/{username} | Delete user +[**getUserByName**](UserApi.md#getUserByName) | **GET** user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginUser) | **GET** user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutUser) | **GET** user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateUser) | **PUT** user/{username} | Updated user # **createUser** -> createUser(body) +> Void createUser(body) Create user @@ -32,7 +32,8 @@ This can only be done by the logged in user. UserApi apiInstance = new UserApi(); User body = new User(); // User | Created user object try { - apiInstance.createUser(body); + Void result = apiInstance.createUser(body); + System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling UserApi#createUser"); e.printStackTrace(); @@ -47,7 +48,7 @@ Name | Type | Description | Notes ### Return type -null (empty response body) +[**Void**](.md) ### Authorization @@ -60,7 +61,7 @@ No authorization required # **createUsersWithArrayInput** -> createUsersWithArrayInput(body) +> Void createUsersWithArrayInput(body) Creates list of users with given input array @@ -76,7 +77,8 @@ Creates list of users with given input array UserApi apiInstance = new UserApi(); List body = Arrays.asList(new User()); // List | List of user object try { - apiInstance.createUsersWithArrayInput(body); + Void result = apiInstance.createUsersWithArrayInput(body); + System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling UserApi#createUsersWithArrayInput"); e.printStackTrace(); @@ -91,7 +93,7 @@ Name | Type | Description | Notes ### Return type -null (empty response body) +[**Void**](.md) ### Authorization @@ -104,7 +106,7 @@ No authorization required # **createUsersWithListInput** -> createUsersWithListInput(body) +> Void createUsersWithListInput(body) Creates list of users with given input array @@ -120,7 +122,8 @@ Creates list of users with given input array UserApi apiInstance = new UserApi(); List body = Arrays.asList(new User()); // List | List of user object try { - apiInstance.createUsersWithListInput(body); + Void result = apiInstance.createUsersWithListInput(body); + System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling UserApi#createUsersWithListInput"); e.printStackTrace(); @@ -135,7 +138,7 @@ Name | Type | Description | Notes ### Return type -null (empty response body) +[**Void**](.md) ### Authorization @@ -148,7 +151,7 @@ No authorization required # **deleteUser** -> deleteUser(username) +> Void deleteUser(username) Delete user @@ -164,7 +167,8 @@ This can only be done by the logged in user. UserApi apiInstance = new UserApi(); String username = "username_example"; // String | The name that needs to be deleted try { - apiInstance.deleteUser(username); + Void result = apiInstance.deleteUser(username); + System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling UserApi#deleteUser"); e.printStackTrace(); @@ -179,7 +183,7 @@ Name | Type | Description | Notes ### Return type -null (empty response body) +[**Void**](.md) ### Authorization @@ -284,7 +288,7 @@ No authorization required # **logoutUser** -> logoutUser() +> Void logoutUser() Logs out current logged in user session @@ -299,7 +303,8 @@ Logs out current logged in user session UserApi apiInstance = new UserApi(); try { - apiInstance.logoutUser(); + Void result = apiInstance.logoutUser(); + System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling UserApi#logoutUser"); e.printStackTrace(); @@ -311,7 +316,7 @@ This endpoint does not need any parameter. ### Return type -null (empty response body) +[**Void**](.md) ### Authorization @@ -324,7 +329,7 @@ No authorization required # **updateUser** -> updateUser(username, body) +> Void updateUser(username, body) Updated user @@ -341,7 +346,8 @@ UserApi apiInstance = new UserApi(); String username = "username_example"; // String | name that need to be deleted User body = new User(); // User | Updated user object try { - apiInstance.updateUser(username, body); + Void result = apiInstance.updateUser(username, body); + System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling UserApi#updateUser"); e.printStackTrace(); @@ -357,7 +363,7 @@ Name | Type | Description | Notes ### Return type -null (empty response body) +[**Void**](.md) ### Authorization diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiCallback.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiCallback.java deleted file mode 100644 index 3ca33cf8017..00000000000 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiCallback.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import java.io.IOException; - -import java.util.Map; -import java.util.List; - -/** - * Callback for asynchronous API call. - * - * @param The return type - */ -public interface ApiCallback { - /** - * This is called when the API call fails. - * - * @param e The exception causing the failure - * @param statusCode Status code of the response if available, otherwise it would be 0 - * @param responseHeaders Headers of the response if available, otherwise it would be null - */ - void onFailure(ApiException e, int statusCode, Map> responseHeaders); - - /** - * This is called when the API call succeeded. - * - * @param result The result deserialized from response - * @param statusCode Status code of the response - * @param responseHeaders Headers of the response - */ - void onSuccess(T result, int statusCode, Map> responseHeaders); - - /** - * This is called when the API upload processing. - * - * @param bytesWritten bytes Written - * @param contentLength content length of request body - * @param done write end - */ - void onUploadProgress(long bytesWritten, long contentLength, boolean done); - - /** - * This is called when the API downlond processing. - * - * @param bytesRead bytes Read - * @param contentLength content lenngth of the response - * @param done Read end - */ - void onDownloadProgress(long bytesRead, long contentLength, boolean done); -} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiException.java deleted file mode 100644 index 3bed001f002..00000000000 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiException.java +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import java.util.Map; -import java.util.List; - - -public class ApiException extends Exception { - private int code = 0; - private Map> responseHeaders = null; - private String responseBody = null; - - public ApiException() {} - - public ApiException(Throwable throwable) { - super(throwable); - } - - public ApiException(String message) { - super(message); - } - - public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { - super(message, throwable); - this.code = code; - this.responseHeaders = responseHeaders; - this.responseBody = responseBody; - } - - public ApiException(String message, int code, Map> responseHeaders, String responseBody) { - this(message, (Throwable) null, code, responseHeaders, responseBody); - } - - public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { - this(message, throwable, code, responseHeaders, null); - } - - public ApiException(int code, Map> responseHeaders, String responseBody) { - this((String) null, (Throwable) null, code, responseHeaders, responseBody); - } - - public ApiException(int code, String message) { - super(message); - this.code = code; - } - - public ApiException(int code, String message, Map> responseHeaders, String responseBody) { - this(code, message); - this.responseHeaders = responseHeaders; - this.responseBody = responseBody; - } - - /** - * Get the HTTP status code. - * - * @return HTTP status code - */ - public int getCode() { - return code; - } - - /** - * Get the HTTP response headers. - * - * @return A map of list of string - */ - public Map> getResponseHeaders() { - return responseHeaders; - } - - /** - * Get the HTTP response body. - * - * @return Response body in the form of string - */ - public String getResponseBody() { - return responseBody; - } -} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiResponse.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiResponse.java deleted file mode 100644 index d7dde1ee939..00000000000 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiResponse.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import java.util.List; -import java.util.Map; - -/** - * API response returned by API call. - * - * @param T The type of data that is deserialized from response body - */ -public class ApiResponse { - final private int statusCode; - final private Map> headers; - final private T data; - - /** - * @param statusCode The status code of HTTP response - * @param headers The headers of HTTP response - */ - public ApiResponse(int statusCode, Map> headers) { - this(statusCode, headers, null); - } - - /** - * @param statusCode The status code of HTTP response - * @param headers The headers of HTTP response - * @param data The object deserialized from response bod - */ - public ApiResponse(int statusCode, Map> headers, T data) { - this.statusCode = statusCode; - this.headers = headers; - this.data = data; - } - - public int getStatusCode() { - return statusCode; - } - - public Map> getHeaders() { - return headers; - } - - public T getData() { - return data; - } -} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/CollectionFormats.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/CollectionFormats.java new file mode 100644 index 00000000000..e96d1561a7c --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/CollectionFormats.java @@ -0,0 +1,95 @@ +package io.swagger.client; + +import java.util.Arrays; +import java.util.List; + +public class CollectionFormats { + + public static class CSVParams { + + protected List params; + + public CSVParams() { + } + + public CSVParams(List params) { + this.params = params; + } + + public CSVParams(String... params) { + this.params = Arrays.asList(params); + } + + public List getParams() { + return params; + } + + public void setParams(List params) { + this.params = params; + } + + @Override + public String toString() { + return StringUtil.join(params.toArray(new String[0]), ","); + } + + } + + public static class SSVParams extends CSVParams { + + public SSVParams() { + } + + public SSVParams(List params) { + super(params); + } + + public SSVParams(String... params) { + super(params); + } + + @Override + public String toString() { + return StringUtil.join(params.toArray(new String[0]), " "); + } + } + + public static class TSVParams extends CSVParams { + + public TSVParams() { + } + + public TSVParams(List params) { + super(params); + } + + public TSVParams(String... params) { + super(params); + } + + @Override + public String toString() { + return StringUtil.join( params.toArray(new String[0]), "\t"); + } + } + + public static class PIPESParams extends CSVParams { + + public PIPESParams() { + } + + public PIPESParams(List params) { + super(params); + } + + public PIPESParams(String... params) { + super(params); + } + + @Override + public String toString() { + return StringUtil.join(params.toArray(new String[0]), "|"); + } + } + +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/Configuration.java deleted file mode 100644 index 5191b9b73c6..00000000000 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/Configuration.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - - -public class Configuration { - private static ApiClient defaultApiClient = new ApiClient(); - - /** - * Get the default API client, which would be used when creating API - * instances without providing an API client. - * - * @return Default API client - */ - public static ApiClient getDefaultApiClient() { - return defaultApiClient; - } - - /** - * Set the default API client, which would be used when creating API - * instances without providing an API client. - * - * @param apiClient API client - */ - public static void setDefaultApiClient(ApiClient apiClient) { - defaultApiClient = apiClient; - } -} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/JSON.java deleted file mode 100644 index 540611eab9d..00000000000 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/JSON.java +++ /dev/null @@ -1,237 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonNull; -import com.google.gson.JsonParseException; -import com.google.gson.JsonPrimitive; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; - -import java.io.IOException; -import java.io.StringReader; -import java.lang.reflect.Type; -import java.util.Date; - -import org.joda.time.DateTime; -import org.joda.time.LocalDate; -import org.joda.time.format.DateTimeFormatter; -import org.joda.time.format.ISODateTimeFormat; - -public class JSON { - private ApiClient apiClient; - private Gson gson; - - /** - * JSON constructor. - * - * @param apiClient An instance of ApiClient - */ - public JSON(ApiClient apiClient) { - this.apiClient = apiClient; - gson = new GsonBuilder() - .registerTypeAdapter(Date.class, new DateAdapter(apiClient)) - .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) - .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) - .create(); - } - - /** - * Get Gson. - * - * @return Gson - */ - public Gson getGson() { - return gson; - } - - /** - * Set Gson. - * - * @param gson Gson - */ - public void setGson(Gson gson) { - this.gson = gson; - } - - /** - * Serialize the given Java object into JSON string. - * - * @param obj Object - * @return String representation of the JSON - */ - public String serialize(Object obj) { - return gson.toJson(obj); - } - - /** - * Deserialize the given JSON string to Java object. - * - * @param Type - * @param body The JSON string - * @param returnType The type to deserialize inot - * @return The deserialized Java object - */ - @SuppressWarnings("unchecked") - public T deserialize(String body, Type returnType) { - try { - if (apiClient.isLenientOnJson()) { - JsonReader jsonReader = new JsonReader(new StringReader(body)); - // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) - jsonReader.setLenient(true); - return gson.fromJson(jsonReader, returnType); - } else { - return gson.fromJson(body, returnType); - } - } catch (JsonParseException e) { - // Fallback processing when failed to parse JSON form response body: - // return the response body string directly for the String return type; - // parse response body into date or datetime for the Date return type. - if (returnType.equals(String.class)) - return (T) body; - else if (returnType.equals(Date.class)) - return (T) apiClient.parseDateOrDatetime(body); - else throw(e); - } - } -} - -class DateAdapter implements JsonSerializer, JsonDeserializer { - private final ApiClient apiClient; - - /** - * Constructor for DateAdapter - * - * @param apiClient Api client - */ - public DateAdapter(ApiClient apiClient) { - super(); - this.apiClient = apiClient; - } - - /** - * Serialize - * - * @param src Date - * @param typeOfSrc Type - * @param context Json Serialization Context - * @return Json Element - */ - @Override - public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { - if (src == null) { - return JsonNull.INSTANCE; - } else { - return new JsonPrimitive(apiClient.formatDatetime(src)); - } - } - - /** - * Deserialize - * - * @param json Json element - * @param date Type - * @param typeOfSrc Type - * @param context Json Serialization Context - * @return Date - * @throw JsonParseException if fail to parse - */ - @Override - public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException { - String str = json.getAsJsonPrimitive().getAsString(); - try { - return apiClient.parseDateOrDatetime(str); - } catch (RuntimeException e) { - throw new JsonParseException(e); - } - } -} - -/** - * Gson TypeAdapter for Joda DateTime type - */ -class DateTimeTypeAdapter extends TypeAdapter { - - private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); - - @Override - public void write(JsonWriter out, DateTime date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - out.value(formatter.print(date)); - } - } - - @Override - public DateTime read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - return formatter.parseDateTime(date); - } - } -} - -/** - * Gson TypeAdapter for Joda LocalDate type - */ -class LocalDateTypeAdapter extends TypeAdapter { - - private final DateTimeFormatter formatter = ISODateTimeFormat.date(); - - @Override - public void write(JsonWriter out, LocalDate date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - out.value(formatter.print(date)); - } - } - - @Override - public LocalDate read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - return formatter.parseLocalDate(date); - } - } -} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/Pair.java deleted file mode 100644 index 15b247eea93..00000000000 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/Pair.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - - -public class Pair { - private String name = ""; - private String value = ""; - - public Pair (String name, String value) { - setName(name); - setValue(value); - } - - private void setName(String name) { - if (!isValidString(name)) return; - - this.name = name; - } - - private void setValue(String value) { - if (!isValidString(value)) return; - - this.value = value; - } - - public String getName() { - return this.name; - } - - public String getValue() { - return this.value; - } - - private boolean isValidString(String arg) { - if (arg == null) return false; - if (arg.trim().isEmpty()) return false; - - return true; - } -} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ProgressRequestBody.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ProgressRequestBody.java deleted file mode 100644 index d9ca742ecd2..00000000000 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ProgressRequestBody.java +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import com.squareup.okhttp.MediaType; -import com.squareup.okhttp.RequestBody; - -import java.io.IOException; - -import okio.Buffer; -import okio.BufferedSink; -import okio.ForwardingSink; -import okio.Okio; -import okio.Sink; - -public class ProgressRequestBody extends RequestBody { - - public interface ProgressRequestListener { - void onRequestProgress(long bytesWritten, long contentLength, boolean done); - } - - private final RequestBody requestBody; - - private final ProgressRequestListener progressListener; - - private BufferedSink bufferedSink; - - public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) { - this.requestBody = requestBody; - this.progressListener = progressListener; - } - - @Override - public MediaType contentType() { - return requestBody.contentType(); - } - - @Override - public long contentLength() throws IOException { - return requestBody.contentLength(); - } - - @Override - public void writeTo(BufferedSink sink) throws IOException { - if (bufferedSink == null) { - bufferedSink = Okio.buffer(sink(sink)); - } - - requestBody.writeTo(bufferedSink); - bufferedSink.flush(); - - } - - private Sink sink(Sink sink) { - return new ForwardingSink(sink) { - - long bytesWritten = 0L; - long contentLength = 0L; - - @Override - public void write(Buffer source, long byteCount) throws IOException { - super.write(source, byteCount); - if (contentLength == 0) { - contentLength = contentLength(); - } - - bytesWritten += byteCount; - progressListener.onRequestProgress(bytesWritten, contentLength, bytesWritten == contentLength); - } - }; - } -} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ProgressResponseBody.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ProgressResponseBody.java deleted file mode 100644 index f8af685999d..00000000000 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ProgressResponseBody.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import com.squareup.okhttp.MediaType; -import com.squareup.okhttp.ResponseBody; - -import java.io.IOException; - -import okio.Buffer; -import okio.BufferedSource; -import okio.ForwardingSource; -import okio.Okio; -import okio.Source; - -public class ProgressResponseBody extends ResponseBody { - - public interface ProgressListener { - void update(long bytesRead, long contentLength, boolean done); - } - - private final ResponseBody responseBody; - private final ProgressListener progressListener; - private BufferedSource bufferedSource; - - public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) { - this.responseBody = responseBody; - this.progressListener = progressListener; - } - - @Override - public MediaType contentType() { - return responseBody.contentType(); - } - - @Override - public long contentLength() throws IOException { - return responseBody.contentLength(); - } - - @Override - public BufferedSource source() throws IOException { - if (bufferedSource == null) { - bufferedSource = Okio.buffer(source(responseBody.source())); - } - return bufferedSource; - } - - private Source source(Source source) { - return new ForwardingSource(source) { - long totalBytesRead = 0L; - - @Override - public long read(Buffer sink, long byteCount) throws IOException { - long bytesRead = super.read(sink, byteCount); - // read() returns the number of bytes read, or -1 if this source is exhausted. - totalBytesRead += bytesRead != -1 ? bytesRead : 0; - progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1); - return bytesRead; - } - }; - } -} - - diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java index 4595a80e745..042a6ba37e5 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java @@ -33,12 +33,12 @@ public interface FakeApi { * @param date None (optional) * @param dateTime None (optional) * @param password None (optional) - * @return Call<Object> + * @return Call<Void> */ @FormUrlEncoded - @POST("/fake") - Call testEndpointParameters( + @POST("fake") + Call testEndpointParameters( @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password ); @@ -48,12 +48,12 @@ Call testEndpointParameters( * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) * @param enumQueryInteger Query parameter enum test (double) (optional) * @param enumQueryDouble Query parameter enum test (double) (optional) - * @return Call<Object> + * @return Call<Void> */ @FormUrlEncoded - @GET("/fake") - Call testEnumQueryParameters( + @GET("fake") + Call testEnumQueryParameters( @Field("enum_query_string") String enumQueryString, @Query("enum_query_integer") BigDecimal enumQueryInteger, @Field("enum_query_double") Double enumQueryDouble ); diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java index 523bde3b9cc..a55cb2ee17f 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java @@ -22,11 +22,11 @@ public interface PetApi { * Add a new pet to the store * * @param body Pet object that needs to be added to the store (required) - * @return Call<Object> + * @return Call<Void> */ - @POST("/pet") - Call addPet( + @POST("pet") + Call addPet( @Body Pet body ); @@ -35,11 +35,11 @@ Call addPet( * * @param petId Pet id to delete (required) * @param apiKey (optional) - * @return Call<Object> + * @return Call<Void> */ - @DELETE("/pet/{petId}") - Call deletePet( + @DELETE("pet/{petId}") + Call deletePet( @Path("petId") Long petId, @Header("api_key") String apiKey ); @@ -50,7 +50,7 @@ Call deletePet( * @return Call<List> */ - @GET("/pet/findByStatus") + @GET("pet/findByStatus") Call> findPetsByStatus( @Query("status") CSVParams status ); @@ -62,7 +62,7 @@ Call> findPetsByStatus( * @return Call<List> */ - @GET("/pet/findByTags") + @GET("pet/findByTags") Call> findPetsByTags( @Query("tags") CSVParams tags ); @@ -74,7 +74,7 @@ Call> findPetsByTags( * @return Call<Pet> */ - @GET("/pet/{petId}") + @GET("pet/{petId}") Call getPetById( @Path("petId") Long petId ); @@ -83,11 +83,11 @@ Call getPetById( * Update an existing pet * * @param body Pet object that needs to be added to the store (required) - * @return Call<Object> + * @return Call<Void> */ - @PUT("/pet") - Call updatePet( + @PUT("pet") + Call updatePet( @Body Pet body ); @@ -97,12 +97,12 @@ Call updatePet( * @param petId ID of pet that needs to be updated (required) * @param name Updated name of the pet (optional) * @param status Updated status of the pet (optional) - * @return Call<Object> + * @return Call<Void> */ @FormUrlEncoded - @POST("/pet/{petId}") - Call updatePetWithForm( + @POST("pet/{petId}") + Call updatePetWithForm( @Path("petId") Long petId, @Field("name") String name, @Field("status") String status ); @@ -115,10 +115,10 @@ Call updatePetWithForm( * @return Call<ModelApiResponse> */ - @FormUrlEncoded - @POST("/pet/{petId}/uploadImage") + @Multipart + @POST("pet/{petId}/uploadImage") Call uploadFile( - @Path("petId") Long petId, @Field("additionalMetadata") String additionalMetadata, @Field("file\"; filename=\"file\"") RequestBody file + @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file\"; filename=\"file\"") RequestBody file ); } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java index 3a811ac7a2e..3e19600bedb 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java @@ -20,11 +20,11 @@ public interface StoreApi { * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * @param orderId ID of the order that needs to be deleted (required) - * @return Call<Object> + * @return Call<Void> */ - @DELETE("/store/order/{orderId}") - Call deleteOrder( + @DELETE("store/order/{orderId}") + Call deleteOrder( @Path("orderId") String orderId ); @@ -34,7 +34,7 @@ Call deleteOrder( * @return Call<Map> */ - @GET("/store/inventory") + @GET("store/inventory") Call> getInventory(); @@ -45,7 +45,7 @@ Call deleteOrder( * @return Call<Order> */ - @GET("/store/order/{orderId}") + @GET("store/order/{orderId}") Call getOrderById( @Path("orderId") Long orderId ); @@ -57,7 +57,7 @@ Call getOrderById( * @return Call<Order> */ - @POST("/store/order") + @POST("store/order") Call placeOrder( @Body Order body ); diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java index 8c564b8423b..3fc76b6a1b2 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java @@ -20,11 +20,11 @@ public interface UserApi { * Create user * This can only be done by the logged in user. * @param body Created user object (required) - * @return Call<Object> + * @return Call<Void> */ - @POST("/user") - Call createUser( + @POST("user") + Call createUser( @Body User body ); @@ -32,11 +32,11 @@ Call createUser( * Creates list of users with given input array * * @param body List of user object (required) - * @return Call<Object> + * @return Call<Void> */ - @POST("/user/createWithArray") - Call createUsersWithArrayInput( + @POST("user/createWithArray") + Call createUsersWithArrayInput( @Body List body ); @@ -44,11 +44,11 @@ Call createUsersWithArrayInput( * Creates list of users with given input array * * @param body List of user object (required) - * @return Call<Object> + * @return Call<Void> */ - @POST("/user/createWithList") - Call createUsersWithListInput( + @POST("user/createWithList") + Call createUsersWithListInput( @Body List body ); @@ -56,11 +56,11 @@ Call createUsersWithListInput( * Delete user * This can only be done by the logged in user. * @param username The name that needs to be deleted (required) - * @return Call<Object> + * @return Call<Void> */ - @DELETE("/user/{username}") - Call deleteUser( + @DELETE("user/{username}") + Call deleteUser( @Path("username") String username ); @@ -71,7 +71,7 @@ Call deleteUser( * @return Call<User> */ - @GET("/user/{username}") + @GET("user/{username}") Call getUserByName( @Path("username") String username ); @@ -84,7 +84,7 @@ Call getUserByName( * @return Call<String> */ - @GET("/user/login") + @GET("user/login") Call loginUser( @Query("username") String username, @Query("password") String password ); @@ -92,11 +92,11 @@ Call loginUser( /** * Logs out current logged in user session * - * @return Call<Object> + * @return Call<Void> */ - @GET("/user/logout") - Call logoutUser(); + @GET("user/logout") + Call logoutUser(); /** @@ -104,11 +104,11 @@ Call loginUser( * This can only be done by the logged in user. * @param username name that need to be deleted (required) * @param body Updated user object (required) - * @return Call<Object> + * @return Call<Void> */ - @PUT("/user/{username}") - Call updateUser( + @PUT("user/{username}") + Call updateUser( @Path("username") String username, @Body User body ); diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/Authentication.java deleted file mode 100644 index 221a7d9dd1f..00000000000 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/Authentication.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client.auth; - -import io.swagger.client.Pair; - -import java.util.Map; -import java.util.List; - -public interface Authentication { - /** - * Apply authentication settings to header and query params. - * - * @param queryParams List of query parameters - * @param headerParams Map of header parameters - */ - void applyToParams(List queryParams, Map headerParams); -} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java new file mode 100644 index 00000000000..c9b6e124d51 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java @@ -0,0 +1,72 @@ +package io.swagger.client.auth; + +import java.io.IOException; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.oltu.oauth2.client.HttpClient; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest; +import org.apache.oltu.oauth2.client.response.OAuthClientResponse; +import org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory; +import org.apache.oltu.oauth2.common.exception.OAuthProblemException; +import org.apache.oltu.oauth2.common.exception.OAuthSystemException; + + +import okhttp3.Interceptor; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Request.Builder; +import okhttp3.Response; +import okhttp3.MediaType; +import okhttp3.RequestBody; + + +public class OAuthOkHttpClient implements HttpClient { + + private OkHttpClient client; + + public OAuthOkHttpClient() { + this.client = new OkHttpClient(); + } + + public OAuthOkHttpClient(OkHttpClient client) { + this.client = client; + } + + public T execute(OAuthClientRequest request, Map headers, + String requestMethod, Class responseClass) + throws OAuthSystemException, OAuthProblemException { + + MediaType mediaType = MediaType.parse("application/json"); + Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri()); + + if(headers != null) { + for (Entry entry : headers.entrySet()) { + if (entry.getKey().equalsIgnoreCase("Content-Type")) { + mediaType = MediaType.parse(entry.getValue()); + } else { + requestBuilder.addHeader(entry.getKey(), entry.getValue()); + } + } + } + + RequestBody body = request.getBody() != null ? RequestBody.create(mediaType, request.getBody()) : null; + requestBuilder.method(requestMethod, body); + + try { + Response response = client.newCall(requestBuilder.build()).execute(); + return OAuthClientResponseFactory.createCustomResponse( + response.body().string(), + response.body().contentType().toString(), + response.code(), + responseClass); + } catch (IOException e) { + throw new OAuthSystemException(e); + } + } + + public void shutdown() { + // Nothing to do here + } + +} diff --git a/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md b/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md index 21a4db7c377..decba432a56 100644 --- a/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md +++ b/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md @@ -4,13 +4,13 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -[**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters +[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** fake | To test enum query parameters # **testEndpointParameters** -> testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) +> Void testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -37,7 +37,8 @@ LocalDate date = new LocalDate(); // LocalDate | None DateTime dateTime = new DateTime(); // DateTime | None String password = "password_example"; // String | None try { - apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + Void result = apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling FakeApi#testEndpointParameters"); e.printStackTrace(); @@ -63,7 +64,7 @@ Name | Type | Description | Notes ### Return type -null (empty response body) +[**Void**](.md) ### Authorization @@ -76,7 +77,7 @@ No authorization required # **testEnumQueryParameters** -> testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble) +> Void testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble) To test enum query parameters @@ -92,7 +93,8 @@ String enumQueryString = "-efg"; // String | Query parameter enum test (string) BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | Query parameter enum test (double) Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) try { - apiInstance.testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); + Void result = apiInstance.testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); + System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling FakeApi#testEnumQueryParameters"); e.printStackTrace(); @@ -109,7 +111,7 @@ Name | Type | Description | Notes ### Return type -null (empty response body) +[**Void**](.md) ### Authorization diff --git a/samples/client/petstore/java/retrofit2rx/docs/PetApi.md b/samples/client/petstore/java/retrofit2rx/docs/PetApi.md index e0314e20e51..40ea199b153 100644 --- a/samples/client/petstore/java/retrofit2rx/docs/PetApi.md +++ b/samples/client/petstore/java/retrofit2rx/docs/PetApi.md @@ -4,19 +4,19 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store -[**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet -[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status -[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags -[**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID -[**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet -[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data -[**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image +[**addPet**](PetApi.md#addPet) | **POST** pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletePet) | **DELETE** pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getPetById) | **GET** pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatePet) | **PUT** pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadFile) | **POST** pet/{petId}/uploadImage | uploads an image # **addPet** -> addPet(body) +> Void addPet(body) Add a new pet to the store @@ -40,7 +40,8 @@ petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); PetApi apiInstance = new PetApi(); Pet body = new Pet(); // Pet | Pet object that needs to be added to the store try { - apiInstance.addPet(body); + Void result = apiInstance.addPet(body); + System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling PetApi#addPet"); e.printStackTrace(); @@ -55,7 +56,7 @@ Name | Type | Description | Notes ### Return type -null (empty response body) +[**Void**](.md) ### Authorization @@ -68,7 +69,7 @@ null (empty response body) # **deletePet** -> deletePet(petId, apiKey) +> Void deletePet(petId, apiKey) Deletes a pet @@ -93,7 +94,8 @@ PetApi apiInstance = new PetApi(); Long petId = 789L; // Long | Pet id to delete String apiKey = "apiKey_example"; // String | try { - apiInstance.deletePet(petId, apiKey); + Void result = apiInstance.deletePet(petId, apiKey); + System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling PetApi#deletePet"); e.printStackTrace(); @@ -109,7 +111,7 @@ Name | Type | Description | Notes ### Return type -null (empty response body) +[**Void**](.md) ### Authorization @@ -283,7 +285,7 @@ Name | Type | Description | Notes # **updatePet** -> updatePet(body) +> Void updatePet(body) Update an existing pet @@ -307,7 +309,8 @@ petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); PetApi apiInstance = new PetApi(); Pet body = new Pet(); // Pet | Pet object that needs to be added to the store try { - apiInstance.updatePet(body); + Void result = apiInstance.updatePet(body); + System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling PetApi#updatePet"); e.printStackTrace(); @@ -322,7 +325,7 @@ Name | Type | Description | Notes ### Return type -null (empty response body) +[**Void**](.md) ### Authorization @@ -335,7 +338,7 @@ null (empty response body) # **updatePetWithForm** -> updatePetWithForm(petId, name, status) +> Void updatePetWithForm(petId, name, status) Updates a pet in the store with form data @@ -361,7 +364,8 @@ Long petId = 789L; // Long | ID of pet that needs to be updated String name = "name_example"; // String | Updated name of the pet String status = "status_example"; // String | Updated status of the pet try { - apiInstance.updatePetWithForm(petId, name, status); + Void result = apiInstance.updatePetWithForm(petId, name, status); + System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling PetApi#updatePetWithForm"); e.printStackTrace(); @@ -378,7 +382,7 @@ Name | Type | Description | Notes ### Return type -null (empty response body) +[**Void**](.md) ### Authorization diff --git a/samples/client/petstore/java/retrofit2rx/docs/StoreApi.md b/samples/client/petstore/java/retrofit2rx/docs/StoreApi.md index 0b30791725a..30e3c11d440 100644 --- a/samples/client/petstore/java/retrofit2rx/docs/StoreApi.md +++ b/samples/client/petstore/java/retrofit2rx/docs/StoreApi.md @@ -4,15 +4,15 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID -[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status -[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID -[**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** store/order/{orderId} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** store/order/{orderId} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** store/order | Place an order for a pet # **deleteOrder** -> deleteOrder(orderId) +> Void deleteOrder(orderId) Delete purchase order by ID @@ -28,7 +28,8 @@ For valid response try integer IDs with value < 1000. Anything above 1000 or StoreApi apiInstance = new StoreApi(); String orderId = "orderId_example"; // String | ID of the order that needs to be deleted try { - apiInstance.deleteOrder(orderId); + Void result = apiInstance.deleteOrder(orderId); + System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling StoreApi#deleteOrder"); e.printStackTrace(); @@ -43,7 +44,7 @@ Name | Type | Description | Notes ### Return type -null (empty response body) +[**Void**](.md) ### Authorization diff --git a/samples/client/petstore/java/retrofit2rx/docs/UserApi.md b/samples/client/petstore/java/retrofit2rx/docs/UserApi.md index 8cdc15992ee..b0a0149a50a 100644 --- a/samples/client/petstore/java/retrofit2rx/docs/UserApi.md +++ b/samples/client/petstore/java/retrofit2rx/docs/UserApi.md @@ -4,19 +4,19 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**createUser**](UserApi.md#createUser) | **POST** /user | Create user -[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array -[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array -[**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user -[**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name -[**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system -[**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session -[**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user +[**createUser**](UserApi.md#createUser) | **POST** user | Create user +[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteUser) | **DELETE** user/{username} | Delete user +[**getUserByName**](UserApi.md#getUserByName) | **GET** user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginUser) | **GET** user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutUser) | **GET** user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateUser) | **PUT** user/{username} | Updated user # **createUser** -> createUser(body) +> Void createUser(body) Create user @@ -32,7 +32,8 @@ This can only be done by the logged in user. UserApi apiInstance = new UserApi(); User body = new User(); // User | Created user object try { - apiInstance.createUser(body); + Void result = apiInstance.createUser(body); + System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling UserApi#createUser"); e.printStackTrace(); @@ -47,7 +48,7 @@ Name | Type | Description | Notes ### Return type -null (empty response body) +[**Void**](.md) ### Authorization @@ -60,7 +61,7 @@ No authorization required # **createUsersWithArrayInput** -> createUsersWithArrayInput(body) +> Void createUsersWithArrayInput(body) Creates list of users with given input array @@ -76,7 +77,8 @@ Creates list of users with given input array UserApi apiInstance = new UserApi(); List body = Arrays.asList(new User()); // List | List of user object try { - apiInstance.createUsersWithArrayInput(body); + Void result = apiInstance.createUsersWithArrayInput(body); + System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling UserApi#createUsersWithArrayInput"); e.printStackTrace(); @@ -91,7 +93,7 @@ Name | Type | Description | Notes ### Return type -null (empty response body) +[**Void**](.md) ### Authorization @@ -104,7 +106,7 @@ No authorization required # **createUsersWithListInput** -> createUsersWithListInput(body) +> Void createUsersWithListInput(body) Creates list of users with given input array @@ -120,7 +122,8 @@ Creates list of users with given input array UserApi apiInstance = new UserApi(); List body = Arrays.asList(new User()); // List | List of user object try { - apiInstance.createUsersWithListInput(body); + Void result = apiInstance.createUsersWithListInput(body); + System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling UserApi#createUsersWithListInput"); e.printStackTrace(); @@ -135,7 +138,7 @@ Name | Type | Description | Notes ### Return type -null (empty response body) +[**Void**](.md) ### Authorization @@ -148,7 +151,7 @@ No authorization required # **deleteUser** -> deleteUser(username) +> Void deleteUser(username) Delete user @@ -164,7 +167,8 @@ This can only be done by the logged in user. UserApi apiInstance = new UserApi(); String username = "username_example"; // String | The name that needs to be deleted try { - apiInstance.deleteUser(username); + Void result = apiInstance.deleteUser(username); + System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling UserApi#deleteUser"); e.printStackTrace(); @@ -179,7 +183,7 @@ Name | Type | Description | Notes ### Return type -null (empty response body) +[**Void**](.md) ### Authorization @@ -284,7 +288,7 @@ No authorization required # **logoutUser** -> logoutUser() +> Void logoutUser() Logs out current logged in user session @@ -299,7 +303,8 @@ Logs out current logged in user session UserApi apiInstance = new UserApi(); try { - apiInstance.logoutUser(); + Void result = apiInstance.logoutUser(); + System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling UserApi#logoutUser"); e.printStackTrace(); @@ -311,7 +316,7 @@ This endpoint does not need any parameter. ### Return type -null (empty response body) +[**Void**](.md) ### Authorization @@ -324,7 +329,7 @@ No authorization required # **updateUser** -> updateUser(username, body) +> Void updateUser(username, body) Updated user @@ -341,7 +346,8 @@ UserApi apiInstance = new UserApi(); String username = "username_example"; // String | name that need to be deleted User body = new User(); // User | Updated user object try { - apiInstance.updateUser(username, body); + Void result = apiInstance.updateUser(username, body); + System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling UserApi#updateUser"); e.printStackTrace(); @@ -357,7 +363,7 @@ Name | Type | Description | Notes ### Return type -null (empty response body) +[**Void**](.md) ### Authorization diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiCallback.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiCallback.java deleted file mode 100644 index 3ca33cf8017..00000000000 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiCallback.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import java.io.IOException; - -import java.util.Map; -import java.util.List; - -/** - * Callback for asynchronous API call. - * - * @param The return type - */ -public interface ApiCallback { - /** - * This is called when the API call fails. - * - * @param e The exception causing the failure - * @param statusCode Status code of the response if available, otherwise it would be 0 - * @param responseHeaders Headers of the response if available, otherwise it would be null - */ - void onFailure(ApiException e, int statusCode, Map> responseHeaders); - - /** - * This is called when the API call succeeded. - * - * @param result The result deserialized from response - * @param statusCode Status code of the response - * @param responseHeaders Headers of the response - */ - void onSuccess(T result, int statusCode, Map> responseHeaders); - - /** - * This is called when the API upload processing. - * - * @param bytesWritten bytes Written - * @param contentLength content length of request body - * @param done write end - */ - void onUploadProgress(long bytesWritten, long contentLength, boolean done); - - /** - * This is called when the API downlond processing. - * - * @param bytesRead bytes Read - * @param contentLength content lenngth of the response - * @param done Read end - */ - void onDownloadProgress(long bytesRead, long contentLength, boolean done); -} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiException.java deleted file mode 100644 index 3bed001f002..00000000000 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiException.java +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import java.util.Map; -import java.util.List; - - -public class ApiException extends Exception { - private int code = 0; - private Map> responseHeaders = null; - private String responseBody = null; - - public ApiException() {} - - public ApiException(Throwable throwable) { - super(throwable); - } - - public ApiException(String message) { - super(message); - } - - public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { - super(message, throwable); - this.code = code; - this.responseHeaders = responseHeaders; - this.responseBody = responseBody; - } - - public ApiException(String message, int code, Map> responseHeaders, String responseBody) { - this(message, (Throwable) null, code, responseHeaders, responseBody); - } - - public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { - this(message, throwable, code, responseHeaders, null); - } - - public ApiException(int code, Map> responseHeaders, String responseBody) { - this((String) null, (Throwable) null, code, responseHeaders, responseBody); - } - - public ApiException(int code, String message) { - super(message); - this.code = code; - } - - public ApiException(int code, String message, Map> responseHeaders, String responseBody) { - this(code, message); - this.responseHeaders = responseHeaders; - this.responseBody = responseBody; - } - - /** - * Get the HTTP status code. - * - * @return HTTP status code - */ - public int getCode() { - return code; - } - - /** - * Get the HTTP response headers. - * - * @return A map of list of string - */ - public Map> getResponseHeaders() { - return responseHeaders; - } - - /** - * Get the HTTP response body. - * - * @return Response body in the form of string - */ - public String getResponseBody() { - return responseBody; - } -} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiResponse.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiResponse.java deleted file mode 100644 index d7dde1ee939..00000000000 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiResponse.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import java.util.List; -import java.util.Map; - -/** - * API response returned by API call. - * - * @param T The type of data that is deserialized from response body - */ -public class ApiResponse { - final private int statusCode; - final private Map> headers; - final private T data; - - /** - * @param statusCode The status code of HTTP response - * @param headers The headers of HTTP response - */ - public ApiResponse(int statusCode, Map> headers) { - this(statusCode, headers, null); - } - - /** - * @param statusCode The status code of HTTP response - * @param headers The headers of HTTP response - * @param data The object deserialized from response bod - */ - public ApiResponse(int statusCode, Map> headers, T data) { - this.statusCode = statusCode; - this.headers = headers; - this.data = data; - } - - public int getStatusCode() { - return statusCode; - } - - public Map> getHeaders() { - return headers; - } - - public T getData() { - return data; - } -} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/CollectionFormats.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/CollectionFormats.java new file mode 100644 index 00000000000..e96d1561a7c --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/CollectionFormats.java @@ -0,0 +1,95 @@ +package io.swagger.client; + +import java.util.Arrays; +import java.util.List; + +public class CollectionFormats { + + public static class CSVParams { + + protected List params; + + public CSVParams() { + } + + public CSVParams(List params) { + this.params = params; + } + + public CSVParams(String... params) { + this.params = Arrays.asList(params); + } + + public List getParams() { + return params; + } + + public void setParams(List params) { + this.params = params; + } + + @Override + public String toString() { + return StringUtil.join(params.toArray(new String[0]), ","); + } + + } + + public static class SSVParams extends CSVParams { + + public SSVParams() { + } + + public SSVParams(List params) { + super(params); + } + + public SSVParams(String... params) { + super(params); + } + + @Override + public String toString() { + return StringUtil.join(params.toArray(new String[0]), " "); + } + } + + public static class TSVParams extends CSVParams { + + public TSVParams() { + } + + public TSVParams(List params) { + super(params); + } + + public TSVParams(String... params) { + super(params); + } + + @Override + public String toString() { + return StringUtil.join( params.toArray(new String[0]), "\t"); + } + } + + public static class PIPESParams extends CSVParams { + + public PIPESParams() { + } + + public PIPESParams(List params) { + super(params); + } + + public PIPESParams(String... params) { + super(params); + } + + @Override + public String toString() { + return StringUtil.join(params.toArray(new String[0]), "|"); + } + } + +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/Configuration.java deleted file mode 100644 index 5191b9b73c6..00000000000 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/Configuration.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - - -public class Configuration { - private static ApiClient defaultApiClient = new ApiClient(); - - /** - * Get the default API client, which would be used when creating API - * instances without providing an API client. - * - * @return Default API client - */ - public static ApiClient getDefaultApiClient() { - return defaultApiClient; - } - - /** - * Set the default API client, which would be used when creating API - * instances without providing an API client. - * - * @param apiClient API client - */ - public static void setDefaultApiClient(ApiClient apiClient) { - defaultApiClient = apiClient; - } -} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/JSON.java deleted file mode 100644 index 540611eab9d..00000000000 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/JSON.java +++ /dev/null @@ -1,237 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonNull; -import com.google.gson.JsonParseException; -import com.google.gson.JsonPrimitive; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; - -import java.io.IOException; -import java.io.StringReader; -import java.lang.reflect.Type; -import java.util.Date; - -import org.joda.time.DateTime; -import org.joda.time.LocalDate; -import org.joda.time.format.DateTimeFormatter; -import org.joda.time.format.ISODateTimeFormat; - -public class JSON { - private ApiClient apiClient; - private Gson gson; - - /** - * JSON constructor. - * - * @param apiClient An instance of ApiClient - */ - public JSON(ApiClient apiClient) { - this.apiClient = apiClient; - gson = new GsonBuilder() - .registerTypeAdapter(Date.class, new DateAdapter(apiClient)) - .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) - .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) - .create(); - } - - /** - * Get Gson. - * - * @return Gson - */ - public Gson getGson() { - return gson; - } - - /** - * Set Gson. - * - * @param gson Gson - */ - public void setGson(Gson gson) { - this.gson = gson; - } - - /** - * Serialize the given Java object into JSON string. - * - * @param obj Object - * @return String representation of the JSON - */ - public String serialize(Object obj) { - return gson.toJson(obj); - } - - /** - * Deserialize the given JSON string to Java object. - * - * @param Type - * @param body The JSON string - * @param returnType The type to deserialize inot - * @return The deserialized Java object - */ - @SuppressWarnings("unchecked") - public T deserialize(String body, Type returnType) { - try { - if (apiClient.isLenientOnJson()) { - JsonReader jsonReader = new JsonReader(new StringReader(body)); - // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) - jsonReader.setLenient(true); - return gson.fromJson(jsonReader, returnType); - } else { - return gson.fromJson(body, returnType); - } - } catch (JsonParseException e) { - // Fallback processing when failed to parse JSON form response body: - // return the response body string directly for the String return type; - // parse response body into date or datetime for the Date return type. - if (returnType.equals(String.class)) - return (T) body; - else if (returnType.equals(Date.class)) - return (T) apiClient.parseDateOrDatetime(body); - else throw(e); - } - } -} - -class DateAdapter implements JsonSerializer, JsonDeserializer { - private final ApiClient apiClient; - - /** - * Constructor for DateAdapter - * - * @param apiClient Api client - */ - public DateAdapter(ApiClient apiClient) { - super(); - this.apiClient = apiClient; - } - - /** - * Serialize - * - * @param src Date - * @param typeOfSrc Type - * @param context Json Serialization Context - * @return Json Element - */ - @Override - public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { - if (src == null) { - return JsonNull.INSTANCE; - } else { - return new JsonPrimitive(apiClient.formatDatetime(src)); - } - } - - /** - * Deserialize - * - * @param json Json element - * @param date Type - * @param typeOfSrc Type - * @param context Json Serialization Context - * @return Date - * @throw JsonParseException if fail to parse - */ - @Override - public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException { - String str = json.getAsJsonPrimitive().getAsString(); - try { - return apiClient.parseDateOrDatetime(str); - } catch (RuntimeException e) { - throw new JsonParseException(e); - } - } -} - -/** - * Gson TypeAdapter for Joda DateTime type - */ -class DateTimeTypeAdapter extends TypeAdapter { - - private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); - - @Override - public void write(JsonWriter out, DateTime date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - out.value(formatter.print(date)); - } - } - - @Override - public DateTime read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - return formatter.parseDateTime(date); - } - } -} - -/** - * Gson TypeAdapter for Joda LocalDate type - */ -class LocalDateTypeAdapter extends TypeAdapter { - - private final DateTimeFormatter formatter = ISODateTimeFormat.date(); - - @Override - public void write(JsonWriter out, LocalDate date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - out.value(formatter.print(date)); - } - } - - @Override - public LocalDate read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - return formatter.parseLocalDate(date); - } - } -} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/Pair.java deleted file mode 100644 index 15b247eea93..00000000000 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/Pair.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - - -public class Pair { - private String name = ""; - private String value = ""; - - public Pair (String name, String value) { - setName(name); - setValue(value); - } - - private void setName(String name) { - if (!isValidString(name)) return; - - this.name = name; - } - - private void setValue(String value) { - if (!isValidString(value)) return; - - this.value = value; - } - - public String getName() { - return this.name; - } - - public String getValue() { - return this.value; - } - - private boolean isValidString(String arg) { - if (arg == null) return false; - if (arg.trim().isEmpty()) return false; - - return true; - } -} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ProgressRequestBody.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ProgressRequestBody.java deleted file mode 100644 index d9ca742ecd2..00000000000 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ProgressRequestBody.java +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import com.squareup.okhttp.MediaType; -import com.squareup.okhttp.RequestBody; - -import java.io.IOException; - -import okio.Buffer; -import okio.BufferedSink; -import okio.ForwardingSink; -import okio.Okio; -import okio.Sink; - -public class ProgressRequestBody extends RequestBody { - - public interface ProgressRequestListener { - void onRequestProgress(long bytesWritten, long contentLength, boolean done); - } - - private final RequestBody requestBody; - - private final ProgressRequestListener progressListener; - - private BufferedSink bufferedSink; - - public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) { - this.requestBody = requestBody; - this.progressListener = progressListener; - } - - @Override - public MediaType contentType() { - return requestBody.contentType(); - } - - @Override - public long contentLength() throws IOException { - return requestBody.contentLength(); - } - - @Override - public void writeTo(BufferedSink sink) throws IOException { - if (bufferedSink == null) { - bufferedSink = Okio.buffer(sink(sink)); - } - - requestBody.writeTo(bufferedSink); - bufferedSink.flush(); - - } - - private Sink sink(Sink sink) { - return new ForwardingSink(sink) { - - long bytesWritten = 0L; - long contentLength = 0L; - - @Override - public void write(Buffer source, long byteCount) throws IOException { - super.write(source, byteCount); - if (contentLength == 0) { - contentLength = contentLength(); - } - - bytesWritten += byteCount; - progressListener.onRequestProgress(bytesWritten, contentLength, bytesWritten == contentLength); - } - }; - } -} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ProgressResponseBody.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ProgressResponseBody.java deleted file mode 100644 index f8af685999d..00000000000 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ProgressResponseBody.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client; - -import com.squareup.okhttp.MediaType; -import com.squareup.okhttp.ResponseBody; - -import java.io.IOException; - -import okio.Buffer; -import okio.BufferedSource; -import okio.ForwardingSource; -import okio.Okio; -import okio.Source; - -public class ProgressResponseBody extends ResponseBody { - - public interface ProgressListener { - void update(long bytesRead, long contentLength, boolean done); - } - - private final ResponseBody responseBody; - private final ProgressListener progressListener; - private BufferedSource bufferedSource; - - public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) { - this.responseBody = responseBody; - this.progressListener = progressListener; - } - - @Override - public MediaType contentType() { - return responseBody.contentType(); - } - - @Override - public long contentLength() throws IOException { - return responseBody.contentLength(); - } - - @Override - public BufferedSource source() throws IOException { - if (bufferedSource == null) { - bufferedSource = Okio.buffer(source(responseBody.source())); - } - return bufferedSource; - } - - private Source source(Source source) { - return new ForwardingSource(source) { - long totalBytesRead = 0L; - - @Override - public long read(Buffer sink, long byteCount) throws IOException { - long bytesRead = super.read(sink, byteCount); - // read() returns the number of bytes read, or -1 if this source is exhausted. - totalBytesRead += bytesRead != -1 ? bytesRead : 0; - progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1); - return bytesRead; - } - }; - } -} - - diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java index ce407e91f48..7a6fec402bb 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java @@ -33,12 +33,12 @@ public interface FakeApi { * @param date None (optional) * @param dateTime None (optional) * @param password None (optional) - * @return Call<Object> + * @return Call<Void> */ @FormUrlEncoded - @POST("/fake") - Observable testEndpointParameters( + @POST("fake") + Observable testEndpointParameters( @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password ); @@ -48,12 +48,12 @@ Observable testEndpointParameters( * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) * @param enumQueryInteger Query parameter enum test (double) (optional) * @param enumQueryDouble Query parameter enum test (double) (optional) - * @return Call<Object> + * @return Call<Void> */ @FormUrlEncoded - @GET("/fake") - Observable testEnumQueryParameters( + @GET("fake") + Observable testEnumQueryParameters( @Field("enum_query_string") String enumQueryString, @Query("enum_query_integer") BigDecimal enumQueryInteger, @Field("enum_query_double") Double enumQueryDouble ); diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java index 15e0c85a2d4..94e2161d5a4 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java @@ -22,11 +22,11 @@ public interface PetApi { * Add a new pet to the store * * @param body Pet object that needs to be added to the store (required) - * @return Call<Object> + * @return Call<Void> */ - @POST("/pet") - Observable addPet( + @POST("pet") + Observable addPet( @Body Pet body ); @@ -35,11 +35,11 @@ Observable addPet( * * @param petId Pet id to delete (required) * @param apiKey (optional) - * @return Call<Object> + * @return Call<Void> */ - @DELETE("/pet/{petId}") - Observable deletePet( + @DELETE("pet/{petId}") + Observable deletePet( @Path("petId") Long petId, @Header("api_key") String apiKey ); @@ -50,7 +50,7 @@ Observable deletePet( * @return Call<List> */ - @GET("/pet/findByStatus") + @GET("pet/findByStatus") Observable> findPetsByStatus( @Query("status") CSVParams status ); @@ -62,7 +62,7 @@ Observable> findPetsByStatus( * @return Call<List> */ - @GET("/pet/findByTags") + @GET("pet/findByTags") Observable> findPetsByTags( @Query("tags") CSVParams tags ); @@ -74,7 +74,7 @@ Observable> findPetsByTags( * @return Call<Pet> */ - @GET("/pet/{petId}") + @GET("pet/{petId}") Observable getPetById( @Path("petId") Long petId ); @@ -83,11 +83,11 @@ Observable getPetById( * Update an existing pet * * @param body Pet object that needs to be added to the store (required) - * @return Call<Object> + * @return Call<Void> */ - @PUT("/pet") - Observable updatePet( + @PUT("pet") + Observable updatePet( @Body Pet body ); @@ -97,12 +97,12 @@ Observable updatePet( * @param petId ID of pet that needs to be updated (required) * @param name Updated name of the pet (optional) * @param status Updated status of the pet (optional) - * @return Call<Object> + * @return Call<Void> */ @FormUrlEncoded - @POST("/pet/{petId}") - Observable updatePetWithForm( + @POST("pet/{petId}") + Observable updatePetWithForm( @Path("petId") Long petId, @Field("name") String name, @Field("status") String status ); @@ -115,10 +115,10 @@ Observable updatePetWithForm( * @return Call<ModelApiResponse> */ - @FormUrlEncoded - @POST("/pet/{petId}/uploadImage") + @Multipart + @POST("pet/{petId}/uploadImage") Observable uploadFile( - @Path("petId") Long petId, @Field("additionalMetadata") String additionalMetadata, @Field("file\"; filename=\"file\"") RequestBody file + @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file\"; filename=\"file\"") RequestBody file ); } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java index ff3e4dcd791..4e93813692d 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java @@ -20,11 +20,11 @@ public interface StoreApi { * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * @param orderId ID of the order that needs to be deleted (required) - * @return Call<Object> + * @return Call<Void> */ - @DELETE("/store/order/{orderId}") - Observable deleteOrder( + @DELETE("store/order/{orderId}") + Observable deleteOrder( @Path("orderId") String orderId ); @@ -34,7 +34,7 @@ Observable deleteOrder( * @return Call<Map> */ - @GET("/store/inventory") + @GET("store/inventory") Observable> getInventory(); @@ -45,7 +45,7 @@ Observable deleteOrder( * @return Call<Order> */ - @GET("/store/order/{orderId}") + @GET("store/order/{orderId}") Observable getOrderById( @Path("orderId") Long orderId ); @@ -57,7 +57,7 @@ Observable getOrderById( * @return Call<Order> */ - @POST("/store/order") + @POST("store/order") Observable placeOrder( @Body Order body ); diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/UserApi.java index 52db68a9332..24a05ec40b8 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/UserApi.java @@ -20,11 +20,11 @@ public interface UserApi { * Create user * This can only be done by the logged in user. * @param body Created user object (required) - * @return Call<Object> + * @return Call<Void> */ - @POST("/user") - Observable createUser( + @POST("user") + Observable createUser( @Body User body ); @@ -32,11 +32,11 @@ Observable createUser( * Creates list of users with given input array * * @param body List of user object (required) - * @return Call<Object> + * @return Call<Void> */ - @POST("/user/createWithArray") - Observable createUsersWithArrayInput( + @POST("user/createWithArray") + Observable createUsersWithArrayInput( @Body List body ); @@ -44,11 +44,11 @@ Observable createUsersWithArrayInput( * Creates list of users with given input array * * @param body List of user object (required) - * @return Call<Object> + * @return Call<Void> */ - @POST("/user/createWithList") - Observable createUsersWithListInput( + @POST("user/createWithList") + Observable createUsersWithListInput( @Body List body ); @@ -56,11 +56,11 @@ Observable createUsersWithListInput( * Delete user * This can only be done by the logged in user. * @param username The name that needs to be deleted (required) - * @return Call<Object> + * @return Call<Void> */ - @DELETE("/user/{username}") - Observable deleteUser( + @DELETE("user/{username}") + Observable deleteUser( @Path("username") String username ); @@ -71,7 +71,7 @@ Observable deleteUser( * @return Call<User> */ - @GET("/user/{username}") + @GET("user/{username}") Observable getUserByName( @Path("username") String username ); @@ -84,7 +84,7 @@ Observable getUserByName( * @return Call<String> */ - @GET("/user/login") + @GET("user/login") Observable loginUser( @Query("username") String username, @Query("password") String password ); @@ -92,11 +92,11 @@ Observable loginUser( /** * Logs out current logged in user session * - * @return Call<Object> + * @return Call<Void> */ - @GET("/user/logout") - Observable logoutUser(); + @GET("user/logout") + Observable logoutUser(); /** @@ -104,11 +104,11 @@ Observable loginUser( * This can only be done by the logged in user. * @param username name that need to be deleted (required) * @param body Updated user object (required) - * @return Call<Object> + * @return Call<Void> */ - @PUT("/user/{username}") - Observable updateUser( + @PUT("user/{username}") + Observable updateUser( @Path("username") String username, @Body User body ); diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/Authentication.java deleted file mode 100644 index 221a7d9dd1f..00000000000 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/Authentication.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package io.swagger.client.auth; - -import io.swagger.client.Pair; - -import java.util.Map; -import java.util.List; - -public interface Authentication { - /** - * Apply authentication settings to header and query params. - * - * @param queryParams List of query parameters - * @param headerParams Map of header parameters - */ - void applyToParams(List queryParams, Map headerParams); -} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java new file mode 100644 index 00000000000..c9b6e124d51 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java @@ -0,0 +1,72 @@ +package io.swagger.client.auth; + +import java.io.IOException; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.oltu.oauth2.client.HttpClient; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest; +import org.apache.oltu.oauth2.client.response.OAuthClientResponse; +import org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory; +import org.apache.oltu.oauth2.common.exception.OAuthProblemException; +import org.apache.oltu.oauth2.common.exception.OAuthSystemException; + + +import okhttp3.Interceptor; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Request.Builder; +import okhttp3.Response; +import okhttp3.MediaType; +import okhttp3.RequestBody; + + +public class OAuthOkHttpClient implements HttpClient { + + private OkHttpClient client; + + public OAuthOkHttpClient() { + this.client = new OkHttpClient(); + } + + public OAuthOkHttpClient(OkHttpClient client) { + this.client = client; + } + + public T execute(OAuthClientRequest request, Map headers, + String requestMethod, Class responseClass) + throws OAuthSystemException, OAuthProblemException { + + MediaType mediaType = MediaType.parse("application/json"); + Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri()); + + if(headers != null) { + for (Entry entry : headers.entrySet()) { + if (entry.getKey().equalsIgnoreCase("Content-Type")) { + mediaType = MediaType.parse(entry.getValue()); + } else { + requestBuilder.addHeader(entry.getKey(), entry.getValue()); + } + } + } + + RequestBody body = request.getBody() != null ? RequestBody.create(mediaType, request.getBody()) : null; + requestBuilder.method(requestMethod, body); + + try { + Response response = client.newCall(requestBuilder.build()).execute(); + return OAuthClientResponseFactory.createCustomResponse( + response.body().string(), + response.body().contentType().toString(), + response.code(), + responseClass); + } catch (IOException e) { + throw new OAuthSystemException(e); + } + } + + public void shutdown() { + // Nothing to do here + } + +} From 9c4d77ed1aff816fd8e8347f30719b39b721a65b Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 7 Jul 2016 16:35:59 +0800 Subject: [PATCH 071/470] update wording for java retrofit1 --- .../java/io/swagger/codegen/languages/JavaClientCodegen.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 27e95190648..e0fa7937a90 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 @@ -36,7 +36,7 @@ public JavaClientCodegen() { supportedLibraries.put("feign", "HTTP client: Netflix Feign 8.16.0. JSON processing: Jackson 2.7.0"); supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.22.2. JSON processing: Jackson 2.7.0"); supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.6.2"); - supportedLibraries.put(RETROFIT_1, "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)"); + supportedLibraries.put(RETROFIT_1, "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.3.1 (Retrofit 1.9.0). IMPORTANT NOTE: retrofit1.x is no longer actively maintained so please upgrade to 'retrofit2' instead."); supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 3.2.0. JSON processing: Gson 2.6.1 (Retrofit 2.0.2). Enable the RxJava adapter using '-DuseRxJava=true'. (RxJava 1.1.3)"); CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); From 56951a2df426df368638e380da97db3797529fd3 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 7 Jul 2016 17:25:54 +0800 Subject: [PATCH 072/470] update wording related to config.json --- README.md | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index dbe835eb982..b4fe389f3ad 100644 --- a/README.md +++ b/README.md @@ -496,8 +496,15 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ -o samples/client/petstore/java \ -c path/to/config.json ``` -Supported config options can be different per language. Running `config-help -l {lang}` will show available options. **These options are applied -by passing them with `-D{optionName}={optionValue}**. +and `config.json` contains the following as an example: +``` +{ + "apiPackage" : "petstore" +} +``` + +Supported config options can be different per language. Running `config-help -l {lang}` will show available options. +**These options are applied via configuration file (e.g. config.json) or by passing them with `-D{optionName}={optionValue}**. (If `-D{optionName}` does not work, please open a [ticket](https://github.com/swagger-api/swagger-codegen/issues/new) and we'll look into it) ``` java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar config-help -l java From 2418448a3cc5c764802d4b19f678f7f125462f2f Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 7 Jul 2016 17:48:43 +0800 Subject: [PATCH 073/470] update swagger core to 1.5.9 for java feign client --- .../main/resources/Java/libraries/feign/build.gradle.mustache | 2 +- .../main/resources/Java/libraries/feign/build.sbt.mustache | 2 +- .../src/main/resources/Java/libraries/feign/pom.mustache | 2 +- samples/client/petstore/java/feign/build.gradle | 4 ++-- samples/client/petstore/java/feign/build.sbt | 4 ++-- samples/client/petstore/java/feign/pom.xml | 2 +- 6 files changed, 8 insertions(+), 8 deletions(-) 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 index 6cf93578816..adbe4800eb9 100644 --- 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 @@ -94,7 +94,7 @@ if(hasProperty('target') && target == 'android') { } ext { - swagger_annotations_version = "1.5.8" + swagger_annotations_version = "1.5.9" jackson_version = "2.7.5" feign_version = "8.17.0" junit_version = "4.12" diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.sbt.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.sbt.mustache index 04ae4ce11aa..98450123af6 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.sbt.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.sbt.mustache @@ -9,7 +9,7 @@ lazy val root = (project in file(".")). publishArtifact in (Compile, packageDoc) := false, resolvers += Resolver.mavenLocal, libraryDependencies ++= Seq( - "io.swagger" % "swagger-annotations" % "1.5.8" % "compile", + "io.swagger" % "swagger-annotations" % "1.5.9" % "compile", "com.netflix.feign" % "feign-core" % "8.16.0" % "compile", "com.netflix.feign" % "feign-jackson" % "8.17.0" % "compile", "com.netflix.feign" % "feign-slf4j" % "8.16.0" % "compile", diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache index 3eb45f850bc..ae217218beb 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache @@ -160,7 +160,7 @@ {{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}} ${java.version} ${java.version} - 1.5.8 + 1.5.9 8.17.0 2.7.5 4.12 diff --git a/samples/client/petstore/java/feign/build.gradle b/samples/client/petstore/java/feign/build.gradle index 5b79cf3c5a5..50c4634a73f 100644 --- a/samples/client/petstore/java/feign/build.gradle +++ b/samples/client/petstore/java/feign/build.gradle @@ -94,9 +94,9 @@ if(hasProperty('target') && target == 'android') { } ext { - swagger_annotations_version = "1.5.8" + swagger_annotations_version = "1.5.9" jackson_version = "2.7.5" - feign_version = "8.16.0" + feign_version = "8.17.0" junit_version = "4.12" oltu_version = "1.0.1" } diff --git a/samples/client/petstore/java/feign/build.sbt b/samples/client/petstore/java/feign/build.sbt index 4e0905c8820..10b1f875927 100644 --- a/samples/client/petstore/java/feign/build.sbt +++ b/samples/client/petstore/java/feign/build.sbt @@ -9,9 +9,9 @@ lazy val root = (project in file(".")). publishArtifact in (Compile, packageDoc) := false, resolvers += Resolver.mavenLocal, libraryDependencies ++= Seq( - "io.swagger" % "swagger-annotations" % "1.5.8" % "compile", + "io.swagger" % "swagger-annotations" % "1.5.9" % "compile", "com.netflix.feign" % "feign-core" % "8.16.0" % "compile", - "com.netflix.feign" % "feign-jackson" % "8.16.0" % "compile", + "com.netflix.feign" % "feign-jackson" % "8.17.0" % "compile", "com.netflix.feign" % "feign-slf4j" % "8.16.0" % "compile", "com.fasterxml.jackson.core" % "jackson-core" % "2.7.5" % "compile", "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.5" % "compile", diff --git a/samples/client/petstore/java/feign/pom.xml b/samples/client/petstore/java/feign/pom.xml index 6c988402422..18c1d9e9296 100644 --- a/samples/client/petstore/java/feign/pom.xml +++ b/samples/client/petstore/java/feign/pom.xml @@ -160,7 +160,7 @@ 1.7 ${java.version} ${java.version} - 1.5.8 + 1.5.9 8.17.0 2.7.5 4.12 From 1276941cc7cb2850bce779d107e4bb42f1808a8d Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 7 Jul 2016 18:31:18 +0800 Subject: [PATCH 074/470] update wording for full util option --- .../java/io/swagger/codegen/languages/AbstractJavaCodegen.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java index c245125f80a..000acb852e3 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java @@ -96,7 +96,7 @@ public AbstractJavaCodegen() { cliOptions.add(CliOption.newBoolean(CodegenConstants.SERIALIZABLE_MODEL, CodegenConstants.SERIALIZABLE_MODEL_DESC)); cliOptions.add(CliOption.newBoolean(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, CodegenConstants .SERIALIZE_BIG_DECIMAL_AS_STRING_DESC)); - cliOptions.add(CliOption.newBoolean(FULL_JAVA_UTIL, "whether to use fully qualified name for classes under java.util")); + cliOptions.add(CliOption.newBoolean(FULL_JAVA_UTIL, "whether to use fully qualified name for classes under java.util. This option only works for Java API client")); cliOptions.add(new CliOption("hideGenerationTimestamp", "hides the timestamp when files were generated")); CliOption dateLibrary = new CliOption(DATE_LIBRARY, "Option. Date library to use"); From 89befeb45b86905937e91a20880b1c36537db26e Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 7 Jul 2016 22:17:27 +0800 Subject: [PATCH 075/470] fix long issue in python3 --- .../main/resources/python/api_client.mustache | 8 ++++++++ samples/client/petstore/python/README.md | 2 +- .../petstore/python/petstore_api/api_client.py | 18 +++++++++++++----- 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index a43766d6032..e75c6be52ed 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -46,6 +46,14 @@ except ImportError: # for python2 from urllib import quote +# special handling of `long` (python2 only) +try: + # Python 2 + long +except NameError: + # Python 3 + long = int + from .configuration import Configuration diff --git a/samples/client/petstore/python/README.md b/samples/client/petstore/python/README.md index 6c34951d301..a8bcf2f5f83 100644 --- a/samples/client/petstore/python/README.md +++ b/samples/client/petstore/python/README.md @@ -5,7 +5,7 @@ This Python package is automatically generated by the [Swagger Codegen](https:// - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-07-06T16:27:27.842+08:00 +- Build date: 2016-07-07T22:03:52.761+08:00 - Build package: class io.swagger.codegen.languages.PythonClientCodegen ## Requirements. diff --git a/samples/client/petstore/python/petstore_api/api_client.py b/samples/client/petstore/python/petstore_api/api_client.py index 2521ba15fd3..ddfaf2ca744 100644 --- a/samples/client/petstore/python/petstore_api/api_client.py +++ b/samples/client/petstore/python/petstore_api/api_client.py @@ -46,6 +46,14 @@ # for python2 from urllib import quote +# special handling of `long` (python2 only) +try: + # Python 2 + long +except NameError: + # Python 3 + long = int + from .configuration import Configuration @@ -183,7 +191,7 @@ def sanitize_for_serialization(self, obj): Builds a JSON POST object. If obj is None, return None. - If obj is str, int, float, bool, return directly. + If obj is str, int, long, float, bool, return directly. If obj is datetime.datetime, datetime.date convert to string in iso8601 format. If obj is list, sanitize each element in the list. @@ -193,7 +201,7 @@ def sanitize_for_serialization(self, obj): :param obj: The data to serialize. :return: The serialized form of data. """ - types = (str, int, float, bool, tuple) + types = (str, int, long, float, bool, tuple) if sys.version_info < (3, 0): types = types + (unicode,) if isinstance(obj, type(None)): @@ -269,14 +277,14 @@ def __deserialize(self, data, klass): # convert str to class # for native types - if klass in ['int', 'float', 'str', 'bool', + if klass in ['int', 'long', 'float', 'str', 'bool', "date", 'datetime', "object"]: klass = eval(klass) # for model types else: klass = eval('models.' + klass) - if klass in [int, float, str, bool]: + if klass in [int, long, float, str, bool]: return self.__deserialize_primitive(data, klass) elif klass == object: return self.__deserialize_object(data) @@ -505,7 +513,7 @@ def __deserialize_primitive(self, data, klass): :param data: str. :param klass: class literal. - :return: int, float, str, bool. + :return: int, long, float, str, bool. """ try: value = klass(data) From 638319db09084c5b376454fbe8a6b7aed7ac5bca Mon Sep 17 00:00:00 2001 From: tao Date: Fri, 24 Jun 2016 17:10:48 -0700 Subject: [PATCH 076/470] add DefaultParam annotation --- .../src/main/resources/JavaJaxRS/formParams.mustache | 2 +- .../resources/JavaJaxRS/libraries/jersey1/formParams.mustache | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/formParams.mustache index 8a1e8f541a1..9a7ff6ea6cf 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/formParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/formParams.mustache @@ -1,3 +1,3 @@ -{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}){{#vendorExtensions.x-multipart}}@FormDataParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{^vendorExtensions.x-multipart}}@FormParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{/notFile}}{{#isFile}} +{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}){{#vendorExtensions.x-multipart}}@FormDataParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{^vendorExtensions.x-multipart}} {{#defaultValue}} @DefaultValue("{{{defaultValue}}}"){{/defaultValue}} @FormParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{/notFile}}{{#isFile}} @FormDataParam("{{paramName}}") InputStream {{paramName}}InputStream, @FormDataParam("{{paramName}}") FormDataContentDisposition {{paramName}}Detail{{/isFile}}{{/isFormParam}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/formParams.mustache index 91c8079ebcd..62d45ea9fef 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/formParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/formParams.mustache @@ -1,2 +1,2 @@ -{{#isFormParam}}{{#notFile}}{{^vendorExtensions.x-multipart}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}){{/vendorExtensions.x-multipart}}{{#vendorExtensions.x-multipart}}@FormDataParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{^vendorExtensions.x-multipart}}@FormParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{/notFile}}{{#isFile}}@FormDataParam("file") InputStream inputStream, +{{#isFormParam}}{{#notFile}}{{^vendorExtensions.x-multipart}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}){{/vendorExtensions.x-multipart}}{{#vendorExtensions.x-multipart}}@FormDataParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{^vendorExtensions.x-multipart}} {{#defaultValue}} @DefaultValue("{{{defaultValue}}}"){{/defaultValue}} @FormParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{/notFile}}{{#isFile}}@FormDataParam("file") InputStream inputStream, @FormDataParam("file") FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file From 9a65a5f0db09a5d35f84737f2d20699051f12171 Mon Sep 17 00:00:00 2001 From: Christian Loitsch Date: Fri, 8 Jul 2016 15:02:28 +0200 Subject: [PATCH 077/470] feat: improve / fix deserialization by parsing type String * added api_helper.dart for a helper function. * defaultApiClient is now a variable instead of a static field inside ApiClient * a lot of functions inside ApiClient are no longer static. * optional params are now named params (needed to introduce a justIgnoreFlag as hack) * queryParams now support the multi format and are therefore no longer a Map, but a List * renamed apiException.mustache to api_exception.mustache to conform with other file names. * removed unused import: 'dart:html' * removed 'package:crypto/crypto.dart' dependency. 'dart:convert' has a base64 converter now. * use null-aware operator for apiClient assignment in xxxApi constructors. * enable testStoreApi (which returned a Future nobody waited for) * fix types in tests. Some ids were passed as Strings instead of ints. * adapt tests to use the optional named arguments (for optional query args) * generate random ids in tests. Otherwise insertion will always succeed if the test has been called once. --- .../codegen/languages/DartClientCodegen.java | 3 +- .../src/main/resources/dart/api.mustache | 24 +- .../main/resources/dart/api_client.mustache | 126 +++--- ...eption.mustache => api_exception.mustache} | 0 .../main/resources/dart/api_helper.mustache | 33 ++ .../src/main/resources/dart/apilib.mustache | 5 +- .../main/resources/dart/auth/oauth.mustache | 2 +- samples/client/petstore/dart/lib/api.dart | 6 +- .../client/petstore/dart/lib/api/pet_api.dart | 374 +++++++++++------- .../petstore/dart/lib/api/store_api.dart | 177 +++++---- .../petstore/dart/lib/api/user_api.dart | 369 ++++++++++------- .../client/petstore/dart/lib/api_client.dart | 166 ++++---- .../client/petstore/dart/lib/api_helper.dart | 33 ++ .../petstore/dart/lib/auth/api_key_auth.dart | 5 +- .../dart/lib/auth/authentication.dart | 2 +- .../dart/lib/auth/http_basic_auth.dart | 4 +- .../client/petstore/dart/lib/auth/oauth.dart | 2 +- samples/client/petstore/dart/pubspec.lock | 177 +++++++-- samples/client/petstore/dart/pubspec.yaml | 1 - .../client/petstore/dart/test/pet_test.dart | 78 ++-- .../client/petstore/dart/test/store_test.dart | 14 +- samples/client/petstore/dart/test/tests.dart | 9 +- .../client/petstore/dart/test/user_test.dart | 50 ++- 23 files changed, 1029 insertions(+), 631 deletions(-) rename modules/swagger-codegen/src/main/resources/dart/{apiException.mustache => api_exception.mustache} (100%) create mode 100644 modules/swagger-codegen/src/main/resources/dart/api_helper.mustache create mode 100644 samples/client/petstore/dart/lib/api_helper.dart diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java index 6bb54cb9d50..a70c5c4c692 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java @@ -141,7 +141,8 @@ public void processOpts() { final String libFolder = sourceFolder + File.separator + "lib"; supportingFiles.add(new SupportingFile("pubspec.mustache", "", "pubspec.yaml")); supportingFiles.add(new SupportingFile("api_client.mustache", libFolder, "api_client.dart")); - supportingFiles.add(new SupportingFile("apiException.mustache", libFolder, "api_exception.dart")); + supportingFiles.add(new SupportingFile("api_exception.mustache", libFolder, "api_exception.dart")); + supportingFiles.add(new SupportingFile("api_helper.mustache", libFolder, "api_helper.dart")); supportingFiles.add(new SupportingFile("apilib.mustache", libFolder, "api.dart")); final String authFolder = sourceFolder + File.separator + "lib" + File.separator + "auth"; diff --git a/modules/swagger-codegen/src/main/resources/dart/api.mustache b/modules/swagger-codegen/src/main/resources/dart/api.mustache index 6fcd49994ec..04c24009380 100644 --- a/modules/swagger-codegen/src/main/resources/dart/api.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/api.mustache @@ -5,19 +5,19 @@ part of api; class {{classname}} { String basePath = "{{basePath}}"; - ApiClient apiClient = ApiClient.defaultApiClient; + final ApiClient apiClient; - {{classname}}([ApiClient apiClient]) { - if (apiClient != null) { - this.apiClient = apiClient; - } - } + {{classname}}([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; {{#operation}} /// {{summary}} /// /// {{notes}} - {{#returnType}}Future<{{{returnType}}}> {{/returnType}}{{^returnType}}Future {{/returnType}}{{nickname}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) async { + {{#returnType}}Future<{{{returnType}}}> {{/returnType}}{{^returnType}}Future {{/returnType}}{{nickname}}({{#allParams}}{{#required}}{{{dataType}}} {{paramName}}, {{/required}}{{/allParams}} { {{#allParams}}{{^required}} {{{dataType}}} {{paramName}}, {{/required}}{{/allParams}} bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; // verify required params are set @@ -33,11 +33,13 @@ class {{classname}} { String path = "{{path}}".replaceAll("{format}","json"){{#pathParams}}.replaceAll("{" + "{{paramName}}" + "}", {{{paramName}}}.toString()){{/pathParams}}; // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - {{#queryParams}}if("null" != {{paramName}}) - queryParams.addAll(convertParametersForCollectionFormat({{collectionFormat}}, {{baseName}}, {{paramName}})); + {{#queryParams}} + if("null" != {{paramName}}) { + queryParams.addAll(_convertParametersForCollectionFormat("{{collectionFormat}}", "{{baseName}}", {{paramName}})); + } {{/queryParams}} {{#headerParams}}headerParams["{{baseName}}"] = {{paramName}}; {{/headerParams}} @@ -84,7 +86,7 @@ class {{classname}} { if(response.statusCode >= 400) { throw new ApiException(response.statusCode, response.body); } else if(response.body != null) { - return {{#returnType}}ApiClient.deserialize(response.body, {{returnBaseType}}){{/returnType}}; + return {{#returnType}} apiClient.deserialize(response.body, '{{{returnType}}}') {{/returnType}}; } else { return {{#returnType}}null{{/returnType}}; } diff --git a/modules/swagger-codegen/src/main/resources/dart/api_client.mustache b/modules/swagger-codegen/src/main/resources/dart/api_client.mustache index 6a9fca0fd8e..e83d8b62a6d 100644 --- a/modules/swagger-codegen/src/main/resources/dart/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/api_client.mustache @@ -7,46 +7,19 @@ class QueryParam { QueryParam(this.name, this.value); } -const _delimiters = const {'csv': ',', 'ssv': ' ', 'tsv': '\t', 'pipes': '|'}; - -// port from Java version -List convertParametersForCollectionFormat( - String collectionFormat, String name, dynamic value) { - var params = {}; - - // preconditions - if (name == null || name.isEmpty || value == null) return params; - - if (value is! List) { - params.add(new QueryParam(name, value as String)); - return params; - } - - List values = value as List; - - // get the collection format - collectionFormat = (collectionFormat == null || collectionFormat.isEmpty) - ? "csv" - : collectionFormat; // default: csv - - if (collectionFormat == "multi") { - return values.map((v) => new QueryParam(name, v)); - } - - String delimiter = _delimiters[collectionFormat] ?? ","; - - params.add(new QueryParam(name, values.join(delimiter))); - return params; -} - class ApiClient { - static ApiClient defaultApiClient = new ApiClient(); + + var client = new {{#browserClient}}Browser{{/browserClient}}Client(); Map _defaultHeaderMap = {}; Map _authentications = {}; - static final dson = new Dartson.JSON(); + + final dson = new Dartson.JSON(); final DateFormat _dateFormatter = new DateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + final _RegList = new RegExp(r'^List<(.*)>$'); + final _RegMap = new RegExp(r'^Map$'); + ApiClient() { // Setup authentications (key: authentication name, value: authentication).{{#authMethods}}{{#isBasic}} _authentications['{{name}}'] = new HttpBasicAuth();{{/isBasic}}{{#isApiKey}} @@ -76,43 +49,57 @@ class ApiClient { } } - static dynamic deserialize(String json, dynamic clazz) { - var result = json; - + dynamic _deserialize(dynamic value, String targetType) { try { - var decodedJson = JSON.decode(json); - - if(decodedJson is List) { - result = []; - for(var obj in decodedJson) { - result.add(_createEntity(obj, clazz)); - } - } else { - result = _createEntity(json, clazz); + switch (targetType) { + case 'String': + return '$value'; + case 'int': + return value is int ? value : int.parse('$value'); + case 'bool': + return value is bool ? value : '$value'.toLowerCase() == 'true'; + case 'double': + return value is double ? value : double.parse('$value'); + {{#models}} + {{#model}} + case '{{classname}}': + return dson.map(value, new {{classname}}()); + {{/model}} + {{/models}} + default: + { + Match match; + if (value is List && + (match = _RegList.firstMatch(targetType)) != null) { + var valueL = value as List; + var newTargetType = match[1]; + return valueL.map((v) => _deserialize(v, newTargetType)).toList(); + } else if (value is Map && + (match = _RegMap.firstMatch(targetType)) != null) { + var valueM = value as Map; + var newTargetType = match[1]; + return new Map.fromIterables(valueM.keys, + valueM.values.map((v) => _deserialize(v, newTargetType))); + } + } } - } on FormatException { - // Just return the passed in value + } catch(e) { + // Just throw the ApiException below } - - return result; + throw new ApiException(500, 'Could not find a suitable class for deserialization'); } - static dynamic _createEntity(dynamic json, dynamic clazz) { - bool isMap = json is Map; - - switch(clazz) { - {{#models}} - {{#model}} - case {{classname}}: - return isMap ? dson.map(json, new {{classname}}()) : dson.decode(json, new {{classname}}()); - {{/model}} - {{/models}} - default: - throw new ApiException(500, 'Could not find a suitable class for deserialization'); - } + dynamic deserialize(String json, String targetType) { + // Remove all spaces. Necessary for reg expressions as well. + targetType = targetType.replaceAll(' ', ''); + + if (targetType == 'String') return json; + + var decodedJson = JSON.decode(json); + return _deserialize(decodedJson, targetType); } - static String serialize(Object obj) { + String serialize(Object obj) { String serialized = ''; if (obj == null) { serialized = ''; @@ -136,13 +123,9 @@ class ApiClient { String contentType, List authNames) async { - updateParamsForAuth(authNames, queryParams, headerParams); + _updateParamsForAuth(authNames, queryParams, headerParams); - var client = new {{#browserClient}}Browser{{/browserClient}}Client(); - - StringBuffer sb = new StringBuffer(); - - var ps = queryParams.where((p) => p.value != null).map((p) => '${p.key}=${p.value}'); + var ps = queryParams.where((p) => p.value != null).map((p) => '${p.name}=${p.value}'); String queryString = ps.isNotEmpty ? '?' + ps.join('&') : ''; @@ -177,12 +160,11 @@ class ApiClient { /// Update query and header parameters based on authentication settings. /// @param authNames The authentications to apply - void updateParamsForAuth(List authNames, List queryParams, Map headerParams) { + void _updateParamsForAuth(List authNames, List queryParams, Map headerParams) { authNames.forEach((authName) { Authentication auth = _authentications[authName]; if (auth == null) throw new ArgumentError("Authentication undefined: " + authName); auth.applyToParams(queryParams, headerParams); }); } - } diff --git a/modules/swagger-codegen/src/main/resources/dart/apiException.mustache b/modules/swagger-codegen/src/main/resources/dart/api_exception.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/dart/apiException.mustache rename to modules/swagger-codegen/src/main/resources/dart/api_exception.mustache diff --git a/modules/swagger-codegen/src/main/resources/dart/api_helper.mustache b/modules/swagger-codegen/src/main/resources/dart/api_helper.mustache new file mode 100644 index 00000000000..fb25306d260 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/dart/api_helper.mustache @@ -0,0 +1,33 @@ +part of api; + +const _delimiters = const {'csv': ',', 'ssv': ' ', 'tsv': '\t', 'pipes': '|'}; + +// port from Java version +List _convertParametersForCollectionFormat( + String collectionFormat, String name, dynamic value) { + var params = []; + + // preconditions + if (name == null || name.isEmpty || value == null) return params; + + if (value is! List) { + params.add(new QueryParam(name, value as String)); + return params; + } + + List values = value as List; + + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty) + ? "csv" + : collectionFormat; // default: csv + + if (collectionFormat == "multi") { + return values.map((v) => new QueryParam(name, v)); + } + + String delimiter = _delimiters[collectionFormat] ?? ","; + + params.add(new QueryParam(name, values.join(delimiter))); + return params; +} diff --git a/modules/swagger-codegen/src/main/resources/dart/apilib.mustache b/modules/swagger-codegen/src/main/resources/dart/apilib.mustache index 24b96817a03..5d2f345703c 100644 --- a/modules/swagger-codegen/src/main/resources/dart/apilib.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/apilib.mustache @@ -2,13 +2,13 @@ library api; import 'dart:async'; import 'dart:convert';{{#browserClient}} -import 'dart:html'; import 'package:http/browser_client.dart';{{/browserClient}} import 'package:http/http.dart'; import 'package:dartson/dartson.dart'; import 'package:intl/intl.dart'; part 'api_client.dart'; +part 'api_helper.dart'; part 'api_exception.dart'; part 'auth/authentication.dart'; part 'auth/api_key_auth.dart'; @@ -19,3 +19,6 @@ part 'auth/http_basic_auth.dart'; {{/apis}}{{/apiInfo}} {{#models}}{{#model}}part 'model/{{classFilename}}.dart'; {{/model}}{{/models}} + +ApiClient defaultApiClient = new ApiClient(); + diff --git a/modules/swagger-codegen/src/main/resources/dart/auth/oauth.mustache b/modules/swagger-codegen/src/main/resources/dart/auth/oauth.mustache index 5e3e2c8b260..e514dd85738 100644 --- a/modules/swagger-codegen/src/main/resources/dart/auth/oauth.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/auth/oauth.mustache @@ -3,7 +3,7 @@ part of api; class OAuth implements Authentication { @override - void applyToParams(Map queryParams, Map headerParams) { + void applyToParams(List queryParams, Map headerParams) { // TODO: support oauth } } \ No newline at end of file diff --git a/samples/client/petstore/dart/lib/api.dart b/samples/client/petstore/dart/lib/api.dart index c296270af64..1a0b0c84cc6 100644 --- a/samples/client/petstore/dart/lib/api.dart +++ b/samples/client/petstore/dart/lib/api.dart @@ -2,14 +2,13 @@ library api; import 'dart:async'; import 'dart:convert'; -import 'dart:html'; import 'package:http/browser_client.dart'; import 'package:http/http.dart'; import 'package:dartson/dartson.dart'; -import 'package:crypto/crypto.dart'; import 'package:intl/intl.dart'; part 'api_client.dart'; +part 'api_helper.dart'; part 'api_exception.dart'; part 'auth/authentication.dart'; part 'auth/api_key_auth.dart'; @@ -27,3 +26,6 @@ part 'model/pet.dart'; part 'model/tag.dart'; part 'model/user.dart'; + +ApiClient defaultApiClient = new ApiClient(); + diff --git a/samples/client/petstore/dart/lib/api/pet_api.dart b/samples/client/petstore/dart/lib/api/pet_api.dart index b6c807e72f0..694ec340d46 100644 --- a/samples/client/petstore/dart/lib/api/pet_api.dart +++ b/samples/client/petstore/dart/lib/api/pet_api.dart @@ -1,34 +1,36 @@ part of api; + class PetApi { String basePath = "http://petstore.swagger.io/v2"; - ApiClient apiClient = ApiClient.defaultApiClient; + final ApiClient apiClient; - PetApi([ApiClient apiClient]) { - if (apiClient != null) { - this.apiClient = apiClient; - } - } + PetApi([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; /// Add a new pet to the store /// /// - Future addPet(Pet body) { + Future addPet(Pet body, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = body; + // verify required params are set - if() { - throw new ApiException(400, "missing required params"); + if(body == null) { + throw new ApiException(400, "Missing required param: body"); } // create path and map variables String path = "/pet".replaceAll("{format}","json"); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - + List contentTypes = ["application/json","application/xml"]; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -44,39 +46,47 @@ class PetApi { else { } - return apiClient.invokeAPI(basePath, path, 'POST', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'POST', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } } /// Deletes a pet /// /// - Future deletePet(int petId, String apiKey) { + Future deletePet(int petId, { String apiKey, bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = null; + // verify required params are set - if( // verify required params are set - if() { - throw new ApiException(400, "missing required params"); - }) { - throw new ApiException(400, "missing required params"); + if(petId == null) { + throw new ApiException(400, "Missing required param: petId"); } // create path and map variables String path = "/pet/{petId}".replaceAll("{format}","json").replaceAll("{" + "petId" + "}", petId.toString()); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - headerParams["api_key"] = apiKey; + headerParams["api_key"] = apiKey; List contentTypes = []; @@ -93,37 +103,49 @@ class PetApi { else { } - return apiClient.invokeAPI(basePath, path, 'DELETE', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'DELETE', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } } /// Finds Pets by status /// /// Multiple status values can be provided with comma separated strings - Future> findPetsByStatus(List status) { + Future> findPetsByStatus(List status, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = null; + // verify required params are set - if() { - throw new ApiException(400, "missing required params"); + if(status == null) { + throw new ApiException(400, "Missing required param: status"); } // create path and map variables String path = "/pet/findByStatus".replaceAll("{format}","json"); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - if("null" != status) - queryParams["status"] = status is List ? status.join(',') : status; + if("null" != status) { + queryParams.addAll(_convertParametersForCollectionFormat("csv", "status", status)); + } List contentTypes = []; @@ -140,37 +162,49 @@ class PetApi { else { } - return apiClient.invokeAPI(basePath, path, 'GET', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ApiClient.deserialize(response.body, Pet); - } - else { - return null; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'GET', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return apiClient.deserialize(response.body, 'List') ; + } else { + return null; + } } /// Finds Pets by tags /// /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - Future> findPetsByTags(List tags) { + Future> findPetsByTags(List tags, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = null; + // verify required params are set - if() { - throw new ApiException(400, "missing required params"); + if(tags == null) { + throw new ApiException(400, "Missing required param: tags"); } // create path and map variables String path = "/pet/findByTags".replaceAll("{format}","json"); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - if("null" != tags) - queryParams["tags"] = tags is List ? tags.join(',') : tags; + if("null" != tags) { + queryParams.addAll(_convertParametersForCollectionFormat("csv", "tags", tags)); + } List contentTypes = []; @@ -187,36 +221,47 @@ class PetApi { else { } - return apiClient.invokeAPI(basePath, path, 'GET', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ApiClient.deserialize(response.body, Pet); - } - else { - return null; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'GET', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return apiClient.deserialize(response.body, 'List') ; + } else { + return null; + } } /// Find pet by ID /// /// Returns a single pet - Future getPetById(int petId) { + Future getPetById(int petId, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = null; + // verify required params are set - if() { - throw new ApiException(400, "missing required params"); + if(petId == null) { + throw new ApiException(400, "Missing required param: petId"); } // create path and map variables String path = "/pet/{petId}".replaceAll("{format}","json").replaceAll("{" + "petId" + "}", petId.toString()); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - + List contentTypes = []; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -232,36 +277,47 @@ class PetApi { else { } - return apiClient.invokeAPI(basePath, path, 'GET', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ApiClient.deserialize(response.body, Pet); - } - else { - return null; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'GET', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return apiClient.deserialize(response.body, 'Pet') ; + } else { + return null; + } } /// Update an existing pet /// /// - Future updatePet(Pet body) { + Future updatePet(Pet body, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = body; + // verify required params are set - if() { - throw new ApiException(400, "missing required params"); + if(body == null) { + throw new ApiException(400, "Missing required param: body"); } // create path and map variables String path = "/pet".replaceAll("{format}","json"); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - + List contentTypes = ["application/json","application/xml"]; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -277,42 +333,47 @@ class PetApi { else { } - return apiClient.invokeAPI(basePath, path, 'PUT', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'PUT', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } } /// Updates a pet in the store with form data /// /// - Future updatePetWithForm(int petId, String name, String status) { + Future updatePetWithForm(int petId, { String name, String status, bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = null; + // verify required params are set - if( // verify required params are set - if( // verify required params are set - if() { - throw new ApiException(400, "missing required params"); - }) { - throw new ApiException(400, "missing required params"); - }) { - throw new ApiException(400, "missing required params"); + if(petId == null) { + throw new ApiException(400, "Missing required param: petId"); } // create path and map variables String path = "/pet/{petId}".replaceAll("{format}","json").replaceAll("{" + "petId" + "}", petId.toString()); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - + List contentTypes = ["application/x-www-form-urlencoded"]; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -342,42 +403,47 @@ if (status != null) formParams['status'] = apiClient.parameterToString(status); } - return apiClient.invokeAPI(basePath, path, 'POST', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'POST', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } } /// uploads an image /// /// - Future uploadFile(int petId, String additionalMetadata, MultipartFile file) { + Future uploadFile(int petId, { String additionalMetadata, MultipartFile file, bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = null; + // verify required params are set - if( // verify required params are set - if( // verify required params are set - if() { - throw new ApiException(400, "missing required params"); - }) { - throw new ApiException(400, "missing required params"); - }) { - throw new ApiException(400, "missing required params"); + if(petId == null) { + throw new ApiException(400, "Missing required param: petId"); } // create path and map variables String path = "/pet/{petId}/uploadImage".replaceAll("{format}","json").replaceAll("{" + "petId" + "}", petId.toString()); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - + List contentTypes = ["multipart/form-data"]; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -407,16 +473,22 @@ if (status != null) } - return apiClient.invokeAPI(basePath, path, 'POST', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ApiClient.deserialize(response.body, ApiResponse); - } - else { - return null; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'POST', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return apiClient.deserialize(response.body, 'ApiResponse') ; + } else { + return null; + } } } diff --git a/samples/client/petstore/dart/lib/api/store_api.dart b/samples/client/petstore/dart/lib/api/store_api.dart index 25e3ccfcf6e..0e42d534603 100644 --- a/samples/client/petstore/dart/lib/api/store_api.dart +++ b/samples/client/petstore/dart/lib/api/store_api.dart @@ -1,34 +1,36 @@ part of api; + class StoreApi { String basePath = "http://petstore.swagger.io/v2"; - ApiClient apiClient = ApiClient.defaultApiClient; + final ApiClient apiClient; - StoreApi([ApiClient apiClient]) { - if (apiClient != null) { - this.apiClient = apiClient; - } - } + StoreApi([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; /// Delete purchase order by ID /// /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - Future deleteOrder(String orderId) { + Future deleteOrder(String orderId, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = null; + // verify required params are set - if() { - throw new ApiException(400, "missing required params"); + if(orderId == null) { + throw new ApiException(400, "Missing required param: orderId"); } // create path and map variables String path = "/store/order/{orderId}".replaceAll("{format}","json").replaceAll("{" + "orderId" + "}", orderId.toString()); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - + List contentTypes = []; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -44,33 +46,44 @@ class StoreApi { else { } - return apiClient.invokeAPI(basePath, path, 'DELETE', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'DELETE', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } } /// Returns pet inventories by status /// /// Returns a map of status codes to quantities - Future> getInventory() { + Future> getInventory( { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = null; + // verify required params are set // create path and map variables String path = "/store/inventory".replaceAll("{format}","json"); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - + List contentTypes = []; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -86,36 +99,47 @@ class StoreApi { else { } - return apiClient.invokeAPI(basePath, path, 'GET', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ApiClient.deserialize(response.body, Map); - } - else { - return null; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'GET', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return apiClient.deserialize(response.body, 'Map') ; + } else { + return null; + } } /// Find purchase order by ID /// /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - Future getOrderById(int orderId) { + Future getOrderById(int orderId, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = null; + // verify required params are set - if() { - throw new ApiException(400, "missing required params"); + if(orderId == null) { + throw new ApiException(400, "Missing required param: orderId"); } // create path and map variables String path = "/store/order/{orderId}".replaceAll("{format}","json").replaceAll("{" + "orderId" + "}", orderId.toString()); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - + List contentTypes = []; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -131,36 +155,47 @@ class StoreApi { else { } - return apiClient.invokeAPI(basePath, path, 'GET', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ApiClient.deserialize(response.body, Order); - } - else { - return null; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'GET', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return apiClient.deserialize(response.body, 'Order') ; + } else { + return null; + } } /// Place an order for a pet /// /// - Future placeOrder(Order body) { + Future placeOrder(Order body, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = body; + // verify required params are set - if() { - throw new ApiException(400, "missing required params"); + if(body == null) { + throw new ApiException(400, "Missing required param: body"); } // create path and map variables String path = "/store/order".replaceAll("{format}","json"); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - + List contentTypes = []; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -176,16 +211,22 @@ class StoreApi { else { } - return apiClient.invokeAPI(basePath, path, 'POST', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ApiClient.deserialize(response.body, Order); - } - else { - return null; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'POST', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return apiClient.deserialize(response.body, 'Order') ; + } else { + return null; + } } } diff --git a/samples/client/petstore/dart/lib/api/user_api.dart b/samples/client/petstore/dart/lib/api/user_api.dart index d774ea1f931..34481806b95 100644 --- a/samples/client/petstore/dart/lib/api/user_api.dart +++ b/samples/client/petstore/dart/lib/api/user_api.dart @@ -1,34 +1,36 @@ part of api; + class UserApi { String basePath = "http://petstore.swagger.io/v2"; - ApiClient apiClient = ApiClient.defaultApiClient; + final ApiClient apiClient; - UserApi([ApiClient apiClient]) { - if (apiClient != null) { - this.apiClient = apiClient; - } - } + UserApi([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; /// Create user /// /// This can only be done by the logged in user. - Future createUser(User body) { + Future createUser(User body, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = body; + // verify required params are set - if() { - throw new ApiException(400, "missing required params"); + if(body == null) { + throw new ApiException(400, "Missing required param: body"); } // create path and map variables String path = "/user".replaceAll("{format}","json"); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - + List contentTypes = []; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -44,36 +46,47 @@ class UserApi { else { } - return apiClient.invokeAPI(basePath, path, 'POST', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'POST', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } } /// Creates list of users with given input array /// /// - Future createUsersWithArrayInput(List body) { + Future createUsersWithArrayInput(List body, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = body; + // verify required params are set - if() { - throw new ApiException(400, "missing required params"); + if(body == null) { + throw new ApiException(400, "Missing required param: body"); } // create path and map variables String path = "/user/createWithArray".replaceAll("{format}","json"); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - + List contentTypes = []; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -89,36 +102,47 @@ class UserApi { else { } - return apiClient.invokeAPI(basePath, path, 'POST', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'POST', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } } /// Creates list of users with given input array /// /// - Future createUsersWithListInput(List body) { + Future createUsersWithListInput(List body, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = body; + // verify required params are set - if() { - throw new ApiException(400, "missing required params"); + if(body == null) { + throw new ApiException(400, "Missing required param: body"); } // create path and map variables String path = "/user/createWithList".replaceAll("{format}","json"); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - + List contentTypes = []; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -134,36 +158,47 @@ class UserApi { else { } - return apiClient.invokeAPI(basePath, path, 'POST', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'POST', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } } /// Delete user /// /// This can only be done by the logged in user. - Future deleteUser(String username) { + Future deleteUser(String username, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = null; + // verify required params are set - if() { - throw new ApiException(400, "missing required params"); + if(username == null) { + throw new ApiException(400, "Missing required param: username"); } // create path and map variables String path = "/user/{username}".replaceAll("{format}","json").replaceAll("{" + "username" + "}", username.toString()); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - + List contentTypes = []; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -179,36 +214,47 @@ class UserApi { else { } - return apiClient.invokeAPI(basePath, path, 'DELETE', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'DELETE', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } } /// Get user by user name /// /// - Future getUserByName(String username) { + Future getUserByName(String username, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = null; + // verify required params are set - if() { - throw new ApiException(400, "missing required params"); + if(username == null) { + throw new ApiException(400, "Missing required param: username"); } // create path and map variables String path = "/user/{username}".replaceAll("{format}","json").replaceAll("{" + "username" + "}", username.toString()); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - + List contentTypes = []; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -224,42 +270,55 @@ class UserApi { else { } - return apiClient.invokeAPI(basePath, path, 'GET', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ApiClient.deserialize(response.body, User); - } - else { - return null; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'GET', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return apiClient.deserialize(response.body, 'User') ; + } else { + return null; + } } /// Logs user into the system /// /// - Future loginUser(String username, String password) { + Future loginUser(String username, String password, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = null; + // verify required params are set - if( // verify required params are set - if() { - throw new ApiException(400, "missing required params"); - }) { - throw new ApiException(400, "missing required params"); + if(username == null) { + throw new ApiException(400, "Missing required param: username"); + } + if(password == null) { + throw new ApiException(400, "Missing required param: password"); } // create path and map variables String path = "/user/login".replaceAll("{format}","json"); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - if("null" != username) - queryParams["username"] = username is List ? username.join(',') : username; -if("null" != password) - queryParams["password"] = password is List ? password.join(',') : password; + if("null" != username) { + queryParams.addAll(_convertParametersForCollectionFormat("", "username", username)); + } + if("null" != password) { + queryParams.addAll(_convertParametersForCollectionFormat("", "password", password)); + } List contentTypes = []; @@ -276,33 +335,44 @@ if("null" != password) else { } - return apiClient.invokeAPI(basePath, path, 'GET', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ApiClient.deserialize(response.body, String); - } - else { - return null; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'GET', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return apiClient.deserialize(response.body, 'String') ; + } else { + return null; + } } /// Logs out current logged in user session /// /// - Future logoutUser() { + Future logoutUser( { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = null; + // verify required params are set // create path and map variables String path = "/user/logout".replaceAll("{format}","json"); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - + List contentTypes = []; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -318,39 +388,50 @@ if("null" != password) else { } - return apiClient.invokeAPI(basePath, path, 'GET', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'GET', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } } /// Updated user /// /// This can only be done by the logged in user. - Future updateUser(String username, User body) { + Future updateUser(String username, User body, { bool justIgnoreThisFlag: true}) async { + if (!justIgnoreThisFlag) { + print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); + // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). + } Object postBody = body; + // verify required params are set - if( // verify required params are set - if() { - throw new ApiException(400, "missing required params"); - }) { - throw new ApiException(400, "missing required params"); + if(username == null) { + throw new ApiException(400, "Missing required param: username"); + } + if(body == null) { + throw new ApiException(400, "Missing required param: body"); } // create path and map variables String path = "/user/{username}".replaceAll("{format}","json").replaceAll("{" + "username" + "}", username.toString()); // query params - Map queryParams = {}; + List queryParams = []; Map headerParams = {}; Map formParams = {}; - + List contentTypes = []; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -366,16 +447,22 @@ if("null" != password) else { } - return apiClient.invokeAPI(basePath, path, 'PUT', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { - if(response.statusCode >= 400) { - throw new ApiException(response.statusCode, response.body); - } - else if(response.body != null){ - return ; - } - else { - return ; - } - }); + var response = await apiClient.invokeAPI(basePath, + path, + 'PUT', + queryParams, + postBody, + headerParams, + formParams, + contentType, + authNames); + + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } else if(response.body != null) { + return ; + } else { + return ; + } } } diff --git a/samples/client/petstore/dart/lib/api_client.dart b/samples/client/petstore/dart/lib/api_client.dart index c4e9a5b1d46..3014e7deade 100644 --- a/samples/client/petstore/dart/lib/api_client.dart +++ b/samples/client/petstore/dart/lib/api_client.dart @@ -1,13 +1,25 @@ part of api; +class QueryParam { + String name; + String value; + + QueryParam(this.name, this.value); +} + class ApiClient { - static ApiClient defaultApiClient = new ApiClient(); + + var client = new BrowserClient(); Map _defaultHeaderMap = {}; Map _authentications = {}; - static final dson = new Dartson.JSON(); + + final dson = new Dartson.JSON(); final DateFormat _dateFormatter = new DateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + final _RegList = new RegExp(r'^List<(.*)>$'); + final _RegMap = new RegExp(r'^Map$'); + ApiClient() { // Setup authentications (key: authentication name, value: authentication). _authentications['petstore_auth'] = new OAuth(); @@ -36,49 +48,63 @@ class ApiClient { } } - static dynamic deserialize(String json, dynamic clazz) { - var result = json; - + dynamic _deserialize(dynamic value, String targetType) { try { - var decodedJson = JSON.decode(json); - - if(decodedJson is List) { - result = []; - for(var obj in decodedJson) { - result.add(_createEntity(obj, clazz)); - } - } else { - result = _createEntity(json, clazz); + switch (targetType) { + case 'String': + return '$value'; + case 'int': + return value is int ? value : int.parse('$value'); + case 'bool': + return value is bool ? value : '$value'.toLowerCase() == 'true'; + case 'double': + return value is double ? value : double.parse('$value'); + case 'ApiResponse': + return dson.map(value, new ApiResponse()); + case 'Category': + return dson.map(value, new Category()); + case 'Order': + return dson.map(value, new Order()); + case 'Pet': + return dson.map(value, new Pet()); + case 'Tag': + return dson.map(value, new Tag()); + case 'User': + return dson.map(value, new User()); + default: + { + Match match; + if (value is List && + (match = _RegList.firstMatch(targetType)) != null) { + var valueL = value as List; + var newTargetType = match[1]; + return valueL.map((v) => _deserialize(v, newTargetType)).toList(); + } else if (value is Map && + (match = _RegMap.firstMatch(targetType)) != null) { + var valueM = value as Map; + var newTargetType = match[1]; + return new Map.fromIterables(valueM.keys, + valueM.values.map((v) => _deserialize(v, newTargetType))); + } + } } - } on FormatException { - // Just return the passed in value + } catch(e) { + // Just throw the ApiException below } - - return result; + throw new ApiException(500, 'Could not find a suitable class for deserialization'); } - static dynamic _createEntity(dynamic json, dynamic clazz) { - bool isMap = json is Map; - - switch(clazz) { - case ApiResponse: - return isMap ? dson.map(json, new ApiResponse()) : dson.decode(json, new ApiResponse()); - case Category: - return isMap ? dson.map(json, new Category()) : dson.decode(json, new Category()); - case Order: - return isMap ? dson.map(json, new Order()) : dson.decode(json, new Order()); - case Pet: - return isMap ? dson.map(json, new Pet()) : dson.decode(json, new Pet()); - case Tag: - return isMap ? dson.map(json, new Tag()) : dson.decode(json, new Tag()); - case User: - return isMap ? dson.map(json, new User()) : dson.decode(json, new User()); - default: - throw new ApiException(500, 'Could not find a suitable class for deserialization'); - } + dynamic deserialize(String json, String targetType) { + // Remove all spaces. Necessary for reg expressions as well. + targetType = targetType.replaceAll(' ', ''); + + if (targetType == 'String') return json; + + var decodedJson = JSON.decode(json); + return _deserialize(decodedJson, targetType); } - static String serialize(Object obj) { + String serialize(Object obj) { String serialized = ''; if (obj == null) { serialized = ''; @@ -90,76 +116,60 @@ class ApiClient { return serialized; } - Future invokeAPI( String host, - String path, - String method, - Map queryParams, - Object body, - Map headerParams, - Map formParams, - String contentType, - List authNames) { - - updateParamsForAuth(authNames, queryParams, headerParams); - - var client = new BrowserClient(); - - StringBuffer sb = new StringBuffer(); - - for(String key in queryParams.keys) { - String value = queryParams[key]; - if (value != null){ - if(sb.toString().length == 0) { - sb.write("?"); - } else { - sb.write("&"); - } - sb.write(key); - sb.write("="); - sb.write(value); - } - } - String querystring = sb.toString(); + // We don't use a Map for queryParams. + // If collectionFormat is 'multi' a key might appear multiple times. + Future invokeAPI(String host, + String path, + String method, + List queryParams, + Object body, + Map headerParams, + Map formParams, + String contentType, + List authNames) async { + + _updateParamsForAuth(authNames, queryParams, headerParams); + + var ps = queryParams.where((p) => p.value != null).map((p) => '${p.name}=${p.value}'); + String queryString = ps.isNotEmpty ? + '?' + ps.join('&') : + ''; - String url = host + path + querystring; + String url = host + path + queryString; headerParams.addAll(_defaultHeaderMap); headerParams['Content-Type'] = contentType; - var completer = new Completer(); - if(body is MultipartRequest) { var request = new MultipartRequest(method, Uri.parse(url)); request.fields.addAll(body.fields); request.files.addAll(body.files); request.headers.addAll(body.headers); request.headers.addAll(headerParams); - client.send(request).then((response) => completer.complete(Response.fromStream(response))); + var response = await client.send(request); + return Response.fromStream(response); } else { var msgBody = contentType == "application/x-www-form-urlencoded" ? formParams : serialize(body); switch(method) { - case "GET": - return client.get(url, headers: headerParams); case "POST": return client.post(url, headers: headerParams, body: msgBody); case "PUT": return client.put(url, headers: headerParams, body: msgBody); case "DELETE": return client.delete(url, headers: headerParams); + default: + return client.get(url, headers: headerParams); } } - - return completer.future; } /// Update query and header parameters based on authentication settings. /// @param authNames The authentications to apply - void updateParamsForAuth(List authNames, Map queryParams, Map headerParams) { + void _updateParamsForAuth(List authNames, List queryParams, Map headerParams) { authNames.forEach((authName) { Authentication auth = _authentications[authName]; if (auth == null) throw new ArgumentError("Authentication undefined: " + authName); auth.applyToParams(queryParams, headerParams); }); } - } diff --git a/samples/client/petstore/dart/lib/api_helper.dart b/samples/client/petstore/dart/lib/api_helper.dart new file mode 100644 index 00000000000..fb25306d260 --- /dev/null +++ b/samples/client/petstore/dart/lib/api_helper.dart @@ -0,0 +1,33 @@ +part of api; + +const _delimiters = const {'csv': ',', 'ssv': ' ', 'tsv': '\t', 'pipes': '|'}; + +// port from Java version +List _convertParametersForCollectionFormat( + String collectionFormat, String name, dynamic value) { + var params = []; + + // preconditions + if (name == null || name.isEmpty || value == null) return params; + + if (value is! List) { + params.add(new QueryParam(name, value as String)); + return params; + } + + List values = value as List; + + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty) + ? "csv" + : collectionFormat; // default: csv + + if (collectionFormat == "multi") { + return values.map((v) => new QueryParam(name, v)); + } + + String delimiter = _delimiters[collectionFormat] ?? ","; + + params.add(new QueryParam(name, values.join(delimiter))); + return params; +} diff --git a/samples/client/petstore/dart/lib/auth/api_key_auth.dart b/samples/client/petstore/dart/lib/auth/api_key_auth.dart index 6e728ae916b..d80d6a6a213 100644 --- a/samples/client/petstore/dart/lib/auth/api_key_auth.dart +++ b/samples/client/petstore/dart/lib/auth/api_key_auth.dart @@ -10,7 +10,7 @@ class ApiKeyAuth implements Authentication { ApiKeyAuth(this.location, this.paramName); @override - void applyToParams(Map queryParams, Map headerParams) { + void applyToParams(List queryParams, Map headerParams) { String value; if (apiKeyPrefix != null) { value = '$apiKeyPrefix $apiKey'; @@ -19,10 +19,9 @@ class ApiKeyAuth implements Authentication { } if (location == 'query' && value != null) { - queryParams[paramName] = value; + queryParams.add(new QueryParam(paramName, value)); } else if (location == 'header' && value != null) { headerParams[paramName] = value; } } - } \ No newline at end of file diff --git a/samples/client/petstore/dart/lib/auth/authentication.dart b/samples/client/petstore/dart/lib/auth/authentication.dart index 4833af90ec0..c0b1f92a42d 100644 --- a/samples/client/petstore/dart/lib/auth/authentication.dart +++ b/samples/client/petstore/dart/lib/auth/authentication.dart @@ -3,5 +3,5 @@ part of api; abstract class Authentication { /// Apply authentication settings to header and query params. - void applyToParams(Map queryParams, Map headerParams); + void applyToParams(List queryParams, Map headerParams); } \ No newline at end of file diff --git a/samples/client/petstore/dart/lib/auth/http_basic_auth.dart b/samples/client/petstore/dart/lib/auth/http_basic_auth.dart index e681c25653d..0645d4358f5 100644 --- a/samples/client/petstore/dart/lib/auth/http_basic_auth.dart +++ b/samples/client/petstore/dart/lib/auth/http_basic_auth.dart @@ -6,9 +6,9 @@ class HttpBasicAuth implements Authentication { String password; @override - void applyToParams(Map queryParams, Map headerParams) { + void applyToParams(List queryParams, Map headerParams) { String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); - headerParams["Authorization"] = "Basic " + CryptoUtils.bytesToBase64(UTF8.encode(str)); + headerParams["Authorization"] = "Basic " + BASE64.encode(UTF8.encode(str)); } } \ No newline at end of file diff --git a/samples/client/petstore/dart/lib/auth/oauth.dart b/samples/client/petstore/dart/lib/auth/oauth.dart index 5e3e2c8b260..e514dd85738 100644 --- a/samples/client/petstore/dart/lib/auth/oauth.dart +++ b/samples/client/petstore/dart/lib/auth/oauth.dart @@ -3,7 +3,7 @@ part of api; class OAuth implements Authentication { @override - void applyToParams(Map queryParams, Map headerParams) { + void applyToParams(List queryParams, Map headerParams) { // TODO: support oauth } } \ No newline at end of file diff --git a/samples/client/petstore/dart/pubspec.lock b/samples/client/petstore/dart/pubspec.lock index 1e4ba01779c..b816620fa90 100644 --- a/samples/client/petstore/dart/pubspec.lock +++ b/samples/client/petstore/dart/pubspec.lock @@ -2,86 +2,177 @@ # See http://pub.dartlang.org/doc/glossary.html#lockfile packages: analyzer: - description: analyzer + description: + name: analyzer + url: "https://pub.dartlang.org" source: hosted - version: "0.25.0+1" + version: "0.26.4" args: - description: args + description: + name: args + url: "https://pub.dartlang.org" source: hosted - version: "0.13.2" + version: "0.13.4+2" + async: + description: + name: async + url: "https://pub.dartlang.org" + source: hosted + version: "1.11.0" barback: - description: barback + description: + name: barback + url: "https://pub.dartlang.org" source: hosted - version: "0.15.2+4" + version: "0.15.2+8" browser: - description: browser + description: + name: browser + url: "https://pub.dartlang.org" source: hosted version: "0.10.0+2" + charcode: + description: + name: charcode + url: "https://pub.dartlang.org" + source: hosted + version: "1.1.0" collection: - description: collection + description: + name: collection + url: "https://pub.dartlang.org" source: hosted - version: "1.1.1" - crypto: - description: crypto + version: "1.9.0" + csslib: + description: + name: csslib + url: "https://pub.dartlang.org" source: hosted - version: "0.9.0" + version: "0.13.2" dartson: - description: dartson + description: + name: dartson + url: "https://pub.dartlang.org" + source: hosted + version: "0.2.5" + glob: + description: + name: glob + url: "https://pub.dartlang.org" source: hosted - version: "0.2.4" + version: "1.1.3" guinness: - description: guinness + description: + name: guinness + url: "https://pub.dartlang.org" source: hosted - version: "0.1.17" + version: "0.1.18" + html: + description: + name: html + url: "https://pub.dartlang.org" + source: hosted + version: "0.12.2+2" http: - description: http + description: + name: http + url: "https://pub.dartlang.org" source: hosted - version: "0.11.2" + version: "0.11.3+8" http_parser: - description: http_parser + description: + name: http_parser + url: "https://pub.dartlang.org" source: hosted - version: "0.0.2+7" + version: "3.0.2" intl: - description: intl + description: + name: intl + url: "https://pub.dartlang.org" source: hosted - version: "0.12.4+2" + version: "0.12.7+1" logging: - description: logging + description: + name: logging + url: "https://pub.dartlang.org" + source: hosted + version: "0.11.3" + package_config: + description: + name: package_config + url: "https://pub.dartlang.org" source: hosted - version: "0.9.3" + version: "0.1.5" path: - description: path + description: + name: path + url: "https://pub.dartlang.org" source: hosted - version: "1.3.6" + version: "1.3.9" petitparser: - description: petitparser + description: + name: petitparser + url: "https://pub.dartlang.org" + source: hosted + version: "1.5.3" + plugin: + description: + name: plugin + url: "https://pub.dartlang.org" source: hosted - version: "1.4.3" + version: "0.1.0" pool: - description: pool + description: + name: pool + url: "https://pub.dartlang.org" source: hosted - version: "1.1.0" + version: "1.2.4" source_maps: - description: source_maps + description: + name: source_maps + url: "https://pub.dartlang.org" source: hosted - version: "0.10.1" + version: "0.10.1+1" source_span: - description: source_span + description: + name: source_span + url: "https://pub.dartlang.org" source: hosted - version: "1.1.2" + version: "1.2.3" stack_trace: - description: stack_trace + description: + name: stack_trace + url: "https://pub.dartlang.org" source: hosted - version: "1.3.4" + version: "1.6.6" string_scanner: - description: string_scanner + description: + name: string_scanner + url: "https://pub.dartlang.org" source: hosted - version: "0.1.3+1" + version: "1.0.0" unittest: - description: unittest + description: + name: unittest + url: "https://pub.dartlang.org" source: hosted - version: "0.11.6+1" - watcher: - description: watcher + version: "0.11.6+4" + utf: + description: + name: utf + url: "https://pub.dartlang.org" source: hosted - version: "0.9.6" + version: "0.9.0+3" + watcher: + description: + name: watcher + url: "https://pub.dartlang.org" + source: hosted + version: "0.9.7+2" + yaml: + description: + name: yaml + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.10" +sdk: ">=1.14.0 <2.0.0" diff --git a/samples/client/petstore/dart/pubspec.yaml b/samples/client/petstore/dart/pubspec.yaml index cbc62b63ca1..e74546ea210 100644 --- a/samples/client/petstore/dart/pubspec.yaml +++ b/samples/client/petstore/dart/pubspec.yaml @@ -4,7 +4,6 @@ description: Swagger API client dependencies: http: '>=0.11.1 <0.12.0' dartson: "^0.2.4" - crypto: "^0.9.0" intl: "^0.12.4+2" dev_dependencies: diff --git a/samples/client/petstore/dart/test/pet_test.dart b/samples/client/petstore/dart/test/pet_test.dart index f93c3ea3e37..e9a7ccd5fa7 100644 --- a/samples/client/petstore/dart/test/pet_test.dart +++ b/samples/client/petstore/dart/test/pet_test.dart @@ -5,7 +5,7 @@ testPetApi() { describe('Pet API ', () { it('adds a new pet and gets it by id', () async { - var id = 137; + var id = newId(); await petApi.addPet(new Pet()..id = id); var pet = await petApi.getPetById(id); @@ -13,45 +13,56 @@ testPetApi() { }); it('doesn\'t get non-existing pet by id', () { - expect(petApi.getPetById(6789099)).toThrowWith(anInstanceOf: ApiException); + expect(petApi.getPetById(newId())) + .toThrowWith(anInstanceOf: ApiException); }); it('deletes existing pet by id', () async { - var id = 7689; + var id = newId(); await petApi.addPet(new Pet()..id = id); - await petApi.deletePet(id, 'special-key'); + await petApi.deletePet(id, apiKey: 'special-key'); expect(petApi.getPetById(id)).toThrowWith(anInstanceOf: ApiException); }); it('updates pet with form', () async { - var id = 52341; - await petApi.addPet(new Pet()..id = id..name='Snowy'); - await petApi.updatePetWithForm('$id', 'Doge', ''); + var id = newId(); + await petApi.addPet(new Pet() + ..id = id + ..name = 'Snowy'); + await petApi.updatePetWithForm(id, name: 'Doge', status: ''); var pet = await petApi.getPetById(id); expect(pet.name).toEqual('Doge'); }); it('updates existing pet', () async { - var id = 900001; + var id = newId(); var name = 'Snowy'; await petApi.addPet(new Pet()..id = id); - await petApi.updatePet(new Pet()..id = id..name = name); + await petApi.updatePet(new Pet() + ..id = id + ..name = name); var pet = await petApi.getPetById(id); expect(pet.name).toEqual(name); }); it('finds pets by status', () async { - var id1 = 754111; - var id2 = 1231341; - var id3 = 6776251; + var id1 = newId(); + var id2 = newId(); + var id3 = newId(); var status = 'available'; - return Future.wait([petApi.addPet(new Pet()..id = id1..status = status), - petApi.addPet(new Pet()..id = id2..status = status), - petApi.addPet(new Pet()..id = id3..status = 'sold')]) - .then((_) async { - + return Future.wait([ + petApi.addPet(new Pet() + ..id = id1 + ..status = status), + petApi.addPet(new Pet() + ..id = id2 + ..status = status), + petApi.addPet(new Pet() + ..id = id3 + ..status = 'sold') + ]).then((_) async { var pets = await petApi.findPetsByStatus([status]); var petIds = pets.map((pet) => pet.id).toList(); expect(petIds).toContain(id1); @@ -61,12 +72,26 @@ testPetApi() { }); it('finds pets by tag', () async { - var snowyId = 253156; - var grumpyId = 734215; - var snowyTags = [new Tag()..id=12211..name='terrier']; - var grumpyTags = [new Tag()..id=455803..name='grumpy']; - await petApi.addPet(new Pet()..id = snowyId..name = 'Snowy'..tags = snowyTags); - await petApi.addPet(new Pet()..id = grumpyId..name = 'Grumpy Cat'..tags = grumpyTags); + var snowyId = newId(); + var grumpyId = newId(); + var snowyTags = [ + new Tag() + ..id = newId() + ..name = 'terrier' + ]; + var grumpyTags = [ + new Tag() + ..id = newId() + ..name = 'grumpy' + ]; + await petApi.addPet(new Pet() + ..id = snowyId + ..name = 'Snowy' + ..tags = snowyTags); + await petApi.addPet(new Pet() + ..id = grumpyId + ..name = 'Grumpy Cat' + ..tags = grumpyTags); var pets = await petApi.findPetsByTags(['grumpy']); var petIds = pets.map((pet) => pet.id).toList(); @@ -75,11 +100,10 @@ testPetApi() { }); it('uploads a pet image', () async { - var id = 672322; + var id = newId(); await petApi.addPet(new Pet()..id = id); var file = new MultipartFile.fromBytes('file', [104, 101, 108, 108, 111]); - await petApi.uploadFile(id, '', file); + await petApi.uploadFile(id, additionalMetadata: '', file: file); }); - }); -} \ No newline at end of file +} diff --git a/samples/client/petstore/dart/test/store_test.dart b/samples/client/petstore/dart/test/store_test.dart index 692760f1be1..39d9cecfac7 100644 --- a/samples/client/petstore/dart/test/store_test.dart +++ b/samples/client/petstore/dart/test/store_test.dart @@ -3,28 +3,26 @@ part of tests; testStoreApi() { var storeApi = new StoreApi(); - describe('Store API ', () async { - + describe('Store API ', () { it('places an order and gets it by id', () async { - var id = 4356; + var id = newId(); await storeApi.placeOrder(new Order()..id = id); - var order = await storeApi.getOrderById(id.toString()); + var order = await storeApi.getOrderById(id); expect(order.id).toEqual(id); }); it('deletes an order', () async { - var id = 637211; + var id = newId(); await storeApi.placeOrder(new Order()..id = id); await storeApi.deleteOrder(id.toString()); - expect(storeApi.getOrderById(id.toString())).toThrowWith(anInstanceOf: ApiException); + expect(storeApi.getOrderById(id)).toThrowWith(anInstanceOf: ApiException); }); it('gets the store inventory', () async { Map inventory = await storeApi.getInventory(); expect(inventory.length).not.toBe(0); }); - }); -} \ No newline at end of file +} diff --git a/samples/client/petstore/dart/test/tests.dart b/samples/client/petstore/dart/test/tests.dart index 173a5587a4d..9511ea17875 100644 --- a/samples/client/petstore/dart/test/tests.dart +++ b/samples/client/petstore/dart/test/tests.dart @@ -1,6 +1,7 @@ library tests; import 'dart:async'; +import 'dart:math'; import 'package:http/http.dart'; import 'package:guinness/guinness.dart'; import 'package:swagger/api.dart'; @@ -9,8 +10,14 @@ part 'pet_test.dart'; part 'store_test.dart'; part 'user_test.dart'; +final random = new Random(); + +int newId() { + return random.nextInt(999999); +} + main() { testPetApi(); testStoreApi(); testUserApi(); -} \ No newline at end of file +} diff --git a/samples/client/petstore/dart/test/user_test.dart b/samples/client/petstore/dart/test/user_test.dart index 886a6bc3c5d..7188a1d25ea 100644 --- a/samples/client/petstore/dart/test/user_test.dart +++ b/samples/client/petstore/dart/test/user_test.dart @@ -4,24 +4,31 @@ testUserApi() { var userApi = new UserApi(); describe('User API ', () { - it('creates a user', () async { - var id = 67567; + var id = newId(); var username = 'Mally45'; - await userApi.createUser(new User()..id = id..username = username); + await userApi.createUser(new User() + ..id = id + ..username = username); var user = await userApi.getUserByName(username); expect(user.id).toEqual(id); }); it('creates users with list input', () async { - var firstId = 46226; - var joe ='Joe'; + var firstId = newId(); + var joe = 'Joe'; var sally = 'Sally'; - var secondId = 95239; + var secondId = newId(); - var users = [ new User()..id = firstId..username = joe, - new User()..id = secondId..username = sally]; + var users = [ + new User() + ..id = firstId + ..username = joe, + new User() + ..id = secondId + ..username = sally + ]; await userApi.createUsersWithListInput(users); var firstUser = await userApi.getUserByName(joe); @@ -31,33 +38,40 @@ testUserApi() { }); it('updates a user', () async { - var username ='Arkjam89'; + var username = 'Arkjam89'; var email = 'test@example.com'; - var user = new User()..id = 733356..username = username; + var user = new User() + ..id = newId() + ..username = username; await userApi.createUser(user); user.email = email; - await userApi.updateUser(username,user); + await userApi.updateUser(username, user); var foundUser = await userApi.getUserByName(username); expect(foundUser.email).toEqual(email); }); it('deletes a user', () async { - var username ='Riddlem325'; - await userApi.createUser(new User()..id = 1231114..username = username); + var username = 'Riddlem325'; + await userApi.createUser(new User() + ..id = newId() + ..username = username); await userApi.deleteUser(username); - expect(userApi.getUserByName(username)).toThrowWith(anInstanceOf: ApiException); + expect(userApi.getUserByName(username)) + .toThrowWith(anInstanceOf: ApiException); }); it('logs a user in', () async { - var username ='sgarad625'; + var username = 'sgarad625'; var password = 'lokimoki1'; - var user = new User()..id = 733356..username = username..password = password; + var user = new User() + ..id = newId() + ..username = username + ..password = password; await userApi.createUser(user); var result = await userApi.loginUser(username, password); expect(result).toContain('logged in user session:'); }); - }); -} \ No newline at end of file +} From 999ef42e81849665e2b85d7777201a3cb8362d19 Mon Sep 17 00:00:00 2001 From: Christian Loitsch Date: Fri, 8 Jul 2016 15:45:53 +0200 Subject: [PATCH 078/470] doc: explain how to run tests --- bin/dart-petstore.sh | 3 ++ samples/client/petstore/dart/README.md | 58 ++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 samples/client/petstore/dart/README.md diff --git a/bin/dart-petstore.sh b/bin/dart-petstore.sh index 292af62977f..9f59540a5a7 100755 --- a/bin/dart-petstore.sh +++ b/bin/dart-petstore.sh @@ -28,4 +28,7 @@ fi export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l dart -o samples/client/petstore/dart" +# for dart vm lib generation: +#ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l dart -o samples/client/petstore/dart --additional-properties browserClient=false" + java $JAVA_OPTS -jar $executable $ags diff --git a/samples/client/petstore/dart/README.md b/samples/client/petstore/dart/README.md new file mode 100644 index 00000000000..17343a5c026 --- /dev/null +++ b/samples/client/petstore/dart/README.md @@ -0,0 +1,58 @@ +# To run these tests: + +Simply start the dart server: `pub serve` + +then open http://127.0.0.1:8080/tests.html + + +This already starts the tests. There is _NO_ feedback! + +Open the javascript / dart console of your browser to verify all tests +passed successfully. + +You should have the following output: +``` +Observatory listening at http://127.0.0.1:39067/ +unittest-suite-wait-for-done +GET http://petstore.swagger.io/v2/pet/957639 404 (Not Found) +GET http://petstore.swagger.io/v2/pet/525946 404 (Not Found) +GET http://petstore.swagger.io/v2/store/order/29756 404 (Not Found) +GET http://petstore.swagger.io/v2/user/Riddlem325 404 (Not Found) +PASS: Pet API adds a new pet and gets it by id +PASS: Pet API doesn't get non-existing pet by id +PASS: Pet API deletes existing pet by id +PASS: Pet API updates pet with form +PASS: Pet API updates existing pet +PASS: Pet API finds pets by status +PASS: Pet API finds pets by tag +PASS: Pet API uploads a pet image +PASS: Store API places an order and gets it by id +PASS: Store API deletes an order +PASS: Store API gets the store inventory +PASS: User API creates a user +PASS: User API creates users with list input +PASS: User API updates a user +PASS: User API deletes a user +PASS: User API logs a user in + +All 16 tests passed. +unittest-suite-success +``` + + +You may also run the tests in the dart vm. + +Either generate the test-package for a vm: +- change bin/dart-petstore.sh and uncomment the vm options line +- run bin/dart-petstore.sh + +or + +- in `lib/api_client.dart` change `new BrowserClient()` to `new Client()` +- in `lib/api.dart` remove the line `import 'package:http/browser_client.dart';` + + + +Then run `test/tests.dart`. + +Have fun. \ No newline at end of file From bf8e1ade56522fd3871ee77157b237ee4f87f826 Mon Sep 17 00:00:00 2001 From: ant3 Date: Sat, 9 Jul 2016 11:31:25 +0100 Subject: [PATCH 079/470] Added tests to jersey2-java8 sample These are the tests from the jersey2 sample - but adapted to use the java8 time classes (rather than Joda time). --- .gitignore | 1 + .../test/java/io/swagger/client/JSONTest.java | 18 +- .../io/swagger/client/api/PetApiTest.java | 398 +++++++++++------- .../io/swagger/client/api/StoreApiTest.java | 170 ++++---- .../io/swagger/client/api/UserApiTest.java | 210 +++------ 5 files changed, 406 insertions(+), 391 deletions(-) diff --git a/.gitignore b/.gitignore index 589e45f6934..3ff09c17cea 100644 --- a/.gitignore +++ b/.gitignore @@ -56,6 +56,7 @@ samples/client/petstore/qt5cpp/PetStore/Makefile #Java/Android **/.gradle samples/client/petstore/java/hello.txt +samples/client/petstore/java/jersey2-java8/hello.txt samples/client/petstore/android/default/hello.txt samples/client/petstore/android/volley/.gradle/ samples/client/petstore/android/volley/build/ diff --git a/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/JSONTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/JSONTest.java index 9386b3d5236..5286976a819 100644 --- a/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/JSONTest.java +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/JSONTest.java @@ -4,9 +4,9 @@ import java.lang.Exception; -import org.joda.time.DateTimeZone; -import org.joda.time.format.DateTimeFormatter; -import org.joda.time.format.ISODateTimeFormat; +import java.time.OffsetDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; import org.junit.*; import static org.junit.Assert.*; @@ -23,23 +23,23 @@ public void setup() { @Test public void testDefaultDate() throws Exception { - final DateTimeFormatter dateFormat = ISODateTimeFormat.dateTime(); + final DateTimeFormatter dateFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME; final String dateStr = "2015-11-07T14:11:05.267Z"; - order.setShipDate(dateFormat.parseDateTime(dateStr)); + order.setShipDate(dateFormat.parse(dateStr, OffsetDateTime::from)); String str = json.getContext(null).writeValueAsString(order); Order o = json.getContext(null).readValue(str, Order.class); - assertEquals(dateStr, dateFormat.print(o.getShipDate())); + assertEquals(dateStr, dateFormat.format(o.getShipDate())); } @Test public void testCustomDate() throws Exception { - final DateTimeFormatter dateFormat = ISODateTimeFormat.dateTimeNoMillis().withZone(DateTimeZone.forID("Etc/GMT+2")); + final DateTimeFormatter dateFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.of("Etc/GMT+2")); final String dateStr = "2015-11-07T14:11:05-02:00"; - order.setShipDate(dateFormat.parseDateTime(dateStr)); + order.setShipDate(dateFormat.parse(dateStr, OffsetDateTime::from)); String str = json.getContext(null).writeValueAsString(order); Order o = json.getContext(null).readValue(str, Order.class); - assertEquals(dateStr, dateFormat.print(o.getShipDate())); + assertEquals(dateStr, dateFormat.format(o.getShipDate())); } } \ No newline at end of file diff --git a/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/PetApiTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/PetApiTest.java index 5ca2d9be1d8..7f4d27c8b77 100644 --- a/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/PetApiTest.java +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/PetApiTest.java @@ -1,180 +1,288 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +package io.swagger.client.api; +import com.fasterxml.jackson.databind.ObjectMapper; -package io.swagger.client.api; +import io.swagger.TestUtils; -import io.swagger.client.ApiException; -import io.swagger.client.model.Pet; -import io.swagger.client.model.ModelApiResponse; -import java.io.File; -import org.junit.Test; +import io.swagger.client.*; +import io.swagger.client.api.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; import java.util.ArrayList; -import java.util.HashMap; +import java.util.Arrays; import java.util.List; import java.util.Map; -/** - * API tests for PetApi - */ +import org.junit.*; +import static org.junit.Assert.*; + public class PetApiTest { + PetApi api = null; + + @Before + public void setup() { + api = new PetApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); + } - private final PetApi api = new PetApi(); - - - /** - * Add a new pet to the store - * - * - * - * @throws ApiException - * if the Api call fails - */ @Test - public void addPetTest() throws ApiException { - Pet body = null; - // api.addPet(body); + public void testApiClient() { + // the default api client is used + assertEquals(Configuration.getDefaultApiClient(), api.getApiClient()); + assertNotNull(api.getApiClient()); + assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath()); + assertFalse(api.getApiClient().isDebugging()); - // TODO: test validations + ApiClient oldClient = api.getApiClient(); + + ApiClient newClient = new ApiClient(); + newClient.setBasePath("http://example.com"); + newClient.setDebugging(true); + + // set api client via constructor + api = new PetApi(newClient); + assertNotNull(api.getApiClient()); + assertEquals("http://example.com", api.getApiClient().getBasePath()); + assertTrue(api.getApiClient().isDebugging()); + + // set api client via setter method + api.setApiClient(oldClient); + assertNotNull(api.getApiClient()); + assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath()); + assertFalse(api.getApiClient().isDebugging()); } - - /** - * Deletes a pet - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void deletePetTest() throws ApiException { - Long petId = null; - String apiKey = null; - // api.deletePet(petId, apiKey); + public void testCreateAndGetPet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); - // TODO: test validations + Pet fetched = api.getPetById(pet.getId()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); } - - /** - * Finds Pets by status - * - * Multiple status values can be provided with comma separated strings - * - * @throws ApiException - * if the Api call fails - */ + + /* @Test - public void findPetsByStatusTest() throws ApiException { - List status = null; - // List response = api.findPetsByStatus(status); + public void testCreateAndGetPetWithByteArray() throws Exception { + Pet pet = createRandomPet(); + byte[] bytes = serializeJson(pet, api.getApiClient()).getBytes(); + api.addPetUsingByteArray(bytes); - // TODO: test validations + byte[] fetchedBytes = api.petPetIdtestingByteArraytrueGet(pet.getId()); + Pet fetched = deserializeJson(new String(fetchedBytes), Pet.class, api.getApiClient()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); } - - /** - * Finds Pets by tags - * - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void findPetsByTagsTest() throws ApiException { - List tags = null; - // List response = api.findPetsByTags(tags); + public void testGetPetByIdInObject() throws Exception { + Pet pet = new Pet(); + pet.setId(TestUtils.nextId()); + pet.setName("pet " + pet.getId()); + + Category category = new Category(); + category.setId(TestUtils.nextId()); + category.setName("category " + category.getId()); + pet.setCategory(category); - // TODO: test validations + pet.setStatus(Pet.StatusEnum.PENDING); + List photos = Arrays.asList(new String[]{"http://foo.bar.com/1"}); + pet.setPhotoUrls(photos); + + api.addPet(pet); + + InlineResponse200 fetched = api.getPetByIdInObject(pet.getId()); + assertEquals(pet.getId(), fetched.getId()); + assertEquals(pet.getName(), fetched.getName()); + + Object categoryObj = fetched.getCategory(); + assertNotNull(categoryObj); + assertTrue(categoryObj instanceof Map); + + Map categoryMap = (Map) categoryObj; + Object categoryIdObj = categoryMap.get("id"); + assertTrue(categoryIdObj instanceof Integer); + Integer categoryIdInt = (Integer) categoryIdObj; + assertEquals(category.getId(), Long.valueOf(categoryIdInt)); + assertEquals(category.getName(), categoryMap.get("name")); } - - /** - * Find pet by ID - * - * Returns a single pet - * - * @throws ApiException - * if the Api call fails - */ + */ + @Test - public void getPetByIdTest() throws ApiException { - Long petId = null; - // Pet response = api.getPetById(petId); + public void testUpdatePet() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + + api.updatePet(pet); - // TODO: test validations + Pet fetched = api.getPetById(pet.getId()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); } - - /** - * Update an existing pet - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void updatePetTest() throws ApiException { - Pet body = null; - // api.updatePet(body); + public void testFindPetsByStatus() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); - // TODO: test validations + api.updatePet(pet); + + List pets = api.findPetsByStatus(Arrays.asList(new String[]{"available"})); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + + assertTrue(found); } - - /** - * Updates a pet in the store with form data - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void updatePetWithFormTest() throws ApiException { - Long petId = null; - String name = null; - String status = null; - // api.updatePetWithForm(petId, name, status); + public void 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); - // TODO: test validations + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + assertTrue(found); } - - /** - * uploads an image - * - * - * - * @throws ApiException - * if the Api call fails - */ + + @Test + public void testUpdatePetWithForm() throws Exception { + Pet pet = createRandomPet(); + pet.setName("frank"); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + + api.updatePetWithForm(fetched.getId(), "furt", null); + Pet updated = api.getPetById(fetched.getId()); + + assertEquals(updated.getName(), "furt"); + } + @Test - public void uploadFileTest() throws ApiException { - Long petId = null; - String additionalMetadata = null; - File file = null; - // ModelApiResponse response = api.uploadFile(petId, additionalMetadata, file); + public void testDeletePet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + api.deletePet(fetched.getId(), null); + + try { + fetched = api.getPetById(fetched.getId()); + fail("expected an error"); + } catch (ApiException e) { + assertEquals(404, e.getCode()); + } + } + + @Test + public void testUploadFile() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + File file = new File("hello.txt"); + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + writer.write("Hello world!"); + writer.close(); + + api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath())); + } + + @Test + public void testEqualsAndHashCode() { + Pet pet1 = new Pet(); + Pet pet2 = new Pet(); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + + pet2.setName("really-happy"); + pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertFalse(pet1.equals(pet2)); + assertFalse(pet2.equals(pet1)); + assertFalse(pet1.hashCode() == (pet2.hashCode())); + assertTrue(pet2.equals(pet2)); + assertTrue(pet2.hashCode() == pet2.hashCode()); + + pet1.setName("really-happy"); + pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + } + + private Pet createRandomPet() { + Pet pet = new Pet(); + pet.setId(TestUtils.nextId()); + pet.setName("gorilla"); + + Category category = new Category(); + category.setName("really-happy"); + + pet.setCategory(category); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); + pet.setPhotoUrls(photos); + + return pet; + } + + private String serializeJson(Object o, ApiClient apiClient) { + ObjectMapper mapper = apiClient.getJSON().getContext(null); + try { + return mapper.writeValueAsString(o); + } catch (Exception e) { + throw new RuntimeException(e); + } + } - // TODO: test validations + private T deserializeJson(String json, Class klass, ApiClient apiClient) { + ObjectMapper mapper = apiClient.getJSON().getContext(null); + try { + return mapper.readValue(json, klass); + } catch (Exception e) { + throw new RuntimeException(e); + } } - } diff --git a/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/StoreApiTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/StoreApiTest.java index 513cc877d45..1d670975dd6 100644 --- a/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/StoreApiTest.java +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/StoreApiTest.java @@ -1,108 +1,100 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - package io.swagger.client.api; -import io.swagger.client.ApiException; -import io.swagger.client.model.Order; -import org.junit.Test; +import io.swagger.TestUtils; + +import io.swagger.client.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; +import java.lang.reflect.Field; +import java.time.ZoneId; import java.util.Map; +import java.text.SimpleDateFormat; + +import java.time.OffsetDateTime; +import org.junit.*; +import static org.junit.Assert.*; -/** - * API tests for StoreApi - */ public class StoreApiTest { + StoreApi api = null; - private final StoreApi api = new StoreApi(); - - - /** - * Delete purchase order by ID - * - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void deleteOrderTest() throws ApiException { - String orderId = null; - // api.deleteOrder(orderId); + @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")); + } - // TODO: test validations + @Test + public void testGetInventory() throws Exception { + Map inventory = api.getInventory(); + assertTrue(inventory.keySet().size() > 0); } - - /** - * Returns pet inventories by status - * - * Returns a map of status codes to quantities - * - * @throws ApiException - * if the Api call fails - */ + + /* @Test - public void getInventoryTest() throws ApiException { - // Map response = api.getInventory(); + public void testGetInventoryInObject() throws Exception { + Object inventoryObj = api.getInventoryInObject(); + assertTrue(inventoryObj instanceof Map); + + Map inventoryMap = (Map) inventoryObj; + assertTrue(inventoryMap.keySet().size() > 0); - // TODO: test validations + Map.Entry firstEntry = (Map.Entry) inventoryMap.entrySet().iterator().next(); + assertTrue(firstEntry.getKey() instanceof String); + assertTrue(firstEntry.getValue() instanceof Integer); } - - /** - * Find purchase order by ID - * - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * - * @throws ApiException - * if the Api call fails - */ + */ + @Test - public void getOrderByIdTest() throws ApiException { - Long orderId = null; - // Order response = api.getOrderById(orderId); + public void testPlaceOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); - // TODO: test validations + Order fetched = api.getOrderById(order.getId()); + assertEquals(order.getId(), fetched.getId()); + assertEquals(order.getPetId(), fetched.getPetId()); + assertEquals(order.getQuantity(), fetched.getQuantity()); + assertEquals(order.getShipDate().toInstant(), fetched.getShipDate().toInstant()); } - - /** - * Place an order for a pet - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void placeOrderTest() throws ApiException { - Order body = null; - // Order response = api.placeOrder(body); + public void testDeleteOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); + + Order fetched = api.getOrderById(order.getId()); + assertEquals(fetched.getId(), order.getId()); + + api.deleteOrder(String.valueOf(order.getId())); + + try { + api.getOrderById(order.getId()); + // fail("expected an error"); + } catch (ApiException e) { + // ok + } + } + + private Order createOrder() { + Order order = new Order(); + order.setPetId(new Long(200)); + order.setQuantity(new Integer(13)); + order.setShipDate(OffsetDateTime.now()); + order.setStatus(Order.StatusEnum.PLACED); + order.setComplete(true); + + try { + Field idField = Order.class.getDeclaredField("id"); + idField.setAccessible(true); + idField.set(order, TestUtils.nextId()); + } catch (Exception e) { + throw new RuntimeException(e); + } - // TODO: test validations + return order; } - } diff --git a/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/UserApiTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/UserApiTest.java index e94858e8c27..c7fb92d2552 100644 --- a/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/UserApiTest.java +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/io/swagger/client/api/UserApiTest.java @@ -1,174 +1,88 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +package io.swagger.client.api; +import io.swagger.TestUtils; -package io.swagger.client.api; +import io.swagger.client.api.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; -import io.swagger.client.ApiException; -import io.swagger.client.model.User; -import org.junit.Test; +import java.util.Arrays; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import org.junit.*; +import static org.junit.Assert.*; -/** - * API tests for UserApi - */ public class UserApiTest { + UserApi api = null; - private final UserApi api = new UserApi(); - - - /** - * Create user - * - * This can only be done by the logged in user. - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void createUserTest() throws ApiException { - User body = null; - // api.createUser(body); - - // TODO: test validations + @Before + public void setup() { + api = new UserApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); } - - /** - * Creates list of users with given input array - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void createUsersWithArrayInputTest() throws ApiException { - List body = null; - // api.createUsersWithArrayInput(body); - // TODO: test validations - } - - /** - * Creates list of users with given input array - * - * - * - * @throws ApiException - * if the Api call fails - */ @Test - public void createUsersWithListInputTest() throws ApiException { - List body = null; - // api.createUsersWithListInput(body); + public void testCreateUser() throws Exception { + User user = createUser(); - // TODO: test validations - } - - /** - * Delete user - * - * This can only be done by the logged in user. - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void deleteUserTest() throws ApiException { - String username = null; - // api.deleteUser(username); + api.createUser(user); - // TODO: test validations + User fetched = api.getUserByName(user.getUsername()); + assertEquals(user.getId(), fetched.getId()); } - - /** - * Get user by user name - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void getUserByNameTest() throws ApiException { - String username = null; - // User response = api.getUserByName(username); + public void testCreateUsersWithArray() throws Exception { + User user1 = createUser(); + user1.setUsername("user" + user1.getId()); + User user2 = createUser(); + user2.setUsername("user" + user2.getId()); + + api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); - // TODO: test validations + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); } - - /** - * Logs user into the system - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void loginUserTest() throws ApiException { - String username = null; - String password = null; - // String response = api.loginUser(username, password); + public void testCreateUsersWithList() throws Exception { + User user1 = createUser(); + user1.setUsername("user" + user1.getId()); + User user2 = createUser(); + user2.setUsername("user" + user2.getId()); + + api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); - // TODO: test validations + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); } - - /** - * Logs out current logged in user session - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void logoutUserTest() throws ApiException { - // api.logoutUser(); + public void testLoginUser() throws Exception { + User user = createUser(); + api.createUser(user); - // TODO: test validations + String token = api.loginUser(user.getUsername(), user.getPassword()); + assertTrue(token.startsWith("logged in user session:")); } - - /** - * Updated user - * - * This can only be done by the logged in user. - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void updateUserTest() throws ApiException { - String username = null; - User body = null; - // api.updateUser(username, body); + public void logoutUser() throws Exception { + api.logoutUser(); + } + + private User createUser() { + User user = new User(); + user.setId(TestUtils.nextId()); + user.setUsername("fred" + user.getId()); + user.setFirstName("Fred"); + user.setLastName("Meyer"); + user.setEmail("fred@fredmeyer.com"); + user.setPassword("xxXXxx"); + user.setPhone("408-867-5309"); + user.setUserStatus(123); - // TODO: test validations + return user; } - } From 8533ca43b441d2681f87e6adaf3291e14d4d0b03 Mon Sep 17 00:00:00 2001 From: christian Date: Sat, 9 Jul 2016 23:50:23 +0200 Subject: [PATCH 080/470] #3285 replaced setModelNamePrefix by setModelNameSuffix --- .../src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java index 8ad3c073bfb..fabd2947298 100644 --- a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java +++ b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java @@ -230,7 +230,7 @@ public void execute() throws MojoExecutionException { } if(isNotEmpty(modelNameSuffix)) { - configurator.setModelNamePrefix(modelNameSuffix); + configurator.setModelNameSuffix(modelNameSuffix); } if (null != templateDirectory) { From 0119a66479d8ee80a059fc55e6290586f34ba87a Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 10 Jul 2016 16:55:36 +0800 Subject: [PATCH 081/470] fix https://github.com/swagger-api/swagger-codegen/pull/3313/files#r70178399 --- .../src/main/resources/csharp/README.mustache | 14 ++++++++++---- .../petstore/csharp/SwaggerClient/IO.Swagger.sln | 10 +++++----- .../client/petstore/csharp/SwaggerClient/README.md | 11 ++++++----- .../SwaggerClient/src/IO.Swagger/IO.Swagger.csproj | 4 ++-- 4 files changed, 23 insertions(+), 16 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/README.mustache b/modules/swagger-codegen/src/main/resources/csharp/README.mustache index bad7879eddf..3baa46ccbea 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/README.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/README.mustache @@ -128,10 +128,16 @@ No model defined in this package ## Documentation for Authorization - -{{^authMethods}} All endpoints do not require authorization. -{{/authMethods}}{{#authMethods}}{{#last}} Authentication schemes defined for the API:{{/last}}{{/authMethods}} -{{#authMethods}}### {{name}} +{{^authMethods}} +All endpoints do not require authorization. +{{/authMethods}} +{{#authMethods}} +{{#last}} +Authentication schemes defined for the API: +{{/last}} +{{/authMethods}} +{{#authMethods}} +### {{name}} {{#isApiKey}}- **Type**: API key - **API key parameter name**: {{keyParamName}} diff --git a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln index d46556b3ff4..46f0f8d51c9 100644 --- a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln +++ b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln @@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 VisualStudioVersion = 12.0.0.0 MinimumVisualStudioVersion = 10.0.0.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{9391D4F3-E89A-41F1-B1C9-A9C885B3F96D}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{CD9F0463-DC9D-458F-A59D-A72DB4583934}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger.Test", "src\IO.Swagger.Test\IO.Swagger.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" EndProject @@ -12,10 +12,10 @@ Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution -{9391D4F3-E89A-41F1-B1C9-A9C885B3F96D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU -{9391D4F3-E89A-41F1-B1C9-A9C885B3F96D}.Debug|Any CPU.Build.0 = Debug|Any CPU -{9391D4F3-E89A-41F1-B1C9-A9C885B3F96D}.Release|Any CPU.ActiveCfg = Release|Any CPU -{9391D4F3-E89A-41F1-B1C9-A9C885B3F96D}.Release|Any CPU.Build.0 = Release|Any CPU +{CD9F0463-DC9D-458F-A59D-A72DB4583934}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{CD9F0463-DC9D-458F-A59D-A72DB4583934}.Debug|Any CPU.Build.0 = Debug|Any CPU +{CD9F0463-DC9D-458F-A59D-A72DB4583934}.Release|Any CPU.ActiveCfg = Release|Any CPU +{CD9F0463-DC9D-458F-A59D-A72DB4583934}.Release|Any CPU.Build.0 = Release|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/samples/client/petstore/csharp/SwaggerClient/README.md b/samples/client/petstore/csharp/SwaggerClient/README.md index e2d622cd13f..e07a8bbc4d6 100644 --- a/samples/client/petstore/csharp/SwaggerClient/README.md +++ b/samples/client/petstore/csharp/SwaggerClient/README.md @@ -1,12 +1,12 @@ # IO.Swagger - the C# library for the Swagger Petstore -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ This C# SDK is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: - API version: 1.0.0 - SDK version: 1.0.0 -- Build date: 2016-06-23T12:09:14.609+08:00 +- Build date: 2016-07-10T16:55:14.469+08:00 - Build package: class io.swagger.codegen.languages.CSharpClientCodegen ## Frameworks supported @@ -14,8 +14,8 @@ This C# SDK is automatically generated by the [Swagger Codegen](https://github.c - Windows Phone 7.1 (Mango) ## Dependencies -- [RestSharp] (https://www.nuget.org/packages/RestSharp) - 105.1.0 or later -- [Json.NET] (https://www.nuget.org/packages/Newtonsoft.Json/) - 7.0.0 or later +- [RestSharp](https://www.nuget.org/packages/RestSharp) - 105.1.0 or later +- [Json.NET](https://www.nuget.org/packages/Newtonsoft.Json/) - 7.0.0 or later The DLLs included in the package may not be the latest version. We recommned using [NuGet] (https://docs.nuget.org/consume/installing-nuget) to obtain the latest version of the packages: ``` @@ -81,6 +81,7 @@ namespace Example } ``` + ## Documentation for API Endpoints All URIs are relative to *http://petstore.swagger.io/v2* @@ -111,6 +112,7 @@ Class | Method | HTTP request | Description *UserApi* | [**UpdateUser**](docs/UserApi.md#updateuser) | **PUT** /user/{username} | Updated user + ## Documentation for Models - [Model.AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) @@ -143,7 +145,6 @@ Class | Method | HTTP request | Description ## Documentation for Authorization - ### api_key - **Type**: API key diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj index 0dfaea20cd8..ca39c546e01 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj @@ -2,7 +2,7 @@ + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.9.1 + + + 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 + + + + net.alchim31.maven + scala-maven-plugin + ${scala-maven-plugin-version} + + + scala-compile-first + process-resources + + add-source + compile + + + + scala-test-compile + process-test-resources + + testCompile + + + + + + -Xms128m + -Xmx1500m + + + + + + + + + org.scala-tools + maven-scala-plugin + + ${scala-version} + + + + + + + com.fasterxml.jackson.module + jackson-module-scala_2.10 + ${jackson-version} + + + com.sun.jersey + jersey-client + ${jersey-version} + + + com.sun.jersey.contribs + jersey-multipart + ${jersey-version} + + + org.jfarcand + jersey-ahc-client + ${jersey-async-version} + compile + + + org.scala-lang + scala-library + ${scala-version} + + + io.swagger + swagger-core + ${swagger-core-version} + + + org.scalatest + scalatest_2.10 + ${scala-test-version} + test + + + junit + junit + ${junit-version} + test + + + joda-time + joda-time + ${joda-time-version} + + + org.joda + joda-convert + ${joda-version} + + + + 2.10.4 + 1.2 + 2.2 + 1.19 + 1.5.8 + 1.0.5 + 1.0.0 + 2.4.2 + + 4.8.1 + 3.1.5 + 2.2.4 + + UTF-8 + + diff --git a/samples/client/petstore-security-test/scala/settings.gradle b/samples/client/petstore-security-test/scala/settings.gradle new file mode 100644 index 00000000000..5452c701c0e --- /dev/null +++ b/samples/client/petstore-security-test/scala/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "swagger-scala-client" \ No newline at end of file diff --git a/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/ApiInvoker.scala b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/ApiInvoker.scala new file mode 100644 index 00000000000..22f3dac7cf8 --- /dev/null +++ b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/ApiInvoker.scala @@ -0,0 +1,226 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.swagger.client + +import com.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.config.DefaultClientConfig +import com.sun.jersey.api.client.filter.LoggingFilter + +import com.sun.jersey.core.util.MultivaluedMapImpl +import com.sun.jersey.multipart.FormDataMultiPart +import com.sun.jersey.multipart.file.FileDataBodyPart + +import java.io.File +import java.net.URLEncoder +import javax.ws.rs.core.MediaType + +import scala.collection.JavaConverters._ +import scala.collection.mutable.HashMap + +import com.fasterxml.jackson.module.scala.DefaultScalaModule +import com.fasterxml.jackson.datatype.joda.JodaModule +import com.fasterxml.jackson.core.JsonGenerator.Feature +import com.fasterxml.jackson.databind._ +import com.fasterxml.jackson.annotation._ +import com.fasterxml.jackson.databind.annotation.JsonSerialize + +object ScalaJsonUtil { + def getJsonMapper = { + val mapper = new ObjectMapper() + mapper.registerModule(new DefaultScalaModule()) + mapper.registerModule(new JodaModule()); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT) + mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY) + mapper + } +} + +class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper, + httpHeaders: HashMap[String, String] = HashMap(), + hostMap: HashMap[String, Client] = HashMap(), + asyncHttpClient: Boolean = false, + authScheme: String = "", + authPreemptive: Boolean = false) { + + var defaultHeaders: HashMap[String, String] = httpHeaders + + def escape(value: String): String = { + URLEncoder.encode(value, "utf-8").replaceAll("\\+", "%20") + } + + def escape(value: Long): String = value.toString + def escape(value: Double): String = value.toString + def escape(value: Float): String = value.toString + + def deserialize(json: String, containerType: String, cls: Class[_]) = { + if (cls == classOf[String]) { + json match { + case s: String => { + if (s.startsWith("\"") && s.endsWith("\"") && s.length > 1) s.substring(1, s.length - 1) + else s + } + case _ => null + } + } else { + containerType.toLowerCase match { + case "array" => { + val typeInfo = mapper.getTypeFactory().constructCollectionType(classOf[java.util.List[_]], cls) + val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]] + response.asScala.toList + } + case "list" => { + val typeInfo = mapper.getTypeFactory().constructCollectionType(classOf[java.util.List[_]], cls) + val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]] + response.asScala.toList + } + case _ => { + json match { + case e: String if ("\"\"" == e) => null + case _ => mapper.readValue(json, cls) + } + } + } + } + } + + def serialize(obj: AnyRef): String = { + if (obj != null) { + obj match { + case e: List[_] => mapper.writeValueAsString(obj.asInstanceOf[List[_]].asJava) + case _ => mapper.writeValueAsString(obj) + } + } else null + } + + def invokeApi(host: String, path: String, method: String, queryParams: Map[String, String], formParams: Map[String, String], body: AnyRef, headerParams: Map[String, String], contentType: String): String = { + val client = getClient(host) + + val querystring = queryParams.filter(k => k._2 != null).map(k => (escape(k._1) + "=" + escape(k._2))).mkString("?", "&", "") + val builder = client.resource(host + path + querystring).accept(contentType) + headerParams.map(p => builder.header(p._1, p._2)) + defaultHeaders.map(p => { + headerParams.contains(p._1) match { + case true => // override default with supplied header + case false => if (p._2 != null) builder.header(p._1, p._2) + } + }) + var formData: MultivaluedMapImpl = null + if(contentType == "application/x-www-form-urlencoded") { + formData = new MultivaluedMapImpl() + formParams.map(p => formData.add(p._1, p._2)) + } + + val response: ClientResponse = method match { + case "GET" => { + builder.get(classOf[ClientResponse]).asInstanceOf[ClientResponse] + } + case "POST" => { + if(formData != null) builder.post(classOf[ClientResponse], formData) + else if(body != null && body.isInstanceOf[File]) { + val file = body.asInstanceOf[File] + val form = new FormDataMultiPart() + form.field("filename", file.getName()) + form.bodyPart(new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE)) + builder.post(classOf[ClientResponse], form) + } + else { + if(body == null) builder.post(classOf[ClientResponse], serialize(body)) + else builder.`type`(contentType).post(classOf[ClientResponse], serialize(body)) + } + } + case "PUT" => { + if(formData != null) builder.post(classOf[ClientResponse], formData) + else if(body == null) builder.put(classOf[ClientResponse], null) + else builder.`type`(contentType).put(classOf[ClientResponse], serialize(body)) + } + case "DELETE" => { + builder.delete(classOf[ClientResponse]) + } + case _ => null + } + response.getStatusInfo().getStatusCode() match { + case 204 => "" + case code: Int if (Range(200, 299).contains(code)) => { + response.hasEntity() match { + case true => response.getEntity(classOf[String]) + case false => "" + } + } + case _ => { + val entity = response.hasEntity() match { + case true => response.getEntity(classOf[String]) + case false => "no data" + } + throw new ApiException( + response.getStatusInfo().getStatusCode(), + entity) + } + } + } + + def getClient(host: String): Client = { + hostMap.contains(host) match { + case true => hostMap(host) + case false => { + val client = newClient(host) + // client.addFilter(new LoggingFilter()) + hostMap += host -> client + client + } + } + } + + def newClient(host: String): Client = asyncHttpClient match { + case true => { + import org.sonatype.spice.jersey.client.ahc.config.DefaultAhcConfig + import org.sonatype.spice.jersey.client.ahc.AhcHttpClient + import com.ning.http.client.Realm + + val config: DefaultAhcConfig = new DefaultAhcConfig() + if (!authScheme.isEmpty) { + val authSchemeEnum = Realm.AuthScheme.valueOf(authScheme) + config.getAsyncHttpClientConfigBuilder + .setRealm(new Realm.RealmBuilder().setScheme(authSchemeEnum) + .setUsePreemptiveAuth(authPreemptive).build) + } + AhcHttpClient.create(config) + } + case _ => Client.create() + } +} + +object ApiInvoker extends ApiInvoker(mapper = ScalaJsonUtil.getJsonMapper, + httpHeaders = HashMap(), + hostMap = HashMap(), + asyncHttpClient = false, + authScheme = "", + authPreemptive = false) + +class ApiException(val code: Int, msg: String) extends RuntimeException(msg) diff --git a/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/api/FakeApi.scala b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/api/FakeApi.scala new file mode 100644 index 00000000000..ce6f4eee77f --- /dev/null +++ b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/api/FakeApi.scala @@ -0,0 +1,92 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.swagger.client.api + +import io.swagger.client.ApiInvoker +import io.swagger.client.ApiException + +import com.sun.jersey.multipart.FormDataMultiPart +import com.sun.jersey.multipart.file.FileDataBodyPart + +import javax.ws.rs.core.MediaType + +import java.io.File +import java.util.Date + +import scala.collection.mutable.HashMap + +class FakeApi(val defBasePath: String = "https://petstore.swagger.io *_/ ' \" =end \\r\\n \\n \\r/v2 *_/ ' \" =end \\r\\n \\n \\r", + defApiInvoker: ApiInvoker = ApiInvoker) { + var basePath = defBasePath + var apiInvoker = defApiInvoker + + def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value + + /** + * To test code injection *_/ ' \" =end \\r\\n \\n \\r + * + * @param testCodeInjectEndRnNR To test code injection *_/ ' \" =end \\r\\n \\n \\r (optional) + * @return void + */ + def testCodeInject * ' " =end rn n r (testCodeInjectEndRnNR: String) = { + // create path and map variables + val path = "/fake".replaceAll("\\{format\\}","json") + val contentTypes = List("application/json", "*/ ' =end + + ", "application/json") + val contentType = contentTypes(0) + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + val formParams = new HashMap[String, String] + + + + var postBody: AnyRef = null + + if(contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart() + + mp.field("test code inject */ ' " =end \r\n \n \r", testCodeInjectEndRnNR.toString(), MediaType.MULTIPART_FORM_DATA_TYPE) + + postBody = mp + } + else { + formParams += "test code inject */ ' " =end \r\n \n \r" -> testCodeInjectEndRnNR.toString() + } + + try { + apiInvoker.invokeApi(basePath, path, "PUT", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { + case s: String => + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + +} diff --git a/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/model/ModelReturn.scala b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/model/ModelReturn.scala new file mode 100644 index 00000000000..08aaff0573a --- /dev/null +++ b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/model/ModelReturn.scala @@ -0,0 +1,32 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.swagger.client.model + + + + +case class ModelReturn ( + /* property description *_/ ' \" =end \\r\\n \\n \\r */ + _return: Integer) diff --git a/samples/client/petstore-security-test/swift/.gitignore b/samples/client/petstore-security-test/swift/.gitignore new file mode 100644 index 00000000000..5e5d5cebcf4 --- /dev/null +++ b/samples/client/petstore-security-test/swift/.gitignore @@ -0,0 +1,63 @@ +# Xcode +# +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + +## Build generated +build/ +DerivedData + +## Various settings +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 +xcuserdata + +## Other +*.xccheckout +*.moved-aside +*.xcuserstate +*.xcscmblueprint + +## Obj-C/Swift specific +*.hmap +*.ipa + +## Playgrounds +timeline.xctimeline +playground.xcworkspace + +# Swift Package Manager +# +# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. +# Packages/ +.build/ + +# CocoaPods +# +# We recommend against adding the Pods directory to your .gitignore. However +# you should judge for yourself, the pros and cons are mentioned at: +# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control +# +# Pods/ + +# Carthage +# +# Add this line if you want to avoid checking in source code from Carthage dependencies. +# Carthage/Checkouts + +Carthage/Build + +# fastlane +# +# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the +# screenshots whenever they are needed. +# For more information about the recommended setup visit: +# https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md + +fastlane/report.xml +fastlane/screenshots diff --git a/samples/client/petstore-security-test/swift/.swagger-codegen-ignore b/samples/client/petstore-security-test/swift/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore-security-test/swift/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore-security-test/swift/Cartfile b/samples/client/petstore-security-test/swift/Cartfile new file mode 100644 index 00000000000..3d90db16891 --- /dev/null +++ b/samples/client/petstore-security-test/swift/Cartfile @@ -0,0 +1 @@ +github "Alamofire/Alamofire" >= 3.1.0 diff --git a/samples/client/petstore-security-test/swift/LICENSE b/samples/client/petstore-security-test/swift/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore-security-test/swift/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore-security-test/swift/SwaggerClient.podspec b/samples/client/petstore-security-test/swift/SwaggerClient.podspec new file mode 100644 index 00000000000..4786bf4084e --- /dev/null +++ b/samples/client/petstore-security-test/swift/SwaggerClient.podspec @@ -0,0 +1,10 @@ +Pod::Spec.new do |s| + s.name = 'SwaggerClient' + s.ios.deployment_target = '8.0' + s.osx.deployment_target = '10.9' + s.version = '0.0.1' + s.source = { :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' } + s.license = 'Apache License, Version 2.0' + s.source_files = 'SwaggerClient/Classes/Swaggers/**/*.swift' + s.dependency 'Alamofire', '~> 3.1.5' +end diff --git a/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/APIHelper.swift b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/APIHelper.swift new file mode 100644 index 00000000000..23e727b6b54 --- /dev/null +++ b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/APIHelper.swift @@ -0,0 +1,40 @@ +// APIHelper.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +class APIHelper { + static func rejectNil(source: [String:AnyObject?]) -> [String:AnyObject]? { + var destination = [String:AnyObject]() + for (key, nillableValue) in source { + if let value: AnyObject = nillableValue { + destination[key] = value + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + static func convertBoolToString(source: [String: AnyObject]?) -> [String:AnyObject]? { + guard let source = source else { + return nil + } + var destination = [String:AnyObject]() + let theTrue = NSNumber(bool: true) + let theFalse = NSNumber(bool: false) + for (key, value) in source { + switch value { + case let x where x === theTrue || x === theFalse: + destination[key] = "\(value as! Bool)" + default: + destination[key] = value + } + } + return destination + } + +} diff --git a/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/APIs.swift b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/APIs.swift new file mode 100644 index 00000000000..afc7afbc094 --- /dev/null +++ b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/APIs.swift @@ -0,0 +1,73 @@ +// APIs.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +public class SwaggerClientAPI { + public static var basePath = "https://petstore.swagger.io *_/ ' \" =end \\r\\n \\n \\r/v2 *_/ ' \" =end \\r\\n \\n \\r" + public static var credential: NSURLCredential? + public static var customHeaders: [String:String] = [:] + static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory() +} + +public class APIBase { + func toParameters(encodable: JSONEncodable?) -> [String: AnyObject]? { + let encoded: AnyObject? = encodable?.encodeToJSON() + + if encoded! is [AnyObject] { + var dictionary = [String:AnyObject]() + for (index, item) in (encoded as! [AnyObject]).enumerate() { + dictionary["\(index)"] = item + } + return dictionary + } else { + return encoded as? [String:AnyObject] + } + } +} + +public class RequestBuilder { + var credential: NSURLCredential? + var headers: [String:String] = [:] + let parameters: [String:AnyObject]? + let isBody: Bool + let method: String + let URLString: String + + required public init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool) { + self.method = method + self.URLString = URLString + self.parameters = parameters + self.isBody = isBody + + addHeaders(SwaggerClientAPI.customHeaders) + } + + public func addHeaders(aHeaders:[String:String]) { + for (header, value) in aHeaders { + headers[header] = value + } + } + + public func execute(completion: (response: Response?, error: ErrorType?) -> Void) { } + + public func addHeader(name name: String, value: String) -> Self { + if !value.isEmpty { + headers[name] = value + } + return self + } + + public func addCredential() -> Self { + self.credential = SwaggerClientAPI.credential + return self + } +} + +protocol RequestBuilderFactory { + func getBuilder() -> RequestBuilder.Type +} + diff --git a/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/APIs/FakeAPI.swift b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/APIs/FakeAPI.swift new file mode 100644 index 00000000000..0d35a764773 --- /dev/null +++ b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/APIs/FakeAPI.swift @@ -0,0 +1,51 @@ +// +// FakeAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire + + + +public class FakeAPI: APIBase { + /** + To test code injection *_/ ' \" =end \\r\\n \\n \\r + + - parameter testCodeInjectEndRnNR: (form) To test code injection *_/ ' \" =end \\r\\n \\n \\r (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func testCodeInjectEndRnNR(testCodeInjectEndRnNR testCodeInjectEndRnNR: String? = nil, completion: ((error: ErrorType?) -> Void)) { + testCodeInjectEndRnNRWithRequestBuilder(testCodeInjectEndRnNR: testCodeInjectEndRnNR).execute { (response, error) -> Void in + completion(error: error); + } + } + + + /** + To test code injection *_/ ' \" =end \\r\\n \\n \\r + - PUT /fake + + - parameter testCodeInjectEndRnNR: (form) To test code injection *_/ ' \" =end \\r\\n \\n \\r (optional) + + - returns: RequestBuilder + */ + public class func testCodeInjectEndRnNRWithRequestBuilder(testCodeInjectEndRnNR testCodeInjectEndRnNR: String? = nil) -> RequestBuilder { + let path = "/fake" + let URLString = SwaggerClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [ + "test code inject */ ' " =end \r\n \n \r": testCodeInjectEndRnNR + ] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = SwaggerClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: false) + } + +} diff --git a/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/AlamofireImplementations.swift new file mode 100644 index 00000000000..2faa0a6f24d --- /dev/null +++ b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/AlamofireImplementations.swift @@ -0,0 +1,112 @@ +// AlamofireImplementations.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire + +class AlamofireRequestBuilderFactory: RequestBuilderFactory { + func getBuilder() -> RequestBuilder.Type { + return AlamofireRequestBuilder.self + } +} + +// Store manager to retain its reference +private var managerStore: [String: Alamofire.Manager] = [:] + +class AlamofireRequestBuilder: RequestBuilder { + required init(method: String, URLString: String, parameters: [String : AnyObject]?, isBody: Bool) { + super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody) + } + + override func execute(completion: (response: Response?, error: ErrorType?) -> Void) { + let managerId = NSUUID().UUIDString + // Create a new manager for each request to customize its request header + let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() + configuration.HTTPAdditionalHeaders = buildHeaders() + let manager = Alamofire.Manager(configuration: configuration) + managerStore[managerId] = manager + + let encoding = isBody ? Alamofire.ParameterEncoding.JSON : Alamofire.ParameterEncoding.URL + let xMethod = Alamofire.Method(rawValue: method) + let fileKeys = parameters == nil ? [] : parameters!.filter { $1.isKindOfClass(NSURL) } + .map { $0.0 } + + if fileKeys.count > 0 { + manager.upload( + xMethod!, URLString, headers: nil, + multipartFormData: { mpForm in + for (k, v) in self.parameters! { + switch v { + case let fileURL as NSURL: + mpForm.appendBodyPart(fileURL: fileURL, name: k) + break + case let string as NSString: + mpForm.appendBodyPart(data: string.dataUsingEncoding(NSUTF8StringEncoding)!, name: k) + break + case let number as NSNumber: + mpForm.appendBodyPart(data: number.stringValue.dataUsingEncoding(NSUTF8StringEncoding)!, name: k) + break + default: + fatalError("Unprocessable value \(v) with key \(k)") + break + } + } + }, + encodingMemoryThreshold: Manager.MultipartFormDataEncodingMemoryThreshold, + encodingCompletion: { encodingResult in + switch encodingResult { + case .Success(let upload, _, _): + self.processRequest(upload, managerId, completion) + case .Failure(let encodingError): + completion(response: nil, error: encodingError) + } + } + ) + } else { + processRequest(manager.request(xMethod!, URLString, parameters: parameters, encoding: encoding), managerId, completion) + } + + } + + private func processRequest(request: Request, _ managerId: String, _ completion: (response: Response?, error: ErrorType?) -> Void) { + if let credential = self.credential { + request.authenticate(usingCredential: credential) + } + + request.validate().responseJSON(options: .AllowFragments) { response in + managerStore.removeValueForKey(managerId) + + if response.result.isFailure { + completion(response: nil, error: response.result.error) + return + } + + if () is T { + completion(response: Response(response: response.response!, body: () as! T), error: nil) + return + } + if let json: AnyObject = response.result.value { + let body = Decoders.decode(clazz: T.self, source: json) + completion(response: Response(response: response.response!, body: body), error: nil) + return + } else if "" is T { + // swagger-parser currently doesn't support void, which will be fixed in future swagger-parser release + // https://github.com/swagger-api/swagger-parser/pull/34 + completion(response: Response(response: response.response!, body: "" as! T), error: nil) + return + } + + completion(response: nil, error: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) + } + } + + private func buildHeaders() -> [String: AnyObject] { + var httpHeaders = Manager.defaultHTTPHeaders + for (key, value) in self.headers { + httpHeaders[key] = value + } + return httpHeaders + } +} diff --git a/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/Extensions.swift b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/Extensions.swift new file mode 100644 index 00000000000..fed87969388 --- /dev/null +++ b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/Extensions.swift @@ -0,0 +1,74 @@ +// Extensions.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire + +extension Bool: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +extension Float: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +extension Int: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +extension Int32: JSONEncodable { + func encodeToJSON() -> AnyObject { return NSNumber(int: self) } +} + +extension Int64: JSONEncodable { + func encodeToJSON() -> AnyObject { return NSNumber(longLong: self) } +} + +extension Double: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +extension String: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +private func encodeIfPossible(object: T) -> AnyObject { + if object is JSONEncodable { + return (object as! JSONEncodable).encodeToJSON() + } else { + return object as! AnyObject + } +} + +extension Array: JSONEncodable { + func encodeToJSON() -> AnyObject { + return self.map(encodeIfPossible) + } +} + +extension Dictionary: JSONEncodable { + func encodeToJSON() -> AnyObject { + var dictionary = [NSObject:AnyObject]() + for (key, value) in self { + dictionary[key as! NSObject] = encodeIfPossible(value) + } + return dictionary + } +} + + +private let dateFormatter: NSDateFormatter = { + let dateFormatter = NSDateFormatter() + dateFormatter.dateFormat = "yyyy-MM-dd" + return dateFormatter +}() + +extension NSDate: JSONEncodable { + func encodeToJSON() -> AnyObject { + return dateFormatter.stringFromDate(self) + } +} + + diff --git a/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/Models.swift b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/Models.swift new file mode 100644 index 00000000000..3f70e2a1c5e --- /dev/null +++ b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/Models.swift @@ -0,0 +1,147 @@ +// Models.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +protocol JSONEncodable { + func encodeToJSON() -> AnyObject +} + +public class Response { + public let statusCode: Int + public let header: [String: String] + public let body: T + + public init(statusCode: Int, header: [String: String], body: T) { + self.statusCode = statusCode + self.header = header + self.body = body + } + + public convenience init(response: NSHTTPURLResponse, body: T) { + let rawHeader = response.allHeaderFields + var header = [String:String]() + for (key, value) in rawHeader { + header[key as! String] = value as? String + } + self.init(statusCode: response.statusCode, header: header, body: body) + } +} + +private var once = dispatch_once_t() +class Decoders { + static private var decoders = Dictionary AnyObject)>() + + static func addDecoder(clazz clazz: T.Type, decoder: ((AnyObject) -> T)) { + let key = "\(T.self)" + decoders[key] = { decoder($0) as! AnyObject } + } + + static func decode(clazz clazz: [T].Type, source: AnyObject) -> [T] { + let array = source as! [AnyObject] + return array.map { Decoders.decode(clazz: T.self, source: $0) } + } + + static func decode(clazz clazz: [Key:T].Type, source: AnyObject) -> [Key:T] { + let sourceDictionary = source as! [Key: AnyObject] + var dictionary = [Key:T]() + for (key, value) in sourceDictionary { + dictionary[key] = Decoders.decode(clazz: T.self, source: value) + } + return dictionary + } + + static func decode(clazz clazz: T.Type, source: AnyObject) -> T { + initialize() + if T.self is Int32.Type && source is NSNumber { + return source.intValue as! T; + } + if T.self is Int64.Type && source is NSNumber { + return source.longLongValue as! T; + } + if source is T { + return source as! T + } + + let key = "\(T.self)" + if let decoder = decoders[key] { + return decoder(source) as! T + } else { + fatalError("Source \(source) is not convertible to type \(clazz): Maybe swagger file is insufficient") + } + } + + static func decodeOptional(clazz clazz: T.Type, source: AnyObject?) -> T? { + if source is NSNull { + return nil + } + return source.map { (source: AnyObject) -> T in + Decoders.decode(clazz: clazz, source: source) + } + } + + static func decodeOptional(clazz clazz: [T].Type, source: AnyObject?) -> [T]? { + if source is NSNull { + return nil + } + return source.map { (someSource: AnyObject) -> [T] in + Decoders.decode(clazz: clazz, source: someSource) + } + } + + static func decodeOptional(clazz clazz: [Key:T].Type, source: AnyObject?) -> [Key:T]? { + if source is NSNull { + return nil + } + return source.map { (someSource: AnyObject) -> [Key:T] in + Decoders.decode(clazz: clazz, source: someSource) + } + } + + static private func initialize() { + dispatch_once(&once) { + let formatters = [ + "yyyy-MM-dd", + "yyyy-MM-dd'T'HH:mm:ssZZZZZ", + "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ", + "yyyy-MM-dd'T'HH:mm:ss'Z'", + "yyyy-MM-dd'T'HH:mm:ss.SSS" + ].map { (format: String) -> NSDateFormatter in + let formatter = NSDateFormatter() + formatter.dateFormat = format + return formatter + } + // Decoder for NSDate + Decoders.addDecoder(clazz: NSDate.self) { (source: AnyObject) -> NSDate in + if let sourceString = source as? String { + for formatter in formatters { + if let date = formatter.dateFromString(sourceString) { + return date + } + } + + } + if let sourceInt = source as? Int { + // treat as a java date + return NSDate(timeIntervalSince1970: Double(sourceInt / 1000) ) + } + fatalError("formatter failed to parse \(source)") + } + + // Decoder for [Return] + Decoders.addDecoder(clazz: [Return].self) { (source: AnyObject) -> [Return] in + return Decoders.decode(clazz: [Return].self, source: source) + } + // Decoder for Return + Decoders.addDecoder(clazz: Return.self) { (source: AnyObject) -> Return in + let sourceDictionary = source as! [NSObject:AnyObject] + let instance = Return() + instance._return = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["return"]) + return instance + } + } + } +} diff --git a/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/Models/Return.swift b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/Models/Return.swift new file mode 100644 index 00000000000..30c76776b83 --- /dev/null +++ b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/Models/Return.swift @@ -0,0 +1,25 @@ +// +// Return.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +/** Model for testing reserved words *_/ ' \" =end \\r\\n \\n \\r */ +public class Return: JSONEncodable { + /** property description *_/ ' \" =end \\r\\n \\n \\r */ + public var _return: Int32? + + public init() {} + + // MARK: JSONEncodable + func encodeToJSON() -> AnyObject { + var nillableDictionary = [String:AnyObject?]() + nillableDictionary["return"] = self._return?.encodeToJSON() + let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} diff --git a/samples/client/petstore-security-test/swift/git_push.sh b/samples/client/petstore-security-test/swift/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore-security-test/swift/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/client/petstore-security-test/typescript-angular/.gitignore b/samples/client/petstore-security-test/typescript-angular/.gitignore new file mode 100644 index 00000000000..35e2fb2b02e --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular/.gitignore @@ -0,0 +1,3 @@ +wwwroot/*.js +node_modules +typings diff --git a/samples/client/petstore-security-test/typescript-angular/.swagger-codegen-ignore b/samples/client/petstore-security-test/typescript-angular/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore-security-test/typescript-angular/API/Client/FakeApi.ts b/samples/client/petstore-security-test/typescript-angular/API/Client/FakeApi.ts new file mode 100644 index 00000000000..7e22ee8d0ed --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular/API/Client/FakeApi.ts @@ -0,0 +1,85 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/// + +/* tslint:disable:no-unused-variable member-ordering */ + +namespace API.Client { + 'use strict'; + + export class FakeApi { + protected basePath = 'https://petstore.swagger.io *_/ ' \" =end \\r\\n \\n \\r/v2 *_/ ' \" =end \\r\\n \\n \\r'; + public defaultHeaders : any = {}; + + static $inject: string[] = ['$http', '$httpParamSerializer', 'basePath']; + + constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { + if (basePath !== undefined) { + this.basePath = basePath; + } + } + + private extendObj(objA: T1, objB: T2) { + for(let key in objB){ + if(objB.hasOwnProperty(key)){ + objA[key] = objB[key]; + } + } + return objA; + } + + /** + * To test code injection *_/ ' \" =end \\r\\n \\n \\r + * + * @param test code inject * ' " =end rn n r To test code injection *_/ ' \" =end \\r\\n \\n \\r + */ + public testCodeInjectEndRnNR (test code inject * ' " =end rn n r?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const localVarPath = this.basePath + '/fake'; + + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; + + formParams['test code inject */ ' " =end \r\n \n \r'] = test code inject * ' " =end rn n r; + + let httpRequestParams: any = { + method: 'PUT', + url: localVarPath, + json: false, + data: this.$httpParamSerializer(formParams), + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + } +} diff --git a/samples/client/petstore-security-test/typescript-angular/API/Client/ModelReturn.ts b/samples/client/petstore-security-test/typescript-angular/API/Client/ModelReturn.ts new file mode 100644 index 00000000000..7509de72a30 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular/API/Client/ModelReturn.ts @@ -0,0 +1,41 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/// + +namespace API.Client { + 'use strict'; + + /** + * Model for testing reserved words *_/ ' \" =end \\r\\n \\n \\r + */ + export interface ModelReturn { + + /** + * property description *_/ ' \" =end \\r\\n \\n \\r + */ + "return"?: number; + } + +} diff --git a/samples/client/petstore-security-test/typescript-angular/API/Client/api.d.ts b/samples/client/petstore-security-test/typescript-angular/API/Client/api.d.ts new file mode 100644 index 00000000000..258d4403228 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular/API/Client/api.d.ts @@ -0,0 +1,3 @@ +/// + +/// diff --git a/samples/client/petstore-security-test/typescript-angular/LICENSE b/samples/client/petstore-security-test/typescript-angular/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore-security-test/typescript-angular/git_push.sh b/samples/client/petstore-security-test/typescript-angular/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/client/petstore-security-test/typescript-angular2/.gitignore b/samples/client/petstore-security-test/typescript-angular2/.gitignore new file mode 100644 index 00000000000..35e2fb2b02e --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular2/.gitignore @@ -0,0 +1,3 @@ +wwwroot/*.js +node_modules +typings diff --git a/samples/client/petstore-security-test/typescript-angular2/.swagger-codegen-ignore b/samples/client/petstore-security-test/typescript-angular2/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular2/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore-security-test/typescript-angular2/LICENSE b/samples/client/petstore-security-test/typescript-angular2/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular2/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore-security-test/typescript-angular2/api/FakeApi.ts b/samples/client/petstore-security-test/typescript-angular2/api/FakeApi.ts new file mode 100644 index 00000000000..88b8e7a6562 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular2/api/FakeApi.ts @@ -0,0 +1,79 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; +import {Injectable, Optional} from '@angular/core'; +import {Observable} from 'rxjs/Observable'; +import * as models from '../model/models'; +import 'rxjs/Rx'; + +/* tslint:disable:no-unused-variable member-ordering */ + +'use strict'; + +@Injectable() +export class FakeApi { + protected basePath = 'https://petstore.swagger.io *_/ ' \" =end \\r\\n \\n \\r/v2 *_/ ' \" =end \\r\\n \\n \\r'; + public defaultHeaders : Headers = new Headers(); + + constructor(protected http: Http, @Optional() basePath: string) { + if (basePath) { + this.basePath = basePath; + } + } + + /** + * To test code injection *_/ ' \" =end \\r\\n \\n \\r + * + * @param test code inject * ' " =end rn n r To test code injection *_/ ' \" =end \\r\\n \\n \\r + */ + public testCodeInjectEndRnNR (test code inject * ' " =end rn n r?: string, extraHttpRequestParams?: any ) : Observable<{}> { + const path = this.basePath + '/fake'; + + let queryParameters = new URLSearchParams(); + let headerParams = this.defaultHeaders; + let formParams = new URLSearchParams(); + + headerParams.set('Content-Type', 'application/x-www-form-urlencoded'); + + formParams['test code inject */ ' " =end \r\n \n \r'] = test code inject * ' " =end rn n r; + + let requestOptions: RequestOptionsArgs = { + method: 'PUT', + headers: headerParams, + search: queryParameters + }; + requestOptions.body = formParams.toString(); + + return this.http.request(path, requestOptions) + .map((response: Response) => { + if (response.status === 204) { + return undefined; + } else { + return response.json(); + } + }); + } + +} diff --git a/samples/client/petstore-security-test/typescript-angular2/api/api.ts b/samples/client/petstore-security-test/typescript-angular2/api/api.ts new file mode 100644 index 00000000000..9525ab85127 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular2/api/api.ts @@ -0,0 +1 @@ +export * from './FakeApi'; diff --git a/samples/client/petstore-security-test/typescript-angular2/git_push.sh b/samples/client/petstore-security-test/typescript-angular2/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular2/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/client/petstore-security-test/typescript-angular2/index.ts b/samples/client/petstore-security-test/typescript-angular2/index.ts new file mode 100644 index 00000000000..557365516ad --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular2/index.ts @@ -0,0 +1,2 @@ +export * from './api/api'; +export * from './model/models'; \ No newline at end of file diff --git a/samples/client/petstore-security-test/typescript-angular2/model/ModelReturn.ts b/samples/client/petstore-security-test/typescript-angular2/model/ModelReturn.ts new file mode 100644 index 00000000000..23c982f6888 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular2/model/ModelReturn.ts @@ -0,0 +1,38 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; +import * as models from './models'; + +/** + * Model for testing reserved words *_/ ' \" =end \\r\\n \\n \\r + */ +export interface ModelReturn { + + + /** + * property description *_/ ' \" =end \\r\\n \\n \\r + */ + return?: number; +} diff --git a/samples/client/petstore-security-test/typescript-angular2/model/models.ts b/samples/client/petstore-security-test/typescript-angular2/model/models.ts new file mode 100644 index 00000000000..df8a2d48008 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular2/model/models.ts @@ -0,0 +1 @@ +export * from './ModelReturn'; diff --git a/samples/client/petstore-security-test/typescript-fetch/.gitignore b/samples/client/petstore-security-test/typescript-fetch/.gitignore new file mode 100644 index 00000000000..35e2fb2b02e --- /dev/null +++ b/samples/client/petstore-security-test/typescript-fetch/.gitignore @@ -0,0 +1,3 @@ +wwwroot/*.js +node_modules +typings diff --git a/samples/client/petstore-security-test/typescript-fetch/.swagger-codegen-ignore b/samples/client/petstore-security-test/typescript-fetch/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-fetch/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore-security-test/typescript-fetch/LICENSE b/samples/client/petstore-security-test/typescript-fetch/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-fetch/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore-security-test/typescript-fetch/README.md b/samples/client/petstore-security-test/typescript-fetch/README.md new file mode 100644 index 00000000000..db2dfccec36 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-fetch/README.md @@ -0,0 +1,54 @@ +# TypeScript-Fetch + +This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The generated Node module can be used in the following environments: + +Environment +* Node.js +* Webpack +* Browserify + +Language level +* ES5 - you must have a Promises/A+ library installed +* ES6 + +Module system +* CommonJS +* ES6 module system + +It can be used in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) + +### Installation ### + +`swagger-codegen` does not generate JavaScript directly. The generated Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile during `prepublish` stage. The should be run automatically during `npm install` or `npm publish`. + +CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` would skip all scripts if the user is `root`. You would need to manually run it with `npm run prepublish` or run `npm install --unsafe-perm`. + +#### NPM #### +You may publish the module to NPM. In this case, you would be able to install the module as any other NPM module. It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). + +You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink everytime you deploy that project. + +You can also directly install the module using `npm install file_path`. If you do `npm install file_path --save`, NPM will save relative path to `package.json`. In this case, `npm install` and `npm shrinkwrap` may misbehave. You would need to manually edit `package.json` and replace it with absolute path. + +Regardless of which method you deployed your NPM module, the ES6 module syntaxes are as follows: +``` +import * as localName from 'npmName'; +import {operationId} from 'npmName'; +``` +The CommonJS syntax is as follows: +``` +import localName = require('npmName'); +``` + +#### Direct copy/symlink #### +You may also simply copy or symlink the generated module into a directory under your project. The syntax of this is as follows: + +With ES6 module syntax, the following syntaxes are supported: +``` +import * as localName from './symlinkDir'; +import {operationId} from './symlinkDir'; +``` +The CommonJS syntax is as follows: +``` +import localName = require('./symlinkDir')'; +``` diff --git a/samples/client/petstore-security-test/typescript-fetch/api.ts b/samples/client/petstore-security-test/typescript-fetch/api.ts new file mode 100644 index 00000000000..b439ec1d8ed --- /dev/null +++ b/samples/client/petstore-security-test/typescript-fetch/api.ts @@ -0,0 +1,125 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as querystring from "querystring"; +import * as url from "url"; + +import * as isomorphicFetch from "isomorphic-fetch"; +import * as assign from "core-js/library/fn/object/assign"; + +interface Dictionary { [index: string]: T; } +export interface FetchAPI { (url: string, init?: any): Promise; } + +const BASE_PATH = "https://petstore.swagger.io *_/ ' \" =end \\r\\n \\n \\r/v2 *_/ ' \" =end \\r\\n \\n \\r"; + +export interface FetchArgs { + url: string; + options: any; +} + +export class BaseAPI { + basePath: string; + fetch: FetchAPI; + + constructor(fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) { + this.basePath = basePath; + this.fetch = fetch; + } +} + +/** + * Model for testing reserved words *_/ ' \" =end \\r\\n \\n \\r + */ +export interface ModelReturn { + /** + * property description *_/ ' \" =end \\r\\n \\n \\r + */ + "return"?: number; +} + + + +/** + * FakeApi - fetch parameter creator + */ +export const FakeApiFetchParamCreactor = { + /** + * To test code injection *_/ ' \" =end \\r\\n \\n \\r + * @param test code inject * ' " =end rn n r To test code injection *_/ ' \" =end \\r\\n \\n \\r + */ + testCodeInjectEndRnNR(params: { test code inject * ' " =end rn n r?: string; }): FetchArgs { + const baseUrl = `/fake`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "PUT" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; + fetchOptions.body = querystring.stringify({ + "test code inject */ ' " =end \r\n \n \r": params.test code inject * ' " =end rn n r, + }); + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +} + +/** + * FakeApi - functional programming interface + */ +export const FakeApiFp = { + /** + * To test code injection *_/ ' \" =end \\r\\n \\n \\r + * @param test code inject * ' " =end rn n r To test code injection *_/ ' \" =end \\r\\n \\n \\r + */ + testCodeInjectEndRnNR(params: { test code inject * ' " =end rn n r?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = FakeApiFetchParamCreactor.testCodeInjectEndRnNR(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, +}; + +/** + * FakeApi - object-oriented interface + */ +export class FakeApi extends BaseAPI { + /** + * To test code injection *_/ ' \" =end \\r\\n \\n \\r + * @param test code inject * ' " =end rn n r To test code injection *_/ ' \" =end \\r\\n \\n \\r + */ + testCodeInjectEndRnNR(params: { test code inject * ' " =end rn n r?: string; }) { + return FakeApiFp.testCodeInjectEndRnNR(params)(this.fetch, this.basePath); + } +} + diff --git a/samples/client/petstore-security-test/typescript-fetch/git_push.sh b/samples/client/petstore-security-test/typescript-fetch/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-fetch/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/client/petstore-security-test/typescript-fetch/package.json b/samples/client/petstore-security-test/typescript-fetch/package.json new file mode 100644 index 00000000000..97e572353a3 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-fetch/package.json @@ -0,0 +1,19 @@ +{ + "name": "typescript-fetch-api", + "version": "0.0.0", + "license": "Apache-2.0", + "main": "./dist/api.js", + "browser": "./dist/api.js", + "typings": "./dist/api.d.ts", + "dependencies": { + "core-js": "^2.4.0", + "isomorphic-fetch": "^2.2.1" + }, + "scripts" : { + "prepublish" : "typings install && tsc" + }, + "devDependencies": { + "typescript": "^1.8.10", + "typings": "^1.0.4" + } +} diff --git a/samples/client/petstore-security-test/typescript-fetch/tsconfig.json b/samples/client/petstore-security-test/typescript-fetch/tsconfig.json new file mode 100644 index 00000000000..72ff2567206 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-fetch/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "declaration": true, + "target": "es5", + "module": "commonjs", + "noImplicitAny": true, + "outDir": "dist", + "rootDir": "." + }, + "exclude": [ + "dist", + "node_modules", + "typings/browser", + "typings/main", + "typings/main.d.ts" + ] +} diff --git a/samples/client/petstore-security-test/typescript-fetch/typings.json b/samples/client/petstore-security-test/typescript-fetch/typings.json new file mode 100644 index 00000000000..a82ea152b4a --- /dev/null +++ b/samples/client/petstore-security-test/typescript-fetch/typings.json @@ -0,0 +1,9 @@ +{ + "version": false, + "dependencies": {}, + "globalDependencies": { + "core-js": "registry:dt/core-js#0.0.0+20160317120654", + "node": "registry:dt/node#4.0.0+20160423143914", + "isomorphic-fetch": "registry:dt/isomorphic-fetch#0.0.0+20160505171433" + } +} diff --git a/samples/client/petstore-security-test/typescript-node/.gitignore b/samples/client/petstore-security-test/typescript-node/.gitignore new file mode 100644 index 00000000000..35e2fb2b02e --- /dev/null +++ b/samples/client/petstore-security-test/typescript-node/.gitignore @@ -0,0 +1,3 @@ +wwwroot/*.js +node_modules +typings diff --git a/samples/client/petstore-security-test/typescript-node/.swagger-codegen-ignore b/samples/client/petstore-security-test/typescript-node/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-node/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore-security-test/typescript-node/LICENSE b/samples/client/petstore-security-test/typescript-node/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-node/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore-security-test/typescript-node/api.ts b/samples/client/petstore-security-test/typescript-node/api.ts new file mode 100644 index 00000000000..4afd3239aa3 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-node/api.ts @@ -0,0 +1,193 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import request = require('request'); +import http = require('http'); +import Promise = require('bluebird'); + +let defaultBasePath = 'https://petstore.swagger.io *_/ ' \" =end \\r\\n \\n \\r/v2 *_/ ' \" =end \\r\\n \\n \\r'; + +// =============================================== +// This file is autogenerated - Please do not edit +// =============================================== + +/* tslint:disable:no-unused-variable */ + +/** +* Model for testing reserved words *_/ ' \" =end \\r\\n \\n \\r +*/ +export class ModelReturn { + /** + * property description *_/ ' \" =end \\r\\n \\n \\r + */ + 'return': number; +} + + +export interface Authentication { + /** + * Apply authentication settings to header and query params. + */ + applyToRequest(requestOptions: request.Options): void; +} + +export class HttpBasicAuth implements Authentication { + public username: string; + public password: string; + applyToRequest(requestOptions: request.Options): void { + requestOptions.auth = { + username: this.username, password: this.password + } + } +} + +export class ApiKeyAuth implements Authentication { + public apiKey: string; + + constructor(private location: string, private paramName: string) { + } + + applyToRequest(requestOptions: request.Options): void { + if (this.location == "query") { + (requestOptions.qs)[this.paramName] = this.apiKey; + } else if (this.location == "header") { + requestOptions.headers[this.paramName] = this.apiKey; + } + } +} + +export class OAuth implements Authentication { + public accessToken: string; + + applyToRequest(requestOptions: request.Options): void { + requestOptions.headers["Authorization"] = "Bearer " + this.accessToken; + } +} + +export class VoidAuth implements Authentication { + public username: string; + public password: string; + applyToRequest(requestOptions: request.Options): void { + // Do nothing + } +} + +export enum FakeApiApiKeys { + api_key, +} + +export class FakeApi { + protected basePath = defaultBasePath; + protected defaultHeaders : any = {}; + protected _useQuerystring : boolean = false; + + protected authentications = { + 'default': new VoidAuth(), + 'api_key': new ApiKeyAuth('header', 'api_key */ ' " =end \r\n \n \r'), + 'petstore_auth': new OAuth(), + } + + constructor(basePath?: string); + constructor(basePathOrUsername: string, password?: string, basePath?: string) { + if (password) { + if (basePath) { + this.basePath = basePath; + } + } else { + if (basePathOrUsername) { + this.basePath = basePathOrUsername + } + } + } + + set useQuerystring(value: boolean) { + this._useQuerystring = value; + } + + public setApiKey(key: FakeApiApiKeys, value: string) { + this.authentications[FakeApiApiKeys[key]].apiKey = value; + } + + set accessToken(token: string) { + this.authentications.petstore_auth.accessToken = token; + } + private extendObj(objA: T1, objB: T2) { + for(let key in objB){ + if(objB.hasOwnProperty(key)){ + objA[key] = objB[key]; + } + } + return objA; + } + /** + * To test code injection *_/ ' \" =end \\r\\n \\n \\r + * + * @param test code inject * ' " =end rn n r To test code injection *_/ ' \" =end \\r\\n \\n \\r + */ + public testCodeInjectEndRnNR (test code inject * ' " =end rn n r?: string) : Promise<{ response: http.ClientResponse; body?: any; }> { + const localVarPath = this.basePath + '/fake'; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + let useFormData = false; + + if (test code inject * ' " =end rn n r !== undefined) { + formParams['test code inject */ ' " =end \r\n \n \r'] = test code inject * ' " =end rn n r; + } + + let requestOptions: request.Options = { + method: 'PUT', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + useQuerystring: this._useQuerystring, + json: true, + }; + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + } +} diff --git a/samples/client/petstore-security-test/typescript-node/git_push.sh b/samples/client/petstore-security-test/typescript-node/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-node/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + From 0d0d353b9d70cb3f9a523c3aeafa47ed94b63926 Mon Sep 17 00:00:00 2001 From: Christian Loitsch Date: Tue, 12 Jul 2016 17:18:45 +0200 Subject: [PATCH 085/470] feat dart: mv basePath to ApiClient Changing the basePath is pretty annoying otherwise, because you would need to set the basePath for every Api. --- .../swagger-codegen/src/main/resources/dart/api.mustache | 4 +--- .../src/main/resources/dart/api_client.mustache | 8 ++++---- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/dart/api.mustache b/modules/swagger-codegen/src/main/resources/dart/api.mustache index 04c24009380..477271c3a79 100644 --- a/modules/swagger-codegen/src/main/resources/dart/api.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/api.mustache @@ -4,7 +4,6 @@ part of api; class {{classname}} { - String basePath = "{{basePath}}"; final ApiClient apiClient; {{classname}}([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; @@ -73,8 +72,7 @@ class {{classname}} { {{/formParams}} } - var response = await apiClient.invokeAPI(basePath, - path, + var response = await apiClient.invokeAPI(path, '{{httpMethod}}', queryParams, postBody, diff --git a/modules/swagger-codegen/src/main/resources/dart/api_client.mustache b/modules/swagger-codegen/src/main/resources/dart/api_client.mustache index e83d8b62a6d..74a6bf82c65 100644 --- a/modules/swagger-codegen/src/main/resources/dart/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/api_client.mustache @@ -9,6 +9,7 @@ class QueryParam { class ApiClient { + String basePath; var client = new {{#browserClient}}Browser{{/browserClient}}Client(); Map _defaultHeaderMap = {}; @@ -20,7 +21,7 @@ class ApiClient { final _RegList = new RegExp(r'^List<(.*)>$'); final _RegMap = new RegExp(r'^Map$'); - ApiClient() { + ApiClient({this.basePath: "{{{basePath}}}"}) { // Setup authentications (key: authentication name, value: authentication).{{#authMethods}}{{#isBasic}} _authentications['{{name}}'] = new HttpBasicAuth();{{/isBasic}}{{#isApiKey}} _authentications['{{name}}'] = new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}");{{/isApiKey}}{{#isOAuth}} @@ -113,8 +114,7 @@ class ApiClient { // We don't use a Map for queryParams. // If collectionFormat is 'multi' a key might appear multiple times. - Future invokeAPI(String host, - String path, + Future invokeAPI(String path, String method, List queryParams, Object body, @@ -130,7 +130,7 @@ class ApiClient { '?' + ps.join('&') : ''; - String url = host + path + queryString; + String url = basePath + path + queryString; headerParams.addAll(_defaultHeaderMap); headerParams['Content-Type'] = contentType; From a5351f7ec05c0470585d79f59d77f2fe23372fc5 Mon Sep 17 00:00:00 2001 From: Christian Loitsch Date: Tue, 12 Jul 2016 18:05:40 +0200 Subject: [PATCH 086/470] feat dart: add pubName to library name. Otherwise projects may not use different apis generated by swagger, because library names must be unique. --- modules/swagger-codegen/src/main/resources/dart/api.mustache | 2 +- .../src/main/resources/dart/api_exception.mustache | 2 +- .../swagger-codegen/src/main/resources/dart/api_helper.mustache | 2 +- modules/swagger-codegen/src/main/resources/dart/apilib.mustache | 2 +- modules/swagger-codegen/src/main/resources/dart/model.mustache | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/dart/api.mustache b/modules/swagger-codegen/src/main/resources/dart/api.mustache index 477271c3a79..9fcd1391406 100644 --- a/modules/swagger-codegen/src/main/resources/dart/api.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/api.mustache @@ -1,4 +1,4 @@ -part of api; +part of {{pubName}}.api; {{#operations}} diff --git a/modules/swagger-codegen/src/main/resources/dart/api_exception.mustache b/modules/swagger-codegen/src/main/resources/dart/api_exception.mustache index c168fb512da..b0130dc61f5 100644 --- a/modules/swagger-codegen/src/main/resources/dart/api_exception.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/api_exception.mustache @@ -1,4 +1,4 @@ -part of api; +part of {{pubName}}.api; class ApiException implements Exception { int code = 0; diff --git a/modules/swagger-codegen/src/main/resources/dart/api_helper.mustache b/modules/swagger-codegen/src/main/resources/dart/api_helper.mustache index fb25306d260..9e2c30228a8 100644 --- a/modules/swagger-codegen/src/main/resources/dart/api_helper.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/api_helper.mustache @@ -1,4 +1,4 @@ -part of api; +part of {{pubName}}.api; const _delimiters = const {'csv': ',', 'ssv': ' ', 'tsv': '\t', 'pipes': '|'}; diff --git a/modules/swagger-codegen/src/main/resources/dart/apilib.mustache b/modules/swagger-codegen/src/main/resources/dart/apilib.mustache index 5d2f345703c..2ff574432f7 100644 --- a/modules/swagger-codegen/src/main/resources/dart/apilib.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/apilib.mustache @@ -1,4 +1,4 @@ -library api; +library {{pubName}}.api; import 'dart:async'; import 'dart:convert';{{#browserClient}} diff --git a/modules/swagger-codegen/src/main/resources/dart/model.mustache b/modules/swagger-codegen/src/main/resources/dart/model.mustache index afd72265646..5fe107c7849 100644 --- a/modules/swagger-codegen/src/main/resources/dart/model.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/model.mustache @@ -1,4 +1,4 @@ -part of api; +part of {{pubName}}.api; {{#models}}{{#model}} @Entity() From 66619b1a0949871b73151051b57454b5fdf621aa Mon Sep 17 00:00:00 2001 From: ircecho Date: Tue, 12 Jul 2016 18:21:34 +0200 Subject: [PATCH 087/470] fix[ruby]: Problem with List of Enum Fixes #3323 --- .../src/main/resources/ruby/partial_model_generic.mustache | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/modules/swagger-codegen/src/main/resources/ruby/partial_model_generic.mustache b/modules/swagger-codegen/src/main/resources/ruby/partial_model_generic.mustache index 0335500863f..95c818a5ac4 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/partial_model_generic.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/partial_model_generic.mustache @@ -124,8 +124,10 @@ return false if @{{{name}}}.nil? {{/required}} {{#isEnum}} + {{^isContainer}} {{{name}}}_validator = EnumAttributeValidator.new('{{{datatype}}}', [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}]) return false unless {{{name}}}_validator.valid?(@{{{name}}}) + {{/isContainer}} {{/isEnum}} {{#hasValidation}} {{#minLength}} @@ -150,6 +152,7 @@ {{#vars}} {{#isEnum}} + {{^isContainer}} # Custom attribute writer method checking allowed values (enum). # @param [Object] {{{name}}} Object to be assigned def {{{name}}}=({{{name}}}) @@ -160,6 +163,7 @@ @{{{name}}} = {{{name}}} end + {{/isContainer}} {{/isEnum}} {{^isEnum}} {{#hasValidation}} From 8003156fd8bf3c0b9b6e59501606f5d9c702c04a Mon Sep 17 00:00:00 2001 From: Christian Loitsch Date: Tue, 12 Jul 2016 19:42:11 +0200 Subject: [PATCH 088/470] feat dart: add pubName to all remaining library parts --- .../swagger-codegen/src/main/resources/dart/api_client.mustache | 2 +- .../src/main/resources/dart/auth/api_key_auth.mustache | 2 +- .../src/main/resources/dart/auth/authentication.mustache | 2 +- .../src/main/resources/dart/auth/http_basic_auth.mustache | 2 +- .../swagger-codegen/src/main/resources/dart/auth/oauth.mustache | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/dart/api_client.mustache b/modules/swagger-codegen/src/main/resources/dart/api_client.mustache index 74a6bf82c65..075dbab135d 100644 --- a/modules/swagger-codegen/src/main/resources/dart/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/api_client.mustache @@ -1,4 +1,4 @@ -part of api; +part of {{pubName}}.api; class QueryParam { String name; diff --git a/modules/swagger-codegen/src/main/resources/dart/auth/api_key_auth.mustache b/modules/swagger-codegen/src/main/resources/dart/auth/api_key_auth.mustache index d80d6a6a213..7f3ac22ecd8 100644 --- a/modules/swagger-codegen/src/main/resources/dart/auth/api_key_auth.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/auth/api_key_auth.mustache @@ -1,4 +1,4 @@ -part of api; +part of {{pubName}}.api; class ApiKeyAuth implements Authentication { diff --git a/modules/swagger-codegen/src/main/resources/dart/auth/authentication.mustache b/modules/swagger-codegen/src/main/resources/dart/auth/authentication.mustache index c0b1f92a42d..e7aef188e44 100644 --- a/modules/swagger-codegen/src/main/resources/dart/auth/authentication.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/auth/authentication.mustache @@ -1,4 +1,4 @@ -part of api; +part of {{pubName}}.api; abstract class Authentication { diff --git a/modules/swagger-codegen/src/main/resources/dart/auth/http_basic_auth.mustache b/modules/swagger-codegen/src/main/resources/dart/auth/http_basic_auth.mustache index 0645d4358f5..4fbcb2321b6 100644 --- a/modules/swagger-codegen/src/main/resources/dart/auth/http_basic_auth.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/auth/http_basic_auth.mustache @@ -1,4 +1,4 @@ -part of api; +part of {{pubName}}.api; class HttpBasicAuth implements Authentication { diff --git a/modules/swagger-codegen/src/main/resources/dart/auth/oauth.mustache b/modules/swagger-codegen/src/main/resources/dart/auth/oauth.mustache index e514dd85738..24413b9c3da 100644 --- a/modules/swagger-codegen/src/main/resources/dart/auth/oauth.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/auth/oauth.mustache @@ -1,4 +1,4 @@ -part of api; +part of {{pubName}}.api; class OAuth implements Authentication { From 9bfb52dbc1d148df7dbc0ba9f07feee6f9ba37c1 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 13 Jul 2016 16:22:58 +0800 Subject: [PATCH 089/470] fix csharp code sample --- .../src/main/resources/csharp/README.mustache | 10 +++++----- .../src/main/resources/csharp/api_doc.mustache | 10 +++++----- .../csharp/SwaggerClient/IO.Swagger.sln | 10 +++++----- .../petstore/csharp/SwaggerClient/README.md | 2 +- .../csharp/SwaggerClient/docs/PetApi.md | 18 +++++++++--------- .../csharp/SwaggerClient/docs/StoreApi.md | 4 ++-- .../src/IO.Swagger/IO.Swagger.csproj | 2 +- 7 files changed, 28 insertions(+), 28 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/README.mustache b/modules/swagger-codegen/src/main/resources/csharp/README.mustache index 3baa46ccbea..a72bb17f89b 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/README.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/README.mustache @@ -68,14 +68,14 @@ namespace Example { {{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}{{#hasAuthMethods}}{{#authMethods}}{{#isBasic}} // Configure HTTP basic authorization: {{{name}}} - Configuration.Default.Username = 'YOUR_USERNAME'; - Configuration.Default.Password = 'YOUR_PASSWORD';{{/isBasic}}{{#isApiKey}} + Configuration.Default.Username = "YOUR_USERNAME"; + Configuration.Default.Password = "YOUR_PASSWORD";{{/isBasic}}{{#isApiKey}} // Configure API key authorization: {{{name}}} - Configuration.Default.ApiKey.Add('{{{keyParamName}}}', 'YOUR_API_KEY'); + Configuration.Default.ApiKey.Add("{{{keyParamName}}}", "YOUR_API_KEY"); // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed - // Configuration.Default.ApiKeyPrefix.Add('{{{keyParamName}}}', 'Bearer');{{/isApiKey}}{{#isOAuth}} + // Configuration.Default.ApiKeyPrefix.Add("{{{keyParamName}}}", "Bearer");{{/isApiKey}}{{#isOAuth}} // Configure OAuth2 access token for authorization: {{{name}}} - Configuration.Default.AccessToken = 'YOUR_ACCESS_TOKEN';{{/isOAuth}}{{/authMethods}} + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN";{{/isOAuth}}{{/authMethods}} {{/hasAuthMethods}} var apiInstance = new {{classname}}(); diff --git a/modules/swagger-codegen/src/main/resources/csharp/api_doc.mustache b/modules/swagger-codegen/src/main/resources/csharp/api_doc.mustache index 5baa88f38b6..224450867ab 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api_doc.mustache @@ -34,14 +34,14 @@ namespace Example { {{#hasAuthMethods}}{{#authMethods}}{{#isBasic}} // Configure HTTP basic authorization: {{{name}}} - Configuration.Default.Username = 'YOUR_USERNAME'; - Configuration.Default.Password = 'YOUR_PASSWORD';{{/isBasic}}{{#isApiKey}} + Configuration.Default.Username = "YOUR_USERNAME"; + Configuration.Default.Password = "YOUR_PASSWORD";{{/isBasic}}{{#isApiKey}} // Configure API key authorization: {{{name}}} - Configuration.Default.ApiKey.Add('{{{keyParamName}}}', 'YOUR_API_KEY'); + Configuration.Default.ApiKey.Add("{{{keyParamName}}}", "YOUR_API_KEY"); // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed - // Configuration.Default.ApiKeyPrefix.Add('{{{keyParamName}}}', 'Bearer');{{/isApiKey}}{{#isOAuth}} + // Configuration.Default.ApiKeyPrefix.Add("{{{keyParamName}}}", "Bearer");{{/isApiKey}}{{#isOAuth}} // Configure OAuth2 access token for authorization: {{{name}}} - Configuration.Default.AccessToken = 'YOUR_ACCESS_TOKEN';{{/isOAuth}}{{/authMethods}} + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN";{{/isOAuth}}{{/authMethods}} {{/hasAuthMethods}} var apiInstance = new {{classname}}(); diff --git a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln index b2fa96608db..cd5b06faa7a 100644 --- a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln +++ b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln @@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 VisualStudioVersion = 12.0.0.0 MinimumVisualStudioVersion = 10.0.0.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{C8F5DE66-0944-4368-91CC-2313B4BFADDE}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{D285D0CA-2FEE-4760-8780-E13C90E527E8}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger.Test", "src\IO.Swagger.Test\IO.Swagger.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" EndProject @@ -12,10 +12,10 @@ Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution -{C8F5DE66-0944-4368-91CC-2313B4BFADDE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU -{C8F5DE66-0944-4368-91CC-2313B4BFADDE}.Debug|Any CPU.Build.0 = Debug|Any CPU -{C8F5DE66-0944-4368-91CC-2313B4BFADDE}.Release|Any CPU.ActiveCfg = Release|Any CPU -{C8F5DE66-0944-4368-91CC-2313B4BFADDE}.Release|Any CPU.Build.0 = Release|Any CPU +{D285D0CA-2FEE-4760-8780-E13C90E527E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{D285D0CA-2FEE-4760-8780-E13C90E527E8}.Debug|Any CPU.Build.0 = Debug|Any CPU +{D285D0CA-2FEE-4760-8780-E13C90E527E8}.Release|Any CPU.ActiveCfg = Release|Any CPU +{D285D0CA-2FEE-4760-8780-E13C90E527E8}.Release|Any CPU.Build.0 = Release|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/samples/client/petstore/csharp/SwaggerClient/README.md b/samples/client/petstore/csharp/SwaggerClient/README.md index 223afe8c377..e3ab66fcbb5 100644 --- a/samples/client/petstore/csharp/SwaggerClient/README.md +++ b/samples/client/petstore/csharp/SwaggerClient/README.md @@ -6,7 +6,7 @@ This C# SDK is automatically generated by the [Swagger Codegen](https://github.c - API version: 1.0.0 - SDK version: 1.0.0 -- Build date: 2016-07-10T17:40:23.847+08:00 +- Build date: 2016-07-13T16:19:48.141+08:00 - Build package: class io.swagger.codegen.languages.CSharpClientCodegen ## Frameworks supported diff --git a/samples/client/petstore/csharp/SwaggerClient/docs/PetApi.md b/samples/client/petstore/csharp/SwaggerClient/docs/PetApi.md index d32081e5471..de9223ef7a4 100644 --- a/samples/client/petstore/csharp/SwaggerClient/docs/PetApi.md +++ b/samples/client/petstore/csharp/SwaggerClient/docs/PetApi.md @@ -38,7 +38,7 @@ namespace Example { // Configure OAuth2 access token for authorization: petstore_auth - Configuration.Default.AccessToken = 'YOUR_ACCESS_TOKEN'; + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; var apiInstance = new PetApi(); var body = new Pet(); // Pet | Pet object that needs to be added to the store @@ -102,7 +102,7 @@ namespace Example { // Configure OAuth2 access token for authorization: petstore_auth - Configuration.Default.AccessToken = 'YOUR_ACCESS_TOKEN'; + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; var apiInstance = new PetApi(); var petId = 789; // long? | Pet id to delete @@ -168,7 +168,7 @@ namespace Example { // Configure OAuth2 access token for authorization: petstore_auth - Configuration.Default.AccessToken = 'YOUR_ACCESS_TOKEN'; + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; var apiInstance = new PetApi(); var status = new List(); // List | Status values that need to be considered for filter @@ -233,7 +233,7 @@ namespace Example { // Configure OAuth2 access token for authorization: petstore_auth - Configuration.Default.AccessToken = 'YOUR_ACCESS_TOKEN'; + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; var apiInstance = new PetApi(); var tags = new List(); // List | Tags to filter by @@ -298,9 +298,9 @@ namespace Example { // Configure API key authorization: api_key - Configuration.Default.ApiKey.Add('api_key', 'YOUR_API_KEY'); + Configuration.Default.ApiKey.Add("api_key", "YOUR_API_KEY"); // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed - // Configuration.Default.ApiKeyPrefix.Add('api_key', 'Bearer'); + // Configuration.Default.ApiKeyPrefix.Add("api_key", "Bearer"); var apiInstance = new PetApi(); var petId = 789; // long? | ID of pet to return @@ -365,7 +365,7 @@ namespace Example { // Configure OAuth2 access token for authorization: petstore_auth - Configuration.Default.AccessToken = 'YOUR_ACCESS_TOKEN'; + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; var apiInstance = new PetApi(); var body = new Pet(); // Pet | Pet object that needs to be added to the store @@ -429,7 +429,7 @@ namespace Example { // Configure OAuth2 access token for authorization: petstore_auth - Configuration.Default.AccessToken = 'YOUR_ACCESS_TOKEN'; + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; var apiInstance = new PetApi(); var petId = 789; // long? | ID of pet that needs to be updated @@ -497,7 +497,7 @@ namespace Example { // Configure OAuth2 access token for authorization: petstore_auth - Configuration.Default.AccessToken = 'YOUR_ACCESS_TOKEN'; + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; var apiInstance = new PetApi(); var petId = 789; // long? | ID of pet to update diff --git a/samples/client/petstore/csharp/SwaggerClient/docs/StoreApi.md b/samples/client/petstore/csharp/SwaggerClient/docs/StoreApi.md index c1e8370f2d9..24d03a779c5 100644 --- a/samples/client/petstore/csharp/SwaggerClient/docs/StoreApi.md +++ b/samples/client/petstore/csharp/SwaggerClient/docs/StoreApi.md @@ -95,9 +95,9 @@ namespace Example { // Configure API key authorization: api_key - Configuration.Default.ApiKey.Add('api_key', 'YOUR_API_KEY'); + Configuration.Default.ApiKey.Add("api_key", "YOUR_API_KEY"); // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed - // Configuration.Default.ApiKeyPrefix.Add('api_key', 'Bearer'); + // Configuration.Default.ApiKeyPrefix.Add("api_key", "Bearer"); var apiInstance = new StoreApi(); diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj index f627b61b790..702c8080e3b 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj @@ -24,7 +24,7 @@ limitations under the License. Debug AnyCPU - {C8F5DE66-0944-4368-91CC-2313B4BFADDE} + {D285D0CA-2FEE-4760-8780-E13C90E527E8} Library Properties Swagger Library From 6d4d81b652944a548b9a2ab89979651f9abcab05 Mon Sep 17 00:00:00 2001 From: Bochun Bai Date: Wed, 13 Jul 2016 17:27:11 +0800 Subject: [PATCH 090/470] Not compare Java String with "==" Replaced with equals() --- .../src/main/resources/Java/auth/ApiKeyAuth.mustache | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache index f73a6f5b3f8..5af060f1173 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache @@ -55,9 +55,9 @@ public class ApiKeyAuth implements Authentication { } else { value = apiKey; } - if (location == "query") { + if ("query".equals(location)) { queryParams.add(new Pair(paramName, value)); - } else if (location == "header") { + } else if ("header".equals(location)) { headerParams.put(paramName, value); } } From f75a42f81038b4e9445c61dc2c658c69a86bcd9d Mon Sep 17 00:00:00 2001 From: Bochun Bai Date: Wed, 13 Jul 2016 18:06:45 +0800 Subject: [PATCH 091/470] Remove more Java String comparison using "==" --- .../resources/Java/libraries/feign/auth/ApiKeyAuth.mustache | 6 +++--- .../Java/libraries/retrofit/auth/ApiKeyAuth.mustache | 6 +++--- .../Java/libraries/retrofit2/auth/ApiKeyAuth.mustache | 6 +++--- .../android/libraries/volley/auth/apikeyauth.mustache | 4 ++-- .../src/main/java/io/swagger/client/auth/ApiKeyAuth.java | 4 ++-- .../src/main/java/io/swagger/client/auth/ApiKeyAuth.java | 4 ++-- .../src/main/java/io/swagger/client/auth/ApiKeyAuth.java | 6 +++--- .../src/main/java/io/swagger/client/auth/ApiKeyAuth.java | 4 ++-- .../src/main/java/io/swagger/client/auth/ApiKeyAuth.java | 4 ++-- .../src/main/java/io/swagger/client/auth/ApiKeyAuth.java | 4 ++-- .../src/main/java/io/swagger/client/auth/ApiKeyAuth.java | 4 ++-- .../src/main/java/io/swagger/client/auth/ApiKeyAuth.java | 6 +++--- .../src/main/java/io/swagger/client/auth/ApiKeyAuth.java | 6 +++--- .../src/main/java/io/swagger/client/auth/ApiKeyAuth.java | 6 +++--- 14 files changed, 35 insertions(+), 35 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/ApiKeyAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/ApiKeyAuth.mustache index 371b24dbe55..9982cd7fc49 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/ApiKeyAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/ApiKeyAuth.mustache @@ -32,10 +32,10 @@ public class ApiKeyAuth implements RequestInterceptor { @Override public void apply(RequestTemplate template) { - if (location == "query") { + if ("query".equals(location)) { template.query(paramName, apiKey); - } else if (location == "header") { + } else if ("header".equals(location)) { template.header(paramName, apiKey); } } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/auth/ApiKeyAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/auth/ApiKeyAuth.mustache index fec45262e93..f6a86f22ab4 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/auth/ApiKeyAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/auth/ApiKeyAuth.mustache @@ -40,7 +40,7 @@ public class ApiKeyAuth implements Interceptor { String paramValue; Request request = chain.request(); - if (location == "query") { + if ("query".equals(location)) { String newQuery = request.uri().getQuery(); paramValue = paramName + "=" + apiKey; if (newQuery == null) { @@ -58,11 +58,11 @@ public class ApiKeyAuth implements Interceptor { } request = request.newBuilder().url(newUri.toURL()).build(); - } else if (location == "header") { + } else if ("header".equals(location)) { request = request.newBuilder() .addHeader(paramName, apiKey) .build(); } return chain.proceed(request); } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/ApiKeyAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/ApiKeyAuth.mustache index 92c0df0ddea..2f4bae3dd02 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/ApiKeyAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/ApiKeyAuth.mustache @@ -40,7 +40,7 @@ public class ApiKeyAuth implements Interceptor { String paramValue; Request request = chain.request(); - if (location == "query") { + if ("query".equals(location)) { String newQuery = request.url().uri().getQuery(); paramValue = paramName + "=" + apiKey; if (newQuery == null) { @@ -58,11 +58,11 @@ public class ApiKeyAuth implements Interceptor { } request = request.newBuilder().url(newUri.toURL()).build(); - } else if (location == "header") { + } else if ("header".equals(location)) { request = request.newBuilder() .addHeader(paramName, apiKey) .build(); } return chain.proceed(request); } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/apikeyauth.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/apikeyauth.mustache index 0805918e0d0..2208935ee42 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/apikeyauth.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/apikeyauth.mustache @@ -53,9 +53,9 @@ public class ApiKeyAuth implements Authentication { } else { value = apiKey; } - if (location == "query") { + if ("query".equals(location)) { queryParams.add(new Pair(paramName, value)); - } else if (location == "header") { + } else if ("header".equals(location)) { headerParams.put(paramName, value); } } diff --git a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index 70697c99ad3..e12f1535217 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -78,9 +78,9 @@ public void applyToParams(List queryParams, Map headerPara } else { value = apiKey; } - if (location == "query") { + if ("query".equals(location)) { queryParams.add(new Pair(paramName, value)); - } else if (location == "header") { + } else if ("header".equals(location)) { headerParams.put(paramName, value); } } diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index f2633f688b7..9f30bc7dff7 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -76,9 +76,9 @@ public void applyToParams(List queryParams, Map headerPara } else { value = apiKey; } - if (location == "query") { + if ("query".equals(location)) { queryParams.add(new Pair(paramName, value)); - } else if (location == "header") { + } else if ("header".equals(location)) { headerParams.put(paramName, value); } } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index 067672104a9..6e963f39d5c 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -32,10 +32,10 @@ public void setApiKey(String apiKey) { @Override public void apply(RequestTemplate template) { - if (location == "query") { + if ("query".equals(location)) { template.query(paramName, apiKey); - } else if (location == "header") { + } else if ("header".equals(location)) { template.header(paramName, apiKey); } } -} \ No newline at end of file +} diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index a125fff5f24..ad7abe402f8 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -78,9 +78,9 @@ public void applyToParams(List queryParams, Map headerPara } else { value = apiKey; } - if (location == "query") { + if ("query".equals(location)) { queryParams.add(new Pair(paramName, value)); - } else if (location == "header") { + } else if ("header".equals(location)) { headerParams.put(paramName, value); } } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index a125fff5f24..ad7abe402f8 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -78,9 +78,9 @@ public void applyToParams(List queryParams, Map headerPara } else { value = apiKey; } - if (location == "query") { + if ("query".equals(location)) { queryParams.add(new Pair(paramName, value)); - } else if (location == "header") { + } else if ("header".equals(location)) { headerParams.put(paramName, value); } } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index a125fff5f24..ad7abe402f8 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -78,9 +78,9 @@ public void applyToParams(List queryParams, Map headerPara } else { value = apiKey; } - if (location == "query") { + if ("query".equals(location)) { queryParams.add(new Pair(paramName, value)); - } else if (location == "header") { + } else if ("header".equals(location)) { headerParams.put(paramName, value); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index a125fff5f24..ad7abe402f8 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -78,9 +78,9 @@ public void applyToParams(List queryParams, Map headerPara } else { value = apiKey; } - if (location == "query") { + if ("query".equals(location)) { queryParams.add(new Pair(paramName, value)); - } else if (location == "header") { + } else if ("header".equals(location)) { headerParams.put(paramName, value); } } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index 59d01238796..2f973bb5e05 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -40,7 +40,7 @@ public Response intercept(Chain chain) throws IOException { String paramValue; Request request = chain.request(); - if (location == "query") { + if ("query".equals(location)) { String newQuery = request.uri().getQuery(); paramValue = paramName + "=" + apiKey; if (newQuery == null) { @@ -58,11 +58,11 @@ public Response intercept(Chain chain) throws IOException { } request = request.newBuilder().url(newUri.toURL()).build(); - } else if (location == "header") { + } else if ("header".equals(location)) { request = request.newBuilder() .addHeader(paramName, apiKey) .build(); } return chain.proceed(request); } -} \ No newline at end of file +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index f210c2110b5..05bf9561fe3 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -40,7 +40,7 @@ public Response intercept(Chain chain) throws IOException { String paramValue; Request request = chain.request(); - if (location == "query") { + if ("query".equals(location)) { String newQuery = request.url().uri().getQuery(); paramValue = paramName + "=" + apiKey; if (newQuery == null) { @@ -58,11 +58,11 @@ public Response intercept(Chain chain) throws IOException { } request = request.newBuilder().url(newUri.toURL()).build(); - } else if (location == "header") { + } else if ("header".equals(location)) { request = request.newBuilder() .addHeader(paramName, apiKey) .build(); } return chain.proceed(request); } -} \ No newline at end of file +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index f210c2110b5..05bf9561fe3 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -40,7 +40,7 @@ public Response intercept(Chain chain) throws IOException { String paramValue; Request request = chain.request(); - if (location == "query") { + if ("query".equals(location)) { String newQuery = request.url().uri().getQuery(); paramValue = paramName + "=" + apiKey; if (newQuery == null) { @@ -58,11 +58,11 @@ public Response intercept(Chain chain) throws IOException { } request = request.newBuilder().url(newUri.toURL()).build(); - } else if (location == "header") { + } else if ("header".equals(location)) { request = request.newBuilder() .addHeader(paramName, apiKey) .build(); } return chain.proceed(request); } -} \ No newline at end of file +} From e2d74de6ca4f58d7d552f0cff55dff4842643be8 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 13 Jul 2016 18:16:52 +0800 Subject: [PATCH 092/470] fix double hyphen in c# generator --- .../languages/AbstractCSharpCodegen.java | 2 +- .../resources/2_0/petstore-security-test.yaml | 52 ++++++------- .../csharp/SwaggerClient/IO.Swagger.sln | 10 +-- .../csharp/SwaggerClient/IO.Swagger.userprefs | 6 +- .../csharp/SwaggerClient/README.md | 33 ++++---- .../csharp/SwaggerClient/docs/FakeApi.md | 27 +++---- .../csharp/SwaggerClient/docs/ModelReturn.md | 2 +- .../IO.Swagger.Test/IO.Swagger.Test.csproj | 10 +-- .../src/IO.Swagger/Api/FakeApi.cs | 76 +++++++++---------- .../src/IO.Swagger/Client/ApiClient.cs | 18 ++--- .../src/IO.Swagger/Client/ApiException.cs | 8 +- .../src/IO.Swagger/Client/ApiResponse.cs | 8 +- .../src/IO.Swagger/Client/Configuration.cs | 10 +-- .../src/IO.Swagger/Client/ExceptionFactory.cs | 8 +- .../src/IO.Swagger/Client/IApiAccessor.cs | 8 +- .../src/IO.Swagger/IO.Swagger.csproj | 10 +-- .../src/IO.Swagger/Model/ModelReturn.cs | 16 ++-- 17 files changed, 153 insertions(+), 151 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java index 8c8b2d77730..f2db3b5e095 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java @@ -669,7 +669,7 @@ public String escapeQuotationMark(String input) { @Override public String escapeUnsafeCharacters(String input) { - return input.replace("*/", "*_/").replace("/*", "/_*"); + return input.replace("*/", "*_/").replace("/*", "/_*").replace("--", "- -"); } } diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml b/modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml index 6a201ba7b3d..16bce94ac7d 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml @@ -1,68 +1,68 @@ swagger: '2.0' info: - description: "This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end \r\n \n \r" - version: 1.0.0 */ ' " =end \r\n \n \r - title: Swagger Petstore */ ' " =end \r\n \n \r - termsOfService: http://swagger.io/terms/ */ ' " =end \r\n \n \r + description: "This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end -- \r\n \n \r" + version: 1.0.0 */ ' " =end -- \r\n \n \r + title: Swagger Petstore */ ' " =end -- \r\n \n \r + termsOfService: http://swagger.io/terms/ */ ' " =end -- \r\n \n \r contact: - email: apiteam@swagger.io */ ' " =end \r\n \n \r + email: apiteam@swagger.io */ ' " =end -- \r\n \n \r license: - name: Apache 2.0 */ ' " =end \r\n \n \r - url: http://www.apache.org/licenses/LICENSE-2.0.html */ ' " =end \r\n \n \r -host: petstore.swagger.io */ ' " =end \r\n \n \r -basePath: /v2 */ ' " =end \r\n \n \r + name: Apache 2.0 */ ' " =end -- \r\n \n \r + url: http://www.apache.org/licenses/LICENSE-2.0.html */ ' " =end -- \r\n \n \r +host: petstore.swagger.io */ ' " =end -- \r\n \n \r +basePath: /v2 */ ' " =end -- \r\n \n \r tags: - name: fake - description: Everything about your Pets */ ' " =end \r\n \n \r + description: Everything about your Pets */ ' " =end -- \r\n \n \r externalDocs: - description: Find out more */ ' " =end \r\n \n \r + description: Find out more */ ' " =end -- \r\n \n \r url: 'http://swagger.io' schemes: - - http */ ' " =end \r\n \n \r + - http */ ' " =end -- \r\n \n \r paths: /fake: put: tags: - fake - summary: To test code injection */ ' " =end \r\n \n \r - descriptions: To test code injection */ ' " =end \r\n \n \r - operationId: testCodeInject */ ' " =end \r\n \n \r + summary: To test code injection */ ' " =end -- \r\n \n \r + descriptions: To test code injection */ ' " =end -- \r\n \n \r + operationId: testCodeInject */ ' " =end -- \r\n \n \r consumes: - application/json - - "*/ ' \" =end \r\n \n \r" + - "*/ ' \" =end -- \r\n \n \r" produces: - application/json - - "*/ ' \" =end \r\n \n \r" + - "*/ ' \" =end -- \r\n \n \r" parameters: - - name: test code inject */ ' " =end \r\n \n \r + - name: test code inject */ ' " =end -- \r\n \n \r type: string in: formData - description: To test code injection */ ' " =end \r\n \n \r + description: To test code injection */ ' " =end -- \r\n \n \r responses: '400': - description: To test code injection */ ' " =end \r\n \n \r + description: To test code injection */ ' " =end -- \r\n \n \r securityDefinitions: petstore_auth: type: oauth2 authorizationUrl: 'http://petstore.swagger.io/api/oauth/dialog' flow: implicit scopes: - 'write:pets': modify pets in your account */ ' " =end \r\n \n \r - 'read:pets': read your pets */ ' " =end \r\n \n \r + 'write:pets': modify pets in your account */ ' " =end -- \r\n \n \r + 'read:pets': read your pets */ ' " =end -- \r\n \n \r api_key: type: apiKey - name: api_key */ ' " =end \r\n \n \r + name: api_key */ ' " =end -- \r\n \n \r in: header definitions: Return: - description: Model for testing reserved words */ ' " =end \r\n \n \r + description: Model for testing reserved words */ ' " =end -- \r\n \n \r properties: return: - description: property description */ ' " =end \r\n \n \r + description: property description */ ' " =end -- \r\n \n \r type: integer format: int32 xml: name: Return externalDocs: - description: Find out more about Swagger */ ' " =end \r\n \n \r + description: Find out more about Swagger */ ' " =end -- \r\n \n \r url: 'http://swagger.io' diff --git a/samples/client/petstore-security-test/csharp/SwaggerClient/IO.Swagger.sln b/samples/client/petstore-security-test/csharp/SwaggerClient/IO.Swagger.sln index 3f6c7053bf8..8dcf7f24348 100644 --- a/samples/client/petstore-security-test/csharp/SwaggerClient/IO.Swagger.sln +++ b/samples/client/petstore-security-test/csharp/SwaggerClient/IO.Swagger.sln @@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 VisualStudioVersion = 12.0.0.0 MinimumVisualStudioVersion = 10.0.0.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{29125490-71E4-47ED-B0D7-34505F58103C}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{8CE139DF-64BC-4591-85F8-8506C2B67514}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger.Test", "src\IO.Swagger.Test\IO.Swagger.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" EndProject @@ -12,10 +12,10 @@ Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution -{29125490-71E4-47ED-B0D7-34505F58103C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU -{29125490-71E4-47ED-B0D7-34505F58103C}.Debug|Any CPU.Build.0 = Debug|Any CPU -{29125490-71E4-47ED-B0D7-34505F58103C}.Release|Any CPU.ActiveCfg = Release|Any CPU -{29125490-71E4-47ED-B0D7-34505F58103C}.Release|Any CPU.Build.0 = Release|Any CPU +{8CE139DF-64BC-4591-85F8-8506C2B67514}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{8CE139DF-64BC-4591-85F8-8506C2B67514}.Debug|Any CPU.Build.0 = Debug|Any CPU +{8CE139DF-64BC-4591-85F8-8506C2B67514}.Release|Any CPU.ActiveCfg = Release|Any CPU +{8CE139DF-64BC-4591-85F8-8506C2B67514}.Release|Any CPU.Build.0 = Release|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/samples/client/petstore-security-test/csharp/SwaggerClient/IO.Swagger.userprefs b/samples/client/petstore-security-test/csharp/SwaggerClient/IO.Swagger.userprefs index 39b58c92731..5e7da6799fe 100644 --- a/samples/client/petstore-security-test/csharp/SwaggerClient/IO.Swagger.userprefs +++ b/samples/client/petstore-security-test/csharp/SwaggerClient/IO.Swagger.userprefs @@ -1,9 +1,9 @@ - + - - + + diff --git a/samples/client/petstore-security-test/csharp/SwaggerClient/README.md b/samples/client/petstore-security-test/csharp/SwaggerClient/README.md index dc258722110..44f3ab7c368 100644 --- a/samples/client/petstore-security-test/csharp/SwaggerClient/README.md +++ b/samples/client/petstore-security-test/csharp/SwaggerClient/README.md @@ -1,12 +1,12 @@ -# IO.Swagger - the C# library for the Swagger Petstore ' \" =end +# IO.Swagger - the C# library for the Swagger Petstore *_/ ' \" =end - - \\r\\n \\n \\r -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ ' \" =end +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end - - This C# SDK is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: -- API version: 1.0.0 ' \" =end +- API version: 1.0.0 *_/ ' \" =end - - \\r\\n \\n \\r - SDK version: 1.0.0 -- Build date: 2016-06-29T22:47:27.264+08:00 +- Build date: 2016-07-13T18:16:08.689+08:00 - Build package: class io.swagger.codegen.languages.CSharpClientCodegen ## Frameworks supported @@ -14,8 +14,8 @@ This C# SDK is automatically generated by the [Swagger Codegen](https://github.c - Windows Phone 7.1 (Mango) ## Dependencies -- [RestSharp] (https://www.nuget.org/packages/RestSharp) - 105.1.0 or later -- [Json.NET] (https://www.nuget.org/packages/Newtonsoft.Json/) - 7.0.0 or later +- [RestSharp](https://www.nuget.org/packages/RestSharp) - 105.1.0 or later +- [Json.NET](https://www.nuget.org/packages/Newtonsoft.Json/) - 7.0.0 or later The DLLs included in the package may not be the latest version. We recommned using [NuGet] (https://docs.nuget.org/consume/installing-nuget) to obtain the latest version of the packages: ``` @@ -54,31 +54,33 @@ namespace Example { var apiInstance = new FakeApi(); - var testCodeInjectEnd = testCodeInjectEnd_example; // string | To test code injection ' \" =end (optional) + var testCodeInjectEndRnNR = testCodeInjectEndRnNR_example; // string | To test code injection *_/ ' \" =end - - \\r\\n \\n \\r (optional) try { - // To test code injection ' \" =end - apiInstance.TestCodeInjectEnd(testCodeInjectEnd); + // To test code injection *_/ ' \" =end - - \\r\\n \\n \\r + apiInstance.TestCodeInjectEndRnNR(testCodeInjectEndRnNR); } catch (Exception e) { - Debug.Print("Exception when calling FakeApi.TestCodeInjectEnd: " + e.Message ); + Debug.Print("Exception when calling FakeApi.TestCodeInjectEndRnNR: " + e.Message ); } } } } ``` + ## Documentation for API Endpoints -All URIs are relative to *https://petstore.swagger.io ' \" =end/v2 ' \" =end* +All URIs are relative to *https://petstore.swagger.io *_/ ' \" =end - - \\r\\n \\n \\r/v2 *_/ ' \" =end - - \\r\\n \\n \\r* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*FakeApi* | [**TestCodeInjectEnd**](docs/FakeApi.md#testcodeinjectend) | **PUT** /fake | To test code injection ' \" =end +*FakeApi* | [**TestCodeInjectEndRnNR**](docs/FakeApi.md#testcodeinjectendrnnr) | **PUT** /fake | To test code injection *_/ ' \" =end - - \\r\\n \\n \\r + ## Documentation for Models - [Model.ModelReturn](docs/ModelReturn.md) @@ -86,11 +88,10 @@ Class | Method | HTTP request | Description ## Documentation for Authorization - ### api_key - **Type**: API key -- **API key parameter name**: api_key */ ' " =end +- **API key parameter name**: api_key */ ' " =end -- \r\n \n \r - **Location**: HTTP header ### petstore_auth @@ -99,6 +100,6 @@ Class | Method | HTTP request | Description - **Flow**: implicit - **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog - **Scopes**: - - write:pets: modify pets in your account */ ' " =end - - read:pets: read your pets */ ' " =end + - write:pets: modify pets in your account */ ' " =end -- \r\n \n \r + - read:pets: read your pets */ ' " =end -- \r\n \n \r diff --git a/samples/client/petstore-security-test/csharp/SwaggerClient/docs/FakeApi.md b/samples/client/petstore-security-test/csharp/SwaggerClient/docs/FakeApi.md index 962ba5fc6e0..39a951cbede 100644 --- a/samples/client/petstore-security-test/csharp/SwaggerClient/docs/FakeApi.md +++ b/samples/client/petstore-security-test/csharp/SwaggerClient/docs/FakeApi.md @@ -1,16 +1,17 @@ # IO.Swagger.Api.FakeApi -All URIs are relative to *https://petstore.swagger.io ' \" =end/v2 ' \" =end* +All URIs are relative to *https://petstore.swagger.io *_/ ' \" =end - - \\r\\n \\n \\r/v2 *_/ ' \" =end - - \\r\\n \\n \\r* Method | HTTP request | Description ------------- | ------------- | ------------- -[**TestCodeInjectEnd**](FakeApi.md#testcodeinjectend) | **PUT** /fake | To test code injection ' \" =end +[**TestCodeInjectEndRnNR**](FakeApi.md#testcodeinjectendrnnr) | **PUT** /fake | To test code injection *_/ ' \" =end - - \\r\\n \\n \\r -# **TestCodeInjectEnd** -> void TestCodeInjectEnd (string testCodeInjectEnd = null) + +# **TestCodeInjectEndRnNR** +> void TestCodeInjectEndRnNR (string testCodeInjectEndRnNR = null) -To test code injection ' \" =end +To test code injection *_/ ' \" =end - - \\r\\n \\n \\r ### Example ```csharp @@ -22,22 +23,22 @@ using IO.Swagger.Model; namespace Example { - public class TestCodeInjectEndExample + public class TestCodeInjectEndRnNRExample { public void main() { var apiInstance = new FakeApi(); - var testCodeInjectEnd = testCodeInjectEnd_example; // string | To test code injection ' \" =end (optional) + var testCodeInjectEndRnNR = testCodeInjectEndRnNR_example; // string | To test code injection *_/ ' \" =end - - \\r\\n \\n \\r (optional) try { - // To test code injection ' \" =end - apiInstance.TestCodeInjectEnd(testCodeInjectEnd); + // To test code injection *_/ ' \" =end - - \\r\\n \\n \\r + apiInstance.TestCodeInjectEndRnNR(testCodeInjectEndRnNR); } catch (Exception e) { - Debug.Print("Exception when calling FakeApi.TestCodeInjectEnd: " + e.Message ); + Debug.Print("Exception when calling FakeApi.TestCodeInjectEndRnNR: " + e.Message ); } } } @@ -48,7 +49,7 @@ namespace Example Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **testCodeInjectEnd** | **string**| To test code injection ' \" =end | [optional] + **testCodeInjectEndRnNR** | **string**| To test code injection *_/ ' \" =end - - \\r\\n \\n \\r | [optional] ### Return type @@ -60,8 +61,8 @@ No authorization required ### HTTP request headers - - **Content-Type**: application/json, */ ' =end - - **Accept**: application/json, */ ' =end + - **Content-Type**: application/json, *_/ ' =end - - + - **Accept**: application/json, *_/ ' =end - - [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/samples/client/petstore-security-test/csharp/SwaggerClient/docs/ModelReturn.md b/samples/client/petstore-security-test/csharp/SwaggerClient/docs/ModelReturn.md index 57af1de2bdc..ba83e94b8ce 100644 --- a/samples/client/petstore-security-test/csharp/SwaggerClient/docs/ModelReturn.md +++ b/samples/client/petstore-security-test/csharp/SwaggerClient/docs/ModelReturn.md @@ -3,7 +3,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**_Return** | **int?** | property description ' \" =end | [optional] +**_Return** | **int?** | property description *_/ ' \" =end - - \\r\\n \\n \\r | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore-security-test/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj b/samples/client/petstore-security-test/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj index 35bf372e00a..dc7be6546d9 100644 --- a/samples/client/petstore-security-test/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj +++ b/samples/client/petstore-security-test/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj @@ -1,11 +1,11 @@ - - - org.apache.maven.plugins - maven-jar-plugin - 2.6 @@ -117,11 +102,13 @@ org.apache.maven.plugins - maven-compiler-plugin - - 1.7 - 1.7 - + maven-site-plugin + 3.5.1 + + + org.apache.maven.plugins + maven-release-plugin + 2.5.3 @@ -166,7 +153,7 @@ org.apache.maven.plugins maven-javadoc-plugin - 2.9 + 2.10.4 true true @@ -180,7 +167,7 @@ org.apache.maven.plugins maven-jxr-plugin - 2.3 + 2.5 true @@ -188,7 +175,7 @@ org.apache.maven.plugins maven-project-info-reports-plugin - 2.6 + 2.9 @@ -200,7 +187,7 @@ - 1.2.1 + 1.3.0 diff --git a/pom.xml b/pom.xml index f31a7c230d9..43305a1c343 100644 --- a/pom.xml +++ b/pom.xml @@ -104,23 +104,9 @@ - - org.apache.maven.plugins - maven-source-plugin - 2.1.2 - - - attach-sources - verify - - jar-no-fork - - - - maven-compiler-plugin - 3.0 + 3.5.1 1.7 1.7 @@ -129,7 +115,7 @@ org.apache.maven.plugins maven-jar-plugin - 2.4 + 3.0.2 @@ -144,18 +130,18 @@ org.apache.maven.plugins maven-site-plugin - 2.1 + 3.5.1 org.apache.maven.plugins maven-release-plugin - 2.1 + 2.5.3 org.apache.maven.plugins maven-javadoc-plugin - 2.10.3 + 2.10.4 true 1.7 @@ -176,7 +162,7 @@ org.apache.maven.plugins maven-source-plugin - 2.1.2 + 3.0.1 attach-sources @@ -653,7 +639,7 @@ org.apache.maven.plugins maven-jxr-plugin - 2.3 + 2.5 true @@ -661,7 +647,7 @@ org.apache.maven.plugins maven-project-info-reports-plugin - 2.6 + 2.9 From d120902e4b47e80e24819b1588a6b0881f793daf Mon Sep 17 00:00:00 2001 From: Wolfgang Berger Date: Fri, 15 Jul 2016 15:36:24 +0200 Subject: [PATCH 109/470] integrate latest objc changes into objc-sessionmanager --- .../objc/Configuration-body.mustache | 2 +- output/objcSessionManager/README.md | 18 +- output/objcSessionManager/pom.xml | 6 +- .../ObjcSessionManagerClientCodegen.java | 1238 ++++++++++------- .../ApiSessionManager-body.mustache | 752 ++++------ .../ApiSessionManager-header.mustache | 131 +- .../BasicAuthTokenProvider-body.mustache | 7 +- .../Configuration-protocol.mustache | 82 +- .../DefaultConfiguration-body.mustache | 132 +- .../DefaultConfiguration-header.mustache | 131 +- .../JSONRequestSerializer-body.mustache | 21 +- .../JSONRequestSerializer-header.mustache | 2 + .../JSONResponseSerializer-body.mustache | 26 +- .../JSONResponseSerializer-header.mustache | 2 + ...JSONValueTransformer+ISO8601-body.mustache | 11 + ...ONValueTransformer+ISO8601-header.mustache | 8 + .../objcSessionManager/Logger-body.mustache | 74 + .../objcSessionManager/Logger-header.mustache | 50 + .../Model.xcdatamodel.mustache | 12 + .../NSManagedObject-body.mustache | 20 + .../NSManagedObject-header.mustache | 49 + .../NSManagedObjectBuilder-body.mustache | 89 ++ .../NSManagedObjectBuilder-header.mustache | 31 + .../objcSessionManager/Object-body.mustache | 17 +- .../objcSessionManager/Object-header.mustache | 3 + .../QueryParamCollection-body.mustache | 10 +- .../QueryParamCollection-header.mustache | 10 +- .../objcSessionManager/README.mustache | 130 +- .../ResponseDeserializer-body.mustache | 231 +++ .../ResponseDeserializer-header.mustache | 46 + .../Sanitizer-body.mustache | 168 +++ .../Sanitizer-header.mustache | 45 + .../objcSessionManager/api-body.mustache | 131 +- .../objcSessionManager/api-header.mustache | 36 +- .../objcSessionManager/api-protocol.mustache | 18 + .../objcSessionManager/api_doc.mustache | 85 ++ .../objcSessionManager/git_push.sh.mustache | 52 + .../objcSessionManager/gitignore.mustache | 53 + .../objcSessionManager/licenceInfo.mustache | 23 + .../objcSessionManager/model-body.mustache | 48 +- .../objcSessionManager/model-header.mustache | 6 +- .../objcSessionManager/model_doc.mustache | 11 + .../objcSessionManager/podspec.mustache | 17 +- .../xccurrentversion.mustache | 8 + output/objcSessionManager_notasold/README.md | 74 + output/objcSessionManager_notasold/pom.xml | 102 ++ .../ObjcSessionManagerClientCodegen.java | 750 ++++++++++ .../services/io.swagger.codegen.CodegenConfig | 1 + .../ApiSessionManager-body.mustache | 461 ++++++ .../ApiSessionManager-header.mustache | 147 ++ .../BasicAuthTokenProvider-body.mustache | 14 + .../BasicAuthTokenProvider-header.mustache | 14 + .../Configuration-protocol.mustache | 75 + .../DefaultConfiguration-body.mustache | 157 +++ .../DefaultConfiguration-header.mustache | 134 ++ .../JSONRequestSerializer-body.mustache | 37 + .../JSONRequestSerializer-header.mustache | 7 + .../JSONResponseSerializer-body.mustache | 39 + .../JSONResponseSerializer-header.mustache | 8 + .../JSONValueTransformer+ISO8601.h | 3 + .../JSONValueTransformer+ISO8601.m | 3 +- .../objcSessionManager/Object-body.mustache | 42 + .../objcSessionManager/Object-header.mustache | 8 + .../QueryParamCollection-body.mustache | 20 + .../QueryParamCollection-header.mustache | 13 + .../objcSessionManager/README.mustache | 143 ++ .../objcSessionManager/api-body.mustache | 161 +++ .../objcSessionManager/api-header.mustache | 34 + .../objcSessionManager/model-body.mustache | 59 + .../objcSessionManager/model-header.mustache | 25 + .../objcSessionManager/podspec.mustache | 37 + output/objcSessionManager_old/README.md | 74 + output/objcSessionManager_old/pom.xml | 102 ++ .../ObjcSessionManagerClientCodegen.java | 750 ++++++++++ .../services/io.swagger.codegen.CodegenConfig | 1 + .../ApiSessionManager-body.mustache | 461 ++++++ .../ApiSessionManager-header.mustache | 147 ++ .../BasicAuthTokenProvider-body.mustache | 14 + .../BasicAuthTokenProvider-header.mustache | 14 + .../Configuration-protocol.mustache | 75 + .../DefaultConfiguration-body.mustache | 157 +++ .../DefaultConfiguration-header.mustache | 134 ++ .../JSONRequestSerializer-body.mustache | 37 + .../JSONRequestSerializer-header.mustache | 7 + .../JSONResponseSerializer-body.mustache | 39 + .../JSONResponseSerializer-header.mustache | 8 + .../JSONValueTransformer+ISO8601.h | 8 + .../JSONValueTransformer+ISO8601.m | 11 + .../objcSessionManager/Object-body.mustache | 42 + .../objcSessionManager/Object-header.mustache | 8 + .../QueryParamCollection-body.mustache | 20 + .../QueryParamCollection-header.mustache | 13 + .../objcSessionManager/README.mustache | 143 ++ .../objcSessionManager/api-body.mustache | 161 +++ .../objcSessionManager/api-header.mustache | 34 + .../objcSessionManager/model-body.mustache | 59 + .../objcSessionManager/model-header.mustache | 25 + .../objcSessionManager/podspec.mustache | 37 + 98 files changed, 8001 insertions(+), 1190 deletions(-) create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601-body.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601-header.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/Logger-body.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/Logger-header.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/Model.xcdatamodel.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/NSManagedObject-body.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/NSManagedObject-header.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/NSManagedObjectBuilder-body.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/NSManagedObjectBuilder-header.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/ResponseDeserializer-body.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/ResponseDeserializer-header.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/Sanitizer-body.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/Sanitizer-header.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/api-protocol.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/api_doc.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/git_push.sh.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/gitignore.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/licenceInfo.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/model_doc.mustache create mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/xccurrentversion.mustache create mode 100644 output/objcSessionManager_notasold/README.md create mode 100644 output/objcSessionManager_notasold/pom.xml create mode 100644 output/objcSessionManager_notasold/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerClientCodegen.java create mode 100644 output/objcSessionManager_notasold/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig create mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache create mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/ApiSessionManager-header.mustache create mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/BasicAuthTokenProvider-body.mustache create mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/BasicAuthTokenProvider-header.mustache create mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/Configuration-protocol.mustache create mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/DefaultConfiguration-body.mustache create mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/DefaultConfiguration-header.mustache create mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONRequestSerializer-body.mustache create mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONRequestSerializer-header.mustache create mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONResponseSerializer-body.mustache create mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONResponseSerializer-header.mustache rename output/{objcSessionManager => objcSessionManager_notasold}/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.h (86%) rename output/{objcSessionManager => objcSessionManager_notasold}/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.m (77%) create mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/Object-body.mustache create mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/Object-header.mustache create mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/QueryParamCollection-body.mustache create mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/QueryParamCollection-header.mustache create mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/README.mustache create mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/api-body.mustache create mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/api-header.mustache create mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/model-body.mustache create mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/model-header.mustache create mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/podspec.mustache create mode 100644 output/objcSessionManager_old/README.md create mode 100644 output/objcSessionManager_old/pom.xml create mode 100644 output/objcSessionManager_old/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerClientCodegen.java create mode 100644 output/objcSessionManager_old/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig create mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache create mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/ApiSessionManager-header.mustache create mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/BasicAuthTokenProvider-body.mustache create mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/BasicAuthTokenProvider-header.mustache create mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/Configuration-protocol.mustache create mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/DefaultConfiguration-body.mustache create mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/DefaultConfiguration-header.mustache create mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONRequestSerializer-body.mustache create mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONRequestSerializer-header.mustache create mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONResponseSerializer-body.mustache create mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONResponseSerializer-header.mustache create mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.h create mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.m create mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/Object-body.mustache create mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/Object-header.mustache create mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/QueryParamCollection-body.mustache create mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/QueryParamCollection-header.mustache create mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/README.mustache create mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/api-body.mustache create mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/api-header.mustache create mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/model-body.mustache create mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/model-header.mustache create mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/podspec.mustache diff --git a/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache b/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache index 1aeca25dd3e..c1819d7fe19 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache @@ -35,7 +35,7 @@ self.mutableApiKey = [NSMutableDictionary dictionary]; self.mutableApiKeyPrefix = [NSMutableDictionary dictionary]; self.mutableDefaultHeaders = [NSMutableDictionary dictionary]; - self.mutableDefaultHeaders[@"User-Agent"] = {{#httpUserAgent}}@"{{httpUserAgent}}"{{/httpUserAgent}}{{^httpUserAgent}}[NSString stringWithFormat:@"Swagger-Codegen/{{version}}/objc (%@; iOS %@; Scale/%0.2f)",[[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]]{{/httpUserAgent}}; + {{#httpUserAgent}}self.mutableDefaultHeaders[@"User-Agent"] = @"{{httpUserAgent}}"{{/httpUserAgent}}; self.logger = [{{classPrefix}}Logger sharedLogger]; } return self; diff --git a/output/objcSessionManager/README.md b/output/objcSessionManager/README.md index 2bd0d9b256e..f70096077f0 100644 --- a/output/objcSessionManager/README.md +++ b/output/objcSessionManager/README.md @@ -1,4 +1,4 @@ -# Swagger Codegen for the ObjcSessionManager library +# Swagger Codegen for the objc-SessionManager library ## Overview This is a boiler-plate project to generate your own client library with Swagger. It's goal is @@ -21,9 +21,9 @@ At this point, you've likely generated a client setup. It will include somethin |-- src |--- main |---- java -|----- io.swagger.codegen.languages.ObjcsessionmanagerGenerator.java // generator file +|----- io.swagger.codegen.languages.ObjcSessionmanagerGenerator.java // generator file |---- resources -|----- ObjcSessionManager // template files +|----- objc-SessionManager // template files |----- META-INF |------ services |------- io.swagger.codegen.CodegenConfig @@ -31,11 +31,11 @@ At this point, you've likely generated a client setup. It will include somethin You _will_ need to make changes in at least the following: -`ObjcsessionmanagerGenerator.java` +`ObjcSessionmanagerGenerator.java` Templates in this folder: -`src/main/resources/ObjcSessionManager` +`src/main/resources/objc-SessionManager` Once modified, you can run this: @@ -46,14 +46,14 @@ mvn package In your generator project. A single jar file will be produced in `target`. You can now use that with codegen: ``` -java -cp /path/to/swagger-codegen-distribution:/path/to/your/jar io.swagger.codegen.Codegen -l ObjcSessionManager -o ./test +java -cp /path/to/swagger-codegen-distribution:/path/to/your/jar io.swagger.codegen.Codegen -l objc-SessionManager -o ./test ``` Now your templates are available to the client generator and you can write output values ## But how do I modify this? -The `ObjcsessionmanagerGenerator.java` has comments in it--lots of comments. There is no good substitute -for reading the code more, though. See how the `ObjcsessionmanagerGenerator` implements `CodegenConfig`. +The `ObjcSessionmanagerGenerator.java` has comments in it--lots of comments. There is no good substitute +for reading the code more, though. See how the `ObjcSessionmanagerGenerator` implements `CodegenConfig`. That class has the signature of all values that can be overridden. For the templates themselves, you have a number of values available to you for generation. @@ -67,7 +67,7 @@ the object you have available during client generation: # -DdebugOperations prints operations passed to the template engine # -DdebugSupportingFiles prints additional data passed to the template engine -java -DdebugOperations -cp /path/to/swagger-codegen-distribution:/path/to/your/jar io.swagger.codegen.Codegen -l ObjcSessionManager -o ./test +java -DdebugOperations -cp /path/to/swagger-codegen-distribution:/path/to/your/jar io.swagger.codegen.Codegen -l objc-SessionManager -o ./test ``` Will, for example, output the debug info for operations. You can use this info diff --git a/output/objcSessionManager/pom.xml b/output/objcSessionManager/pom.xml index 6ec6fe8a8fb..d4545ae9dec 100644 --- a/output/objcSessionManager/pom.xml +++ b/output/objcSessionManager/pom.xml @@ -2,9 +2,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 io.swagger - ObjcSessionManager-swagger-codegen + objc-SessionManager-swagger-codegen jar - ObjcSessionManager-swagger-codegen + objc-SessionManager-swagger-codegen 1.0.0 2.2.0 @@ -95,7 +95,7 @@ - 2.1.5 + 2.2.0-SNAPSHOT 1.0.0 4.8.1 diff --git a/output/objcSessionManager/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerClientCodegen.java b/output/objcSessionManager/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerClientCodegen.java index b340a39cb19..e74eda786d0 100644 --- a/output/objcSessionManager/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerClientCodegen.java +++ b/output/objcSessionManager/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerClientCodegen.java @@ -1,515 +1,755 @@ package io.swagger.codegen.languages; -import io.swagger.codegen.CliOption; -import io.swagger.codegen.CodegenConfig; -import io.swagger.codegen.CodegenConstants; -import io.swagger.codegen.CodegenProperty; -import io.swagger.codegen.CodegenType; -import io.swagger.codegen.DefaultCodegen; -import io.swagger.codegen.SupportingFile; +import io.swagger.codegen.*; +import io.swagger.models.ArrayModel; +import io.swagger.models.Model; import io.swagger.models.properties.*; import java.io.File; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; +import java.util.List; +import java.util.Map; import java.util.Set; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; public class ObjcSessionManagerClientCodegen extends DefaultCodegen implements CodegenConfig { - - public static final String CLASS_PREFIX = "classPrefix"; - public static final String POD_NAME = "podName"; - public static final String AUTHOR_NAME = "authorName"; - public static final String AUTHOR_EMAIL = "authorEmail"; - public static final String GIT_REPO_URL = "gitRepoURL"; - public static final String LICENSE = "license"; - - protected Set foundationClasses = new HashSet(); - protected String podName = "SwaggerClient"; - protected String podVersion = "1.0.0"; - protected String classPrefix = "SWG"; - protected String authorName = "Swagger"; - protected String authorEmail = "apiteam@swagger.io"; - protected String license = "MIT"; - protected String gitRepoURL = "https://github.com/swagger-api/swagger-codegen"; - protected String[] specialWords = {"new", "copy"}; - - - - public ObjcSessionManagerClientCodegen() { - super(); + public static final String CLASS_PREFIX = "classPrefix"; + public static final String POD_NAME = "podName"; + public static final String AUTHOR_NAME = "authorName"; + public static final String AUTHOR_EMAIL = "authorEmail"; + public static final String LICENSE = "license"; + public static final String GIT_REPO_URL = "gitRepoURL"; + public static final String DEFAULT_LICENSE = "Apache License, Version 2.0"; + public static final String CORE_DATA = "coreData"; + + protected Set foundationClasses = new HashSet(); + protected String podName = "SwaggerClient"; + protected String podVersion = "1.0.0"; + protected String classPrefix = "SWG"; + protected String authorName = "Swagger"; + protected String authorEmail = "apiteam@swagger.io"; + protected String license = DEFAULT_LICENSE; + protected String gitRepoURL = "https://github.com/swagger-api/swagger-codegen"; + protected String[] specialWords = {"new", "copy"}; + protected String apiDocPath = "docs/"; + protected String modelDocPath = "docs/"; + protected String modelFilesPath = "Model/"; + protected String coreFilesPath = "Core/"; + protected String apiFilesPath = "Api/"; + + protected boolean generateCoreData = false; + + protected Set advancedMapingTypes = new HashSet(); + + public ObjcSessionManagerClientCodegen() { + super(); - outputFolder = "generated-code" + File.separator + "objcSessionManager"; - - modelTemplateFiles.put("model-header.mustache", ".h"); - modelTemplateFiles.put("model-body.mustache", ".m"); - - apiTemplateFiles.put("api-header.mustache", ".h"); - apiTemplateFiles.put("api-body.mustache", ".m"); - - embeddedTemplateDir = templateDir = "objcSessionManager"; - - defaultIncludes.clear(); - defaultIncludes.add("bool"); - defaultIncludes.add("BOOL"); - defaultIncludes.add("int"); - defaultIncludes.add("NSURL"); - defaultIncludes.add("NSString"); - defaultIncludes.add("NSObject"); - defaultIncludes.add("NSArray"); - defaultIncludes.add("NSNumber"); - defaultIncludes.add("NSDate"); - defaultIncludes.add("NSDictionary"); - defaultIncludes.add("NSMutableArray"); - defaultIncludes.add("NSMutableDictionary"); - - languageSpecificPrimitives.clear(); - languageSpecificPrimitives.add("NSNumber"); - languageSpecificPrimitives.add("NSString"); - languageSpecificPrimitives.add("NSObject"); - languageSpecificPrimitives.add("NSDate"); - languageSpecificPrimitives.add("NSURL"); - languageSpecificPrimitives.add("bool"); - languageSpecificPrimitives.add("BOOL"); - - typeMapping.clear(); - typeMapping.put("enum", "NSString"); - typeMapping.put("date", "NSDate"); - typeMapping.put("DateTime", "NSDate"); - typeMapping.put("boolean", "NSNumber"); - typeMapping.put("string", "NSString"); - typeMapping.put("integer", "NSNumber"); - typeMapping.put("int", "NSNumber"); - typeMapping.put("float", "NSNumber"); - typeMapping.put("long", "NSNumber"); - typeMapping.put("double", "NSNumber"); - typeMapping.put("array", "NSArray"); - typeMapping.put("map", "NSDictionary"); - typeMapping.put("number", "NSNumber"); - typeMapping.put("List", "NSArray"); - typeMapping.put("object", "NSObject"); - typeMapping.put("file", "NSURL"); - - - // ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm - reservedWords = new HashSet( - Arrays.asList( - // local variable names in API methods (endpoints) - "resourcePath", "pathParams", "queryParams", "headerParams", - "responseContentType", "requestContentType", "authSettings", - "formParams", "files", "bodyParam", - // objc reserved words - "auto", "else", "long", "switch", - "break", "enum", "register", "typedef", - "case", "extern", "return", "union", - "char", "float", "short", "unsigned", - "const", "for", "signed", "void", - "continue", "goto", "sizeof", "volatile", - "default", "if", "id", "static", "while", - "do", "int", "struct", "_Packed", - "double", "protocol", "interface", "implementation", - "NSObject", "NSInteger", "NSNumber", "CGFloat", - "property", "nonatomic", "retain", "strong", - "weak", "unsafe_unretained", "readwrite", "readonly", - "description" - )); - - importMapping = new HashMap(); - - foundationClasses = new HashSet( + outputFolder = "generated-code" + File.separator + "objcSessionManager"; + modelTemplateFiles.put("model-header.mustache", ".h"); + modelTemplateFiles.put("model-body.mustache", ".m"); + apiTemplateFiles.put("api-header.mustache", ".h"); + apiTemplateFiles.put("api-body.mustache", ".m"); + embeddedTemplateDir = templateDir = "objcSessionManager"; + modelDocTemplateFiles.put("model_doc.mustache", ".md"); + apiDocTemplateFiles.put("api_doc.mustache", ".md"); + + defaultIncludes.clear(); + defaultIncludes.add("bool"); + defaultIncludes.add("BOOL"); + defaultIncludes.add("int"); + defaultIncludes.add("NSURL"); + defaultIncludes.add("NSString"); + defaultIncludes.add("NSObject"); + defaultIncludes.add("NSArray"); + defaultIncludes.add("NSNumber"); + defaultIncludes.add("NSDate"); + defaultIncludes.add("NSDictionary"); + defaultIncludes.add("NSMutableArray"); + defaultIncludes.add("NSMutableDictionary"); + defaultIncludes.add("NSManagedObject"); + defaultIncludes.add("NSData"); + + advancedMapingTypes.add("NSDictionary"); + advancedMapingTypes.add("NSArray"); + advancedMapingTypes.add("NSMutableArray"); + advancedMapingTypes.add("NSMutableDictionary"); + advancedMapingTypes.add("NSObject"); + advancedMapingTypes.add("NSNumber"); + advancedMapingTypes.add("NSURL"); + advancedMapingTypes.add("NSString"); + advancedMapingTypes.add("NSDate"); + + languageSpecificPrimitives.clear(); + languageSpecificPrimitives.add("NSNumber"); + languageSpecificPrimitives.add("NSString"); + languageSpecificPrimitives.add("NSObject"); + languageSpecificPrimitives.add("NSDate"); + languageSpecificPrimitives.add("NSData"); + languageSpecificPrimitives.add("NSURL"); + languageSpecificPrimitives.add("bool"); + languageSpecificPrimitives.add("BOOL"); + + typeMapping.clear(); + typeMapping.put("enum", "NSString"); + typeMapping.put("date", "NSDate"); + typeMapping.put("datetime", "NSDate"); + typeMapping.put("boolean", "NSNumber"); + typeMapping.put("string", "NSString"); + typeMapping.put("integer", "NSNumber"); + typeMapping.put("int", "NSNumber"); + typeMapping.put("float", "NSNumber"); + typeMapping.put("long", "NSNumber"); + typeMapping.put("double", "NSNumber"); + typeMapping.put("array", "NSArray"); + typeMapping.put("map", "NSDictionary"); + typeMapping.put("number", "NSNumber"); + typeMapping.put("bigdecimal", "NSNumber"); + typeMapping.put("List", "NSArray"); + typeMapping.put("object", "NSObject"); + typeMapping.put("file", "NSURL"); + typeMapping.put("binary", "NSData"); + typeMapping.put("bytearray", "NSData"); + typeMapping.put("byte", "NSData"); + typeMapping.put("uuid", "NSString"); + typeMapping.put("password", "NSString"); + + // ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm + setReservedWordsLowerCase( Arrays.asList( - "NSNumber", - "NSObject", - "NSString", - "NSDate", - "NSURL", - "NSDictionary") - ); - - instantiationTypes.put("array", "NSMutableArray"); - instantiationTypes.put("map", "NSMutableDictionary"); - - cliOptions.clear(); - cliOptions.add(new CliOption(CLASS_PREFIX, "prefix for generated classes (convention: Abbreviation of pod name e.g. `HN` for `HackerNews`).`") - .defaultValue("SWG")); - cliOptions.add(new CliOption(POD_NAME, "cocoapods package name (convention: CameCase).") - .defaultValue("SwaggerClient")); - cliOptions.add(new CliOption(CodegenConstants.POD_VERSION, "cocoapods package version.") - .defaultValue("1.0.0")); - cliOptions.add(new CliOption(AUTHOR_NAME, "Name to use in the podspec file.").defaultValue("Swagger")); - cliOptions.add(new CliOption(AUTHOR_EMAIL, "Email to use in the podspec file.").defaultValue("apiteam@swagger.io")); - cliOptions.add(new CliOption(GIT_REPO_URL, "URL for the git repo where this podspec should point to.") - .defaultValue("https://github.com/swagger-api/swagger-codegen")); - cliOptions.add(new CliOption(LICENSE, "License to use in the podspec file.").defaultValue("MIT")); - } - - @Override - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - @Override - public String getName() { - return "objc-SessionManager"; - } - - @Override - public String getHelp() { - return "Generates an Objective-C client library."; - } - - @Override - public void processOpts() { - super.processOpts(); - - if (additionalProperties.containsKey(POD_NAME)) { - setPodName((String) additionalProperties.get(POD_NAME)); - } - - if (additionalProperties.containsKey(CodegenConstants.POD_VERSION)) { - setPodVersion((String) additionalProperties.get(CodegenConstants.POD_VERSION)); - } - - if (additionalProperties.containsKey(CLASS_PREFIX)) { - setClassPrefix((String) additionalProperties.get(CLASS_PREFIX)); - } - - if (additionalProperties.containsKey(AUTHOR_NAME)) { - setAuthorName((String) additionalProperties.get(AUTHOR_NAME)); - } - - if (additionalProperties.containsKey(AUTHOR_EMAIL)) { - setAuthorEmail((String) additionalProperties.get(AUTHOR_EMAIL)); - } - - if (additionalProperties.containsKey(GIT_REPO_URL)) { - setGitRepoURL((String) additionalProperties.get(GIT_REPO_URL)); - } - - if (additionalProperties.containsKey(LICENSE)) { - setLicense((String) additionalProperties.get(LICENSE)); - } - - additionalProperties.put(POD_NAME, podName); - additionalProperties.put(CodegenConstants.POD_VERSION, podVersion); - additionalProperties.put(CLASS_PREFIX, classPrefix); - additionalProperties.put(AUTHOR_NAME, authorName); - additionalProperties.put(AUTHOR_EMAIL, authorEmail); - additionalProperties.put(GIT_REPO_URL, gitRepoURL); - additionalProperties.put(LICENSE, license); - - String swaggerFolder = podName; - - modelPackage = swaggerFolder; - apiPackage = swaggerFolder; - - supportingFiles.add(new SupportingFile("Object-header.mustache", swaggerFolder, classPrefix + "Object.h")); - supportingFiles.add(new SupportingFile("Object-body.mustache", swaggerFolder, classPrefix + "Object.m")); - supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", swaggerFolder, classPrefix + "QueryParamCollection.h")); - supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", swaggerFolder, classPrefix + "QueryParamCollection.m")); - supportingFiles.add(new SupportingFile("ApiSessionManager-header.mustache", swaggerFolder, classPrefix + "ApiSessionManager.h")); - supportingFiles.add(new SupportingFile("ApiSessionManager-body.mustache", swaggerFolder, classPrefix + "ApiSessionManager.m")); - supportingFiles.add(new SupportingFile("JSONResponseSerializer-header.mustache", swaggerFolder, classPrefix + "JSONResponseSerializer.h")); - supportingFiles.add(new SupportingFile("JSONResponseSerializer-body.mustache", swaggerFolder, classPrefix + "JSONResponseSerializer.m")); - supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", swaggerFolder, classPrefix + "JSONRequestSerializer.m")); - supportingFiles.add(new SupportingFile("JSONRequestSerializer-header.mustache", swaggerFolder, classPrefix + "JSONRequestSerializer.h")); - supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.m", swaggerFolder, "JSONValueTransformer+ISO8601.m")); - supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.h", swaggerFolder, "JSONValueTransformer+ISO8601.h")); - supportingFiles.add(new SupportingFile("Configuration-protocol.mustache", swaggerFolder, classPrefix + "Configuration.h")); - supportingFiles.add(new SupportingFile("DefaultConfiguration-body.mustache", swaggerFolder, classPrefix + "DefaultConfiguration.m")); - supportingFiles.add(new SupportingFile("DefaultConfiguration-header.mustache", swaggerFolder, classPrefix + "DefaultConfiguration.h")); - supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-header.mustache", swaggerFolder, classPrefix + "BasicAuthTokenProvider.h")); - supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-body.mustache", swaggerFolder, classPrefix + "BasicAuthTokenProvider.m")); - supportingFiles.add(new SupportingFile("podspec.mustache", "", podName + ".podspec")); - supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - } - - @Override - public String toInstantiationType(Property p) { - if (p instanceof MapProperty) { - return instantiationTypes.get("map"); - } else if (p instanceof ArrayProperty) { - return instantiationTypes.get("array"); - } else { - return null; - } - } - - @Override - public String getTypeDeclaration(String name) { - if (languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name)) { - return name; - } else { - return name + "*"; - } - } - - @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) && !foundationClasses.contains(type)) { - return toModelName(type); - } - } else { - type = swaggerType; - } - return toModelName(type); - } - - @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - String innerType = getSwaggerType(inner); - - String innerTypeDeclaration = getTypeDeclaration(inner); - - if (innerTypeDeclaration.endsWith("*")) { - innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); - } - - // In this codition, type of property p is array of primitive, - // return container type with pointer, e.g. `NSArray* /* NSString */' - if (languageSpecificPrimitives.contains(innerType)) { - return getSwaggerType(p) + "*" + " /* " + innerTypeDeclaration + " */"; - } - // In this codition, type of property p is array of model, - // return container type combine inner type with pointer, e.g. `NSArray*' - else { - return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*"; - } - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - - String innerTypeDeclaration = getTypeDeclaration(inner); - - if (innerTypeDeclaration.endsWith("*")) { - innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); - } - return getSwaggerType(p) + "* /* NSString, " + innerTypeDeclaration + " */"; - } else { - String swaggerType = getSwaggerType(p); - - // In this codition, type of p is objective-c primitive type, e.g. `NSSNumber', - // return type of p with pointer, e.g. `NSNumber*' - if (languageSpecificPrimitives.contains(swaggerType) && - foundationClasses.contains(swaggerType)) { - return swaggerType + "*"; - } - // In this codition, type of p is c primitive type, e.g. `bool', - // return type of p, e.g. `bool' - else if (languageSpecificPrimitives.contains(swaggerType)) { - return swaggerType; - } - // In this codition, type of p is objective-c object type, e.g. `SWGPet', - // return type of p with pointer, e.g. `SWGPet*' - else { - return swaggerType + "*"; - } - } - } - - @Override - public String toModelName(String type) { - type = type.replaceAll("[^0-9a-zA-Z_]", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - - // language build-in classes - if (typeMapping.keySet().contains(type) || - foundationClasses.contains(type) || - importMapping.values().contains(type) || - defaultIncludes.contains(type) || - languageSpecificPrimitives.contains(type)) { - return camelize(type); - } - // custom classes - else { - return classPrefix + camelize(type); - } - } - - @Override - public String toModelFilename(String name) { - // should be the same as the model name - return toModelName(name); - } - - @Override - protected void setNonArrayMapProperty(CodegenProperty property, String type) { - super.setNonArrayMapProperty(property, type); - if ("NSDictionary".equals(type)) { - property.setter = "initWithDictionary"; - } else { - property.setter = "initWithValues"; - } - } - - @Override - public String toModelImport(String name) { - return name; + // local variable names in API methods (endpoints) + "resourcePath", "pathParams", "queryParams", "headerParams", + "responseContentType", "requestContentType", "authSettings", + "formParams", "localVarFiles", "bodyParam", + // objc reserved words + "auto", "else", "long", "switch", + "break", "enum", "register", "typedef", + "case", "extern", "return", "union", + "char", "float", "short", "unsigned", + "const", "for", "signed", "void", + "continue", "goto", "sizeof", "volatile", + "default", "if", "id", "static", "while", + "do", "int", "struct", "_Packed", + "double", "protocol", "interface", "implementation", + "NSObject", "NSInteger", "NSNumber", "CGFloat", + "property", "nonatomic", "retain", "strong", + "weak", "unsafe_unretained", "readwrite", "readonly", + "description" + )); + + importMapping = new HashMap(); + + foundationClasses = new HashSet( + Arrays.asList( + "NSNumber", + "NSObject", + "NSString", + "NSDate", + "NSData", + "NSURL", + "NSDictionary") + ); + + instantiationTypes.put("array", "NSMutableArray"); + instantiationTypes.put("map", "NSMutableDictionary"); + + cliOptions.clear(); + cliOptions.add(new CliOption(CORE_DATA, "Should generate core data models").defaultValue("false")); + cliOptions.add(new CliOption(CLASS_PREFIX, "prefix for generated classes (convention: Abbreviation of pod name e.g. `HN` for `HackerNews`).`") + .defaultValue("SWG")); + cliOptions.add(new CliOption(POD_NAME, "cocoapods package name (convention: CameCase).") + .defaultValue("SwaggerClient")); + cliOptions.add(new CliOption(CodegenConstants.POD_VERSION, "cocoapods package version.") + .defaultValue("1.0.0")); + cliOptions.add(new CliOption(AUTHOR_NAME, "Name to use in the podspec file.").defaultValue("Swagger")); + cliOptions.add(new CliOption(AUTHOR_EMAIL, "Email to use in the podspec file.").defaultValue("apiteam@swagger.io")); + cliOptions.add(new CliOption(GIT_REPO_URL, "URL for the git repo where this podspec should point to.") + .defaultValue("https://github.com/swagger-api/swagger-codegen")); + } + + @Override + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + @Override + public String getName() { + return "objc-SessionManager"; + } + + @Override + public String getHelp() { + return "Generates an Objective-C client library."; + } + + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey(POD_NAME)) { + setPodName((String) additionalProperties.get(POD_NAME)); + } + + if (additionalProperties.containsKey(CodegenConstants.POD_VERSION)) { + setPodVersion((String) additionalProperties.get(CodegenConstants.POD_VERSION)); + } + + if (additionalProperties.containsKey(CORE_DATA)) { + Object coreData = additionalProperties.get(CORE_DATA); + if(((String)coreData).equalsIgnoreCase("true")) { + generateCoreData = true; + } + } + if (additionalProperties.containsKey(CLASS_PREFIX)) { + setClassPrefix((String) additionalProperties.get(CLASS_PREFIX)); + } + + if (additionalProperties.containsKey(AUTHOR_NAME)) { + setAuthorName((String) additionalProperties.get(AUTHOR_NAME)); + } + + if (additionalProperties.containsKey(AUTHOR_EMAIL)) { + setAuthorEmail((String) additionalProperties.get(AUTHOR_EMAIL)); + } + + if (additionalProperties.containsKey(GIT_REPO_URL)) { + setGitRepoURL((String) additionalProperties.get(GIT_REPO_URL)); + } + + if(generateCoreData) { + modelTemplateFiles.put("NSManagedObject-header.mustache", "ManagedObject.h"); + modelTemplateFiles.put("NSManagedObject-body.mustache", "ManagedObject.m"); + modelTemplateFiles.put("NSManagedObjectBuilder-header.mustache", "ManagedObjectBuilder.h"); + modelTemplateFiles.put("NSManagedObjectBuilder-body.mustache", "ManagedObjectBuilder.m"); + } + + additionalProperties.put(POD_NAME, podName); + additionalProperties.put(CodegenConstants.POD_VERSION, podVersion); + additionalProperties.put(CLASS_PREFIX, classPrefix); + additionalProperties.put(AUTHOR_NAME, authorName); + additionalProperties.put(AUTHOR_EMAIL, authorEmail); + additionalProperties.put(GIT_REPO_URL, gitRepoURL); + additionalProperties.put(LICENSE, license); + + // make api and model doc path available in mustache template + additionalProperties.put("apiDocPath", apiDocPath); + additionalProperties.put("modelDocPath", modelDocPath); + additionalProperties.put("useCoreData", generateCoreData); + + modelPackage = podName; + apiPackage = podName; + + supportingFiles.add(new SupportingFile("Object-header.mustache", coreFileFolder(), classPrefix + "Object.h")); + supportingFiles.add(new SupportingFile("Object-body.mustache", coreFileFolder(), classPrefix + "Object.m")); + supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.h")); + supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.m")); + supportingFiles.add(new SupportingFile("ApiSessionManager-header.mustache", coreFileFolder(), classPrefix + "ApiSessionManager.h")); // !! + supportingFiles.add(new SupportingFile("ApiSessionManager-body.mustache", coreFileFolder(), classPrefix + "ApiSessionManager.m")); // !! + supportingFiles.add(new SupportingFile("JSONResponseSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.h")); + supportingFiles.add(new SupportingFile("JSONResponseSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.m")); + supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.m")); + supportingFiles.add(new SupportingFile("JSONRequestSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.h")); + supportingFiles.add(new SupportingFile("ResponseDeserializer-body.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.m")); // !! + supportingFiles.add(new SupportingFile("ResponseDeserializer-header.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.h")); // !! + supportingFiles.add(new SupportingFile("Sanitizer-body.mustache", coreFileFolder(), classPrefix + "Sanitizer.m")); // !! + supportingFiles.add(new SupportingFile("Sanitizer-header.mustache", coreFileFolder(), classPrefix + "Sanitizer.h")); // !! + supportingFiles.add(new SupportingFile("Logger-body.mustache", coreFileFolder(), classPrefix + "Logger.m")); // !! + supportingFiles.add(new SupportingFile("Logger-header.mustache", coreFileFolder(), classPrefix + "Logger.h")); // !! + supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-body.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.m")); + supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-header.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.h")); + //supportingFiles.add(new SupportingFile("Configuration-body.mustache", coreFileFolder(), classPrefix + "Configuration.m")); // !! + //supportingFiles.add(new SupportingFile("Configuration-header.mustache", coreFileFolder(), classPrefix + "Configuration.h")); // !! + supportingFiles.add(new SupportingFile("Configuration-protocol.mustache", coreFileFolder(), classPrefix + "Configuration.h")); + supportingFiles.add(new SupportingFile("DefaultConfiguration-body.mustache", coreFileFolder(), classPrefix + "DefaultConfiguration.m")); + supportingFiles.add(new SupportingFile("DefaultConfiguration-header.mustache", coreFileFolder(), classPrefix + "DefaultConfiguration.h")); + supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-header.mustache", coreFileFolder(), classPrefix + "BasicAuthTokenProvider.h")); + supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-body.mustache", coreFileFolder(), classPrefix + "BasicAuthTokenProvider.m")); + supportingFiles.add(new SupportingFile("api-protocol.mustache", coreFileFolder(), classPrefix + "Api.h")); // !! + supportingFiles.add(new SupportingFile("podspec.mustache", "", podName + ".podspec")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); // !! + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); // !! + + if(generateCoreData) { + supportingFiles.add(new SupportingFile("xccurrentversion.mustache", (modelPackage() + "/" + modelFilesPath + "/").replace("/", File.separator) + classPrefix + "Model.xcdatamodeld", ".xccurrentversion")); + supportingFiles.add(new SupportingFile("Model.xcdatamodel.mustache",(modelPackage() + "/" + modelFilesPath + "/").replace("/", File.separator) + classPrefix + "Model.xcdatamodeld" + File.separator + classPrefix + "Model.xcdatamodel", "contents")); + } + + // is apiclient + //supportingFiles.add(new SupportingFile("ApiSessionManager-header.mustache", swaggerFolder, classPrefix + "ApiSessionManager.h")); + //supportingFiles.add(new SupportingFile("ApiSessionManager-body.mustache", swaggerFolder, classPrefix + "ApiSessionManager.m")); + + // protocol! + //supportingFiles.add(new SupportingFile("Configuration-protocol.mustache", swaggerFolder, classPrefix + "Configuration.h")); + //supportingFiles.add(new SupportingFile("DefaultConfiguration-body.mustache", swaggerFolder, classPrefix + "DefaultConfiguration.m")); + //supportingFiles.add(new SupportingFile("DefaultConfiguration-header.mustache", swaggerFolder, classPrefix + "DefaultConfiguration.h")); + + // missing! + //supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-header.mustache", swaggerFolder, classPrefix + "BasicAuthTokenProvider.h")); + //supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-body.mustache", swaggerFolder, classPrefix + "BasicAuthTokenProvider.m")); } - @Override - public String apiFileFolder() { - return outputFolder + File.separatorChar + apiPackage(); - } - - @Override - public String modelFileFolder() { - return outputFolder + File.separatorChar + modelPackage(); - } - - @Override - public String toApiName(String name) { - return classPrefix + camelize(name) + "Api"; - } - - @Override - public String toApiFilename(String name) { - return classPrefix + camelize(name) + "Api"; - } - - @Override - public String toVarName(String name) { - // sanitize name - name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - - // if it's all upper case, do noting - if (name.matches("^[A-Z_]$")) { - return name; - } - - // if name starting with special word, escape with '_' - for(int i =0; i < specialWords.length; i++) { - if (name.matches("(?i:^" + specialWords[i] + ".*)")) - name = escapeSpecialWord(name); - } - - // camelize (lower first character) the variable name - // e.g. `pet_id` to `petId` - name = camelize(name, true); - - // for reserved word or word starting with number, prepend `_` - if (reservedWords.contains(name) || name.matches("^\\d.*")) { - name = escapeReservedWord(name); - } - - - return name; - } - - @Override - public String toParamName(String name) { - // should be the same as variable name - return toVarName(name); - } - - @Override - public String escapeReservedWord(String name) { - return "_" + name; - } - - @SuppressWarnings("static-method") - public String escapeSpecialWord(String name) { - return "var_" + name; - } - - @Override - public String toOperationId(String operationId) { - // throw exception if method name is empty - if (StringUtils.isEmpty(operationId)) { - throw new RuntimeException("Empty method name (operationId) not allowed"); - } - - // method name cannot use reserved keyword, e.g. return - if (reservedWords.contains(operationId)) { - throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); - } - - return camelize(sanitizeName(operationId), true); - } - - public void setClassPrefix(String classPrefix) { - this.classPrefix = classPrefix; - } - - public void setPodName(String podName) { - this.podName = podName; - } - - public void setPodVersion(String podVersion) { - this.podVersion = podVersion; - } - - public void setAuthorEmail(String authorEmail) { - this.authorEmail = authorEmail; - } - - public void setAuthorName(String authorName) { - this.authorName = authorName; - } - - public void setGitRepoURL(String gitRepoURL) { - this.gitRepoURL = gitRepoURL; - } - - 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; - } -} \ No newline at end of file + @Override + public String toInstantiationType(Property p) { + if (p instanceof MapProperty) { + return instantiationTypes.get("map"); + } else if (p instanceof ArrayProperty) { + return instantiationTypes.get("array"); + } else { + return null; + } + } + + @Override + public String getTypeDeclaration(String name) { + if (languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name)) { + return name; + } else { + return name + "*"; + } + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType.toLowerCase())) { + type = typeMapping.get(swaggerType.toLowerCase()); + if (languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type)) { + return toModelNameWithoutReservedWordCheck(type); + } + } else { + type = swaggerType; + } + return toModelNameWithoutReservedWordCheck(type); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + String innerTypeDeclaration = getTypeDeclaration(inner); + if (innerTypeDeclaration.endsWith("*")) { + innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); + } + // In this condition, type of property p is array of primitive, + // return container type with pointer, e.g. `NSArray**' + if (languageSpecificPrimitives.contains(innerTypeDeclaration)) { + return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*"; + } + // In this condition, type of property p is array of model, + // return container type combine inner type with pointer, e.g. `NSArray*' + else { + for (String sd : advancedMapingTypes) { + if(innerTypeDeclaration.startsWith(sd)) { + return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*"; + } + } + return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*"; + } + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + String innerTypeDeclaration = getTypeDeclaration(inner); + + if (innerTypeDeclaration.endsWith("*")) { + innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); + } + if (languageSpecificPrimitives.contains(innerTypeDeclaration)) { + return getSwaggerType(p) + "*"; + } else { + for (String s : advancedMapingTypes) { + if(innerTypeDeclaration.startsWith(s)) { + return getSwaggerType(p) + "*"; + } + } + return getSwaggerType(p) + "*"; + } + } else { + String swaggerType = getSwaggerType(p); + // In this condition, type of p is objective-c primitive type, e.g. `NSSNumber', + // return type of p with pointer, e.g. `NSNumber*' + if (languageSpecificPrimitives.contains(swaggerType) && + foundationClasses.contains(swaggerType)) { + return swaggerType + "*"; + } + // In this condition, type of p is c primitive type, e.g. `bool', + // return type of p, e.g. `bool' + else if (languageSpecificPrimitives.contains(swaggerType)) { + return swaggerType; + } + // In this condition, type of p is objective-c object type, e.g. `SWGPet', + // return type of p with pointer, e.g. `SWGPet*' + else { + return swaggerType + "*"; + } + } + } + + @Override + public boolean isDataTypeBinary(String dataType) { + return dataType.toLowerCase().startsWith("nsdata"); + } + + @Override + public String toModelName(String type) { + // model name cannot use reserved keyword + if (reservedWords.contains(type)) { + LOGGER.warn(type+ " (reserved word) cannot be used as model name. Renamed to " + ("model_" + type) + " before further processing"); + type = "model_" + type; // e.g. return => ModelReturn (after camelize) + } + + // model name starts with number + /* no need for the fix below as objc model starts with prefix (e.g. SWG) + if (type.matches("^\\d.*")) { + LOGGER.warn(type + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + type)); + type = "model_" + type; // e.g. 200Response => Model200Response (after camelize) + } + */ + + return toModelNameWithoutReservedWordCheck(type); + } + + /* + * Convert input to proper model name according to ObjC style guide + * without checking for reserved words + * + * @param type Model anme + * @return model Name in ObjC style guide + */ + public String toModelNameWithoutReservedWordCheck(String type) { + type = type.replaceAll("[^0-9a-zA-Z_]", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + + // language build-in classes + if (typeMapping.keySet().contains(type) || + foundationClasses.contains(type) || + importMapping.values().contains(type) || + defaultIncludes.contains(type) || + languageSpecificPrimitives.contains(type)) { + return camelize(type); + } + // custom classes + else { + if (!StringUtils.isEmpty(modelNameSuffix)) { // set model suffix + type = type + "_" + modelNameSuffix; + } + + if (!StringUtils.isEmpty(modelNamePrefix)) { // set model prefix + type = modelNamePrefix + "_" + type; + } + + return classPrefix + camelize(type); // add class prefix + } + } + + @Override + public String toModelFilename(String name) { + // should be the same as the model name + return toModelName(name); + } + + @Override + protected void setNonArrayMapProperty(CodegenProperty property, String type) { + super.setNonArrayMapProperty(property, type); + if ("NSDictionary".equals(type)) { + property.setter = "initWithDictionary"; + } else { + property.setter = "initWithValues"; + } + } + + @Override + public String toModelImport(String name) { + return name; + } + + @Override + public String apiDocFileFolder() { + return (outputFolder + "/" + apiDocPath).replace("/", File.separator); + } + + @Override + public String modelDocFileFolder() { + return (outputFolder + "/" + modelDocPath).replace("/", File.separator); + } + + @Override + public String toModelDocFilename(String name) { + return toModelName(name); + } + + @Override + public String toApiDocFilename(String name) { + return toApiName(name); + } + + @Override + public String apiFileFolder() { + return (outputFolder + "/"+ apiPackage() + "/" + apiFilesPath).replace("/", File.separator); + } + + @Override + public String modelFileFolder() { + return (outputFolder + "/"+ modelPackage() + "/" + modelFilesPath).replace("/", File.separator); + } + + public String coreFileFolder() { + return (apiPackage() + "/" + coreFilesPath).replace("/", File.separator); + } + + @Override + public String toApiName(String name) { + return classPrefix + camelize(name) + "Api"; + } + + @Override + public String toApiFilename(String name) { + return classPrefix + camelize(name) + "Api"; + } + + @Override + public String toVarName(String name) { + // sanitize name + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + + // if it's all upper case, do noting + if (name.matches("^[A-Z_]$")) { + return name; + } + + // if name starting with special word, escape with '_' + for(int i =0; i < specialWords.length; i++) { + if (name.matches("(?i:^" + specialWords[i] + ".*)")) + name = escapeSpecialWord(name); + } + + // camelize (lower first character) the variable name + // e.g. `pet_id` to `petId` + name = camelize(name, true); + + // for reserved word or word starting with number, prepend `_` + if (isReservedWord(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } + + + return name; + } + + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @SuppressWarnings("static-method") + public String escapeSpecialWord(String name) { + return "var_" + name; + } + + @Override + public String toOperationId(String operationId) { + // throw exception if method name is empty + if (StringUtils.isEmpty(operationId)) { + throw new RuntimeException("Empty method name (operationId) not allowed"); + } + + // method name cannot use reserved keyword, e.g. return + if (isReservedWord(operationId)) { + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId), true)); + operationId = "call_" + operationId; + } + + return camelize(sanitizeName(operationId), true); + } + + public void setClassPrefix(String classPrefix) { + this.classPrefix = classPrefix; + } + + public void setPodName(String podName) { + this.podName = podName; + } + + public void setPodVersion(String podVersion) { + this.podVersion = podVersion; + } + + public void setAuthorEmail(String authorEmail) { + this.authorEmail = authorEmail; + } + + public void setAuthorName(String authorName) { + this.authorName = authorName; + } + + public void setGitRepoURL(String gitRepoURL) { + this.gitRepoURL = gitRepoURL; + } + + public void setLicense(String license) { + this.license = license; + } + + @Override + public Map postProcessOperations(Map objs) { + Map operations = (Map) objs.get("operations"); + if (operations != null) { + List ops = (List) operations.get("operation"); + for (CodegenOperation operation : ops) { + if (!operation.allParams.isEmpty()) { + String firstParamName = operation.allParams.get(0).paramName; + operation.vendorExtensions.put("firstParamAltName", camelize(firstParamName)); + } + } + } + return objs; + } + + @Override + public void postProcessModelProperty(CodegenModel model, CodegenProperty property){ + super.postProcessModelProperty(model,property); + property.vendorExtensions.put("x-uppercaseName", camelize(property.name)); + } + + /** + * 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; + } + + @Override + public void setParameterExampleValue(CodegenParameter p) { + String example; + + if (p.defaultValue == null) { + example = p.example; + } else { + example = p.defaultValue; + } + + String type = p.baseType; + if (type == null) { + type = p.dataType; + } + + if ("NSString*".equalsIgnoreCase(type)) { + if (example == null) { + example = p.paramName + "_example"; + } + example = "@\"" + escapeText(example) + "\""; + } else if ("NSNumber*".equals(type)) { + if (example == null) { + example = "56"; + } + example = "@" + example; + /* OBJC uses NSNumber to represent both int, long, double and float + } else if ("Float".equalsIgnoreCase(type) || "Double".equalsIgnoreCase(type)) { + if (example == null) { + example = "3.4"; + } */ + } else if ("BOOLEAN".equalsIgnoreCase(type) || "bool".equalsIgnoreCase(type)) { + if (example == null) { + example = "True"; + } + } else if ("NSURL*".equalsIgnoreCase(type)) { + if (example == null) { + example = "/path/to/file"; + } + //[NSURL fileURLWithPath:@"path/to/file"] + example = "[NSURL fileURLWithPath:@\"" + escapeText(example) + "\"]"; + /*} else if ("NSDate".equalsIgnoreCase(type)) { + if (example == null) { + example = "2013-10-20"; + } + example = "'" + escapeText(example) + "'";*/ + } else if ("NSDate*".equalsIgnoreCase(type)) { + if (example == null) { + example = "2013-10-20T19:20:30+01:00"; + } + example = "@\"" + escapeText(example) + "\""; + } else if (!languageSpecificPrimitives.contains(type)) { + // type is a model class, e.g. User + type = type.replace("*", ""); + // e.g. [[SWGPet alloc] init + example = "[[" + type + " alloc] init]"; + } else { + LOGGER.warn("Type " + type + " not handled properly in setParameterExampleValue"); + } + + if (example == null) { + example = "NULL"; + } else if (Boolean.TRUE.equals(p.isListContainer)) { + example = "@[" + example + "]"; + } else if (Boolean.TRUE.equals(p.isMapContainer)) { + example = "@{@\"key\" : " + example + "}"; + } + + p.example = example; + } + + @Override + public String escapeQuotationMark(String input) { + // remove " to avoid code injection + return input.replace("\"", ""); + } + + @Override + public String escapeUnsafeCharacters(String input) { + return input.replace("*/", "*_/").replace("/*", "/_*"); + } + +} diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache index f319f65d03e..31382dc7b2f 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache @@ -4,15 +4,42 @@ #import "{{classPrefix}}JSONRequestSerializer.h" #import "{{classPrefix}}JSONResponseSerializer.h" #import "{{classPrefix}}QueryParamCollection.h" -#import "{{classPrefix}}Object.h" #import "{{classPrefix}}DefaultConfiguration.h" -#define {{classPrefix}}DebugLog(format, ...) [{{classPrefix}}ApiSessionManager debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__]; - NSString * const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}ResponseObject"; +static bool offlineState = false; +static bool cacheEnabled = false; +static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilityStatusNotReachable; +static void (^reachabilityChangeBlock)(int); + + +static NSDictionary * {{classPrefix}}__headerFieldsForResponse(NSURLResponse *response) { + if(![response isKindOfClass:[NSHTTPURLResponse class]]) { + return nil; + } + return ((NSHTTPURLResponse*)response).allHeaderFields; +} + +static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) { + NSDictionary * headers = {{classPrefix}}__headerFieldsForResponse(response); + if(!headers[@"Content-Disposition"]) { + return [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]]; + } + NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?"; + NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern + options:NSRegularExpressionCaseInsensitive + error:nil]; + NSString *contentDispositionHeader = headers[@"Content-Disposition"]; + NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader + options:0 + range:NSMakeRange(0, [contentDispositionHeader length])]; + return [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]]; +} + + @interface {{classPrefix}}ApiSessionManager () @property (nonatomic, strong, readwrite) id<{{classPrefix}}Configuration> configuration; @@ -44,24 +71,164 @@ NSString * const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}Respon self = [super initWithBaseURL:url]; if (self) { _configuration = configuration; + _timeoutInterval = 60; + _responseDeserializer = [[{{classPrefix}}ResponseDeserializer alloc] init]; + _sanitizer = [[{{classPrefix}}Sanitizer alloc] init]; + + self.requestSerializer = [AFJSONRequestSerializer serializer]; + self.responseSerializer = [AFJSONResponseSerializer serializer]; + self.securityPolicy = [self customSecurityPolicy]; + + // configure reachability + [self configureCacheReachibility]; } return self; } -- (NSURLSessionTask *)requestWithCompletionBlock:(NSString *)path - method:(NSString *)method - pathParams:(NSDictionary *)pathParams - queryParams:(NSDictionary *)queryParams - formParams:(NSDictionary *)formParams - files:(NSDictionary *)files - body:(id)body - headerParams:(NSDictionary *)headerParams - authSettings:(NSArray *)authSettings - requestContentType:(NSString *)requestContentType - responseContentType:(NSString *)responseContentType - responseType:(NSString *)responseType - completionBlock:(void (^)(id, NSError *))completionBlock { +#pragma mark - Setter Methods + ++ (void) setOfflineState:(BOOL) state { + offlineState = state; +} + ++ (void) setCacheEnabled:(BOOL)enabled { + cacheEnabled = enabled; +} + ++(void) setReachabilityStatus:(AFNetworkReachabilityStatus)status { + reachabilityStatus = status; +} + +- (void)setHeaderValue:(NSString*) value forKey:(NSString*) forKey { + [self.requestSerializer setValue:value forHTTPHeaderField:forKey]; +} + +- (void)setRequestSerializer:(AFHTTPRequestSerializer *)requestSerializer { + [super setRequestSerializer:requestSerializer]; + requestSerializer.timeoutInterval = self.timeoutInterval; +} + +#pragma mark - Cache Methods + ++(void)clearCache { + [[NSURLCache sharedURLCache] removeAllCachedResponses]; +} + ++(void)configureCacheWithMemoryAndDiskCapacity: (unsigned long) memorySize + diskSize: (unsigned long) diskSize { + NSAssert(memorySize > 0, @"invalid in-memory cache size"); + NSAssert(diskSize >= 0, @"invalid disk cache size"); + + NSURLCache *cache = + [[NSURLCache alloc] + initWithMemoryCapacity:memorySize + diskCapacity:diskSize + diskPath:@"swagger_url_cache"]; + + [NSURLCache setSharedURLCache:cache]; +} + +#pragma mark - Reachability Methods + ++(AFNetworkReachabilityStatus) getReachabilityStatus { + return reachabilityStatus; +} + ++(BOOL) getOfflineState { + return offlineState; +} + ++(void) setReachabilityChangeBlock:(void(^)(int))changeBlock { + reachabilityChangeBlock = changeBlock; +} + +- (void) configureCacheReachibility { + [self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { + reachabilityStatus = status; + {{classPrefix}}DebugLog(@"reachability changed to %@",AFStringFromNetworkReachabilityStatus(status)); + [{{classPrefix}}ApiSessionManager setOfflineState:status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable]; + + // call the reachability block, if configured + if (reachabilityChangeBlock != nil) { + reachabilityChangeBlock(status); + } + }]; + + [self.reachabilityManager startMonitoring]; +} + +#pragma mark - Task Methods + +- (NSURLSessionDataTask*) taskWithCompletionBlock: (NSURLRequest *)request + completionBlock: (void (^)(id, NSError *))completionBlock { + + NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { + {{classPrefix}}DebugLogResponse(response, responseObject,request,error); + + if(!error) { + completionBlock(responseObject, nil); + return; + } + + NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; + if (responseObject) { + // Add in the (parsed) response body. + userInfo[{{classPrefix}}ResponseObjectErrorKey] = responseObject; + } + NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; + completionBlock(nil, augmentedError); + }]; + + return task; +} + +- (NSURLSessionDataTask*) downloadTaskWithCompletionBlock: (NSURLRequest *)request + completionBlock: (void (^)(id, NSError *))completionBlock { + + id<{{classPrefix}}Configuration> config = self.configuration; + + NSURLSessionDataTask* task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + {{classPrefix}}DebugLogResponse(response, responseObject,request,error); + + if(error) { + NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; + if (responseObject) { + userInfo[{{classPrefix}}ResponseObjectErrorKey] = responseObject; + } + NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; + completionBlock(nil, augmentedError); + } + + NSString *directory = config.tempFolderPath ?: NSTemporaryDirectory(); + NSString *filename = {{classPrefix}}__fileNameForResponse(response); + + NSString *filepath = [directory stringByAppendingPathComponent:filename]; + NSURL *file = [NSURL fileURLWithPath:filepath]; + + [responseObject writeToURL:file atomically:YES]; + + completionBlock(file, nil); + }]; + + return task; +} + +#pragma mark - Perform Request Methods + +- (NSURLSessionTask*) requestWithPath: (NSString*) path + method: (NSString*) method + pathParams: (NSDictionary *) pathParams + queryParams: (NSDictionary*) queryParams + formParams: (NSDictionary *) formParams + files: (NSDictionary *) files + body: (id) body + headerParams: (NSDictionary*) headerParams + authSettings: (NSArray *) authSettings + requestContentType: (NSString*) requestContentType + responseContentType: (NSString*) responseContentType + responseType: (NSString *) responseType + completionBlock: (void (^)(id, NSError *))completionBlock { // setting request serializer if ([requestContentType isEqualToString:@"application/json"]) { @@ -74,48 +241,52 @@ NSString * const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}Respon self.requestSerializer = [AFHTTPRequestSerializer serializer]; } else { - NSAssert(false, @"unsupport request type %@", requestContentType); + self.requestSerializer = [AFHTTPRequestSerializer serializer]; + NSAssert(NO, @"Unsupported request type %@", requestContentType); } // setting response serializer if ([responseContentType isEqualToString:@"application/json"]) { self.responseSerializer = [{{classPrefix}}JSONResponseSerializer serializer]; - } - else { + } else { self.responseSerializer = [AFHTTPResponseSerializer serializer]; } // sanitize parameters - pathParams = [self sanitizeForSerialization:pathParams]; - queryParams = [self sanitizeForSerialization:queryParams]; - headerParams = [self sanitizeForSerialization:headerParams]; - formParams = [self sanitizeForSerialization:formParams]; - body = [self sanitizeForSerialization:body]; + pathParams = [self.sanitizer sanitizeForSerialization:pathParams]; + queryParams = [self.sanitizer sanitizeForSerialization:queryParams]; + headerParams = [self.sanitizer sanitizeForSerialization:headerParams]; + formParams = [self.sanitizer sanitizeForSerialization:formParams]; + if(![body isKindOfClass:[NSData class]]) { + body = [self.sanitizer sanitizeForSerialization:body]; + } // auth setting [self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings]; - + NSMutableString *resourcePath = [NSMutableString stringWithString:path]; [pathParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - [resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", key, @"}"]] - withString:[{{classPrefix}}ApiSessionManager escape:obj]]; + NSString * safeString = ([obj isKindOfClass:[NSString class]]) ? obj : [NSString stringWithFormat:@"%@", obj]; + safeString = {{classPrefix}}PercentEscapedStringFromString(safeString); + [resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"{%@}", key]] withString:safeString]; }]; - + NSMutableURLRequest * request = nil; NSString* pathWithQueryParams = [self pathWithQueryParamsToString:resourcePath queryParams:queryParams]; if ([pathWithQueryParams hasPrefix:@"/"]) { pathWithQueryParams = [pathWithQueryParams substringFromIndex:1]; } - + NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString]; if (files.count > 0) { + __weak __typeof(self)weakSelf = self; request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:nil constructingBodyWithBlock:^(id formData) { [formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - NSString *objString = [self parameterToString:obj]; + NSString *objString = [weakSelf.sanitizer parameterToString:obj]; NSData *data = [objString dataUsingEncoding:NSUTF8StringEncoding]; [formData appendPartWithFormData:data name:key]; }]; @@ -141,16 +312,12 @@ NSString * const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}Respon } // request cache - BOOL hasHeaderParams = false; - if (headerParams != nil && [headerParams count] > 0) { - hasHeaderParams = true; - } - - if (self.configuration.offlineState) { + BOOL hasHeaderParams = [headerParams count] > 0; + if (offlineState) { {{classPrefix}}DebugLog(@"%@ cache forced", resourcePath); [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; } - else if(!hasHeaderParams && [method isEqualToString:@"GET"] && self.configuration.cacheEnabled) { + else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { {{classPrefix}}DebugLog(@"%@ cache enabled", resourcePath); [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; } @@ -158,28 +325,32 @@ NSString * const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}Respon {{classPrefix}}DebugLog(@"%@ cache disabled", resourcePath); [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; } - - if (hasHeaderParams) { - for(NSString * key in [headerParams keyEnumerator]) { + + if (hasHeaderParams){ + for(NSString * key in [headerParams keyEnumerator]){ [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; } } [self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"]; - - - // Always disable cookies! - [request setHTTPShouldHandleCookies:NO]; + + [self postProcessRequest:request]; + NSURLSessionTask *task = nil; - - if ([responseType isEqualToString:@"NSURL*"]) { + + if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) { task = [self downloadTaskWithCompletionBlock:request completionBlock:^(id data, NSError *error) { completionBlock(data, error); }]; } else { - task = [self taskWithCompletionBlock:request completionBlock:^(id data, NSError *error) { - completionBlock([self deserialize:data class:responseType], error); + [self taskWithCompletionBlock:request completionBlock:^(id data, NSError *error) { + NSError * serializationError; + id response = [self.responseDeserializer deserialize:data class:responseType error:&serializationError]; + if(!response && !error){ + error = serializationError; + } + completionBlock(response, error); }]; } @@ -188,84 +359,73 @@ NSString * const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}Respon return task; } -#pragma mark - Task Methods - -- (NSURLSessionDataTask *) taskWithCompletionBlock: (NSURLRequest *)request - completionBlock: (void (^)(id, NSError *))completionBlock { - - NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { - if (error) { - NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; - if (responseObject) { - // Add in the (parsed) response body. - userInfo[{{classPrefix}}ResponseObjectErrorKey] = responseObject; - } - NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; - - completionBlock(nil, augmentedError); - } else { - completionBlock(responseObject, nil); - } - }]; - - return task; +// Added for easier override to modify request +- (void)postProcessRequest:(NSMutableURLRequest *)request { + // Always disable cookies! + [request setHTTPShouldHandleCookies:NO]; } -- (NSURLSessionDownloadTask *) downloadTaskWithCompletionBlock: (NSURLRequest *)request - completionBlock: (void (^)(id, NSError *))completionBlock { - - id<{{classPrefix}}Configuration> config = self.configuration; - - NSURLSessionDownloadTask *task = [self downloadTaskWithRequest:request progress:nil destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) { - NSString *directory = nil; - if (config.tempFolderPath) { - directory = config.tempFolderPath; - } - else { - directory = NSTemporaryDirectory(); - } - - NSDictionary *headers = nil; - if ([response isKindOfClass:[NSHTTPURLResponse class]]) - { - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; - headers = httpResponse.allHeaderFields; - } - - NSString *filename = nil; - if ([headers objectForKey:@"Content-Disposition"]) { - - NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?"; - NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern - options:NSRegularExpressionCaseInsensitive - error:nil]; - NSString *contentDispositionHeader = [headers objectForKey:@"Content-Disposition"]; - NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader - options:0 - range:NSMakeRange(0, [contentDispositionHeader length])]; - filename = [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]]; +#pragma mark - + +- (NSString*)pathWithQueryParamsToString:(NSString*) path + queryParams:(NSDictionary*) queryParams { + if(queryParams.count == 0) { + return path; + } + NSString * separator = nil; + NSUInteger counter = 0; + + NSMutableString * requestUrl = [NSMutableString stringWithFormat:@"%@", path]; + + NSDictionary *separatorStyles = @{@"csv" : @",", + @"tsv" : @"\t", + @"pipes": @"|" + }; + for(NSString * key in [queryParams keyEnumerator]){ + if (counter == 0) { + separator = @"?"; + } else { + separator = @"&"; } - else { - filename = [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]]; + id queryParam = [queryParams valueForKey:key]; + if(!queryParam) { + continue; } - - NSString *filepath = [directory stringByAppendingPathComponent:filename]; - NSURL *file = [NSURL fileURLWithPath:filepath]; - - return file; - } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) { - if (error) { - completionBlock(nil, error); + NSString *safeKey = {{classPrefix}}PercentEscapedStringFromString(key); + if ([queryParam isKindOfClass:[NSString class]]){ + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, {{classPrefix}}PercentEscapedStringFromString(queryParam)]]; + + } else if ([queryParam isKindOfClass:[{{classPrefix}}QueryParamCollection class]]){ + {{classPrefix}}QueryParamCollection * coll = ({{classPrefix}}QueryParamCollection*) queryParam; + NSArray* values = [coll values]; + NSString* format = [coll format]; + + if([format isEqualToString:@"multi"]) { + for(id obj in values) { + if (counter > 0) { + separator = @"&"; + } + NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([NSString stringWithFormat:@"%@",obj]); + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; + counter += 1; + } + continue; + } + NSString * separatorStyle = separatorStyles[format]; + NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([values componentsJoinedByString:separatorStyle]); + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; } else { - completionBlock(filePath, nil); + NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([NSString stringWithFormat:@"%@",queryParam]); + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; } - }]; - - return task; + counter += 1; + } + return requestUrl; } -#pragma mark - Serialization - +/** + * Update header and query params based on authentication settings + */ - (void) updateHeaderParams:(NSDictionary *__autoreleasing *)headers queryParams:(NSDictionary *__autoreleasing *)querys WithAuthSettings:(NSArray *)authSettings { @@ -279,355 +439,45 @@ NSString * const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}Respon id<{{classPrefix}}Configuration> config = self.configuration; for (NSString *auth in authSettings) { - //NSDictionary *authSetting = [[config authSettings] objectForKey:auth]; NSDictionary *authSetting = config.authSettings[auth]; - - if (authSetting) { - if ([authSetting[@"in"] isEqualToString:@"header"]) { - [headersWithAuth setObject:authSetting[@"value"] forKey:authSetting[@"key"]]; - } - else if ([authSetting[@"in"] isEqualToString:@"query"]) { - [querysWithAuth setObject:authSetting[@"value"] forKey:authSetting[@"key"]]; - } - } - } - - *headers = [NSDictionary dictionaryWithDictionary:headersWithAuth]; - *querys = [NSDictionary dictionaryWithDictionary:querysWithAuth]; -} -- (id)sanitizeForSerialization:(id)object { - - if (object == nil) { - return nil; - } - else if ([object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSNumber class]] || [object isKindOfClass:[{{classPrefix}}QueryParamCollection class]]) { - return object; - } - else if ([object isKindOfClass:[NSDate class]]) { - return [object ISO8601String]; - } - else if ([object isKindOfClass:[NSArray class]]) { - NSArray *objectArray = object; - NSMutableArray *sanitizedObjs = [NSMutableArray arrayWithCapacity:[objectArray count]]; - [object enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - if (obj) { - [sanitizedObjs addObject:[self sanitizeForSerialization:obj]]; - } - }]; - return sanitizedObjs; - } - else if ([object isKindOfClass:[NSDictionary class]]) { - NSDictionary *objectDict = object; - NSMutableDictionary *sanitizedObjs = [NSMutableDictionary dictionaryWithCapacity:[objectDict count]]; - [object enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - if (obj) { - [sanitizedObjs setValue:[self sanitizeForSerialization:obj] forKey:key]; - } - }]; - return sanitizedObjs; - } - else if ([object isKindOfClass:[{{classPrefix}}Object class]]) { - return [object toDictionary]; - } - else { - NSException *e = [NSException - exceptionWithName:@"InvalidObjectArgumentException" - reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", object] - userInfo:nil]; - @throw e; - } -} - -- (id)deserialize:(id)data class:(NSString *)class { - - NSRegularExpression *regexp = nil; - NSTextCheckingResult *match = nil; - NSMutableArray *resultArray = nil; - NSMutableDictionary *resultDict = nil; - NSString *innerType = nil; - - // return nil if data is nil or class is nil - if (!data || !class) { - return nil; - } - - // remove "*" from class, if ends with "*" - if ([class hasSuffix:@"*"]) { - class = [class substringToIndex:[class length] - 1]; - } - - // pure object - if ([class isEqualToString:@"NSObject"]) { - return data; - } - - // list of models - NSString *arrayOfModelsPat = @"NSArray<(.+)>"; - regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfModelsPat - options:NSRegularExpressionCaseInsensitive - error:nil]; - - match = [regexp firstMatchInString:class - options:0 - range:NSMakeRange(0, [class length])]; - - if (match) { - NSArray *dataArray = data; - innerType = [class substringWithRange:[match rangeAtIndex:1]]; - - resultArray = [NSMutableArray arrayWithCapacity:[dataArray count]]; - [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - [resultArray addObject:[self deserialize:obj class:innerType]]; + if(!authSetting) { // auth setting is set only if the key is non-empty + continue; } - ]; - - return resultArray; - } - - // list of primitives - NSString *arrayOfPrimitivesPat = @"NSArray\\* /\\* (.+) \\*/"; - regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfPrimitivesPat - options:NSRegularExpressionCaseInsensitive - error:nil]; - match = [regexp firstMatchInString:class - options:0 - range:NSMakeRange(0, [class length])]; - - if (match) { - NSArray *dataArray = data; - innerType = [class substringWithRange:[match rangeAtIndex:1]]; - - resultArray = [NSMutableArray arrayWithCapacity:[dataArray count]]; - [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - [resultArray addObject:[self deserialize:obj class:innerType]]; - }]; - - return resultArray; - } - - // map - NSString *dictPat = @"NSDictionary\\* /\\* (.+?), (.+) \\*/"; - regexp = [NSRegularExpression regularExpressionWithPattern:dictPat - options:NSRegularExpressionCaseInsensitive - error:nil]; - match = [regexp firstMatchInString:class - options:0 - range:NSMakeRange(0, [class length])]; - - if (match) { - NSDictionary *dataDict = data; - NSString *valueType = [class substringWithRange:[match rangeAtIndex:2]]; - - resultDict = [NSMutableDictionary dictionaryWithCapacity:[dataDict count]]; - [data enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - [resultDict setValue:[self deserialize:obj class:valueType] forKey:key]; - }]; - - return resultDict; - } - - // primitives - NSArray *primitiveTypes = @[@"NSString", @"NSDate", @"NSNumber"]; - - if ([primitiveTypes containsObject:class]) { - if ([class isEqualToString:@"NSString"]) { - return [NSString stringWithString:data]; - } - else if ([class isEqualToString:@"NSDate"]) { - return [NSDate dateWithISO8601String:data]; - } - else if ([class isEqualToString:@"NSNumber"]) { - // NSNumber from NSNumber - if ([data isKindOfClass:[NSNumber class]]) { - return data; - } - else if ([data isKindOfClass:[NSString class]]) { - // NSNumber (NSCFBoolean) from NSString - if ([[data lowercaseString] isEqualToString:@"true"] || [[data lowercaseString] isEqualToString:@"false"]) { - return [NSNumber numberWithBool:[data boolValue]]; - // NSNumber from NSString - } else { - NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; - formatter.numberStyle = NSNumberFormatterDecimalStyle; - return [formatter numberFromString:data]; - } - } - } - } - - // model - Class ModelClass = NSClassFromString(class); - if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) { - return [[ModelClass alloc] initWithDictionary:data error:nil]; - } - - return nil; -} - -- (NSString *)pathWithQueryParamsToString:(NSString *)path - queryParams:(NSDictionary *)queryParams { - NSString * separator = nil; - int counter = 0; - - NSMutableString * requestUrl = [NSMutableString stringWithFormat:@"%@", path]; - if (queryParams != nil){ - for(NSString * key in [queryParams keyEnumerator]){ - if (counter == 0) separator = @"?"; - else separator = @"&"; - id queryParam = [queryParams valueForKey:key]; - if ([queryParam isKindOfClass:[NSString class]]){ - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [{{classPrefix}}ApiSessionManager escape:key], [{{classPrefix}}ApiSessionManager escape:[queryParams valueForKey:key]]]]; - } - 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"]) { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [{{classPrefix}}ApiSessionManager escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@","]]]]; - - } - else if ([format isEqualToString:@"tsv"]) { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [{{classPrefix}}ApiSessionManager escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@"\t"]]]]; - - } - else if ([format isEqualToString:@"pipes"]) { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [{{classPrefix}}ApiSessionManager escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@"|"]]]]; - - } - else if ([format isEqualToString:@"multi"]) { - for(id obj in values) { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [{{classPrefix}}ApiSessionManager escape:key], [NSString stringWithFormat:@"%@", obj]]]; - counter += 1; - } - - } - } - else { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [{{classPrefix}}ApiSessionManager escape:key], [NSString stringWithFormat:@"%@", [queryParams valueForKey:key]]]]; - } - - counter += 1; + NSString *type = authSetting[@"in"]; + NSString *key = authSetting[@"key"]; + NSString *value = authSetting[@"value"]; + if ([type isEqualToString:@"header"] && [key length] > 0 ) { + headersWithAuth[key] = value; + } else if ([type isEqualToString:@"query"] && [key length] != 0) { + querysWithAuth[key] = value; } } - return requestUrl; -} - -- (NSString *)parameterToString:(id)param { - - if ([param isKindOfClass:[NSString class]]) { - return param; - } - else if ([param isKindOfClass:[NSNumber class]]) { - return [param stringValue]; - } - else if ([param isKindOfClass:[NSDate class]]) { - return [param ISO8601String]; - } - else if ([param isKindOfClass:[NSArray class]]) { - NSMutableArray *mutableParam; - [param enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - [mutableParam addObject:[self parameterToString:obj]]; - }]; - return [mutableParam componentsJoinedByString:@","]; - } - else { - NSException *e = [NSException - exceptionWithName:@"InvalidObjectArgumentException" - reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", param] - userInfo:nil]; - @throw e; - } + + *headers = [NSDictionary dictionaryWithDictionary:headersWithAuth]; + *querys = [NSDictionary dictionaryWithDictionary:querysWithAuth]; } -#pragma mark - Utility Methods +- (AFSecurityPolicy *) customSecurityPolicy { + AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; -/* - * Detect `Accept` from accepts - */ -+ (NSString *)selectHeaderAccept:(NSArray *)accepts { - if (accepts == nil || [accepts count] == 0) { - return @""; - } - - NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]]; - for (NSString *string in accepts) { - NSString * lowerAccept = [string lowercaseString]; - if ([lowerAccept containsString:@"application/json"]) { - return @"application/json"; - } - [lowerAccepts addObject:lowerAccept]; - } - - if (lowerAccepts.count == 1) { - return [lowerAccepts firstObject]; - } - - return [lowerAccepts componentsJoinedByString:@", "]; -} + id<{{classPrefix}}Configuration> config = self.configuration; -/* - * Detect `Content-Type` from contentTypes - */ -+ (NSString *)selectHeaderContentType:(NSArray *)contentTypes { - if (contentTypes == nil || [contentTypes count] == 0) { - return @"application/json"; - } - - NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]]; - [contentTypes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - [lowerContentTypes addObject:[obj lowercaseString]]; - }]; - - if ([lowerContentTypes containsObject:@"application/json"]) { - return @"application/json"; - } - else { - return lowerContentTypes[0]; + if (config.sslCaCert) { + NSData *certData = [NSData dataWithContentsOfFile:config.sslCaCert]; + [securityPolicy setPinnedCertificates:[NSSet setWithObject:certData]]; } -} -+ (NSString*)escape:(id)unescaped { - if ([unescaped isKindOfClass:[NSString class]]){ - return (NSString *)CFBridgingRelease - (CFURLCreateStringByAddingPercentEscapes( - NULL, - (__bridge CFStringRef) unescaped, - NULL, - (CFStringRef)@"!*'();:@&=+$,/?%#[]", - kCFStringEncodingUTF8)); + if (config.verifySSL) { + [securityPolicy setAllowInvalidCertificates:NO]; } else { - return [NSString stringWithFormat:@"%@", unescaped]; + [securityPolicy setAllowInvalidCertificates:YES]; + [securityPolicy setValidatesDomainName:NO]; } -} - -#pragma mark - Log Methods -+ (void)debugLog:(NSString *)method - message:(NSString *)format, ... { - NSMutableString *message = [NSMutableString stringWithCapacity:1]; - - if (method) { - [message appendString:[NSString stringWithFormat:@"%@: ", method]]; - } - - va_list args; - va_start(args, format); - - [message appendString:[[NSString alloc] initWithFormat:format arguments:args]]; - - NSLog(@"%@", message); - - va_end(args); + return securityPolicy; } @end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-header.mustache index 1af58428f9a..f94d680375e 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-header.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-header.mustache @@ -6,6 +6,8 @@ #import #import "{{classPrefix}}Configuration.h" +#import "{{classPrefix}}ResponseDeserializer.h" +#import "{{classPrefix}}Sanitizer.h" /** * A key for `NSError` user info dictionaries. @@ -19,6 +21,92 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; @property (nonatomic, strong, readonly) id<{{classPrefix}}Configuration> configuration; +@property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy; +@property(nonatomic, assign) NSTimeInterval timeoutInterval; +@property(nonatomic, readonly) NSOperationQueue* queue; + +@property(nonatomic, strong) id<{{classPrefix}}ResponseDeserializer> responseDeserializer; + +@property(nonatomic, strong) id<{{classPrefix}}Sanitizer> sanitizer; + +/** + * Clears Cache + */ ++(void)clearCache; + +/** + * Turns on cache + * + * @param enabled If the cached is enable, must be `YES` or `NO` + */ ++(void)setCacheEnabled:(BOOL) enabled; + +/** + * Sets the client unreachable + * + * @param state off line state, must be `YES` or `NO` + */ ++(void) setOfflineState:(BOOL) state; + +/** + * Gets if the client is unreachable + * + * @return The client offline state + */ ++(BOOL) getOfflineState; + +/** + * Sets the client reachability, this may be overridden by the reachability manager if reachability changes + * + * @param The client reachability. + */ ++(void) setReachabilityStatus:(AFNetworkReachabilityStatus) status; + +/** + * Gets the client reachability + * + * @return The client reachability. + */ ++(AFNetworkReachabilityStatus) getReachabilityStatus; + +/** + * Customizes the behavior when the reachability changed + * + * @param changeBlock The block will be executed when the reachability changed. + */ ++(void) setReachabilityChangeBlock:(void(^)(int))changeBlock; + +/** + * Sets the api client reachability strategy + */ +- (void)configureCacheReachibility; + +/** + * Sets header for request + * + * @param value The header value + * @param forKey The header key + */ +-(void)setHeaderValue:(NSString*) value + forKey:(NSString*) forKey; + +/** + * Updates header parameters and query parameters for authentication + * + * @param headers The header parameter will be udpated, passed by pointer to pointer. + * @param querys The query parameters will be updated, passed by pointer to pointer. + * @param authSettings The authentication names NSArray. + */ +- (void) updateHeaderParams:(NSDictionary **)headers + queryParams:(NSDictionary **)querys + WithAuthSettings:(NSArray *)authSettings; + + +/** + * Initializes the session manager with a configuration. + * + * @param configuration The configuration implementation + */ - (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration; /** @@ -37,36 +125,25 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; * * @return The created session task. */ -- (NSURLSessionTask *)requestWithCompletionBlock:(NSString*)path - method:(NSString*) method - pathParams:(NSDictionary *)pathParams - queryParams:(NSDictionary*)queryParams - formParams:(NSDictionary *)formParams - files:(NSDictionary *)files - body:(id)body - headerParams:(NSDictionary *)headerParams - authSettings: (NSArray *)authSettings - requestContentType:(NSString *)requestContentType - responseContentType:(NSString *)responseContentType - responseType:(NSString *)responseType - completionBlock:(void (^)(id, NSError *))completionBlock; +- (NSURLSessionTask*) requestWithPath: (NSString*) path + method: (NSString*) method + pathParams: (NSDictionary *) pathParams + queryParams: (NSDictionary*) queryParams + formParams: (NSDictionary *) formParams + files: (NSDictionary *) files + body: (id) body + headerParams: (NSDictionary*) headerParams + authSettings: (NSArray *) authSettings + requestContentType: (NSString*) requestContentType + responseContentType: (NSString*) responseContentType + responseType: (NSString *) responseType + completionBlock: (void (^)(id, NSError *))completionBlock; /** - * Detects Accept header from accepts NSArray - * - * @param accepts NSArray of header - * - * @return The Accept header - */ -+ (NSString *)selectHeaderAccept:(NSArray *)accepts; - -/** - * Detects Content-Type header from contentTypes NSArray - * - * @param contentTypes NSArray of header + * Custom security policy * - * @return The Content-Type header + * @return AFSecurityPolicy */ -+ (NSString *)selectHeaderContentType:(NSArray *)contentTypes; +- (AFSecurityPolicy *) customSecurityPolicy; @end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/BasicAuthTokenProvider-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/BasicAuthTokenProvider-body.mustache index e2ba00badb7..a928e5e8f4e 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/BasicAuthTokenProvider-body.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/BasicAuthTokenProvider-body.mustache @@ -4,10 +4,15 @@ + (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password { + // return empty string if username and password are empty + if (username.length == 0 && password.length == 0){ + return @""; + } + NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password]; NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; - + return basicAuthCredentials; } diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/Configuration-protocol.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/Configuration-protocol.mustache index 7c585f598f9..db429a38150 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/Configuration-protocol.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/Configuration-protocol.mustache @@ -1,23 +1,75 @@ -/** The `{{classPrefix}}Configuration` protocol defines the interface of a configuration object for the sdk. - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ - #import +#import "{{classPrefix}}Logger.h" + +{{>licenceInfo}} @protocol {{classPrefix}}Configuration -@property (nonatomic, readonly) BOOL debug; -@property (nonatomic, readonly) BOOL cacheEnabled; -@property (nonatomic, readonly) BOOL offlineState; -@property (nonatomic, readonly) NSString *tempFolderPath; +/** + * Api logger + */ +@property (readonly, nonatomic) {{classPrefix}}Logger *logger; -@property (nonatomic, readonly) NSDictionary *authSettings; +/** + * Base url + */ +@property (readonly, nonatomic) NSString *host; + +/** + * Api key values for Api Key type Authentication + */ +@property (readonly, nonatomic) NSDictionary *apiKey; + +/** + * Api key prefix values to be prepend to the respective api key + */ +@property (readonly, nonatomic) NSDictionary *apiKeyPrefix; + +/** + * Username for HTTP Basic Authentication + */ +@property (readonly, nonatomic) NSString *username; + +/** + * Password for HTTP Basic Authentication + */ +@property (readonly, nonatomic) NSString *password; + +/** + * Access token for OAuth + */ +@property (readonly, nonatomic) NSString *accessToken; + +/** + * Temp folder for file download + */ +@property (readonly, nonatomic) NSString *tempFolderPath; + +/** + * Debug switch, default false + */ +@property (readonly, nonatomic) BOOL debug; + +/** + * SSL/TLS verification + * Set this to NO to skip verifying SSL certificate when calling API from https server + */ +@property (readonly, nonatomic) BOOL verifySSL; + +/** + * SSL/TLS verification + * Set this to customize the certificate file to verify the peer + */ +@property (readonly, nonatomic) NSString *sslCaCert; + +/** + * Authentication Settings + */ +@property (readonly, nonatomic) NSDictionary *authSettings; -@property (nonatomic, readonly) NSString *host; -@property (nonatomic, readonly) NSString *username; -@property (nonatomic, readonly) NSString *password; +/** +* Default headers for all services +*/ +@property (readonly, nonatomic, strong) NSDictionary *defaultHeaders; @end \ No newline at end of file diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/DefaultConfiguration-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/DefaultConfiguration-body.mustache index 62696b6e56f..7d99c336a94 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/DefaultConfiguration-body.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/DefaultConfiguration-body.mustache @@ -1,8 +1,17 @@ #import "{{classPrefix}}DefaultConfiguration.h" +#import "{{classPrefix}}BasicAuthTokenProvider.h" + +@interface {{classPrefix}}DefaultConfiguration () + +@property (nonatomic, strong) NSMutableDictionary *mutableDefaultHeaders; +@property (nonatomic, strong) NSMutableDictionary *mutableApiKey; +@property (nonatomic, strong) NSMutableDictionary *mutableApiKeyPrefix; + +@end @implementation {{classPrefix}}DefaultConfiguration -#pragma mark - Singletion Methods +#pragma mark - Singleton Methods + (instancetype)sharedConfiguration { @@ -22,18 +31,129 @@ _host = @"{{basePath}}"; _username = @""; _password = @""; - _tempFolderPath = nil; - _debug = NO; - _cacheEnabled = YES; - _offlineState = NO; + _accessToken= @""; + _verifySSL = YES; + _mutableApiKey = [NSMutableDictionary dictionary]; + _mutableApiKeyPrefix = [NSMutableDictionary dictionary]; + _mutableDefaultHeaders = [NSMutableDictionary dictionary]; + {{#httpUserAgent}}_mutableDefaultHeaders[@"User-Agent"] = @"{{httpUserAgent}}"{{/httpUserAgent}}; + _logger = [{{classPrefix}}Logger sharedLogger]; } return self; } +#pragma mark - Instance Methods + +- (NSString *) getApiKeyWithPrefix:(NSString *)key { + NSString *prefix = self.apiKeyPrefix[key]; + NSString *apiKey = self.apiKey[key]; + if (prefix && apiKey != (id)[NSNull null] && apiKey.length > 0) { // both api key prefix and api key are set + return [NSString stringWithFormat:@"%@ %@", prefix, apiKey]; + } + else if (apiKey != (id)[NSNull null] && apiKey.length > 0) { // only api key, no api key prefix + return [NSString stringWithFormat:@"%@", self.apiKey[key]]; + } + else { // return empty string if nothing is set + return @""; + } +} + +- (NSString *) getBasicAuthToken { + + NSString *basicAuthToken = [{{classPrefix}}BasicAuthTokenProvider createBasicAuthTokenWithUsername:self.username password:self.password]; + return basicAuthToken; +} + +- (NSString *) getAccessToken { + if (self.accessToken.length == 0) { // token not set, return empty string + return @""; + } else { + return [NSString stringWithFormat:@"Bearer %@", self.accessToken]; + } +} + +#pragma mark - Setter Methods + +- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString *)identifier { + [self.mutableApiKey setValue:apiKey forKey:identifier]; +} + +- (void) removeApiKey:(NSString *)identifier { + [self.mutableApiKey removeObjectForKey:identifier]; +} + +- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier { + [self.mutableApiKeyPrefix setValue:prefix forKey:identifier]; +} + +- (void) removeApiKeyPrefix:(NSString *)identifier { + [self.mutableApiKeyPrefix removeObjectForKey:identifier]; +} + #pragma mark - - (NSDictionary *) authSettings { - return @{}; + return @{ +{{#authMethods}} +{{#isApiKey}} + @"{{name}}": + @{ + @"type": @"api_key", + @"in": {{#isKeyInHeader}}@"header"{{/isKeyInHeader}}{{#isKeyInQuery}}@"query"{{/isKeyInQuery}}, + @"key": @"{{keyParamName}}", + @"value": [self getApiKeyWithPrefix:@"{{keyParamName}}"] + }, +{{/isApiKey}} +{{#isBasic}} + @"{{name}}": + @{ + @"type": @"basic", + @"in": @"header", + @"key": @"Authorization", + @"value": [self getBasicAuthToken] + }, +{{/isBasic}} +{{#isOAuth}} + @"{{name}}": + @{ + @"type": @"oauth", + @"in": @"header", + @"key": @"Authorization", + @"value": [self getAccessToken] + }, +{{/isOAuth}} +{{/authMethods}} + }; +} + +-(BOOL)debug { + return self.logger.isEnabled; +} + +-(void)setDebug:(BOOL)debug { + self.logger.enabled = debug; +} + + + +- (void)setDefaultHeaderValue:(NSString *)value forKey:(NSString *)key { + if(!value) { + [self.mutableDefaultHeaders removeObjectForKey:key]; + return; + } + self.mutableDefaultHeaders[key] = value; +} + +-(void) removeDefaultHeaderForKey:(NSString*)key { + [self.mutableDefaultHeaders removeObjectForKey:key]; +} + +- (NSString *)defaultHeaderForKey:(NSString *)key { + return self.mutableDefaultHeaders[key]; +} + +- (NSDictionary *)defaultHeaders { + return [self.mutableDefaultHeaders copy]; } @end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/DefaultConfiguration-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/DefaultConfiguration-header.mustache index a5da4a2fc68..3d74bceb2b6 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/DefaultConfiguration-header.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/DefaultConfiguration-header.mustache @@ -1,26 +1,129 @@ -/** The `{{classPrefix}}Configuration` class provides a default implementation of the configuration protocol for the sdk. - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ - #import #import "{{classPrefix}}Configuration.h" +{{>licenceInfo}} + @interface {{classPrefix}}DefaultConfiguration : NSObject <{{classPrefix}}Configuration> + ({{classPrefix}}DefaultConfiguration *)sharedConfiguration; -@property (nonatomic, assign) BOOL debug; +/** + * Default api logger + */ +@property (nonatomic, strong) {{classPrefix}}Logger * logger; + +/** + * Default base url + */ +@property (nonatomic) NSString *host; + +/** + * Api key values for Api Key type Authentication + * + * To add or remove api key, use `setApiKey:forApiKeyIdentifier:`. + */ +@property (readonly, nonatomic, strong) NSDictionary *apiKey; + +/** + * Api key prefix values to be prepend to the respective api key + * + * To add or remove prefix, use `setApiKeyPrefix:forApiKeyPrefixIdentifier:`. + */ +@property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix; + +/** + * Username for HTTP Basic Authentication + */ + @property (nonatomic) NSString *username; + +/** + * Password for HTTP Basic Authentication + */ +@property (nonatomic) NSString *password; + +/** + * Access token for OAuth + */ +@property (nonatomic) NSString *accessToken; + +/** + * Temp folder for file download + */ +@property (nonatomic) NSString *tempFolderPath; + +/** + * Debug switch, default false + */ +@property (nonatomic) BOOL debug; + +/** + * SSL/TLS verification + * Set this to NO to skip verifying SSL certificate when calling API from https server + */ +@property (nonatomic) BOOL verifySSL; + +/** + * SSL/TLS verification + * Set this to customize the certificate file to verify the peer + */ +@property (nonatomic) NSString *sslCaCert; + +/** + * Sets API key + * + * To remove a apiKey for an identifier, just set the apiKey to nil. + * + * @param apiKey API key or token. + * @param identifier API key identifier (authentication schema). + * + */ +- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString*)identifier; + +/** + * Removes api key + * + * @param identifier API key identifier. + */ +- (void) removeApiKey:(NSString *)identifier; + +/** + * Sets the prefix for API key + * + * @param apiKeyPrefix API key prefix. + * @param identifier API key identifier. + */ +- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier; + +/** + * Removes api key prefix + * + * @param identifier API key identifier. + */ +- (void) removeApiKeyPrefix:(NSString *)identifier; + +/** +* Default headers for all services +*/ +@property (readonly, nonatomic, strong) NSDictionary *defaultHeaders; -@property (nonatomic, assign) BOOL cacheEnabled; -@property (nonatomic, assign) BOOL offlineState; +/** +* Removes header from defaultHeaders +* +* @param Header name. +*/ +-(void) removeDefaultHeaderForKey:(NSString*)key; -@property (nonatomic, strong) NSString *host; -@property (nonatomic, strong) NSString *username; -@property (nonatomic, strong) NSString *password; +/** +* Sets the header for key +* +* @param value Value for header name +* @param key Header name +*/ +-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key; -@property (nonatomic, strong) NSString *tempFolderPath; +/** +* @param Header key name. +*/ +-(NSString*) defaultHeaderForKey:(NSString*)key; @end \ No newline at end of file diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONRequestSerializer-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONRequestSerializer-body.mustache index 3896c49cfb7..63513335d9a 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONRequestSerializer-body.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONRequestSerializer-body.mustache @@ -15,22 +15,23 @@ /// - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request withParameters:(id)parameters - error:(NSError *__autoreleasing *)error { - + error:(NSError *__autoreleasing *)error +{ + if (!parameters) { + return request; + } // If the body data which will be serialized isn't NSArray or NSDictionary // then put the data in the http request body directly. if ([parameters isKindOfClass:[NSArray class]] || [parameters isKindOfClass:[NSDictionary class]]) { return [super requestBySerializingRequest:request withParameters:parameters error:error]; } - else { - NSMutableURLRequest *mutableRequest = [request mutableCopy]; - - if (parameters) { - [mutableRequest setHTTPBody:[parameters dataUsingEncoding:self.stringEncoding]]; - } - - return mutableRequest; + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + if([parameters isKindOfClass:[NSData class]]) { + [mutableRequest setHTTPBody:parameters]; + } else { + [mutableRequest setHTTPBody:[parameters dataUsingEncoding:self.stringEncoding]]; } + return mutableRequest; } @end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONRequestSerializer-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONRequestSerializer-header.mustache index a0732b93706..1259c5d1530 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONRequestSerializer-header.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONRequestSerializer-header.mustache @@ -1,5 +1,7 @@ #import #import +{{>licenceInfo}} + @interface {{classPrefix}}JSONRequestSerializer : AFJSONRequestSerializer @end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONResponseSerializer-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONResponseSerializer-body.mustache index c36c171018c..7fa5e7b19e0 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONResponseSerializer-body.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONResponseSerializer-body.mustache @@ -1,13 +1,5 @@ #import "{{classPrefix}}JSONResponseSerializer.h" -static BOOL JSONParseError(NSError *error) { - if ([error.domain isEqualToString:NSCocoaErrorDomain] && error.code == 3840) { - return YES; - } - - return NO; -} - @implementation {{classPrefix}}JSONResponseSerializer /// @@ -17,17 +9,17 @@ static BOOL JSONParseError(NSError *error) { /// /// @param response The response to be processed. /// @param data The response data to be decoded. -/// @param error The error that occurred while attempting to decode the respnse data. +/// @param error The error that occurred while attempting to decode the response data. /// /// @return The object decoded from the specified response data. /// -- (id)responseObjectForResponse:(NSURLResponse *)response - data:(NSData *)data - error:(NSError *__autoreleasing *)error { +- (id) responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error { NSDictionary *responseJson = [super responseObjectForResponse:response data:data error:error]; // if response data is not a valid json, return string of data. - if (JSONParseError(*error)) { + if ([self isParseError:*error]) { *error = nil; NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; return responseString; @@ -36,4 +28,12 @@ static BOOL JSONParseError(NSError *error) { return responseJson; } +-(BOOL)isParseError:(NSError *)error { + return [error.domain isEqualToString:NSCocoaErrorDomain] && error.code == 3840; +} + ++ (instancetype)serializer { + return [self serializerWithReadingOptions:NSJSONReadingAllowFragments]; +} + @end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONResponseSerializer-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONResponseSerializer-header.mustache index 7a5f152e271..360e4f9cdc5 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONResponseSerializer-header.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONResponseSerializer-header.mustache @@ -1,6 +1,8 @@ #import #import +{{>licenceInfo}} + @interface {{classPrefix}}JSONResponseSerializer : AFJSONResponseSerializer @end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601-body.mustache new file mode 100644 index 00000000000..b544a1dae58 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601-body.mustache @@ -0,0 +1,11 @@ +#import +#import "JSONValueTransformer+ISO8601.h" + +@implementation JSONValueTransformer (ISO8601) + +- (NSDate *) NSDateFromNSString:(NSString *)string +{ + return [NSDate dateWithISO8601String:string]; +} + +@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601-header.mustache new file mode 100644 index 00000000000..f621e7184a9 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601-header.mustache @@ -0,0 +1,8 @@ +#import +#import + +{{>licenceInfo}} + +@interface JSONValueTransformer (ISO8601) + +@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/Logger-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/Logger-body.mustache new file mode 100644 index 00000000000..9a8f7de2418 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/Logger-body.mustache @@ -0,0 +1,74 @@ +#import "{{classPrefix}}Logger.h" + +@interface {{classPrefix}}Logger () + +@end + +@implementation {{classPrefix}}Logger + ++ (instancetype) sharedLogger { + static {{classPrefix}}Logger *shardLogger = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + shardLogger = [[self alloc] init]; + }); + return shardLogger; +} + +#pragma mark - Log Methods + +- (void)debugLog:(NSString *)method + message:(NSString *)format, ... { + if (!self.isEnabled) { + return; + } + + NSMutableString *message = [NSMutableString stringWithCapacity:1]; + + if (method) { + [message appendFormat:@"%@: ", method]; + } + + va_list args; + va_start(args, format); + + [message appendString:[[NSString alloc] initWithFormat:format arguments:args]]; + + // If set logging file handler, log into file, + // otherwise log into console. + if (self.loggingFileHandler) { + [self.loggingFileHandler seekToEndOfFile]; + [self.loggingFileHandler writeData:[message dataUsingEncoding:NSUTF8StringEncoding]]; + } else { + NSLog(@"%@", message); + } + + va_end(args); +} + +- (void)logResponse:(NSURLResponse *)response responseObject:(id)responseObject request:(NSURLRequest *)request error:(NSError *)error { + NSString *message = [NSString stringWithFormat:@"\n[DEBUG] HTTP request body \n~BEGIN~\n %@\n~END~\n"\ + "[DEBUG] HTTP response body \n~BEGIN~\n %@\n~END~\n", + [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding], + responseObject]; + + {{classPrefix}}DebugLog(message); +} + +- (void) setLoggingFile:(NSString *)loggingFile { + if(_loggingFile == loggingFile) { + return; + } + // close old file handler + if ([self.loggingFileHandler isKindOfClass:[NSFileHandle class]]) { + [self.loggingFileHandler closeFile]; + } + _loggingFile = loggingFile; + _loggingFileHandler = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; + if (_loggingFileHandler == nil) { + [[NSFileManager defaultManager] createFileAtPath:_loggingFile contents:nil attributes:nil]; + _loggingFileHandler = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; + } +} + +@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/Logger-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/Logger-header.mustache new file mode 100644 index 00000000000..37afea41a09 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/Logger-header.mustache @@ -0,0 +1,50 @@ +#import + +{{>licenceInfo}} + +#ifndef {{classPrefix}}DebugLogResponse +#define {{classPrefix}}DebugLogResponse(response, responseObject,request, error) [[{{classPrefix}}Logger sharedLogger] logResponse:response responseObject:responseObject request:request error:error]; +#endif + +/** + * Log debug message macro + */ +#ifndef {{classPrefix}}DebugLog +#define {{classPrefix}}DebugLog(format, ...) [[{{classPrefix}}Logger sharedLogger] debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__]; +#endif + +@interface {{classPrefix}}Logger : NSObject + ++(instancetype)sharedLogger; + +/** + * Enabled switch, default NO - default set by {{classPrefix}}Configuration debug property + */ +@property (nonatomic, assign, getter=isEnabled) BOOL enabled; + +/** + * Debug file location, default log in console + */ +@property (nonatomic, strong) NSString *loggingFile; + +/** + * Log file handler, this property is used by sdk internally. + */ +@property (nonatomic, strong, readonly) NSFileHandle *loggingFileHandler; + +/** + * Log debug message + */ +-(void)debugLog:(NSString *)method message:(NSString *)format, ...; + +/** + * Logs request and response + * + * @param response NSURLResponse for the HTTP request. + * @param responseObject response object of the HTTP request. + * @param request The HTTP request. + * @param error The error of the HTTP request. + */ +- (void)logResponse:(NSURLResponse *)response responseObject:(id)responseObject request:(NSURLRequest *)request error:(NSError *)error; + +@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/Model.xcdatamodel.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/Model.xcdatamodel.mustache new file mode 100644 index 00000000000..90dcd63e3d9 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/Model.xcdatamodel.mustache @@ -0,0 +1,12 @@ + + + + {{#models}}{{#model}} +{{#isArrayModel}} +{{/isArrayModel}}{{^isArrayModel}}{{#vars}}{{#complexType}} {{/complexType}}{{^complexType}} {{/complexType}}{{#vendorExtensions.x-is-unique}} + {{/vendorExtensions.x-is-unique}} +{{/vars}} +{{/isArrayModel}} + + {{/model}}{{/models}} + \ No newline at end of file diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/NSManagedObject-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/NSManagedObject-body.mustache new file mode 100644 index 00000000000..205a692af5e --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/NSManagedObject-body.mustache @@ -0,0 +1,20 @@ +{{#models}} +{{#model}} +#import "{{classname}}ManagedObject.h" + +/** +* NOTE: This class is auto generated by the swagger code generator program. +* https://github.com/swagger-api/swagger-codegen +* Do not edit the class manually. +*/ +@implementation {{classname}}ManagedObject +{{#isArrayModel}} + +@dynamic entries; + +{{/isArrayModel}}{{^isArrayModel}}{{#vars}} +@dynamic {{name}};{{/vars}} +{{/isArrayModel}} +{{/model}} +@end +{{/models}} diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/NSManagedObject-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/NSManagedObject-header.mustache new file mode 100644 index 00000000000..53bc9172472 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/NSManagedObject-header.mustache @@ -0,0 +1,49 @@ +#import +#import + +{{>licenceInfo}} + +{{#imports}}#import "{{import}}ManagedObject.h" +{{/imports}} +{{newline}} +{{#models}} +{{#model}} + +NS_ASSUME_NONNULL_BEGIN +{{#isArrayModel}} + +@interface {{classname}}ManagedObject : NSManagedObject + +@property (nullable, nonatomic, retain) NSSet<{{{arrayModelType}}}ManagedObject*>* entries; + +{{/isArrayModel}}{{^isArrayModel}} +@interface {{classname}}ManagedObject : {{#parent}}{{{parent}}}ManagedObject{{/parent}}{{^parent}}NSManagedObject{{/parent}} + +{{#vars}} +{{#description}}/* {{{description}}} {{^required}}[optional]{{/required}} + */{{/description}} +@property (nullable, nonatomic, retain) {{^complexType}}{{{ datatype }}}{{/complexType}}{{#complexType}}{{#isListContainer}}NSSet<{{{complexType}}}ManagedObject*>*{{/isListContainer}}{{^isListContainer}}{{#isMapContainer}}{{{ datatype }}}{{/isMapContainer}}{{^isMapContainer}}{{{complexType}}}ManagedObject*{{/isMapContainer}}{{/isListContainer}}{{/complexType}} {{name}}; +{{/vars}} +{{/isArrayModel}} +@end + +@interface {{classname}}ManagedObject (GeneratedAccessors) +{{#isArrayModel}} +- (void)addEntriesObject:({{arrayModelType}}ManagedObject *)value; +- (void)removeEntriesObject:({{arrayModelType}}ManagedObject *)value; +- (void)addEntries:(NSSet<{{{arrayModelType}}}ManagedObject*> *)values; +- (void)removeEntries:(NSSet<{{{arrayModelType}}}ManagedObject*> *)values; +{{/isArrayModel}} +{{^isArrayModel}} +{{#vars}}{{#isListContainer}}{{#complexType}}- (void)add{{vendorExtensions.x-uppercaseName}}Object:({{complexType}}ManagedObject *)value; +- (void)remove{{vendorExtensions.x-uppercaseName}}Object:({{complexType}}ManagedObject *)value; +- (void)add{{vendorExtensions.x-uppercaseName}}:(NSSet<{{{complexType}}}ManagedObject*> *)values; +- (void)remove{{vendorExtensions.x-uppercaseName}}:(NSSet<{{{complexType}}}ManagedObject*> *)values; +{{/complexType}}{{/isListContainer}}{{/vars}} +{{/isArrayModel}} +@end + + +NS_ASSUME_NONNULL_END +{{/model}} +{{/models}} \ No newline at end of file diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/NSManagedObjectBuilder-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/NSManagedObjectBuilder-body.mustache new file mode 100644 index 00000000000..b6b69135286 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/NSManagedObjectBuilder-body.mustache @@ -0,0 +1,89 @@ + +{{#models}}{{#model}} +#import "{{classname}}ManagedObjectBuilder.h" + +/** +* NOTE: This class is auto generated by the swagger code generator program. +* https://github.com/swagger-api/swagger-codegen +* Do not edit the class manually. +*/ + +@implementation {{classname}}ManagedObjectBuilder + +-(instancetype)init { + self = [super init]; + if (self != nil) { +{{#isArrayModel}} _entriesBuilder = [[{{arrayModelType}}ManagedObjectBuilder alloc] init]; +{{/isArrayModel}}{{#vars}}{{#complexType}}{{^isMapContainer}} _{{name}}Builder = [[{{complexType}}ManagedObjectBuilder alloc] init]; +{{/isMapContainer}}{{/complexType}}{{/vars}} } + return self; +} + +-({{classname}}ManagedObject*)createNew{{classname}}ManagedObjectInContext:(NSManagedObjectContext*)context { + {{classname}}ManagedObject *managedObject = [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([{{classname}}ManagedObject class]) inManagedObjectContext:context]; + return managedObject; +} + +-({{classname}}ManagedObject*){{classname}}ManagedObjectFrom{{classname}}:({{classname}}*)object context:(NSManagedObjectContext*)context { + {{classname}}ManagedObject* new{{classname}} = [self createNew{{{classname}}}ManagedObjectInContext:context]; + [self update{{classname}}ManagedObject:new{{classname}} with{{classname}}:object]; + return new{{classname}}; +} + +-(void)update{{classname}}ManagedObject:({{classname}}ManagedObject*)managedObject with{{classname}}:({{classname}}*)object { + if(!managedObject || !object) { + return; + } +{{#vars}}{{^complexType}} managedObject.{{name}} = [object.{{name}} copy];{{/complexType}}{{#complexType}}{{#isListContainer}} if(object.{{name}}) { + NSMutableSet * convertedObjs = [NSMutableSet set]; + for (id innerObject in object.{{name}}) { + id convertedObj = [self.{{name}}Builder {{complexType}}ManagedObjectFrom{{complexType}}:innerObject context:managedObject.managedObjectContext]; + [convertedObjs addObject:convertedObj]; + } + managedObject.{{name}} = convertedObjs; + }{{/isListContainer}}{{^isListContainer}}{{^isMapContainer}} + if(!managedObject.{{name}}) { + managedObject.{{name}} = [self.{{name}}Builder {{complexType}}ManagedObjectFrom{{complexType}}:object.{{name}} context:managedObject.managedObjectContext]; + } else { + [self.{{name}}Builder update{{complexType}}ManagedObject:managedObject.{{name}} with{{complexType}}:object.{{name}}]; + }{{/isMapContainer}}{{#isMapContainer}}managedObject.{{name}} = [object.{{name}} copy];{{/isMapContainer}}{{/isListContainer}}{{/complexType}} +{{/vars}}{{#isArrayModel}} NSMutableSet * convertedObjs = [NSMutableSet set]; + for (id innerObject in object) { + id convertedObj = [self.entriesBuilder {{arrayModelType}}ManagedObjectFrom{{arrayModelType}}:innerObject context:managedObject.managedObjectContext]; + [convertedObjs addObject:convertedObj]; + } + managedObject.entries = convertedObjs;{{/isArrayModel}} +} + +-({{classname}}*){{classname}}From{{classname}}ManagedObject:({{classname}}ManagedObject*)obj { + if(!obj) { + return nil; + } + {{classname}}* new{{classname}} = [[{{classname}} alloc] init]; + [self update{{classname}}:new{{classname}} with{{classname}}ManagedObject:obj]; + return new{{classname}}; +} + +-(void)update{{classname}}:({{classname}}*)new{{classname}} with{{classname}}ManagedObject:({{classname}}ManagedObject*)obj { +{{#isArrayModel}} [new{{classname}} removeAllObjects]; + NSMutableArray* convertedObjs = [NSMutableArray array]; + for (id innerObject in obj.entries) { + id convertedObj = [self.entriesBuilder {{arrayModelType}}From{{arrayModelType}}ManagedObject:innerObject]; + [convertedObjs addObject:convertedObj]; + } + [new{{classname}} addObjectsFromArray:convertedObjs]; +{{/isArrayModel}}{{#vars}}{{^complexType}} new{{classname}}.{{name}} = [obj.{{name}} copy];{{/complexType}}{{#complexType}}{{#isListContainer}} if(obj.{{name}} != nil) { + NSMutableArray* convertedObjs = [NSMutableArray array]; + for (id innerObject in obj.{{name}}) { + id convertedObj = [self.{{name}}Builder {{complexType}}From{{complexType}}ManagedObject:innerObject]; + [convertedObjs addObject:convertedObj]; + } + new{{classname}}.{{name}} = ({{{ datatype }}})convertedObjs; + } + {{/isListContainer}}{{^isListContainer}} new{{classname}}.{{name}} = [self.{{name}}Builder {{complexType}}From{{complexType}}ManagedObject:obj.{{name}}];{{/isListContainer}}{{/complexType}} + {{/vars}} +} + +@end +{{/model}} +{{/models}} \ No newline at end of file diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/NSManagedObjectBuilder-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/NSManagedObjectBuilder-header.mustache new file mode 100644 index 00000000000..15778de3217 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/NSManagedObjectBuilder-header.mustache @@ -0,0 +1,31 @@ +#import +#import + +{{#imports}}#import "{{import}}ManagedObjectBuilder.h" +{{/imports}} +{{#models}} +{{#model}} + +#import "{{classname}}ManagedObject.h" +#import "{{classname}}.h" + +{{>licenceInfo}} + +@interface {{classname}}ManagedObjectBuilder : NSObject + +{{#isArrayModel}}@property (nonatomic, strong) {{arrayModelType}}ManagedObjectBuilder * entriesBuilder;{{/isArrayModel}}{{#vars}}{{#complexType}}@property (nonatomic, strong) {{complexType}}ManagedObjectBuilder * {{name}}Builder; +{{/complexType}}{{/vars}} + +-({{classname}}ManagedObject*)createNew{{classname}}ManagedObjectInContext:(NSManagedObjectContext*)context; + +-({{classname}}ManagedObject*){{classname}}ManagedObjectFrom{{classname}}:({{classname}}*)object context:(NSManagedObjectContext*)context; + +-(void)update{{classname}}ManagedObject:({{classname}}ManagedObject*)object with{{classname}}:({{classname}}*)object2; + +-({{classname}}*){{classname}}From{{classname}}ManagedObject:({{classname}}ManagedObject*)obj; + +-(void)update{{classname}}:({{classname}}*)object with{{classname}}ManagedObject:({{classname}}ManagedObject*)object2; + +@end +{{/model}} +{{/models}} diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/Object-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/Object-body.mustache index 458249a49a2..88df6d6c9ae 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/Object-body.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/Object-body.mustache @@ -2,10 +2,11 @@ @implementation {{classPrefix}}Object -// workaround for JSONModel multithreading issues -// https://github.com/icanzilb/JSONModel/issues/441 -- (instancetype)initWithDictionary:(NSDictionary *)dict error:(NSError **)err -{ +/** + * Workaround for JSONModel multithreading issues + * https://github.com/icanzilb/JSONModel/issues/441 + */ +- (instancetype)initWithDictionary:(NSDictionary *)dict error:(NSError **)err { static NSMutableSet *classNames; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ @@ -30,4 +31,12 @@ return self; } +/** + * Gets the string presentation of the object. + * This method will be called when logging model object using `NSLog`. + */ +- (NSString *)description { + return [[self toDictionary] description]; +} + @end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/Object-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/Object-header.mustache index d96e379908f..89da6a4d8b6 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/Object-header.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/Object-header.mustache @@ -1,5 +1,8 @@ #import #import +{{>licenceInfo}} + @interface {{classPrefix}}Object : JSONModel + @end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/QueryParamCollection-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/QueryParamCollection-body.mustache index f2d31cf4560..b1c901dbffa 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/QueryParamCollection-body.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/QueryParamCollection-body.mustache @@ -1,14 +1,10 @@ #import "{{classPrefix}}QueryParamCollection.h" -@interface {{classPrefix}}QueryParamCollection () - -@property (nonatomic, strong) NSArray * values; -@property (nonatomic, strong) NSString * format; - -@end - @implementation {{classPrefix}}QueryParamCollection +@synthesize values = _values; +@synthesize format = _format; + - (id)initWithValuesAndFormat:(NSArray *)values format:(NSString *)format { diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/QueryParamCollection-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/QueryParamCollection-header.mustache index 7dc3cbc6e1c..9729c182bd8 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/QueryParamCollection-header.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/QueryParamCollection-header.mustache @@ -1,11 +1,13 @@ #import +{{>licenceInfo}} + @interface {{classPrefix}}QueryParamCollection : NSObject -@property (nonatomic, readonly) NSArray * values; -@property (nonatomic, readonly) NSString * format; +@property(nonatomic, readonly) NSArray* values; +@property(nonatomic, readonly) NSString* format; -- (id)initWithValuesAndFormat:(NSArray *)values - format:(NSString *)format; +- (id) initWithValuesAndFormat: (NSArray*) values + format: (NSString*) format; @end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/README.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/README.mustache index 30a8927c41a..4355ecc1af5 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/README.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/README.mustache @@ -1,20 +1,140 @@ # {{podName}} +{{#appDescription}} +{{{appDescription}}} +{{/appDescription}} + +This ObjC package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: + +- API version: {{appVersion}} +- Package version: {{artifactVersion}} +- Build date: {{generatedDate}} +- Build package: {{generatorClass}} +{{#infoUrl}} +For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + ## Requirements -The API client library requires ARC (Automatic Reference Counting) to be enabled in your Xcode project. +The SDK requires [**ARC (Automatic Reference Counting)**](http://stackoverflow.com/questions/7778356/how-to-enable-disable-automatic-reference-counting) to be enabled in the Xcode project. -## Installation +## Installation & Usage +### Install from Github using [CocoaPods](https://cocoapods.org/) -To install it, put the API client library in your project and then simply add the following line to your Podfile: +Add the following to the Podfile: ```ruby -pod "{{podName}}", :path => "/path/to/lib" +pod '{{podName}}', :git => 'https://github.com/{{gitUserId}}/{{gitRepoId}}.git' +``` + +To specify a particular branch, append `, :branch => 'branch-name-here'` + +To specify a particular commit, append `, :commit => '11aa22'` + +### Install from local path using [CocoaPods](https://cocoapods.org/) + +Put the SDK under your project folder (e.g. /path/to/objc_project/Vendor/{{podName}}) and then add the following to the Podfile: + +```ruby +pod '{{podName}}', :path => 'Vendor/{{podName}}' +``` + +### Usage + +Import the following: + +```objc +#import <{{podName}}/{{{classPrefix}}}ApiClient.h> +#import <{{podName}}/{{{classPrefix}}}Configuration.h> +// load models +{{#models}}{{#model}}#import <{{podName}}/{{{classname}}}.h> +{{/model}}{{/models}}// load API classes for accessing endpoints +{{#apiInfo}}{{#apis}}#import <{{podName}}/{{{classname}}}.h> +{{/apis}}{{/apiInfo}} ``` ## Recommendation -It's recommended to create an instance of ApiClient per thread in a multithreaded environment to avoid any potential issue. +It's recommended to create an instance of ApiClient per thread in a multi-threaded environment to avoid any potential issue. + +## Getting Started + +Please follow the [installation procedure](#installation--usage) and then run the following: + +```objc +{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}} +{{#hasAuthMethods}} +{{classPrefix}}Configuration *apiConfig = [{{classPrefix}}Configuration sharedConfig]; +{{#authMethods}}{{#isBasic}}// Configure HTTP basic authorization (authentication scheme: {{{name}}}) +[apiConfig setUsername:@"YOUR_USERNAME"]; +[apiConfig setPassword:@"YOUR_PASSWORD"]; +{{/isBasic}}{{#isApiKey}} +// Configure API key authorization: (authentication scheme: {{{name}}}) +[apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"{{{keyParamName}}}"]; +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +//[apiConfig setApiKeyPrefix:@"Bearer" forApiKeyIdentifier:@"{{{keyParamName}}}"]; +{{/isApiKey}}{{#isOAuth}} +// Configure OAuth2 access token for authorization: (authentication scheme: {{{name}}}) +[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; +{{/isOAuth}}{{/authMethods}} +{{/hasAuthMethods}} + +{{#allParams}}{{{dataType}}} *{{paramName}} = {{{example}}}; // {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} +{{/allParams}} + +{{classname}} *apiInstance = [[{{classname}} alloc] init]; + +{{#summary}}// {{{.}}} +{{/summary}}[apiInstance {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} + {{paramName}}{{/secondaryParam}}:{{paramName}}{{/allParams}} + {{#hasParams}}completionHandler: {{/hasParams}}^({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error) { +{{#returnType}} + if (output) { + NSLog(@"%@", output); + } +{{/returnType}} + if (error) { + NSLog(@"Error: %@", error); + } + }]; +{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} +``` + +## Documentation for API Endpoints + +All URIs are relative to *{{basePath}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + +## Documentation For Models + +{{#models}}{{#model}} - [{{{classname}}}]({{modelDocPath}}{{{classname}}}.md) +{{/model}}{{/models}} + +## Documentation For Authorization + +{{^authMethods}} All endpoints do not require authorization. +{{/authMethods}}{{#authMethods}}{{#last}} Authentication schemes defined for the API:{{/last}}{{/authMethods}} +{{#authMethods}}## {{{name}}} + +{{#isApiKey}}- **Type**: API key +- **API key parameter name**: {{{keyParamName}}} +- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} +{{/isApiKey}} +{{#isBasic}}- **Type**: HTTP basic authentication +{{/isBasic}} +{{#isOAuth}}- **Type**: OAuth +- **Flow**: {{{flow}}} +- **Authorization URL**: {{{authorizationUrl}}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - **{{{scope}}}**: {{{description}}} +{{/scopes}} +{{/isOAuth}} + +{{/authMethods}} ## Author diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/ResponseDeserializer-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/ResponseDeserializer-body.mustache new file mode 100644 index 00000000000..812ed061c04 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/ResponseDeserializer-body.mustache @@ -0,0 +1,231 @@ +#import "{{classPrefix}}ResponseDeserializer.h" +#import +#import + +NSString *const {{classPrefix}}DeserializationErrorDomainKey = @"{{classPrefix}}DeserializationErrorDomainKey"; + +NSInteger const {{classPrefix}}TypeMismatchErrorCode = 143553; + +NSInteger const {{classPrefix}}EmptyValueOccurredErrorCode = 143509; + +NSInteger const {{classPrefix}}UnknownResponseObjectErrorCode = 143528; + + +@interface {{classPrefix}}ResponseDeserializer () + +@property (nonatomic, strong) NSNumberFormatter* numberFormatter; +@property (nonatomic, strong) NSArray *primitiveTypes; +@property (nonatomic, strong) NSArray *basicReturnTypes; + +@property (nonatomic, strong) NSRegularExpression* arrayOfModelsPatExpression; +@property (nonatomic, strong) NSRegularExpression* arrayOfPrimitivesPatExpression; +@property (nonatomic, strong) NSRegularExpression* dictPatExpression; +@property (nonatomic, strong) NSRegularExpression* dictModelsPatExpression; + +@end + +@implementation {{classPrefix}}ResponseDeserializer + +- (instancetype)init { + self = [super init]; + if (self) { + NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; + formatter.numberStyle = NSNumberFormatterDecimalStyle; + _numberFormatter = formatter; + _primitiveTypes = @[@"NSString", @"NSDate", @"NSNumber"]; + _basicReturnTypes = @[@"NSObject", @"id", @"NSData"]; + _arrayOfModelsPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSArray<(.+)>" + options:NSRegularExpressionCaseInsensitive + error:nil]; + _arrayOfPrimitivesPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSArray\\* /\\* (.+) \\*/" + options:NSRegularExpressionCaseInsensitive + error:nil]; + _dictPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSDictionary\\* /\\* (.+?), (.+) \\*/" + options:NSRegularExpressionCaseInsensitive + error:nil]; + _dictModelsPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSDictionary\\<(.+?), (.+)*\\>" + options:NSRegularExpressionCaseInsensitive + error:nil]; + } + return self; +} + +#pragma mark - Deserialize methods + +- (id) deserialize:(id) data class:(NSString *) className error:(NSError **) error { + // return nil if data is nil or className is nil + if (!data || !className || [data isKindOfClass:[NSNull class]]) { + return nil; + } + + // remove "*" from className, if ends with "*" + if ([className hasSuffix:@"*"]) { + className = [className substringToIndex:[className length] - 1]; + } + // pure object + if ([self.basicReturnTypes containsObject:className]) { + return data; + } + + // primitives + if ([self.primitiveTypes containsObject:className]) { + return [self deserializePrimitiveValue:data class:className error:error]; + } + + NSTextCheckingResult *match = nil; + NSRange range = NSMakeRange(0, [className length]); + // list of models + match = [self.arrayOfModelsPatExpression firstMatchInString:className options:0 range:range]; + if (match) { + NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]]; + return [self deserializeArrayValue:data innerType:innerType error:error]; + } + + // list of primitives + match = [self.arrayOfPrimitivesPatExpression firstMatchInString:className options:0 range:range]; + if (match) { + NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]]; + return [self deserializeArrayValue:data innerType:innerType error:error]; + } + + // map + match = [self.dictPatExpression firstMatchInString:className options:0 range:range]; + if (match) { + NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]]; + return [self deserializeDictionaryValue:data valueType:valueType error:error]; + } + + match = [self.dictModelsPatExpression firstMatchInString:className options:0 range:range]; + if (match) { + NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]]; + return [self deserializeDictionaryValue:data valueType:valueType error:error]; + } + + // model + Class ModelClass = NSClassFromString(className); + if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) { + return [(JSONModel *) [ModelClass alloc] initWithDictionary:data error:error]; + } + + if(error) { + *error = [self unknownResponseErrorWithExpectedType:className data:data]; + } + return nil; +} + +- (id) deserializeDictionaryValue:(id) data valueType:(NSString *) valueType error:(NSError**)error { + if(![data isKindOfClass: [NSDictionary class]]) { + if(error) { + *error = [self typeMismatchErrorWithExpectedType:NSStringFromClass([NSDictionary class]) data:data]; + } + return nil; + } + __block NSMutableDictionary *resultDict = [NSMutableDictionary dictionaryWithCapacity:[data count]]; + for (id key in [data allKeys]) { + id obj = [data valueForKey:key]; + id dicObj = [self deserialize:obj class:valueType error:error]; + if(dicObj) { + [resultDict setValue:dicObj forKey:key]; + } else if([obj isKindOfClass:[NSNull class]]) { + if(self.treatNullAsError) { + if (error) { + *error = [self emptyValueOccurredError]; + } + resultDict = nil; + break; + } + } else { + resultDict = nil; + break; + } + } + return resultDict; +} + +- (id) deserializeArrayValue:(id) data innerType:(NSString *) innerType error:(NSError**)error { + if(![data isKindOfClass: [NSArray class]]) { + if(error) { + *error = [self typeMismatchErrorWithExpectedType:NSStringFromClass([NSArray class]) data:data]; + } + return nil; + } + NSMutableArray* resultArray = [NSMutableArray arrayWithCapacity:[data count]]; + for (id obj in data) { + id arrObj = [self deserialize:obj class:innerType error:error]; + if(arrObj) { + [resultArray addObject:arrObj]; + } else if([obj isKindOfClass:[NSNull class]]) { + if(self.treatNullAsError) { + if (error) { + *error = [self emptyValueOccurredError]; + } + resultArray = nil; + break; + } + } else { + resultArray = nil; + break; + } + } + return resultArray; +}; + +- (id) deserializePrimitiveValue:(id) data class:(NSString *) className error:(NSError**)error { + if ([className isEqualToString:@"NSString"]) { + return [NSString stringWithString:data]; + } + else if ([className isEqualToString:@"NSDate"]) { + return [self deserializeDateValue:data error:error]; + } + else if ([className isEqualToString:@"NSNumber"]) { + // NSNumber from NSNumber + if ([data isKindOfClass:[NSNumber class]]) { + return data; + } + else if ([data isKindOfClass:[NSString class]]) { + // NSNumber (NSCFBoolean) from NSString + if ([[data lowercaseString] isEqualToString:@"true"] || [[data lowercaseString] isEqualToString:@"false"]) { + return @([data boolValue]); + // NSNumber from NSString + } else { + NSNumber* formattedValue = [self.numberFormatter numberFromString:data]; + if(!formattedValue && [data length] > 0 && error) { + *error = [self typeMismatchErrorWithExpectedType:className data:data]; + } + return formattedValue; + } + } + } + if(error) { + *error = [self typeMismatchErrorWithExpectedType:className data:data]; + } + return nil; +} + +- (id) deserializeDateValue:(id) data error:(NSError**)error { + NSDate *date =[NSDate dateWithISO8601String:data]; + if(!date && [data length] > 0 && error) { + *error = [self typeMismatchErrorWithExpectedType:NSStringFromClass([NSDate class]) data:data]; + } + return date; +}; + +-(NSError *)typeMismatchErrorWithExpectedType:(NSString *)expected data:(id)data { + NSString * message = [NSString stringWithFormat:NSLocalizedString(@"Received response [%@] is not an object of type %@",nil),data, expected]; + NSDictionary * userInfo = @{NSLocalizedDescriptionKey : message}; + return [NSError errorWithDomain:{{classPrefix}}DeserializationErrorDomainKey code:{{classPrefix}}TypeMismatchErrorCode userInfo:userInfo]; +} + +-(NSError *)emptyValueOccurredError { + NSString * message = NSLocalizedString(@"Received response contains null value in dictionary or array response",nil); + NSDictionary * userInfo = @{NSLocalizedDescriptionKey : message}; + return [NSError errorWithDomain:{{classPrefix}}DeserializationErrorDomainKey code:{{classPrefix}}EmptyValueOccurredErrorCode userInfo:userInfo]; +} + +-(NSError *)unknownResponseErrorWithExpectedType:(NSString *)expected data:(id)data { + NSString * message = [NSString stringWithFormat:NSLocalizedString(@"Unknown response expected type %@ [reponse: %@]",nil),expected,data]; + NSDictionary * userInfo = @{NSLocalizedDescriptionKey : message}; + return [NSError errorWithDomain:{{classPrefix}}DeserializationErrorDomainKey code:{{classPrefix}}UnknownResponseObjectErrorCode userInfo:userInfo]; +} + +@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/ResponseDeserializer-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/ResponseDeserializer-header.mustache new file mode 100644 index 00000000000..90aa174d7c4 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/ResponseDeserializer-header.mustache @@ -0,0 +1,46 @@ +#import + +{{>licenceInfo}} + +/** + * A key for deserialization ErrorDomain + */ +extern NSString *const {{classPrefix}}DeserializationErrorDomainKey; + +/** + * Code for deserialization type mismatch error + */ +extern NSInteger const {{classPrefix}}TypeMismatchErrorCode; + +/** + * Code for deserialization empty value error + */ +extern NSInteger const {{classPrefix}}EmptyValueOccurredErrorCode; + +/** + * Error code for unknown response + */ +extern NSInteger const {{classPrefix}}UnknownResponseObjectErrorCode; + +@protocol {{classPrefix}}ResponseDeserializer + +/** + * Deserializes the given data to Objective-C object. + * + * @param data The data will be deserialized. + * @param class The type of objective-c object. + * @param error The error + */ +- (id) deserialize:(id) data class:(NSString *) className error:(NSError**)error; + +@end + +@interface {{classPrefix}}ResponseDeserializer : NSObject <{{classPrefix}}ResponseDeserializer> + +/** + * If an null value occurs in dictionary or array if set to YES whole response will be invalid else will be ignored + * @default NO + */ +@property (nonatomic, assign) BOOL treatNullAsError; + +@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/Sanitizer-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/Sanitizer-body.mustache new file mode 100644 index 00000000000..00d74aaa1f7 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/Sanitizer-body.mustache @@ -0,0 +1,168 @@ +#import "{{classPrefix}}Sanitizer.h" +#import "{{classPrefix}}Object.h" +#import "{{classPrefix}}QueryParamCollection.h" +#import + +NSString * {{classPrefix}}PercentEscapedStringFromString(NSString *string) { + static NSString * const k{{classPrefix}}CharactersGeneralDelimitersToEncode = @":#[]@"; + static NSString * const k{{classPrefix}}CharactersSubDelimitersToEncode = @"!$&'()*+,;="; + + NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy]; + [allowedCharacterSet removeCharactersInString:[k{{classPrefix}}CharactersGeneralDelimitersToEncode stringByAppendingString:k{{classPrefix}}CharactersSubDelimitersToEncode]]; + + static NSUInteger const batchSize = 50; + + NSUInteger index = 0; + NSMutableString *escaped = @"".mutableCopy; + + while (index < string.length) { + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wgnu" + NSUInteger length = MIN(string.length - index, batchSize); + #pragma GCC diagnostic pop + NSRange range = NSMakeRange(index, length); + + // To avoid breaking up character sequences such as 👴🏻👮🏽 + range = [string rangeOfComposedCharacterSequencesForRange:range]; + + NSString *substring = [string substringWithRange:range]; + NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet]; + [escaped appendString:encoded]; + + index += range.length; + } + + return escaped; +} + +@interface {{classPrefix}}Sanitizer () + +@property (nonatomic, strong) NSRegularExpression* jsonHeaderTypeExpression; + +@end + +@implementation {{classPrefix}}Sanitizer + +static NSString * kApplicationJSONType = @"application/json"; + +-(instancetype)init { + self = [super init]; + if ( !self ) { + return nil; + } + _jsonHeaderTypeExpression = [NSRegularExpression regularExpressionWithPattern:@"(.*)application(.*)json(.*)" options:NSRegularExpressionCaseInsensitive error:nil]; + return self; +} + + +- (id) sanitizeForSerialization:(id) object { + if (object == nil) { + return nil; + } + else if ([object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSNumber class]] || [object isKindOfClass:[{{classPrefix}}QueryParamCollection class]]) { + return object; + } + else if ([object isKindOfClass:[NSDate class]]) { + return [self dateParameterToString:object]; + } + else if ([object isKindOfClass:[NSArray class]]) { + NSArray *objectArray = object; + NSMutableArray *sanitizedObjs = [NSMutableArray arrayWithCapacity:[objectArray count]]; + [object enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + id sanitizedObj = [self sanitizeForSerialization:obj]; + if (sanitizedObj) { + [sanitizedObjs addObject:sanitizedObj]; + } + }]; + return sanitizedObjs; + } + else if ([object isKindOfClass:[NSDictionary class]]) { + NSDictionary *objectDict = object; + NSMutableDictionary *sanitizedObjs = [NSMutableDictionary dictionaryWithCapacity:[objectDict count]]; + [object enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + id sanitizedObj = [self sanitizeForSerialization:obj]; + if (sanitizedObj) { + sanitizedObjs[key] = sanitizedObj; + } + }]; + return sanitizedObjs; + } + else if ([object isKindOfClass:[{{classPrefix}}Object class]]) { + return [object toDictionary]; + } + else { + NSException *e = [NSException + exceptionWithName:@"InvalidObjectArgumentException" + reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", object] + userInfo:nil]; + @throw e; + } +} + +- (NSString *) parameterToString:(id)param { + if ([param isKindOfClass:[NSString class]]) { + return param; + } + else if ([param isKindOfClass:[NSNumber class]]) { + return [param stringValue]; + } + else if ([param isKindOfClass:[NSDate class]]) { + return [self dateParameterToString:param]; + } + else if ([param isKindOfClass:[NSArray class]]) { + NSMutableArray *mutableParam = [NSMutableArray array]; + [param enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + [mutableParam addObject:[self parameterToString:obj]]; + }]; + return [mutableParam componentsJoinedByString:@","]; + } + else { + NSException *e = [NSException + exceptionWithName:@"InvalidObjectArgumentException" + reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", param] + userInfo:nil]; + @throw e; + } +} + +- (NSString *)dateParameterToString:(id)param { + return [param ISO8601String]; +} + +#pragma mark - Utility Methods + +/* + * Detect `Accept` from accepts + */ +- (NSString *) selectHeaderAccept:(NSArray *)accepts { + if (accepts.count == 0) { + return @""; + } + NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]]; + for (NSString *string in accepts) { + if ([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0) { + return kApplicationJSONType; + } + [lowerAccepts addObject:[string lowercaseString]]; + } + return [lowerAccepts componentsJoinedByString:@", "]; +} + +/* + * Detect `Content-Type` from contentTypes + */ +- (NSString *) selectHeaderContentType:(NSArray *)contentTypes { + if (contentTypes.count == 0) { + return kApplicationJSONType; + } + NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]]; + for (NSString *string in contentTypes) { + if([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0){ + return kApplicationJSONType; + } + [lowerContentTypes addObject:[string lowercaseString]]; + } + return [lowerContentTypes firstObject]; +} + +@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/Sanitizer-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/Sanitizer-header.mustache new file mode 100644 index 00000000000..f975018a020 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/Sanitizer-header.mustache @@ -0,0 +1,45 @@ +#import + +{{>licenceInfo}} + +extern NSString * {{classPrefix}}PercentEscapedStringFromString(NSString *string); + +@protocol {{classPrefix}}Sanitizer + +/** + * Sanitize object for request + * + * @param object The query/path/header/form/body param to be sanitized. + */ +- (id) sanitizeForSerialization:(id) object; + +/** + * Convert parameter to NSString + */ +- (NSString *) parameterToString: (id) param; + +/** + * Detects Accept header from accepts NSArray + * + * @param accepts NSArray of header + * + * @return The Accept header + */ +-(NSString *) selectHeaderAccept:(NSArray *)accepts; + +/** + * Detects Content-Type header from contentTypes NSArray + * + * @param contentTypes NSArray of header + * + * @return The Content-Type header + */ +-(NSString *) selectHeaderContentType:(NSArray *)contentTypes; + +@end + +@interface {{classPrefix}}Sanitizer : NSObject <{{classPrefix}}Sanitizer> + + + +@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/api-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/api-body.mustache index 369046fe484..ff9b42d38d4 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/api-body.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/api-body.mustache @@ -7,19 +7,23 @@ @interface {{classname}} () -@property (nonatomic, strong, readwrite) {{classPrefix}}ApiSessionManager *sessionManager; @property (nonatomic, strong, readwrite) NSMutableDictionary *defaultHeaders; @end @implementation {{classname}} +NSString* k{{classname}}ErrorDomain = @"{{classname}}ErrorDomain"; +NSInteger k{{classname}}MissingParamErrorCode = 234513; + +@synthesize apiSessionManager = _apiSessionManager; + #pragma mark - Initialize methods -- (id)initWithSessionManager:({{classPrefix}}ApiSessionManager *)sessionManager { +-(instancetype) initWithApiSessionManager:({{classPrefix}}ApiSessionManager *)apiSessionManager { self = [super init]; if (self) { - _sessionManager = sessionManager; + _apiSessionManager = apiSessionManager; _defaultHeaders = [NSMutableDictionary dictionary]; } @@ -28,7 +32,15 @@ #pragma mark - -- (void)addHeader:(NSString *)value forKey:(NSString *)key { +-(NSString*) defaultHeaderForKey:(NSString*)key { + return self.defaultHeaders[key]; +} + +-(void) addHeader:(NSString*)value forKey:(NSString*)key { + [self setDefaultHeaderValue:value forKey:key]; +} + +-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key { [self.defaultHeaders setValue:value forKey:key]; } @@ -38,112 +50,107 @@ /// /// {{{summary}}} /// {{{notes}}} -/// {{#allParams}} @param {{paramName}} {{{description}}} +/// {{#allParams}} @param {{paramName}} {{{description}}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} /// /// {{/allParams}} @returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} /// -- (NSURLSessionTask *){{nickname}}WithCompletionBlock{{^allParams}}: {{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}} - {{/allParams}} - {{#returnBaseType}}{{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{{returnType}}} output, NSError* error))completionBlock { {{/returnBaseType}} - {{^returnBaseType}}{{#hasParams}}completionHandler: {{/hasParams}}(void (^)(NSError* error))completionBlock { {{/returnBaseType}} - - {{#allParams}}{{#required}} +-(NSURLSessionTask*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} + {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}} + {{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler { + {{#allParams}} + {{#required}} // verify the required parameter '{{paramName}}' is set if ({{paramName}} == nil) { - [NSException raise:@"Invalid parameter" format:@"Missing the required parameter `{{paramName}}` when calling `{{nickname}}`"]; + NSParameterAssert({{paramName}}); + if(handler) { + NSDictionary * userInfo = @{NSLocalizedDescriptionKey : [NSString stringWithFormat:NSLocalizedString(@"Missing required parameter '%@'", nil),@"{{paramName}}"] }; + NSError* error = [NSError errorWithDomain:k{{classname}}ErrorDomain code:k{{classname}}MissingParamErrorCode userInfo:userInfo]; + handler({{#returnType}}nil, {{/returnType}}error); + } + return nil; } - {{/required}}{{/allParams}} + {{/required}} + {{/allParams}} NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"{{path}}"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; - {{#pathParams}}if ({{paramName}} != nil) { + {{#pathParams}} + if ({{paramName}} != nil) { pathParams[@"{{baseName}}"] = {{paramName}}; } {{/pathParams}} NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - {{#queryParams}}if ({{paramName}} != nil) { + {{#queryParams}} + if ({{paramName}} != nil) { {{#collectionFormat}} - queryParams[@"{{baseName}}"] = [[{{classPrefix}}QueryParamCollection alloc] initWithValuesAndFormat: {{baseName}} format: @"{{collectionFormat}}"]; + queryParams[@"{{baseName}}"] = [[{{classPrefix}}QueryParamCollection alloc] initWithValuesAndFormat: {{paramName}} format: @"{{collectionFormat}}"]; {{/collectionFormat}} {{^collectionFormat}}queryParams[@"{{baseName}}"] = {{paramName}};{{/collectionFormat}} } {{/queryParams}} - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - - {{#headerParams}}if ({{paramName}} != nil) { + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiSessionManager.configuration.defaultHeaders]; + [headerParams addEntriesFromDictionary:self.defaultHeaders]; + {{#headerParams}} + if ({{paramName}} != nil) { headerParams[@"{{baseName}}"] = {{paramName}}; } {{/headerParams}} - // HTTP header `Accept` - headerParams[@"Accept"] = [{{classPrefix}}ApiSessionManager selectHeaderAccept:@[{{#produces}}@"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}}]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiSessionManager.sanitizer selectHeaderAccept:@[{{#produces}}@"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}}]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [{{classPrefix}}ApiSessionManager selectHeaderContentType:@[{{#consumes}}@"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}]]; + NSString *requestContentType = [self.apiSessionManager.sanitizer selectHeaderContentType:@[{{#consumes}}@"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}]]; // Authentication setting NSArray *authSettings = @[{{#authMethods}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary *files = [[NSMutableDictionary alloc] init]; + NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; {{#bodyParam}} bodyParam = {{paramName}}; - {{/bodyParam}}{{^bodyParam}} + {{/bodyParam}} + {{^bodyParam}} {{#formParams}} {{#notFile}} if ({{paramName}}) { formParams[@"{{baseName}}"] = {{paramName}}; } - {{/notFile}}{{#isFile}} - files[@"{{paramName}}"] = {{paramName}}; + {{/notFile}} + {{#isFile}} + localVarFiles[@"{{paramName}}"] = {{paramName}}; {{/isFile}} {{/formParams}} {{/bodyParam}} - {{#requiredParamCount}} - {{#requiredParams}} - if ({{paramName}} == nil) { - // error - } - {{/requiredParams}} - {{/requiredParamCount}} - return [self.sessionManager requestWithCompletionBlock: resourcePath - method: @"{{httpMethod}}" - pathParams: pathParams - queryParams: queryParams - formParams: formParams - files: files - body: bodyParam - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - responseType: {{^returnType}}nil{{/returnType}}{{#returnType}}@"{{{ returnType }}}"{{/returnType}} - completionBlock: ^(id data, NSError *error) { - {{^returnType}}completionBlock(error);{{/returnType}} - {{#returnType}}completionBlock(({{{ returnType }}})data, error);{{/returnType}} - } - ]; + return [self.apiSessionManager requestWithPath: resourcePath + method: @"{{httpMethod}}" + pathParams: pathParams + queryParams: queryParams + formParams: formParams + files: localVarFiles + body: bodyParam + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + responseType: {{^returnType}}nil{{/returnType}}{{#returnType}}@"{{{ returnType }}}"{{/returnType}} + completionBlock: ^(id data, NSError *error) { + if(handler) { + handler({{#returnType}}({{{ returnType }}})data, {{/returnType}}error); + } + }]; } {{/operation}} diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/api-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/api-header.mustache index d20008561d4..12fe8c7b954 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/api-header.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/api-header.mustache @@ -1,42 +1,32 @@ #import {{#imports}}#import "{{import}}.h" {{/imports}} -#import "{{classPrefix}}ApiSessionManager.h" -{{newline}} +#import "{{classPrefix}}Api.h" -/** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ +{{>licenceInfo}} -{{#operations}} -@interface {{classname}}: NSObject -@property (nonatomic, strong, readonly) {{classPrefix}}ApiSessionManager *sessionManager; +@interface {{classname}}: NSObject <{{classPrefix}}Api> -- (instancetype)initWithSessionManager:({{classPrefix}}ApiSessionManager *)sessionManager; -- (void)addHeader:(NSString *)value forKey:(NSString *)key; +extern NSString* k{{classname}}ErrorDomain; +extern NSInteger k{{classname}}MissingParamErrorCode; +{{#operations}} {{#operation}} -/// -/// /// {{{summary}}} /// {{#notes}}{{{notes}}}{{/notes}} /// -/// {{#allParams}}@param {{paramName}} {{description}} -/// {{/allParams}} +/// {{#allParams}}@param {{paramName}} {{description}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} +/// {{/allParams}}{{#responses}} +/// code:{{{code}}} message:"{{{message}}}"{{#hasMore}},{{/hasMore}}{{/responses}} /// /// @return {{{returnType}}} -- (NSURLSessionTask *){{nickname}}WithCompletionBlock {{^allParams}}:{{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}:({{{dataType}}}){{paramName}} {{#hasMore}} -{{/hasMore}}{{/allParams}} - {{#returnBaseType}}{{#hasParams}} - completionHandler:{{/hasParams}}(void (^)({{{returnType}}} output, NSError *error))completionBlock;{{/returnBaseType}} - {{^returnBaseType}}{{#hasParams}} - completionHandler: {{/hasParams}}(void (^)(NSError * error))completionBlock;{{/returnBaseType}} +-(NSURLSessionTask*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} + {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}} + {{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler; {{newline}} {{/operation}} - {{/operations}} + @end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/api-protocol.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/api-protocol.mustache new file mode 100644 index 00000000000..79c9da59ce4 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/api-protocol.mustache @@ -0,0 +1,18 @@ +#import +#import "{{classPrefix}}Object.h" +#import "{{classPrefix}}ApiSessionManager.h" + +{{>licenceInfo}} + +@protocol {{classPrefix}}Api + +@property(readonly, nonatomic, strong) {{classPrefix}}ApiSessionManager *apiSessionManager; + +-(instancetype) initWithApiSessionManager:({{classPrefix}}ApiSessionManager *)apiSessionManager; + +-(void) addHeader:(NSString*)value forKey:(NSString*)key DEPRECATED_MSG_ATTRIBUTE("setDefaultHeaderValue:forKey:"); + +-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key; +-(NSString*) defaultHeaderForKey:(NSString*)key; + +@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/api_doc.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/api_doc.mustache new file mode 100644 index 00000000000..44fe31d6404 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/api_doc.mustache @@ -0,0 +1,85 @@ +# {{classname}}{{#description}} +{{description}}{{/description}} + +All URIs are relative to *{{basePath}}* + +Method | HTTP request | Description +------------- | ------------- | ------------- +{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}} + +{{#operations}} +{{#operation}} +# **{{{operationId}}}** +```objc +-(NSNumber*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} + {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}} + {{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler; +``` + +{{{summary}}}{{#notes}} + +{{{notes}}}{{/notes}} + +### Example +```objc +{{#hasAuthMethods}} +{{classPrefix}}Configuration *apiConfig = [{{classPrefix}}Configuration sharedConfig]; +{{#authMethods}}{{#isBasic}}// Configure HTTP basic authorization (authentication scheme: {{{name}}}) +[apiConfig setUsername:@"YOUR_USERNAME"]; +[apiConfig setPassword:@"YOUR_PASSWORD"]; +{{/isBasic}}{{#isApiKey}} +// Configure API key authorization: (authentication scheme: {{{name}}}) +[apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"{{{keyParamName}}}"]; +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +//[apiConfig setApiKeyPrefix:@"Bearer" forApiKeyIdentifier:@"{{{keyParamName}}}"]; +{{/isApiKey}}{{#isOAuth}} +// Configure OAuth2 access token for authorization: (authentication scheme: {{{name}}}) +[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; +{{/isOAuth}}{{/authMethods}} +{{/hasAuthMethods}} + +{{#allParams}}{{{dataType}}} {{paramName}} = {{{example}}}; // {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} +{{/allParams}} + +{{classname}}*apiInstance = [[{{classname}} alloc] init]; + +{{#summary}}// {{{.}}} +{{/summary}}[apiInstance {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} + {{paramName}}{{/secondaryParam}}:{{paramName}}{{/allParams}} + {{#hasParams}}completionHandler: {{/hasParams}}^({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error) { +{{#returnType}} + if (output) { + NSLog(@"%@", output); + } +{{/returnType}} + if (error) { + NSLog(@"Error calling {{classname}}->{{operationId}}: %@", error); + } + }]; +``` + +### Parameters +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} +Name | Type | Description | Notes +------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} +{{#allParams}} **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} +{{/allParams}} + +### Return type + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void (empty response body){{/returnType}} + +### Authorization + +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{{name}}}](../README.md#{{{name}}}){{^-last}}, {{/-last}}{{/authMethods}} + +### HTTP request headers + + - **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} + - **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +{{/operation}} +{{/operations}} diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/git_push.sh.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/git_push.sh.mustache new file mode 100644 index 00000000000..e153ce23ecf --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/git_push.sh.mustache @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/gitignore.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/gitignore.mustache new file mode 100644 index 00000000000..79d9331b6d4 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/gitignore.mustache @@ -0,0 +1,53 @@ +# Xcode +# +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + +## Build generated +build/ +DerivedData + +## Various settings +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 +xcuserdata + +## Other +*.xccheckout +*.moved-aside +*.xcuserstate +*.xcscmblueprint + +## Obj-C/Swift specific +*.hmap +*.ipa + +# CocoaPods +# +# We recommend against adding the Pods directory to your .gitignore. However +# you should judge for yourself, the pros and cons are mentioned at: +# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control +# +# Pods/ + +# Carthage +# +# Add this line if you want to avoid checking in source code from Carthage dependencies. +# Carthage/Checkouts + +Carthage/Build + +# fastlane +# +# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the +# screenshots whenever they are needed. +# For more information about the recommended setup visit: +# https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md + +fastlane/report.xml +fastlane/screenshots diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/licenceInfo.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/licenceInfo.mustache new file mode 100644 index 00000000000..2f0f1940e89 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/licenceInfo.mustache @@ -0,0 +1,23 @@ +/** +* {{{appName}}} +* {{{appDescription}}} +* +* {{#version}}OpenAPI spec version: {{{version}}}{{/version}} +* {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} +* +* NOTE: This class is auto generated by the swagger code generator program. +* https://github.com/swagger-api/swagger-codegen.git +* Do not edit the class manually. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ \ No newline at end of file diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/model-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/model-body.mustache index 3d70cebfae2..2a4a548458e 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/model-body.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/model-body.mustache @@ -6,22 +6,40 @@ - (instancetype)init { self = [super init]; - if (self) { - // initalise property's default value, if any + // initialize property's default value, if any {{#vars}}{{#defaultValue}}self.{{name}} = {{{defaultValue}}}; {{/defaultValue}}{{/vars}} } - return self; } +{{#vars}}{{^vendorExtensions.x-unique-id-key}}{{/vendorExtensions.x-unique-id-key}}{{#vendorExtensions.x-unique-id-key}} +-(NSString*)indexPropertyName { + return @"{{name}}"; +} +{{/vendorExtensions.x-unique-id-key}}{{/vars}} +{{#discriminator}} +/** + * Maps "discriminator" value to the sub-class name, so that inheritance is supported. + */ +- (id)initWithDictionary:(NSDictionary *)dict error:(NSError *__autoreleasing *)err { + NSString * discriminatedClassName = [dict valueForKey:@"{{discriminator}}"]; + if(discriminatedClassName == nil ){ + return [super initWithDictionary:dict error:err]; + } + Class class = NSClassFromString([@"{{classPrefix}}" stringByAppendingString:discriminatedClassName]); + if([self class ] == class) { + return [super initWithDictionary:dict error:err]; + } + return [[class alloc] initWithDictionary:dict error: err]; +} +{{/discriminator}} /** * Maps json key to property name. * This method is used by `JSONModel`. */ -+ (JSONKeyMapper *)keyMapper -{ ++ (JSONKeyMapper *)keyMapper { return [[JSONKeyMapper alloc] initWithDictionary:@{ {{#vars}}@"{{baseName}}": @"{{name}}"{{#hasMore}}, {{/hasMore}}{{/vars}} }]; } @@ -30,24 +48,10 @@ * If `propertyName` is optional, then return `YES`, otherwise return `NO`. * This method is used by `JSONModel`. */ -+ (BOOL)propertyIsOptional:(NSString *)propertyName -{ - NSArray *optionalProperties = @[{{#vars}}{{^required}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/required}}{{/vars}}]; ++ (BOOL)propertyIsOptional:(NSString *)propertyName { - if ([optionalProperties containsObject:propertyName]) { - return YES; - } - else { - return NO; - } -} - -/** - * Gets the string presentation of the object. - * This method will be called when logging model object using `NSLog`. - */ -- (NSString *)description { - return [[self toDictionary] description]; + NSArray *optionalProperties = @[{{#vars}}{{^required}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/required}}{{/vars}}]; + return [optionalProperties containsObject:propertyName]; } {{/model}} diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/model-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/model-header.mustache index f9a33042491..04570e71a2f 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/model-header.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/model-header.mustache @@ -1,11 +1,7 @@ #import #import "{{classPrefix}}Object.h" -/** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ +{{>licenceInfo}} {{#imports}}#import "{{import}}.h" {{/imports}} diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/model_doc.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/model_doc.mustache new file mode 100644 index 00000000000..569550df372 --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/model_doc.mustache @@ -0,0 +1,11 @@ +{{#models}}{{#model}}# {{classname}} + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{datatype}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{datatype}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#readOnly}}[readonly] {{/readOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}} +{{/vars}} + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + +{{/model}}{{/models}} diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/podspec.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/podspec.mustache index 338ded84e89..bd0bd9f328e 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/podspec.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/podspec.mustache @@ -13,24 +13,25 @@ Pod::Spec.new do |s| {{#apiInfo}}{{#apis}}{{^hasMore}} s.summary = "{{appName}}" s.description = <<-DESC - {{appDescription}} + {{{appDescription}}} DESC {{/hasMore}}{{/apis}}{{/apiInfo}} s.platform = :ios, '7.0' s.requires_arc = true - s.framework = 'SystemConfiguration' - + {{^useCoreData}}s.framework = 'SystemConfiguration'{{/useCoreData}}{{#useCoreData}}s.frameworks = 'SystemConfiguration', 'CoreData'{{/useCoreData}} + s.homepage = "{{gitRepoURL}}" - s.license = "{{license}}" + s.license = "{{#license}}{{license}}{{/license}}{{^license}}Apache License, Version 2.0{{/license}}" s.source = { :git => "{{gitRepoURL}}.git", :tag => "#{s.version}" } s.author = { "{{authorName}}" => "{{authorEmail}}" } - s.source_files = '{{podName}}/**/*' + s.source_files = '{{podName}}/**/*.{m,h}' s.public_header_files = '{{podName}}/**/*.h' +{{#useCoreData}} s.resources = '{{podName}}/**/*.{xcdatamodeld,xcdatamodel}'{{/useCoreData}} - s.dependency 'AFNetworking', '~> 2.3' - s.dependency 'JSONModel', '~> 1.1' - s.dependency 'ISO8601', '~> 0.3' + s.dependency 'AFNetworking', '~> 3' + s.dependency 'JSONModel', '~> 1.2' + s.dependency 'ISO8601', '~> 0.5' end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/xccurrentversion.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/xccurrentversion.mustache new file mode 100644 index 00000000000..528b389e3ef --- /dev/null +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/xccurrentversion.mustache @@ -0,0 +1,8 @@ + + + + + _XCCurrentVersionName + {{classPrefix}}Model.xcdatamodel + + diff --git a/output/objcSessionManager_notasold/README.md b/output/objcSessionManager_notasold/README.md new file mode 100644 index 00000000000..40c3ef4fd44 --- /dev/null +++ b/output/objcSessionManager_notasold/README.md @@ -0,0 +1,74 @@ +# Swagger Codegen for the ObjcSessionManagerClientCodegen library + +## Overview +This is a boiler-plate project to generate your own client library with Swagger. It's goal is +to get you started with the basic plumbing so you can put in your own logic. It won't work without +your changes applied. + +## What's Swagger? +The goal of Swagger™ is to define a standard, language-agnostic interface to REST APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined via Swagger, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. Similar to what interfaces have done for lower-level programming, Swagger removes the guesswork in calling the service. + + +Check out [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) for additional information about the Swagger project, including additional libraries with support for other languages and more. + +## How do I use this? +At this point, you've likely generated a client setup. It will include something along these lines: + +``` +. +|- README.md // this file +|- pom.xml // build script +|-- src +|--- main +|---- java +|----- io.swagger.codegen.languages.ObjcsessionmanagerclientcodegenGenerator.java // generator file +|---- resources +|----- ObjcSessionManagerClientCodegen // template files +|----- META-INF +|------ services +|------- io.swagger.codegen.CodegenConfig +``` + +You _will_ need to make changes in at least the following: + +`ObjcsessionmanagerclientcodegenGenerator.java` + +Templates in this folder: + +`src/main/resources/ObjcSessionManagerClientCodegen` + +Once modified, you can run this: + +``` +mvn package +``` + +In your generator project. A single jar file will be produced in `target`. You can now use that with codegen: + +``` +java -cp /path/to/swagger-codegen-distribution:/path/to/your/jar io.swagger.codegen.Codegen -l ObjcSessionManagerClientCodegen -o ./test +``` + +Now your templates are available to the client generator and you can write output values + +## But how do I modify this? +The `ObjcsessionmanagerclientcodegenGenerator.java` has comments in it--lots of comments. There is no good substitute +for reading the code more, though. See how the `ObjcsessionmanagerclientcodegenGenerator` implements `CodegenConfig`. +That class has the signature of all values that can be overridden. + +For the templates themselves, you have a number of values available to you for generation. +You can execute the `java` command from above while passing different debug flags to show +the object you have available during client generation: + +``` +# The following additional debug options are available for all codegen targets: +# -DdebugSwagger prints the OpenAPI Specification as interpreted by the codegen +# -DdebugModels prints models passed to the template engine +# -DdebugOperations prints operations passed to the template engine +# -DdebugSupportingFiles prints additional data passed to the template engine + +java -DdebugOperations -cp /path/to/swagger-codegen-distribution:/path/to/your/jar io.swagger.codegen.Codegen -l ObjcSessionManagerClientCodegen -o ./test +``` + +Will, for example, output the debug info for operations. You can use this info +in the `api.mustache` file. \ No newline at end of file diff --git a/output/objcSessionManager_notasold/pom.xml b/output/objcSessionManager_notasold/pom.xml new file mode 100644 index 00000000000..ddbd6e88190 --- /dev/null +++ b/output/objcSessionManager_notasold/pom.xml @@ -0,0 +1,102 @@ + + 4.0.0 + io.swagger + ObjcSessionManager-swagger-codegen + jar + ObjcSessionManager-swagger-codegen + 1.0.0 + + 2.2.0 + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + + + 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-codegen + ${swagger-codegen-version} + provided + + + + 2.2.0-SNAPSHOT + 1.0.0 + 4.8.1 + + diff --git a/output/objcSessionManager_notasold/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerClientCodegen.java b/output/objcSessionManager_notasold/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerClientCodegen.java new file mode 100644 index 00000000000..4fd59986fb7 --- /dev/null +++ b/output/objcSessionManager_notasold/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerClientCodegen.java @@ -0,0 +1,750 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.ArrayModel; +import io.swagger.models.Model; +import io.swagger.models.properties.*; + +import java.io.File; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.lang3.StringUtils; + +public class ObjcSessionManagerClientCodegen extends DefaultCodegen implements CodegenConfig { + public static final String CLASS_PREFIX = "classPrefix"; + public static final String POD_NAME = "podName"; + public static final String AUTHOR_NAME = "authorName"; + public static final String AUTHOR_EMAIL = "authorEmail"; + public static final String LICENSE = "license"; + public static final String GIT_REPO_URL = "gitRepoURL"; + public static final String DEFAULT_LICENSE = "Apache License, Version 2.0"; + public static final String CORE_DATA = "coreData"; + + protected Set foundationClasses = new HashSet(); + protected String podName = "SwaggerClient"; + protected String podVersion = "1.0.0"; + protected String classPrefix = "SWG"; + protected String authorName = "Swagger"; + protected String authorEmail = "apiteam@swagger.io"; + protected String license = DEFAULT_LICENSE; + protected String gitRepoURL = "https://github.com/swagger-api/swagger-codegen"; + protected String[] specialWords = {"new", "copy"}; + protected String apiDocPath = "docs/"; + protected String modelDocPath = "docs/"; + protected String modelFilesPath = "Model/"; + protected String coreFilesPath = "Core/"; + protected String apiFilesPath = "Api/"; + + protected boolean generateCoreData = false; + + protected Set advancedMapingTypes = new HashSet(); + + public ObjcSessionManagerClientCodegen() { + super(); + + outputFolder = "generated-code" + File.separator + "objcSessionManager"; + modelTemplateFiles.put("model-header.mustache", ".h"); + modelTemplateFiles.put("model-body.mustache", ".m"); + apiTemplateFiles.put("api-header.mustache", ".h"); + apiTemplateFiles.put("api-body.mustache", ".m"); + embeddedTemplateDir = templateDir = "objcSessionManager"; + modelDocTemplateFiles.put("model_doc.mustache", ".md"); + apiDocTemplateFiles.put("api_doc.mustache", ".md"); + + defaultIncludes.clear(); + defaultIncludes.add("bool"); + defaultIncludes.add("BOOL"); + defaultIncludes.add("int"); + defaultIncludes.add("NSURL"); + defaultIncludes.add("NSString"); + defaultIncludes.add("NSObject"); + defaultIncludes.add("NSArray"); + defaultIncludes.add("NSNumber"); + defaultIncludes.add("NSDate"); + defaultIncludes.add("NSDictionary"); + defaultIncludes.add("NSMutableArray"); + defaultIncludes.add("NSMutableDictionary"); + defaultIncludes.add("NSManagedObject"); + defaultIncludes.add("NSData"); + + advancedMapingTypes.add("NSDictionary"); + advancedMapingTypes.add("NSArray"); + advancedMapingTypes.add("NSMutableArray"); + advancedMapingTypes.add("NSMutableDictionary"); + advancedMapingTypes.add("NSObject"); + advancedMapingTypes.add("NSNumber"); + advancedMapingTypes.add("NSURL"); + advancedMapingTypes.add("NSString"); + advancedMapingTypes.add("NSDate"); + + languageSpecificPrimitives.clear(); + languageSpecificPrimitives.add("NSNumber"); + languageSpecificPrimitives.add("NSString"); + languageSpecificPrimitives.add("NSObject"); + languageSpecificPrimitives.add("NSDate"); + languageSpecificPrimitives.add("NSData"); + languageSpecificPrimitives.add("NSURL"); + languageSpecificPrimitives.add("bool"); + languageSpecificPrimitives.add("BOOL"); + + typeMapping.clear(); + typeMapping.put("enum", "NSString"); + typeMapping.put("date", "NSDate"); + typeMapping.put("datetime", "NSDate"); + typeMapping.put("boolean", "NSNumber"); + typeMapping.put("string", "NSString"); + typeMapping.put("integer", "NSNumber"); + typeMapping.put("int", "NSNumber"); + typeMapping.put("float", "NSNumber"); + typeMapping.put("long", "NSNumber"); + typeMapping.put("double", "NSNumber"); + typeMapping.put("array", "NSArray"); + typeMapping.put("map", "NSDictionary"); + typeMapping.put("number", "NSNumber"); + typeMapping.put("bigdecimal", "NSNumber"); + typeMapping.put("List", "NSArray"); + typeMapping.put("object", "NSObject"); + typeMapping.put("file", "NSURL"); + typeMapping.put("binary", "NSData"); + typeMapping.put("bytearray", "NSData"); + typeMapping.put("byte", "NSData"); + typeMapping.put("uuid", "NSString"); + typeMapping.put("password", "NSString"); + + // ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm + setReservedWordsLowerCase( + Arrays.asList( + // local variable names in API methods (endpoints) + "resourcePath", "pathParams", "queryParams", "headerParams", + "responseContentType", "requestContentType", "authSettings", + "formParams", "localVarFiles", "bodyParam", + // objc reserved words + "auto", "else", "long", "switch", + "break", "enum", "register", "typedef", + "case", "extern", "return", "union", + "char", "float", "short", "unsigned", + "const", "for", "signed", "void", + "continue", "goto", "sizeof", "volatile", + "default", "if", "id", "static", "while", + "do", "int", "struct", "_Packed", + "double", "protocol", "interface", "implementation", + "NSObject", "NSInteger", "NSNumber", "CGFloat", + "property", "nonatomic", "retain", "strong", + "weak", "unsafe_unretained", "readwrite", "readonly", + "description" + )); + + importMapping = new HashMap(); + + foundationClasses = new HashSet( + Arrays.asList( + "NSNumber", + "NSObject", + "NSString", + "NSDate", + "NSData", + "NSURL", + "NSDictionary") + ); + + instantiationTypes.put("array", "NSMutableArray"); + instantiationTypes.put("map", "NSMutableDictionary"); + + cliOptions.clear(); + cliOptions.add(new CliOption(CORE_DATA, "Should generate core data models").defaultValue("false")); + cliOptions.add(new CliOption(CLASS_PREFIX, "prefix for generated classes (convention: Abbreviation of pod name e.g. `HN` for `HackerNews`).`") + .defaultValue("SWG")); + cliOptions.add(new CliOption(POD_NAME, "cocoapods package name (convention: CameCase).") + .defaultValue("SwaggerClient")); + cliOptions.add(new CliOption(CodegenConstants.POD_VERSION, "cocoapods package version.") + .defaultValue("1.0.0")); + cliOptions.add(new CliOption(AUTHOR_NAME, "Name to use in the podspec file.").defaultValue("Swagger")); + cliOptions.add(new CliOption(AUTHOR_EMAIL, "Email to use in the podspec file.").defaultValue("apiteam@swagger.io")); + cliOptions.add(new CliOption(GIT_REPO_URL, "URL for the git repo where this podspec should point to.") + .defaultValue("https://github.com/swagger-api/swagger-codegen")); + } + + @Override + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + @Override + public String getName() { + return "objc"; + } + + @Override + public String getHelp() { + return "Generates an Objective-C client library."; + } + + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey(POD_NAME)) { + setPodName((String) additionalProperties.get(POD_NAME)); + } + + if (additionalProperties.containsKey(CodegenConstants.POD_VERSION)) { + setPodVersion((String) additionalProperties.get(CodegenConstants.POD_VERSION)); + } + + if (additionalProperties.containsKey(CORE_DATA)) { + Object coreData = additionalProperties.get(CORE_DATA); + if(((String)coreData).equalsIgnoreCase("true")) { + generateCoreData = true; + } + } + if (additionalProperties.containsKey(CLASS_PREFIX)) { + setClassPrefix((String) additionalProperties.get(CLASS_PREFIX)); + } + + if (additionalProperties.containsKey(AUTHOR_NAME)) { + setAuthorName((String) additionalProperties.get(AUTHOR_NAME)); + } + + if (additionalProperties.containsKey(AUTHOR_EMAIL)) { + setAuthorEmail((String) additionalProperties.get(AUTHOR_EMAIL)); + } + + if (additionalProperties.containsKey(GIT_REPO_URL)) { + setGitRepoURL((String) additionalProperties.get(GIT_REPO_URL)); + } + + if(generateCoreData) { + modelTemplateFiles.put("NSManagedObject-header.mustache", "ManagedObject.h"); + modelTemplateFiles.put("NSManagedObject-body.mustache", "ManagedObject.m"); + modelTemplateFiles.put("NSManagedObjectBuilder-header.mustache", "ManagedObjectBuilder.h"); + modelTemplateFiles.put("NSManagedObjectBuilder-body.mustache", "ManagedObjectBuilder.m"); + } + + additionalProperties.put(POD_NAME, podName); + additionalProperties.put(CodegenConstants.POD_VERSION, podVersion); + additionalProperties.put(CLASS_PREFIX, classPrefix); + additionalProperties.put(AUTHOR_NAME, authorName); + additionalProperties.put(AUTHOR_EMAIL, authorEmail); + additionalProperties.put(GIT_REPO_URL, gitRepoURL); + additionalProperties.put(LICENSE, license); + + // make api and model doc path available in mustache template + additionalProperties.put("apiDocPath", apiDocPath); + additionalProperties.put("modelDocPath", modelDocPath); + additionalProperties.put("useCoreData", generateCoreData); + + modelPackage = podName; + apiPackage = podName; + + supportingFiles.add(new SupportingFile("Object-header.mustache", coreFileFolder(), classPrefix + "Object.h")); + supportingFiles.add(new SupportingFile("Object-body.mustache", coreFileFolder(), classPrefix + "Object.m")); + supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.h")); + supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.m")); + supportingFiles.add(new SupportingFile("ApiClient-header.mustache", coreFileFolder(), classPrefix + "ApiClient.h")); // !! + supportingFiles.add(new SupportingFile("ApiClient-body.mustache", coreFileFolder(), classPrefix + "ApiClient.m")); // !! + supportingFiles.add(new SupportingFile("JSONResponseSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.h")); + supportingFiles.add(new SupportingFile("JSONResponseSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.m")); + supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.m")); + supportingFiles.add(new SupportingFile("JSONRequestSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.h")); + supportingFiles.add(new SupportingFile("ResponseDeserializer-body.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.m")); // !! + supportingFiles.add(new SupportingFile("ResponseDeserializer-header.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.h")); // !! + supportingFiles.add(new SupportingFile("Sanitizer-body.mustache", coreFileFolder(), classPrefix + "Sanitizer.m")); // !! + supportingFiles.add(new SupportingFile("Sanitizer-header.mustache", coreFileFolder(), classPrefix + "Sanitizer.h")); // !! + supportingFiles.add(new SupportingFile("Logger-body.mustache", coreFileFolder(), classPrefix + "Logger.m")); // !! + supportingFiles.add(new SupportingFile("Logger-header.mustache", coreFileFolder(), classPrefix + "Logger.h")); // !! + supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-body.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.m")); + supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-header.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.h")); + supportingFiles.add(new SupportingFile("Configuration-body.mustache", coreFileFolder(), classPrefix + "Configuration.m")); // !! + supportingFiles.add(new SupportingFile("Configuration-header.mustache", coreFileFolder(), classPrefix + "Configuration.h")); // !! + supportingFiles.add(new SupportingFile("api-protocol.mustache", coreFileFolder(), classPrefix + "Api.h")); // !! + supportingFiles.add(new SupportingFile("podspec.mustache", "", podName + ".podspec")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); // !! + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); // !! + + if(generateCoreData) { + supportingFiles.add(new SupportingFile("xccurrentversion.mustache", (modelPackage() + "/" + modelFilesPath + "/").replace("/", File.separator) + classPrefix + "Model.xcdatamodeld", ".xccurrentversion")); + supportingFiles.add(new SupportingFile("Model.xcdatamodel.mustache",(modelPackage() + "/" + modelFilesPath + "/").replace("/", File.separator) + classPrefix + "Model.xcdatamodeld" + File.separator + classPrefix + "Model.xcdatamodel", "contents")); + } + + // is apiclient + //supportingFiles.add(new SupportingFile("ApiSessionManager-header.mustache", swaggerFolder, classPrefix + "ApiSessionManager.h")); + //supportingFiles.add(new SupportingFile("ApiSessionManager-body.mustache", swaggerFolder, classPrefix + "ApiSessionManager.m")); + + // protocol! + //supportingFiles.add(new SupportingFile("Configuration-protocol.mustache", swaggerFolder, classPrefix + "Configuration.h")); + //supportingFiles.add(new SupportingFile("DefaultConfiguration-body.mustache", swaggerFolder, classPrefix + "DefaultConfiguration.m")); + //supportingFiles.add(new SupportingFile("DefaultConfiguration-header.mustache", swaggerFolder, classPrefix + "DefaultConfiguration.h")); + + // missing! + //supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-header.mustache", swaggerFolder, classPrefix + "BasicAuthTokenProvider.h")); + //supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-body.mustache", swaggerFolder, classPrefix + "BasicAuthTokenProvider.m")); + } + + @Override + public String toInstantiationType(Property p) { + if (p instanceof MapProperty) { + return instantiationTypes.get("map"); + } else if (p instanceof ArrayProperty) { + return instantiationTypes.get("array"); + } else { + return null; + } + } + + @Override + public String getTypeDeclaration(String name) { + if (languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name)) { + return name; + } else { + return name + "*"; + } + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType.toLowerCase())) { + type = typeMapping.get(swaggerType.toLowerCase()); + if (languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type)) { + return toModelNameWithoutReservedWordCheck(type); + } + } else { + type = swaggerType; + } + return toModelNameWithoutReservedWordCheck(type); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + String innerTypeDeclaration = getTypeDeclaration(inner); + if (innerTypeDeclaration.endsWith("*")) { + innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); + } + // In this condition, type of property p is array of primitive, + // return container type with pointer, e.g. `NSArray**' + if (languageSpecificPrimitives.contains(innerTypeDeclaration)) { + return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*"; + } + // In this condition, type of property p is array of model, + // return container type combine inner type with pointer, e.g. `NSArray*' + else { + for (String sd : advancedMapingTypes) { + if(innerTypeDeclaration.startsWith(sd)) { + return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*"; + } + } + return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*"; + } + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + String innerTypeDeclaration = getTypeDeclaration(inner); + + if (innerTypeDeclaration.endsWith("*")) { + innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); + } + if (languageSpecificPrimitives.contains(innerTypeDeclaration)) { + return getSwaggerType(p) + "*"; + } else { + for (String s : advancedMapingTypes) { + if(innerTypeDeclaration.startsWith(s)) { + return getSwaggerType(p) + "*"; + } + } + return getSwaggerType(p) + "*"; + } + } else { + String swaggerType = getSwaggerType(p); + // In this condition, type of p is objective-c primitive type, e.g. `NSSNumber', + // return type of p with pointer, e.g. `NSNumber*' + if (languageSpecificPrimitives.contains(swaggerType) && + foundationClasses.contains(swaggerType)) { + return swaggerType + "*"; + } + // In this condition, type of p is c primitive type, e.g. `bool', + // return type of p, e.g. `bool' + else if (languageSpecificPrimitives.contains(swaggerType)) { + return swaggerType; + } + // In this condition, type of p is objective-c object type, e.g. `SWGPet', + // return type of p with pointer, e.g. `SWGPet*' + else { + return swaggerType + "*"; + } + } + } + + @Override + public boolean isDataTypeBinary(String dataType) { + return dataType.toLowerCase().startsWith("nsdata"); + } + + @Override + public String toModelName(String type) { + // model name cannot use reserved keyword + if (reservedWords.contains(type)) { + LOGGER.warn(type+ " (reserved word) cannot be used as model name. Renamed to " + ("model_" + type) + " before further processing"); + type = "model_" + type; // e.g. return => ModelReturn (after camelize) + } + + // model name starts with number + /* no need for the fix below as objc model starts with prefix (e.g. SWG) + if (type.matches("^\\d.*")) { + LOGGER.warn(type + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + type)); + type = "model_" + type; // e.g. 200Response => Model200Response (after camelize) + } + */ + + return toModelNameWithoutReservedWordCheck(type); + } + + /* + * Convert input to proper model name according to ObjC style guide + * without checking for reserved words + * + * @param type Model anme + * @return model Name in ObjC style guide + */ + public String toModelNameWithoutReservedWordCheck(String type) { + type = type.replaceAll("[^0-9a-zA-Z_]", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + + // language build-in classes + if (typeMapping.keySet().contains(type) || + foundationClasses.contains(type) || + importMapping.values().contains(type) || + defaultIncludes.contains(type) || + languageSpecificPrimitives.contains(type)) { + return camelize(type); + } + // custom classes + else { + if (!StringUtils.isEmpty(modelNameSuffix)) { // set model suffix + type = type + "_" + modelNameSuffix; + } + + if (!StringUtils.isEmpty(modelNamePrefix)) { // set model prefix + type = modelNamePrefix + "_" + type; + } + + return classPrefix + camelize(type); // add class prefix + } + } + + @Override + public String toModelFilename(String name) { + // should be the same as the model name + return toModelName(name); + } + + @Override + protected void setNonArrayMapProperty(CodegenProperty property, String type) { + super.setNonArrayMapProperty(property, type); + if ("NSDictionary".equals(type)) { + property.setter = "initWithDictionary"; + } else { + property.setter = "initWithValues"; + } + } + + @Override + public String toModelImport(String name) { + return name; + } + + @Override + public String apiDocFileFolder() { + return (outputFolder + "/" + apiDocPath).replace("/", File.separator); + } + + @Override + public String modelDocFileFolder() { + return (outputFolder + "/" + modelDocPath).replace("/", File.separator); + } + + @Override + public String toModelDocFilename(String name) { + return toModelName(name); + } + + @Override + public String toApiDocFilename(String name) { + return toApiName(name); + } + + @Override + public String apiFileFolder() { + return (outputFolder + "/"+ apiPackage() + "/" + apiFilesPath).replace("/", File.separator); + } + + @Override + public String modelFileFolder() { + return (outputFolder + "/"+ modelPackage() + "/" + modelFilesPath).replace("/", File.separator); + } + + public String coreFileFolder() { + return (apiPackage() + "/" + coreFilesPath).replace("/", File.separator); + } + + @Override + public String toApiName(String name) { + return classPrefix + camelize(name) + "Api"; + } + + @Override + public String toApiFilename(String name) { + return classPrefix + camelize(name) + "Api"; + } + + @Override + public String toVarName(String name) { + // sanitize name + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + + // if it's all upper case, do noting + if (name.matches("^[A-Z_]$")) { + return name; + } + + // if name starting with special word, escape with '_' + for(int i =0; i < specialWords.length; i++) { + if (name.matches("(?i:^" + specialWords[i] + ".*)")) + name = escapeSpecialWord(name); + } + + // camelize (lower first character) the variable name + // e.g. `pet_id` to `petId` + name = camelize(name, true); + + // for reserved word or word starting with number, prepend `_` + if (isReservedWord(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } + + + return name; + } + + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @SuppressWarnings("static-method") + public String escapeSpecialWord(String name) { + return "var_" + name; + } + + @Override + public String toOperationId(String operationId) { + // throw exception if method name is empty + if (StringUtils.isEmpty(operationId)) { + throw new RuntimeException("Empty method name (operationId) not allowed"); + } + + // method name cannot use reserved keyword, e.g. return + if (isReservedWord(operationId)) { + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId), true)); + operationId = "call_" + operationId; + } + + return camelize(sanitizeName(operationId), true); + } + + public void setClassPrefix(String classPrefix) { + this.classPrefix = classPrefix; + } + + public void setPodName(String podName) { + this.podName = podName; + } + + public void setPodVersion(String podVersion) { + this.podVersion = podVersion; + } + + public void setAuthorEmail(String authorEmail) { + this.authorEmail = authorEmail; + } + + public void setAuthorName(String authorName) { + this.authorName = authorName; + } + + public void setGitRepoURL(String gitRepoURL) { + this.gitRepoURL = gitRepoURL; + } + + public void setLicense(String license) { + this.license = license; + } + + @Override + public Map postProcessOperations(Map objs) { + Map operations = (Map) objs.get("operations"); + if (operations != null) { + List ops = (List) operations.get("operation"); + for (CodegenOperation operation : ops) { + if (!operation.allParams.isEmpty()) { + String firstParamName = operation.allParams.get(0).paramName; + operation.vendorExtensions.put("firstParamAltName", camelize(firstParamName)); + } + } + } + return objs; + } + + @Override + public void postProcessModelProperty(CodegenModel model, CodegenProperty property){ + super.postProcessModelProperty(model,property); + property.vendorExtensions.put("x-uppercaseName", camelize(property.name)); + } + + /** + * 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; + } + + @Override + public void setParameterExampleValue(CodegenParameter p) { + String example; + + if (p.defaultValue == null) { + example = p.example; + } else { + example = p.defaultValue; + } + + String type = p.baseType; + if (type == null) { + type = p.dataType; + } + + if ("NSString*".equalsIgnoreCase(type)) { + if (example == null) { + example = p.paramName + "_example"; + } + example = "@\"" + escapeText(example) + "\""; + } else if ("NSNumber*".equals(type)) { + if (example == null) { + example = "56"; + } + example = "@" + example; + /* OBJC uses NSNumber to represent both int, long, double and float + } else if ("Float".equalsIgnoreCase(type) || "Double".equalsIgnoreCase(type)) { + if (example == null) { + example = "3.4"; + } */ + } else if ("BOOLEAN".equalsIgnoreCase(type) || "bool".equalsIgnoreCase(type)) { + if (example == null) { + example = "True"; + } + } else if ("NSURL*".equalsIgnoreCase(type)) { + if (example == null) { + example = "/path/to/file"; + } + //[NSURL fileURLWithPath:@"path/to/file"] + example = "[NSURL fileURLWithPath:@\"" + escapeText(example) + "\"]"; + /*} else if ("NSDate".equalsIgnoreCase(type)) { + if (example == null) { + example = "2013-10-20"; + } + example = "'" + escapeText(example) + "'";*/ + } else if ("NSDate*".equalsIgnoreCase(type)) { + if (example == null) { + example = "2013-10-20T19:20:30+01:00"; + } + example = "@\"" + escapeText(example) + "\""; + } else if (!languageSpecificPrimitives.contains(type)) { + // type is a model class, e.g. User + type = type.replace("*", ""); + // e.g. [[SWGPet alloc] init + example = "[[" + type + " alloc] init]"; + } else { + LOGGER.warn("Type " + type + " not handled properly in setParameterExampleValue"); + } + + if (example == null) { + example = "NULL"; + } else if (Boolean.TRUE.equals(p.isListContainer)) { + example = "@[" + example + "]"; + } else if (Boolean.TRUE.equals(p.isMapContainer)) { + example = "@{@\"key\" : " + example + "}"; + } + + p.example = example; + } + + @Override + public String escapeQuotationMark(String input) { + // remove " to avoid code injection + return input.replace("\"", ""); + } + + @Override + public String escapeUnsafeCharacters(String input) { + return input.replace("*/", "*_/").replace("/*", "/_*"); + } + +} diff --git a/output/objcSessionManager_notasold/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/output/objcSessionManager_notasold/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig new file mode 100644 index 00000000000..e3cfa53811b --- /dev/null +++ b/output/objcSessionManager_notasold/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig @@ -0,0 +1 @@ +io.swagger.codegen.languages.ObjcSessionManagerClientCodegen \ No newline at end of file diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache new file mode 100644 index 00000000000..5e5ad41e2df --- /dev/null +++ b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache @@ -0,0 +1,461 @@ +#import + +#import "{{classPrefix}}ApiSessionManager.h" +#import "{{classPrefix}}JSONRequestSerializer.h" +#import "{{classPrefix}}JSONResponseSerializer.h" +#import "{{classPrefix}}QueryParamCollection.h" +#import "{{classPrefix}}Object.h" +#import "{{classPrefix}}DefaultConfiguration.h" + + +NSString * const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}ResponseObject"; + + +static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) { + NSDictionary * headers = {{classPrefix}}__headerFieldsForResponse(response); + if(!headers[@"Content-Disposition"]) { + return [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]]; + } + NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?"; + NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern + options:NSRegularExpressionCaseInsensitive + error:nil]; + NSString *contentDispositionHeader = headers[@"Content-Disposition"]; + NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader + options:0 + range:NSMakeRange(0, [contentDispositionHeader length])]; + return [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]]; +} + + +@interface {{classPrefix}}ApiSessionManager () + +@property (nonatomic, strong, readwrite) id<{{classPrefix}}Configuration> configuration; + +@end + +@implementation {{classPrefix}}ApiSessionManager + +- (instancetype)init { + + return [self initWithConfiguration:[{{classPrefix}}DefaultConfiguration sharedConfiguration]]; +} + +- (instancetype)initWithBaseURL:(NSURL *)url { + + return [self initWithBaseURL:url + configuration:[{{classPrefix}}DefaultConfiguration sharedConfiguration]]; + +} + +- (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration { + + return [self initWithBaseURL:[NSURL URLWithString:configuration.host] configuration:configuration]; +} + +- (instancetype)initWithBaseURL:(NSURL *)url + configuration:(id<{{classPrefix}}Configuration>)configuration { + + self = [super initWithBaseURL:url]; + if (self) { + _configuration = configuration; + } + + return self; +} + +#pragma mark - Setter Methods + ++ (void) setOfflineState:(BOOL) state { + offlineState = state; +} + ++ (void) setCacheEnabled:(BOOL)enabled { + cacheEnabled = enabled; +} + ++(void) setReachabilityStatus:(AFNetworkReachabilityStatus)status { + reachabilityStatus = status; +} + +- (void)setHeaderValue:(NSString*) value forKey:(NSString*) forKey { + [self.requestSerializer setValue:value forHTTPHeaderField:forKey]; +} + +- (void)setRequestSerializer:(AFHTTPRequestSerializer *)requestSerializer { + [super setRequestSerializer:requestSerializer]; + requestSerializer.timeoutInterval = self.timeoutInterval; +} + +#pragma mark - Cache Methods + ++(void)clearCache { + [[NSURLCache sharedURLCache] removeAllCachedResponses]; +} + ++(void)configureCacheWithMemoryAndDiskCapacity: (unsigned long) memorySize + diskSize: (unsigned long) diskSize { + NSAssert(memorySize > 0, @"invalid in-memory cache size"); + NSAssert(diskSize >= 0, @"invalid disk cache size"); + + NSURLCache *cache = + [[NSURLCache alloc] + initWithMemoryCapacity:memorySize + diskCapacity:diskSize + diskPath:@"swagger_url_cache"]; + + [NSURLCache setSharedURLCache:cache]; +} + +#pragma mark - Reachability Methods + ++(AFNetworkReachabilityStatus) getReachabilityStatus { + return reachabilityStatus; +} + ++(BOOL) getOfflineState { + return offlineState; +} + ++(void) setReachabilityChangeBlock:(void(^)(int))changeBlock { + reachabilityChangeBlock = changeBlock; +} + +- (void) configureCacheReachibility { + [self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { + reachabilityStatus = status; + {{classPrefix}}DebugLog(@"reachability changed to %@",AFStringFromNetworkReachabilityStatus(status)); + [{{classPrefix}}ApiClient setOfflineState:status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable]; + + // call the reachability block, if configured + if (reachabilityChangeBlock != nil) { + reachabilityChangeBlock(status); + } + }]; + + [self.reachabilityManager startMonitoring]; +} + +#pragma mark - Task Methods + +- (NSURLSessionDataTask*) taskWithCompletionBlock: (NSURLRequest *)request + completionBlock: (void (^)(id, NSError *))completionBlock { + + NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { + {{classPrefix}}DebugLogResponse(response, responseObject,request,error); + + if(!error) { + completionBlock(responseObject, nil); + return; + } + + NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; + if (responseObject) { + // Add in the (parsed) response body. + userInfo[{{classPrefix}}ResponseObjectErrorKey] = responseObject; + } + NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; + completionBlock(nil, augmentedError); + }]; + + return task; +} + +- (NSURLSessionDownloadTask*) downloadTaskWithCompletionBlock: (NSURLRequest *)request + completionBlock: (void (^)(id, NSError *))completionBlock { + + id<{{classPrefix}}Configuration> config = self.configuration; + + NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + {{classPrefix}}DebugLogResponse(response, responseObject,request,error); + + if(error) { + NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; + if (responseObject) { + userInfo[{{classPrefix}}ResponseObjectErrorKey] = responseObject; + } + NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; + completionBlock(nil, augmentedError); + } + + NSString *directory = config.tempFolderPath ?: NSTemporaryDirectory(); + NSString *filename = {{classPrefix}}__fileNameForResponse(response); + + NSString *filepath = [directory stringByAppendingPathComponent:filename]; + NSURL *file = [NSURL fileURLWithPath:filepath]; + + [responseObject writeToURL:file atomically:YES]; + + completionBlock(file, nil); + }]; + + return task; +} + +#pragma mark - Perform Request Methods + +- (NSURLSessionTask*) requestWithPath: (NSString*) path + method: (NSString*) method + pathParams: (NSDictionary *) pathParams + queryParams: (NSDictionary*) queryParams + formParams: (NSDictionary *) formParams + files: (NSDictionary *) files + body: (id) body + headerParams: (NSDictionary*) headerParams + authSettings: (NSArray *) authSettings + requestContentType: (NSString*) requestContentType + responseContentType: (NSString*) responseContentType + responseType: (NSString *) responseType + completionBlock: (void (^)(id, NSError *))completionBlock { + + // setting request serializer + if ([requestContentType isEqualToString:@"application/json"]) { + self.requestSerializer = [{{classPrefix}}JSONRequestSerializer serializer]; + } + else if ([requestContentType isEqualToString:@"application/x-www-form-urlencoded"]) { + self.requestSerializer = [AFHTTPRequestSerializer serializer]; + } + else if ([requestContentType isEqualToString:@"multipart/form-data"]) { + self.requestSerializer = [AFHTTPRequestSerializer serializer]; + } + else { + self.requestSerializer = [AFHTTPRequestSerializer serializer]; + NSAssert(NO, @"Unsupported request type %@", requestContentType); + } + + // setting response serializer + if ([responseContentType isEqualToString:@"application/json"]) { + self.responseSerializer = [{{classPrefix}}JSONResponseSerializer serializer]; + } else { + self.responseSerializer = [AFHTTPResponseSerializer serializer]; + } + + // sanitize parameters + pathParams = [self.sanitizer sanitizeForSerialization:pathParams]; + queryParams = [self.sanitizer sanitizeForSerialization:queryParams]; + headerParams = [self.sanitizer sanitizeForSerialization:headerParams]; + formParams = [self.sanitizer sanitizeForSerialization:formParams]; + if(![body isKindOfClass:[NSData class]]) { + body = [self.sanitizer sanitizeForSerialization:body]; + } + + // auth setting + [self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings]; + + NSMutableString *resourcePath = [NSMutableString stringWithString:path]; + [pathParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + NSString * safeString = ([obj isKindOfClass:[NSString class]]) ? obj : [NSString stringWithFormat:@"%@", obj]; + safeString = {{classPrefix}}PercentEscapedStringFromString(safeString); + [resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"{%@}", key]] withString:safeString]; + }]; + + NSMutableURLRequest * request = nil; + + NSString* pathWithQueryParams = [self pathWithQueryParamsToString:resourcePath queryParams:queryParams]; + if ([pathWithQueryParams hasPrefix:@"/"]) { + pathWithQueryParams = [pathWithQueryParams substringFromIndex:1]; + } + + NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString]; + if (files.count > 0) { + __weak __typeof(self)weakSelf = self; + request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" + URLString:urlString + parameters:nil + constructingBodyWithBlock:^(id formData) { + [formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + NSString *objString = [weakSelf.sanitizer parameterToString:obj]; + NSData *data = [objString dataUsingEncoding:NSUTF8StringEncoding]; + [formData appendPartWithFormData:data name:key]; + }]; + [files enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + NSURL *filePath = (NSURL *)obj; + [formData appendPartWithFileURL:filePath name:key error:nil]; + }]; + } error:nil]; + } + else { + if (formParams) { + request = [self.requestSerializer requestWithMethod:method + URLString:urlString + parameters:formParams + error:nil]; + } + if (body) { + request = [self.requestSerializer requestWithMethod:method + URLString:urlString + parameters:body + error:nil]; + } + } + + // request cache + BOOL hasHeaderParams = [headerParams count] > 0; + if (offlineState) { + {{classPrefix}}DebugLog(@"%@ cache forced", resourcePath); + [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; + } + else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { + {{classPrefix}}DebugLog(@"%@ cache enabled", resourcePath); + [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; + } + else { + {{classPrefix}}DebugLog(@"%@ cache disabled", resourcePath); + [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; + } + + if (hasHeaderParams){ + for(NSString * key in [headerParams keyEnumerator]){ + [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; + } + } + [self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"]; + + [self postProcessRequest:request]; + + + NSURLSessionTask *task = nil + + if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) { + task = [self downloadTaskWithCompletionBlock:request completionBlock:^(id data, NSError *error) { + completionBlock(data, error); + }]; + } + else { + [self taskWithCompletionBlock:request completionBlock:^(id data, NSError *error) { + NSError * serializationError; + id response = [self.responseDeserializer deserialize:data class:responseType error:&serializationError]; + if(!response && !error){ + error = serializationError; + } + completionBlock(response, error); + }]; + } + + [task resume]; + + return task; +} + +// Added for easier override to modify request +- (void)postProcessRequest:(NSMutableURLRequest *)request { + // Always disable cookies! + [request setHTTPShouldHandleCookies:NO]; +} + +#pragma mark - + +- (NSString*)pathWithQueryParamsToString:(NSString*) path + queryParams:(NSDictionary*) queryParams { + if(queryParams.count == 0) { + return path; + } + NSString * separator = nil; + NSUInteger counter = 0; + + NSMutableString * requestUrl = [NSMutableString stringWithFormat:@"%@", path]; + + NSDictionary *separatorStyles = @{@"csv" : @",", + @"tsv" : @"\t", + @"pipes": @"|" + }; + for(NSString * key in [queryParams keyEnumerator]){ + if (counter == 0) { + separator = @"?"; + } else { + separator = @"&"; + } + id queryParam = [queryParams valueForKey:key]; + if(!queryParam) { + continue; + } + NSString *safeKey = {{classPrefix}}PercentEscapedStringFromString(key); + if ([queryParam isKindOfClass:[NSString class]]){ + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, {{classPrefix}}PercentEscapedStringFromString(queryParam)]]; + + } else if ([queryParam isKindOfClass:[{{classPrefix}}QueryParamCollection class]]){ + {{classPrefix}}QueryParamCollection * coll = ({{classPrefix}}QueryParamCollection*) queryParam; + NSArray* values = [coll values]; + NSString* format = [coll format]; + + if([format isEqualToString:@"multi"]) { + for(id obj in values) { + if (counter > 0) { + separator = @"&"; + } + NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([NSString stringWithFormat:@"%@",obj]); + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; + counter += 1; + } + continue; + } + NSString * separatorStyle = separatorStyles[format]; + NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([values componentsJoinedByString:separatorStyle]); + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; + } else { + NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([NSString stringWithFormat:@"%@",queryParam]); + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; + } + counter += 1; + } + return requestUrl; +} + +/** + * Update header and query params based on authentication settings + */ +- (void) updateHeaderParams:(NSDictionary *__autoreleasing *)headers + queryParams:(NSDictionary *__autoreleasing *)querys + WithAuthSettings:(NSArray *)authSettings { + + if (!authSettings || [authSettings count] == 0) { + return; + } + + NSMutableDictionary *headersWithAuth = [NSMutableDictionary dictionaryWithDictionary:*headers]; + NSMutableDictionary *querysWithAuth = [NSMutableDictionary dictionaryWithDictionary:*querys]; + + id<{{classPrefix}}Configuration> config = self.configuration; + for (NSString *auth in authSettings) { + NSDictionary *authSetting = config.authSettings[auth]; + + if(!authSetting) { // auth setting is set only if the key is non-empty + continue; + } + + NSString *type = authSetting[@"in"]; + NSString *key = authSetting[@"key"]; + NSString *value = authSetting[@"value"]; + if ([type isEqualToString:@"header"] && [key length] > 0 ) { + headersWithAuth[key] = value; + } else if ([type isEqualToString:@"query"] && [key length] != 0) { + querysWithAuth[key] = value; + } + } + + *headers = [NSDictionary dictionaryWithDictionary:headersWithAuth]; + *querys = [NSDictionary dictionaryWithDictionary:querysWithAuth]; +} + +- (AFSecurityPolicy *) customSecurityPolicy { + AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; + + id<{{classPrefix}}Configuration> config = self.configuration; + + if (config.sslCaCert) { + NSData *certData = [NSData dataWithContentsOfFile:config.sslCaCert]; + [securityPolicy setPinnedCertificates:@[certData]]; + } + + if (config.verifySSL) { + [securityPolicy setAllowInvalidCertificates:NO]; + } + else { + [securityPolicy setAllowInvalidCertificates:YES]; + [securityPolicy setValidatesDomainName:NO]; + } + + return securityPolicy; +} + +@end diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/ApiSessionManager-header.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/ApiSessionManager-header.mustache new file mode 100644 index 00000000000..010966b14a5 --- /dev/null +++ b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/ApiSessionManager-header.mustache @@ -0,0 +1,147 @@ +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + +#import +#import "{{classPrefix}}Configuration.h" + +/** + * A key for `NSError` user info dictionaries. + * + * The corresponding value is the parsed response body for an HTTP error. + */ +extern NSString *const {{classPrefix}}ResponseObjectErrorKey; + + +@interface {{classPrefix}}ApiSessionManager : AFHTTPSessionManager + +@property (nonatomic, strong, readonly) id<{{classPrefix}}Configuration> configuration; + +@property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy; +@property(nonatomic, assign) NSTimeInterval timeoutInterval; +@property(nonatomic, readonly) NSOperationQueue* queue; + +@property(nonatomic, strong) id<{{classPrefix}}ResponseDeserializer> responseDeserializer; + +@property(nonatomic, strong) id<{{classPrefix}}Sanitizer> sanitizer; + +/** + * Clears Cache + */ ++(void)clearCache; + +/** + * Turns on cache + * + * @param enabled If the cached is enable, must be `YES` or `NO` + */ ++(void)setCacheEnabled:(BOOL) enabled; + +/** + * Sets the client unreachable + * + * @param state off line state, must be `YES` or `NO` + */ ++(void) setOfflineState:(BOOL) state; + +/** + * Gets if the client is unreachable + * + * @return The client offline state + */ ++(BOOL) getOfflineState; + +/** + * Sets the client reachability, this may be overridden by the reachability manager if reachability changes + * + * @param The client reachability. + */ ++(void) setReachabilityStatus:(AFNetworkReachabilityStatus) status; + +/** + * Gets the client reachability + * + * @return The client reachability. + */ ++(AFNetworkReachabilityStatus) getReachabilityStatus; + +/** + * Customizes the behavior when the reachability changed + * + * @param changeBlock The block will be executed when the reachability changed. + */ ++(void) setReachabilityChangeBlock:(void(^)(int))changeBlock; + +/** + * Sets the api client reachability strategy + */ +- (void)configureCacheReachibility; + +/** + * Sets header for request + * + * @param value The header value + * @param forKey The header key + */ +-(void)setHeaderValue:(NSString*) value + forKey:(NSString*) forKey; + +/** + * Updates header parameters and query parameters for authentication + * + * @param headers The header parameter will be udpated, passed by pointer to pointer. + * @param querys The query parameters will be updated, passed by pointer to pointer. + * @param authSettings The authentication names NSArray. + */ +- (void) updateHeaderParams:(NSDictionary **)headers + queryParams:(NSDictionary **)querys + WithAuthSettings:(NSArray *)authSettings; + + +/** + * Initializes the session manager with a configuration. + * + * @param configuration The configuration implementation + */ +- (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration; + +/** + * Performs request + * + * @param path Request url. + * @param method Request method. + * @param pathParams Request path parameters. + * @param queryParams Request query parameters. + * @param body Request body. + * @param headerParams Request header parameters. + * @param authSettings Request authentication names. + * @param requestContentType Request content-type. + * @param responseContentType Response content-type. + * @param completionBlock The block will be executed when the request completed. + * + * @return The created session task. + */ +- (NSURLSessionTask *)requestWithCompletionBlock:(NSString*)path + method:(NSString*) method + pathParams:(NSDictionary *)pathParams + queryParams:(NSDictionary*)queryParams + formParams:(NSDictionary *)formParams + files:(NSDictionary *)files + body:(id)body + headerParams:(NSDictionary *)headerParams + authSettings: (NSArray *)authSettings + requestContentType:(NSString *)requestContentType + responseContentType:(NSString *)responseContentType + responseType:(NSString *)responseType + completionBlock:(void (^)(id, NSError *))completionBlock; + +/** + * Custom security policy + * + * @return AFSecurityPolicy + */ +- (AFSecurityPolicy *) customSecurityPolicy; + +@end diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/BasicAuthTokenProvider-body.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/BasicAuthTokenProvider-body.mustache new file mode 100644 index 00000000000..e2ba00badb7 --- /dev/null +++ b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/BasicAuthTokenProvider-body.mustache @@ -0,0 +1,14 @@ +#import "{{classPrefix}}BasicAuthTokenProvider.h" + +@implementation {{classPrefix}}BasicAuthTokenProvider + ++ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password { + + NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password]; + NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; + basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; + + return basicAuthCredentials; +} + +@end diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/BasicAuthTokenProvider-header.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/BasicAuthTokenProvider-header.mustache new file mode 100644 index 00000000000..dfb287568a0 --- /dev/null +++ b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/BasicAuthTokenProvider-header.mustache @@ -0,0 +1,14 @@ +/** The `{{classPrefix}}BasicAuthTokenProvider` class creates a basic auth token from username and password. + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + +#import + +@interface {{classPrefix}}BasicAuthTokenProvider : NSObject + ++ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password; + +@end \ No newline at end of file diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/Configuration-protocol.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/Configuration-protocol.mustache new file mode 100644 index 00000000000..db429a38150 --- /dev/null +++ b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/Configuration-protocol.mustache @@ -0,0 +1,75 @@ +#import +#import "{{classPrefix}}Logger.h" + +{{>licenceInfo}} + +@protocol {{classPrefix}}Configuration + +/** + * Api logger + */ +@property (readonly, nonatomic) {{classPrefix}}Logger *logger; + +/** + * Base url + */ +@property (readonly, nonatomic) NSString *host; + +/** + * Api key values for Api Key type Authentication + */ +@property (readonly, nonatomic) NSDictionary *apiKey; + +/** + * Api key prefix values to be prepend to the respective api key + */ +@property (readonly, nonatomic) NSDictionary *apiKeyPrefix; + +/** + * Username for HTTP Basic Authentication + */ +@property (readonly, nonatomic) NSString *username; + +/** + * Password for HTTP Basic Authentication + */ +@property (readonly, nonatomic) NSString *password; + +/** + * Access token for OAuth + */ +@property (readonly, nonatomic) NSString *accessToken; + +/** + * Temp folder for file download + */ +@property (readonly, nonatomic) NSString *tempFolderPath; + +/** + * Debug switch, default false + */ +@property (readonly, nonatomic) BOOL debug; + +/** + * SSL/TLS verification + * Set this to NO to skip verifying SSL certificate when calling API from https server + */ +@property (readonly, nonatomic) BOOL verifySSL; + +/** + * SSL/TLS verification + * Set this to customize the certificate file to verify the peer + */ +@property (readonly, nonatomic) NSString *sslCaCert; + +/** + * Authentication Settings + */ +@property (readonly, nonatomic) NSDictionary *authSettings; + +/** +* Default headers for all services +*/ +@property (readonly, nonatomic, strong) NSDictionary *defaultHeaders; + +@end \ No newline at end of file diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/DefaultConfiguration-body.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/DefaultConfiguration-body.mustache new file mode 100644 index 00000000000..a45eba7ba55 --- /dev/null +++ b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/DefaultConfiguration-body.mustache @@ -0,0 +1,157 @@ +#import "{{classPrefix}}DefaultConfiguration.h" + +@implementation {{classPrefix}}DefaultConfiguration + +#pragma mark - Singleton Methods + ++ (instancetype)sharedConfiguration { + + static {{classPrefix}}DefaultConfiguration *shardConfig = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + shardConfig = [[self alloc] init]; + }); + return shardConfig; +} + +#pragma mark - Initialize Methods + +- (instancetype)init { + self = [super init]; + if (self) { + _host = @"{{basePath}}"; + _username = @""; + _password = @""; + _accessToken= @""; + _verifySSL = YES; + _mutableApiKey = [NSMutableDictionary dictionary]; + _mutableApiKeyPrefix = [NSMutableDictionary dictionary]; + _mutableDefaultHeaders = [NSMutableDictionary dictionary]; + _mutableDefaultHeaders[@"User-Agent"] = {{#httpUserAgent}}@"{{httpUserAgent}}"{{/httpUserAgent}}{{^httpUserAgent}}[NSString stringWithFormat:@"Swagger-Codegen/{{version}}/objc (%@; iOS %@; Scale/%0.2f)",[[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]]{{/httpUserAgent}}; + _logger = [{{classPrefix}}Logger sharedLogger]; + } + return self; +} + +#pragma mark - Instance Methods + +- (NSString *) getApiKeyWithPrefix:(NSString *)key { + NSString *prefix = self.apiKeyPrefix[key]; + NSString *apiKey = self.apiKey[key]; + if (prefix && apiKey != (id)[NSNull null] && apiKey.length > 0) { // both api key prefix and api key are set + return [NSString stringWithFormat:@"%@ %@", prefix, apiKey]; + } + else if (apiKey != (id)[NSNull null] && apiKey.length > 0) { // only api key, no api key prefix + return [NSString stringWithFormat:@"%@", self.apiKey[key]]; + } + else { // return empty string if nothing is set + return @""; + } +} + +- (NSString *) getBasicAuthToken { + // return empty string if username and password are empty + if (self.username.length == 0 && self.password.length == 0){ + return @""; + } + + NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.username, self.password]; + NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; + basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; + + return basicAuthCredentials; +} + +- (NSString *) getAccessToken { + if (self.accessToken.length == 0) { // token not set, return empty string + return @""; + } else { + return [NSString stringWithFormat:@"Bearer %@", self.accessToken]; + } +} + +#pragma mark - Setter Methods + +- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString *)identifier { + [self.mutableApiKey setValue:apiKey forKey:identifier]; +} + +- (void) removeApiKey:(NSString *)identifier { + [self.mutableApiKey removeObjectForKey:identifier]; +} + +- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier { + [self.mutableApiKeyPrefix setValue:prefix forKey:identifier]; +} + +- (void) removeApiKeyPrefix:(NSString *)identifier { + [self.mutableApiKeyPrefix removeObjectForKey:identifier]; +} + +#pragma mark - + +- (NSDictionary *) authSettings { + return @{ +{{#authMethods}} +{{#isApiKey}} + @"{{name}}": + @{ + @"type": @"api_key", + @"in": {{#isKeyInHeader}}@"header"{{/isKeyInHeader}}{{#isKeyInQuery}}@"query"{{/isKeyInQuery}}, + @"key": @"{{keyParamName}}", + @"value": [self getApiKeyWithPrefix:@"{{keyParamName}}"] + }, +{{/isApiKey}} +{{#isBasic}} + @"{{name}}": + @{ + @"type": @"basic", + @"in": @"header", + @"key": @"Authorization", + @"value": [self getBasicAuthToken] + }, +{{/isBasic}} +{{#isOAuth}} + @"{{name}}": + @{ + @"type": @"oauth", + @"in": @"header", + @"key": @"Authorization", + @"value": [self getAccessToken] + }, +{{/isOAuth}} +{{/authMethods}} + }; +} + +-(BOOL)debug { + return self.logger.isEnabled; +} + +-(void)setDebug:(BOOL)debug { + self.logger.enabled = debug; +} + + + +- (void)setDefaultHeaderValue:(NSString *)value forKey:(NSString *)key { + if(!value) { + [self.mutableDefaultHeaders removeObjectForKey:key]; + return; + } + self.mutableDefaultHeaders[key] = value; +} + +-(void) removeDefaultHeaderForKey:(NSString*)key { + [self.mutableDefaultHeaders removeObjectForKey:key]; +} + +- (NSString *)defaultHeaderForKey:(NSString *)key { + return self.mutableDefaultHeaders[key]; +} + +- (NSDictionary *)defaultHeaders { + return [self.mutableDefaultHeaders copy]; +} + +@end diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/DefaultConfiguration-header.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/DefaultConfiguration-header.mustache new file mode 100644 index 00000000000..46f3b32fc93 --- /dev/null +++ b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/DefaultConfiguration-header.mustache @@ -0,0 +1,134 @@ +#import +#import "{{classPrefix}}Configuration.h" + +{{>licenceInfo}} + +@interface {{classPrefix}}DefaultConfiguration : NSObject <{{classPrefix}}Configuration> + ++ ({{classPrefix}}DefaultConfiguration *)sharedConfiguration; + +/** + * Default api logger + */ +@property (nonatomic, strong) {{classPrefix}}Logger * logger; + +/** + * Default api client + */ +@property (nonatomic) {{classPrefix}}ApiClient *apiClient; + +/** + * Default base url + */ +@property (nonatomic) NSString *host; + +/** + * Api key values for Api Key type Authentication + * + * To add or remove api key, use `setApiKey:forApiKeyIdentifier:`. + */ +@property (readonly, nonatomic, strong) NSDictionary *apiKey; + +/** + * Api key prefix values to be prepend to the respective api key + * + * To add or remove prefix, use `setApiKeyPrefix:forApiKeyPrefixIdentifier:`. + */ +@property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix; + +/** + * Username for HTTP Basic Authentication + */ + @property (nonatomic) NSString *username; + +/** + * Password for HTTP Basic Authentication + */ +@property (nonatomic) NSString *password; + +/** + * Access token for OAuth + */ +@property (nonatomic) NSString *accessToken; + +/** + * Temp folder for file download + */ +@property (nonatomic) NSString *tempFolderPath; + +/** + * Debug switch, default false + */ +@property (nonatomic) BOOL debug; + +/** + * SSL/TLS verification + * Set this to NO to skip verifying SSL certificate when calling API from https server + */ +@property (nonatomic) BOOL verifySSL; + +/** + * SSL/TLS verification + * Set this to customize the certificate file to verify the peer + */ +@property (nonatomic) NSString *sslCaCert; + +/** + * Sets API key + * + * To remove a apiKey for an identifier, just set the apiKey to nil. + * + * @param apiKey API key or token. + * @param identifier API key identifier (authentication schema). + * + */ +- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString*)identifier; + +/** + * Removes api key + * + * @param identifier API key identifier. + */ +- (void) removeApiKey:(NSString *)identifier; + +/** + * Sets the prefix for API key + * + * @param apiKeyPrefix API key prefix. + * @param identifier API key identifier. + */ +- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier; + +/** + * Removes api key prefix + * + * @param identifier API key identifier. + */ +- (void) removeApiKeyPrefix:(NSString *)identifier; + +/** +* Default headers for all services +*/ +@property (readonly, nonatomic, strong) NSDictionary *defaultHeaders; + +/** +* Removes header from defaultHeaders +* +* @param Header name. +*/ +-(void) removeDefaultHeaderForKey:(NSString*)key; + +/** +* Sets the header for key +* +* @param value Value for header name +* @param key Header name +*/ +-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key; + +/** +* @param Header key name. +*/ +-(NSString*) defaultHeaderForKey:(NSString*)key; + +@end \ No newline at end of file diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONRequestSerializer-body.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONRequestSerializer-body.mustache new file mode 100644 index 00000000000..63513335d9a --- /dev/null +++ b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONRequestSerializer-body.mustache @@ -0,0 +1,37 @@ +#import "{{classPrefix}}JSONRequestSerializer.h" + +@implementation {{classPrefix}}JSONRequestSerializer + +/// +/// When customize a request serializer, +/// the serializer must conform the protocol `AFURLRequestSerialization` +/// and implements the protocol method `requestBySerializingRequest:withParameters:error:` +/// +/// @param request The original request. +/// @param parameters The parameters to be encoded. +/// @param error The error that occurred while attempting to encode the request parameters. +/// +/// @return A serialized request. +/// +- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request + withParameters:(id)parameters + error:(NSError *__autoreleasing *)error +{ + if (!parameters) { + return request; + } + // If the body data which will be serialized isn't NSArray or NSDictionary + // then put the data in the http request body directly. + if ([parameters isKindOfClass:[NSArray class]] || [parameters isKindOfClass:[NSDictionary class]]) { + return [super requestBySerializingRequest:request withParameters:parameters error:error]; + } + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + if([parameters isKindOfClass:[NSData class]]) { + [mutableRequest setHTTPBody:parameters]; + } else { + [mutableRequest setHTTPBody:[parameters dataUsingEncoding:self.stringEncoding]]; + } + return mutableRequest; +} + +@end diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONRequestSerializer-header.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONRequestSerializer-header.mustache new file mode 100644 index 00000000000..1259c5d1530 --- /dev/null +++ b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONRequestSerializer-header.mustache @@ -0,0 +1,7 @@ +#import +#import + +{{>licenceInfo}} + +@interface {{classPrefix}}JSONRequestSerializer : AFJSONRequestSerializer +@end diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONResponseSerializer-body.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONResponseSerializer-body.mustache new file mode 100644 index 00000000000..7fa5e7b19e0 --- /dev/null +++ b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONResponseSerializer-body.mustache @@ -0,0 +1,39 @@ +#import "{{classPrefix}}JSONResponseSerializer.h" + +@implementation {{classPrefix}}JSONResponseSerializer + +/// +/// When customize a response serializer, +/// the serializer must conform the protocol `AFURLResponseSerialization` +/// and implements the protocol method `responseObjectForResponse:error:` +/// +/// @param response The response to be processed. +/// @param data The response data to be decoded. +/// @param error The error that occurred while attempting to decode the response data. +/// +/// @return The object decoded from the specified response data. +/// +- (id) responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error { + NSDictionary *responseJson = [super responseObjectForResponse:response data:data error:error]; + + // if response data is not a valid json, return string of data. + if ([self isParseError:*error]) { + *error = nil; + NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; + return responseString; + } + + return responseJson; +} + +-(BOOL)isParseError:(NSError *)error { + return [error.domain isEqualToString:NSCocoaErrorDomain] && error.code == 3840; +} + ++ (instancetype)serializer { + return [self serializerWithReadingOptions:NSJSONReadingAllowFragments]; +} + +@end diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONResponseSerializer-header.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONResponseSerializer-header.mustache new file mode 100644 index 00000000000..360e4f9cdc5 --- /dev/null +++ b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONResponseSerializer-header.mustache @@ -0,0 +1,8 @@ +#import +#import + +{{>licenceInfo}} + +@interface {{classPrefix}}JSONResponseSerializer : AFJSONResponseSerializer + +@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.h b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.h similarity index 86% rename from output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.h rename to output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.h index 6f66d0e1c13..f621e7184a9 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.h +++ b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.h @@ -1,5 +1,8 @@ #import #import +{{>licenceInfo}} + @interface JSONValueTransformer (ISO8601) + @end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.m b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.m similarity index 77% rename from output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.m rename to output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.m index aaa7a808f32..b544a1dae58 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.m +++ b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.m @@ -3,7 +3,8 @@ @implementation JSONValueTransformer (ISO8601) -- (NSDate *)NSDateFromNSString:(NSString *)string { +- (NSDate *) NSDateFromNSString:(NSString *)string +{ return [NSDate dateWithISO8601String:string]; } diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/Object-body.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/Object-body.mustache new file mode 100644 index 00000000000..88df6d6c9ae --- /dev/null +++ b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/Object-body.mustache @@ -0,0 +1,42 @@ +#import "{{classPrefix}}Object.h" + +@implementation {{classPrefix}}Object + +/** + * Workaround for JSONModel multithreading issues + * https://github.com/icanzilb/JSONModel/issues/441 + */ +- (instancetype)initWithDictionary:(NSDictionary *)dict error:(NSError **)err { + static NSMutableSet *classNames; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + classNames = [NSMutableSet new]; + }); + + BOOL initSync; + @synchronized([self class]) + { + NSString *className = NSStringFromClass([self class]); + initSync = ![classNames containsObject:className]; + if(initSync) + { + [classNames addObject:className]; + self = [super initWithDictionary:dict error:err]; + } + } + if(!initSync) + { + self = [super initWithDictionary:dict error:err]; + } + return self; +} + +/** + * Gets the string presentation of the object. + * This method will be called when logging model object using `NSLog`. + */ +- (NSString *)description { + return [[self toDictionary] description]; +} + +@end diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/Object-header.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/Object-header.mustache new file mode 100644 index 00000000000..89da6a4d8b6 --- /dev/null +++ b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/Object-header.mustache @@ -0,0 +1,8 @@ +#import +#import + +{{>licenceInfo}} + +@interface {{classPrefix}}Object : JSONModel + +@end diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/QueryParamCollection-body.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/QueryParamCollection-body.mustache new file mode 100644 index 00000000000..b1c901dbffa --- /dev/null +++ b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/QueryParamCollection-body.mustache @@ -0,0 +1,20 @@ +#import "{{classPrefix}}QueryParamCollection.h" + +@implementation {{classPrefix}}QueryParamCollection + +@synthesize values = _values; +@synthesize format = _format; + +- (id)initWithValuesAndFormat:(NSArray *)values + format:(NSString *)format { + + self = [super init]; + if (self) { + _values = values; + _format = format; + } + + return self; +} + +@end diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/QueryParamCollection-header.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/QueryParamCollection-header.mustache new file mode 100644 index 00000000000..9729c182bd8 --- /dev/null +++ b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/QueryParamCollection-header.mustache @@ -0,0 +1,13 @@ +#import + +{{>licenceInfo}} + +@interface {{classPrefix}}QueryParamCollection : NSObject + +@property(nonatomic, readonly) NSArray* values; +@property(nonatomic, readonly) NSString* format; + +- (id) initWithValuesAndFormat: (NSArray*) values + format: (NSString*) format; + +@end diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/README.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/README.mustache new file mode 100644 index 00000000000..4355ecc1af5 --- /dev/null +++ b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/README.mustache @@ -0,0 +1,143 @@ +# {{podName}} + +{{#appDescription}} +{{{appDescription}}} +{{/appDescription}} + +This ObjC package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: + +- API version: {{appVersion}} +- Package version: {{artifactVersion}} +- Build date: {{generatedDate}} +- Build package: {{generatorClass}} +{{#infoUrl}} +For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + +## Requirements + +The SDK requires [**ARC (Automatic Reference Counting)**](http://stackoverflow.com/questions/7778356/how-to-enable-disable-automatic-reference-counting) to be enabled in the Xcode project. + +## Installation & Usage +### Install from Github using [CocoaPods](https://cocoapods.org/) + +Add the following to the Podfile: + +```ruby +pod '{{podName}}', :git => 'https://github.com/{{gitUserId}}/{{gitRepoId}}.git' +``` + +To specify a particular branch, append `, :branch => 'branch-name-here'` + +To specify a particular commit, append `, :commit => '11aa22'` + +### Install from local path using [CocoaPods](https://cocoapods.org/) + +Put the SDK under your project folder (e.g. /path/to/objc_project/Vendor/{{podName}}) and then add the following to the Podfile: + +```ruby +pod '{{podName}}', :path => 'Vendor/{{podName}}' +``` + +### Usage + +Import the following: + +```objc +#import <{{podName}}/{{{classPrefix}}}ApiClient.h> +#import <{{podName}}/{{{classPrefix}}}Configuration.h> +// load models +{{#models}}{{#model}}#import <{{podName}}/{{{classname}}}.h> +{{/model}}{{/models}}// load API classes for accessing endpoints +{{#apiInfo}}{{#apis}}#import <{{podName}}/{{{classname}}}.h> +{{/apis}}{{/apiInfo}} +``` + +## Recommendation + +It's recommended to create an instance of ApiClient per thread in a multi-threaded environment to avoid any potential issue. + +## Getting Started + +Please follow the [installation procedure](#installation--usage) and then run the following: + +```objc +{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}} +{{#hasAuthMethods}} +{{classPrefix}}Configuration *apiConfig = [{{classPrefix}}Configuration sharedConfig]; +{{#authMethods}}{{#isBasic}}// Configure HTTP basic authorization (authentication scheme: {{{name}}}) +[apiConfig setUsername:@"YOUR_USERNAME"]; +[apiConfig setPassword:@"YOUR_PASSWORD"]; +{{/isBasic}}{{#isApiKey}} +// Configure API key authorization: (authentication scheme: {{{name}}}) +[apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"{{{keyParamName}}}"]; +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +//[apiConfig setApiKeyPrefix:@"Bearer" forApiKeyIdentifier:@"{{{keyParamName}}}"]; +{{/isApiKey}}{{#isOAuth}} +// Configure OAuth2 access token for authorization: (authentication scheme: {{{name}}}) +[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; +{{/isOAuth}}{{/authMethods}} +{{/hasAuthMethods}} + +{{#allParams}}{{{dataType}}} *{{paramName}} = {{{example}}}; // {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} +{{/allParams}} + +{{classname}} *apiInstance = [[{{classname}} alloc] init]; + +{{#summary}}// {{{.}}} +{{/summary}}[apiInstance {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} + {{paramName}}{{/secondaryParam}}:{{paramName}}{{/allParams}} + {{#hasParams}}completionHandler: {{/hasParams}}^({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error) { +{{#returnType}} + if (output) { + NSLog(@"%@", output); + } +{{/returnType}} + if (error) { + NSLog(@"Error: %@", error); + } + }]; +{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} +``` + +## Documentation for API Endpoints + +All URIs are relative to *{{basePath}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + +## Documentation For Models + +{{#models}}{{#model}} - [{{{classname}}}]({{modelDocPath}}{{{classname}}}.md) +{{/model}}{{/models}} + +## Documentation For Authorization + +{{^authMethods}} All endpoints do not require authorization. +{{/authMethods}}{{#authMethods}}{{#last}} Authentication schemes defined for the API:{{/last}}{{/authMethods}} +{{#authMethods}}## {{{name}}} + +{{#isApiKey}}- **Type**: API key +- **API key parameter name**: {{{keyParamName}}} +- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} +{{/isApiKey}} +{{#isBasic}}- **Type**: HTTP basic authentication +{{/isBasic}} +{{#isOAuth}}- **Type**: OAuth +- **Flow**: {{{flow}}} +- **Authorization URL**: {{{authorizationUrl}}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - **{{{scope}}}**: {{{description}}} +{{/scopes}} +{{/isOAuth}} + +{{/authMethods}} + +## Author + +{{#apiInfo}}{{#apis}}{{^hasMore}}{{infoEmail}} +{{/hasMore}}{{/apis}}{{/apiInfo}} + diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/api-body.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/api-body.mustache new file mode 100644 index 00000000000..050368f9899 --- /dev/null +++ b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/api-body.mustache @@ -0,0 +1,161 @@ +{{#operations}} +#import "{{classname}}.h" +#import "{{classPrefix}}QueryParamCollection.h" +{{#imports}}#import "{{import}}.h" +{{/imports}} +{{newline}} + +@interface {{classname}} () + +@property (nonatomic, strong, readwrite) NSMutableDictionary *defaultHeaders; + +@end + +@implementation {{classname}} + +NSString* k{{classname}}ErrorDomain = @"{{classname}}ErrorDomain"; +NSInteger k{{classname}}MissingParamErrorCode = 234513; + +@synthesize sessionManager = _sessionManager; + +#pragma mark - Initialize methods + +- (id)initWithSessionManager:({{classPrefix}}ApiSessionManager *)sessionManager { + self = [super init]; + if (self) { + _sessionManager = sessionManager; + _defaultHeaders = [NSMutableDictionary dictionary]; + } + + return self; +} + +#pragma mark - + +-(NSString*) defaultHeaderForKey:(NSString*)key { + return self.defaultHeaders[key]; +} + +-(void) addHeader:(NSString*)value forKey:(NSString*)key { + [self setDefaultHeaderValue:value forKey:key]; +} + +-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key { + [self.defaultHeaders setValue:value forKey:key]; +} + +#pragma mark - Api Methods + +{{#operation}} +/// +/// {{{summary}}} +/// {{{notes}}} +/// {{#allParams}} @param {{paramName}} {{{description}}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} +/// +/// {{/allParams}} @returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} +/// +-(NSURLSessionTask*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} + {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}} + {{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler { + {{#allParams}} + {{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == nil) { + NSParameterAssert({{paramName}}); + if(handler) { + NSDictionary * userInfo = @{NSLocalizedDescriptionKey : [NSString stringWithFormat:NSLocalizedString(@"Missing required parameter '%@'", nil),@"{{paramName}}"] }; + NSError* error = [NSError errorWithDomain:k{{classname}}ErrorDomain code:k{{classname}}MissingParamErrorCode userInfo:userInfo]; + handler({{#returnType}}nil, {{/returnType}}error); + } + return nil; + } + + {{/required}} + {{/allParams}} + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"{{path}}"]; + + // remove format in URL if needed + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + {{#pathParams}} + if ({{paramName}} != nil) { + pathParams[@"{{baseName}}"] = {{paramName}}; + } + {{/pathParams}} + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + {{#queryParams}} + if ({{paramName}} != nil) { + {{#collectionFormat}} + queryParams[@"{{baseName}}"] = [[{{classPrefix}}QueryParamCollection alloc] initWithValuesAndFormat: {{paramName}} format: @"{{collectionFormat}}"]; + {{/collectionFormat}} + {{^collectionFormat}}queryParams[@"{{baseName}}"] = {{paramName}};{{/collectionFormat}} + } + {{/queryParams}} + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders]; + [headerParams addEntriesFromDictionary:self.defaultHeaders]; + {{#headerParams}} + if ({{paramName}} != nil) { + headerParams[@"{{baseName}}"] = {{paramName}}; + } + {{/headerParams}} + // HTTP header `Accept` + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[{{#produces}}@"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}}]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; + } + + // response content type + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; + + // request content type + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[{{#consumes}}@"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}]]; + + // Authentication setting + NSArray *authSettings = @[{{#authMethods}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; + + id bodyParam = nil; + NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; + {{#bodyParam}} + bodyParam = {{paramName}}; + {{/bodyParam}} + {{^bodyParam}} + {{#formParams}} + {{#notFile}} + if ({{paramName}}) { + formParams[@"{{baseName}}"] = {{paramName}}; + } + {{/notFile}} + {{#isFile}} + localVarFiles[@"{{paramName}}"] = {{paramName}}; + {{/isFile}} + {{/formParams}} + {{/bodyParam}} + + return [self.sessionManager requestWithPath: resourcePath + method: @"{{httpMethod}}" + pathParams: pathParams + queryParams: queryParams + formParams: formParams + files: localVarFiles + body: bodyParam + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + responseType: {{^returnType}}nil{{/returnType}}{{#returnType}}@"{{{ returnType }}}"{{/returnType}} + completionBlock: ^(id data, NSError *error) { + if(handler) { + handler({{#returnType}}({{{ returnType }}})data, {{/returnType}}error); + } + } + ]; +} + +{{/operation}} + +{{newline}} +{{/operations}} +@end diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/api-header.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/api-header.mustache new file mode 100644 index 00000000000..1b28b47c882 --- /dev/null +++ b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/api-header.mustache @@ -0,0 +1,34 @@ +#import +{{#imports}}#import "{{import}}.h" +{{/imports}} +#import "{{classPrefix}}ApiSessionManager.h" + +{{>licenceInfo}} + + +@interface {{classname}}: NSObject <{{classPrefix}}Api> + +extern NSString* k{{classname}}ErrorDomain; +extern NSInteger k{{classname}}MissingParamErrorCode; + ++(instancetype) sharedAPI; + +{{#operations}} +{{#operation}} +/// {{{summary}}} +/// {{#notes}}{{{notes}}}{{/notes}} +/// +/// {{#allParams}}@param {{paramName}} {{description}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} +/// {{/allParams}}{{#responses}} +/// code:{{{code}}} message:"{{{message}}}"{{#hasMore}},{{/hasMore}}{{/responses}} +/// +/// @return {{{returnType}}} +-(NSURLSessionTask*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} + {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}} + {{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler; + +{{newline}} +{{/operation}} +{{/operations}} + +@end diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/model-body.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/model-body.mustache new file mode 100644 index 00000000000..2a4a548458e --- /dev/null +++ b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/model-body.mustache @@ -0,0 +1,59 @@ +{{#models}} +{{#model}} +#import "{{classname}}.h" + +@implementation {{classname}} + +- (instancetype)init { + self = [super init]; + if (self) { + // initialize property's default value, if any + {{#vars}}{{#defaultValue}}self.{{name}} = {{{defaultValue}}}; + {{/defaultValue}}{{/vars}} + } + return self; +} +{{#vars}}{{^vendorExtensions.x-unique-id-key}}{{/vendorExtensions.x-unique-id-key}}{{#vendorExtensions.x-unique-id-key}} +-(NSString*)indexPropertyName { + return @"{{name}}"; +} +{{/vendorExtensions.x-unique-id-key}}{{/vars}} +{{#discriminator}} +/** + * Maps "discriminator" value to the sub-class name, so that inheritance is supported. + */ +- (id)initWithDictionary:(NSDictionary *)dict error:(NSError *__autoreleasing *)err { + NSString * discriminatedClassName = [dict valueForKey:@"{{discriminator}}"]; + if(discriminatedClassName == nil ){ + return [super initWithDictionary:dict error:err]; + } + Class class = NSClassFromString([@"{{classPrefix}}" stringByAppendingString:discriminatedClassName]); + if([self class ] == class) { + return [super initWithDictionary:dict error:err]; + } + return [[class alloc] initWithDictionary:dict error: err]; +} +{{/discriminator}} + +/** + * Maps json key to property name. + * This method is used by `JSONModel`. + */ ++ (JSONKeyMapper *)keyMapper { + return [[JSONKeyMapper alloc] initWithDictionary:@{ {{#vars}}@"{{baseName}}": @"{{name}}"{{#hasMore}}, {{/hasMore}}{{/vars}} }]; +} + +/** + * Indicates whether the property with the given name is optional. + * If `propertyName` is optional, then return `YES`, otherwise return `NO`. + * This method is used by `JSONModel`. + */ ++ (BOOL)propertyIsOptional:(NSString *)propertyName { + + NSArray *optionalProperties = @[{{#vars}}{{^required}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/required}}{{/vars}}]; + return [optionalProperties containsObject:propertyName]; +} + +{{/model}} +@end +{{/models}} diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/model-header.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/model-header.mustache new file mode 100644 index 00000000000..04570e71a2f --- /dev/null +++ b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/model-header.mustache @@ -0,0 +1,25 @@ +#import +#import "{{classPrefix}}Object.h" + +{{>licenceInfo}} + +{{#imports}}#import "{{import}}.h" +{{/imports}} +{{newline}} +{{#models}} +{{#model}} + +@protocol {{classname}} +@end + +@interface {{classname}} : {{#parent}}{{{parent}}}{{/parent}}{{^parent}}{{classPrefix}}Object{{/parent}} + +{{#vars}} +{{#description}}/* {{{description}}} {{^required}}[optional]{{/required}} + */{{/description}} +@property(nonatomic) {{{ datatype }}} {{name}}; +{{/vars}} + +@end +{{/model}} +{{/models}} diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/podspec.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/podspec.mustache new file mode 100644 index 00000000000..bd0bd9f328e --- /dev/null +++ b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/podspec.mustache @@ -0,0 +1,37 @@ +# +# Be sure to run `pod lib lint {{podName}}.podspec' to ensure this is a +# valid spec and remove all comments before submitting the spec. +# +# Any lines starting with a # are optional, but encouraged +# +# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html +# + +Pod::Spec.new do |s| + s.name = "{{podName}}" + s.version = "{{podVersion}}" +{{#apiInfo}}{{#apis}}{{^hasMore}} + s.summary = "{{appName}}" + s.description = <<-DESC + {{{appDescription}}} + DESC +{{/hasMore}}{{/apis}}{{/apiInfo}} + s.platform = :ios, '7.0' + s.requires_arc = true + + {{^useCoreData}}s.framework = 'SystemConfiguration'{{/useCoreData}}{{#useCoreData}}s.frameworks = 'SystemConfiguration', 'CoreData'{{/useCoreData}} + + s.homepage = "{{gitRepoURL}}" + s.license = "{{#license}}{{license}}{{/license}}{{^license}}Apache License, Version 2.0{{/license}}" + s.source = { :git => "{{gitRepoURL}}.git", :tag => "#{s.version}" } + s.author = { "{{authorName}}" => "{{authorEmail}}" } + + s.source_files = '{{podName}}/**/*.{m,h}' + s.public_header_files = '{{podName}}/**/*.h' +{{#useCoreData}} s.resources = '{{podName}}/**/*.{xcdatamodeld,xcdatamodel}'{{/useCoreData}} + + s.dependency 'AFNetworking', '~> 3' + s.dependency 'JSONModel', '~> 1.2' + s.dependency 'ISO8601', '~> 0.5' +end + diff --git a/output/objcSessionManager_old/README.md b/output/objcSessionManager_old/README.md new file mode 100644 index 00000000000..2bd0d9b256e --- /dev/null +++ b/output/objcSessionManager_old/README.md @@ -0,0 +1,74 @@ +# Swagger Codegen for the ObjcSessionManager library + +## Overview +This is a boiler-plate project to generate your own client library with Swagger. It's goal is +to get you started with the basic plumbing so you can put in your own logic. It won't work without +your changes applied. + +## What's Swagger? +The goal of Swagger™ is to define a standard, language-agnostic interface to REST APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined via Swagger, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. Similar to what interfaces have done for lower-level programming, Swagger removes the guesswork in calling the service. + + +Check out [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) for additional information about the Swagger project, including additional libraries with support for other languages and more. + +## How do I use this? +At this point, you've likely generated a client setup. It will include something along these lines: + +``` +. +|- README.md // this file +|- pom.xml // build script +|-- src +|--- main +|---- java +|----- io.swagger.codegen.languages.ObjcsessionmanagerGenerator.java // generator file +|---- resources +|----- ObjcSessionManager // template files +|----- META-INF +|------ services +|------- io.swagger.codegen.CodegenConfig +``` + +You _will_ need to make changes in at least the following: + +`ObjcsessionmanagerGenerator.java` + +Templates in this folder: + +`src/main/resources/ObjcSessionManager` + +Once modified, you can run this: + +``` +mvn package +``` + +In your generator project. A single jar file will be produced in `target`. You can now use that with codegen: + +``` +java -cp /path/to/swagger-codegen-distribution:/path/to/your/jar io.swagger.codegen.Codegen -l ObjcSessionManager -o ./test +``` + +Now your templates are available to the client generator and you can write output values + +## But how do I modify this? +The `ObjcsessionmanagerGenerator.java` has comments in it--lots of comments. There is no good substitute +for reading the code more, though. See how the `ObjcsessionmanagerGenerator` implements `CodegenConfig`. +That class has the signature of all values that can be overridden. + +For the templates themselves, you have a number of values available to you for generation. +You can execute the `java` command from above while passing different debug flags to show +the object you have available during client generation: + +``` +# The following additional debug options are available for all codegen targets: +# -DdebugSwagger prints the OpenAPI Specification as interpreted by the codegen +# -DdebugModels prints models passed to the template engine +# -DdebugOperations prints operations passed to the template engine +# -DdebugSupportingFiles prints additional data passed to the template engine + +java -DdebugOperations -cp /path/to/swagger-codegen-distribution:/path/to/your/jar io.swagger.codegen.Codegen -l ObjcSessionManager -o ./test +``` + +Will, for example, output the debug info for operations. You can use this info +in the `api.mustache` file. \ No newline at end of file diff --git a/output/objcSessionManager_old/pom.xml b/output/objcSessionManager_old/pom.xml new file mode 100644 index 00000000000..6ec6fe8a8fb --- /dev/null +++ b/output/objcSessionManager_old/pom.xml @@ -0,0 +1,102 @@ + + 4.0.0 + io.swagger + ObjcSessionManager-swagger-codegen + jar + ObjcSessionManager-swagger-codegen + 1.0.0 + + 2.2.0 + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + + + 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-codegen + ${swagger-codegen-version} + provided + + + + 2.1.5 + 1.0.0 + 4.8.1 + + diff --git a/output/objcSessionManager_old/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerClientCodegen.java b/output/objcSessionManager_old/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerClientCodegen.java new file mode 100644 index 00000000000..4fd59986fb7 --- /dev/null +++ b/output/objcSessionManager_old/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerClientCodegen.java @@ -0,0 +1,750 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.ArrayModel; +import io.swagger.models.Model; +import io.swagger.models.properties.*; + +import java.io.File; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.lang3.StringUtils; + +public class ObjcSessionManagerClientCodegen extends DefaultCodegen implements CodegenConfig { + public static final String CLASS_PREFIX = "classPrefix"; + public static final String POD_NAME = "podName"; + public static final String AUTHOR_NAME = "authorName"; + public static final String AUTHOR_EMAIL = "authorEmail"; + public static final String LICENSE = "license"; + public static final String GIT_REPO_URL = "gitRepoURL"; + public static final String DEFAULT_LICENSE = "Apache License, Version 2.0"; + public static final String CORE_DATA = "coreData"; + + protected Set foundationClasses = new HashSet(); + protected String podName = "SwaggerClient"; + protected String podVersion = "1.0.0"; + protected String classPrefix = "SWG"; + protected String authorName = "Swagger"; + protected String authorEmail = "apiteam@swagger.io"; + protected String license = DEFAULT_LICENSE; + protected String gitRepoURL = "https://github.com/swagger-api/swagger-codegen"; + protected String[] specialWords = {"new", "copy"}; + protected String apiDocPath = "docs/"; + protected String modelDocPath = "docs/"; + protected String modelFilesPath = "Model/"; + protected String coreFilesPath = "Core/"; + protected String apiFilesPath = "Api/"; + + protected boolean generateCoreData = false; + + protected Set advancedMapingTypes = new HashSet(); + + public ObjcSessionManagerClientCodegen() { + super(); + + outputFolder = "generated-code" + File.separator + "objcSessionManager"; + modelTemplateFiles.put("model-header.mustache", ".h"); + modelTemplateFiles.put("model-body.mustache", ".m"); + apiTemplateFiles.put("api-header.mustache", ".h"); + apiTemplateFiles.put("api-body.mustache", ".m"); + embeddedTemplateDir = templateDir = "objcSessionManager"; + modelDocTemplateFiles.put("model_doc.mustache", ".md"); + apiDocTemplateFiles.put("api_doc.mustache", ".md"); + + defaultIncludes.clear(); + defaultIncludes.add("bool"); + defaultIncludes.add("BOOL"); + defaultIncludes.add("int"); + defaultIncludes.add("NSURL"); + defaultIncludes.add("NSString"); + defaultIncludes.add("NSObject"); + defaultIncludes.add("NSArray"); + defaultIncludes.add("NSNumber"); + defaultIncludes.add("NSDate"); + defaultIncludes.add("NSDictionary"); + defaultIncludes.add("NSMutableArray"); + defaultIncludes.add("NSMutableDictionary"); + defaultIncludes.add("NSManagedObject"); + defaultIncludes.add("NSData"); + + advancedMapingTypes.add("NSDictionary"); + advancedMapingTypes.add("NSArray"); + advancedMapingTypes.add("NSMutableArray"); + advancedMapingTypes.add("NSMutableDictionary"); + advancedMapingTypes.add("NSObject"); + advancedMapingTypes.add("NSNumber"); + advancedMapingTypes.add("NSURL"); + advancedMapingTypes.add("NSString"); + advancedMapingTypes.add("NSDate"); + + languageSpecificPrimitives.clear(); + languageSpecificPrimitives.add("NSNumber"); + languageSpecificPrimitives.add("NSString"); + languageSpecificPrimitives.add("NSObject"); + languageSpecificPrimitives.add("NSDate"); + languageSpecificPrimitives.add("NSData"); + languageSpecificPrimitives.add("NSURL"); + languageSpecificPrimitives.add("bool"); + languageSpecificPrimitives.add("BOOL"); + + typeMapping.clear(); + typeMapping.put("enum", "NSString"); + typeMapping.put("date", "NSDate"); + typeMapping.put("datetime", "NSDate"); + typeMapping.put("boolean", "NSNumber"); + typeMapping.put("string", "NSString"); + typeMapping.put("integer", "NSNumber"); + typeMapping.put("int", "NSNumber"); + typeMapping.put("float", "NSNumber"); + typeMapping.put("long", "NSNumber"); + typeMapping.put("double", "NSNumber"); + typeMapping.put("array", "NSArray"); + typeMapping.put("map", "NSDictionary"); + typeMapping.put("number", "NSNumber"); + typeMapping.put("bigdecimal", "NSNumber"); + typeMapping.put("List", "NSArray"); + typeMapping.put("object", "NSObject"); + typeMapping.put("file", "NSURL"); + typeMapping.put("binary", "NSData"); + typeMapping.put("bytearray", "NSData"); + typeMapping.put("byte", "NSData"); + typeMapping.put("uuid", "NSString"); + typeMapping.put("password", "NSString"); + + // ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm + setReservedWordsLowerCase( + Arrays.asList( + // local variable names in API methods (endpoints) + "resourcePath", "pathParams", "queryParams", "headerParams", + "responseContentType", "requestContentType", "authSettings", + "formParams", "localVarFiles", "bodyParam", + // objc reserved words + "auto", "else", "long", "switch", + "break", "enum", "register", "typedef", + "case", "extern", "return", "union", + "char", "float", "short", "unsigned", + "const", "for", "signed", "void", + "continue", "goto", "sizeof", "volatile", + "default", "if", "id", "static", "while", + "do", "int", "struct", "_Packed", + "double", "protocol", "interface", "implementation", + "NSObject", "NSInteger", "NSNumber", "CGFloat", + "property", "nonatomic", "retain", "strong", + "weak", "unsafe_unretained", "readwrite", "readonly", + "description" + )); + + importMapping = new HashMap(); + + foundationClasses = new HashSet( + Arrays.asList( + "NSNumber", + "NSObject", + "NSString", + "NSDate", + "NSData", + "NSURL", + "NSDictionary") + ); + + instantiationTypes.put("array", "NSMutableArray"); + instantiationTypes.put("map", "NSMutableDictionary"); + + cliOptions.clear(); + cliOptions.add(new CliOption(CORE_DATA, "Should generate core data models").defaultValue("false")); + cliOptions.add(new CliOption(CLASS_PREFIX, "prefix for generated classes (convention: Abbreviation of pod name e.g. `HN` for `HackerNews`).`") + .defaultValue("SWG")); + cliOptions.add(new CliOption(POD_NAME, "cocoapods package name (convention: CameCase).") + .defaultValue("SwaggerClient")); + cliOptions.add(new CliOption(CodegenConstants.POD_VERSION, "cocoapods package version.") + .defaultValue("1.0.0")); + cliOptions.add(new CliOption(AUTHOR_NAME, "Name to use in the podspec file.").defaultValue("Swagger")); + cliOptions.add(new CliOption(AUTHOR_EMAIL, "Email to use in the podspec file.").defaultValue("apiteam@swagger.io")); + cliOptions.add(new CliOption(GIT_REPO_URL, "URL for the git repo where this podspec should point to.") + .defaultValue("https://github.com/swagger-api/swagger-codegen")); + } + + @Override + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + @Override + public String getName() { + return "objc"; + } + + @Override + public String getHelp() { + return "Generates an Objective-C client library."; + } + + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey(POD_NAME)) { + setPodName((String) additionalProperties.get(POD_NAME)); + } + + if (additionalProperties.containsKey(CodegenConstants.POD_VERSION)) { + setPodVersion((String) additionalProperties.get(CodegenConstants.POD_VERSION)); + } + + if (additionalProperties.containsKey(CORE_DATA)) { + Object coreData = additionalProperties.get(CORE_DATA); + if(((String)coreData).equalsIgnoreCase("true")) { + generateCoreData = true; + } + } + if (additionalProperties.containsKey(CLASS_PREFIX)) { + setClassPrefix((String) additionalProperties.get(CLASS_PREFIX)); + } + + if (additionalProperties.containsKey(AUTHOR_NAME)) { + setAuthorName((String) additionalProperties.get(AUTHOR_NAME)); + } + + if (additionalProperties.containsKey(AUTHOR_EMAIL)) { + setAuthorEmail((String) additionalProperties.get(AUTHOR_EMAIL)); + } + + if (additionalProperties.containsKey(GIT_REPO_URL)) { + setGitRepoURL((String) additionalProperties.get(GIT_REPO_URL)); + } + + if(generateCoreData) { + modelTemplateFiles.put("NSManagedObject-header.mustache", "ManagedObject.h"); + modelTemplateFiles.put("NSManagedObject-body.mustache", "ManagedObject.m"); + modelTemplateFiles.put("NSManagedObjectBuilder-header.mustache", "ManagedObjectBuilder.h"); + modelTemplateFiles.put("NSManagedObjectBuilder-body.mustache", "ManagedObjectBuilder.m"); + } + + additionalProperties.put(POD_NAME, podName); + additionalProperties.put(CodegenConstants.POD_VERSION, podVersion); + additionalProperties.put(CLASS_PREFIX, classPrefix); + additionalProperties.put(AUTHOR_NAME, authorName); + additionalProperties.put(AUTHOR_EMAIL, authorEmail); + additionalProperties.put(GIT_REPO_URL, gitRepoURL); + additionalProperties.put(LICENSE, license); + + // make api and model doc path available in mustache template + additionalProperties.put("apiDocPath", apiDocPath); + additionalProperties.put("modelDocPath", modelDocPath); + additionalProperties.put("useCoreData", generateCoreData); + + modelPackage = podName; + apiPackage = podName; + + supportingFiles.add(new SupportingFile("Object-header.mustache", coreFileFolder(), classPrefix + "Object.h")); + supportingFiles.add(new SupportingFile("Object-body.mustache", coreFileFolder(), classPrefix + "Object.m")); + supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.h")); + supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.m")); + supportingFiles.add(new SupportingFile("ApiClient-header.mustache", coreFileFolder(), classPrefix + "ApiClient.h")); // !! + supportingFiles.add(new SupportingFile("ApiClient-body.mustache", coreFileFolder(), classPrefix + "ApiClient.m")); // !! + supportingFiles.add(new SupportingFile("JSONResponseSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.h")); + supportingFiles.add(new SupportingFile("JSONResponseSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.m")); + supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.m")); + supportingFiles.add(new SupportingFile("JSONRequestSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.h")); + supportingFiles.add(new SupportingFile("ResponseDeserializer-body.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.m")); // !! + supportingFiles.add(new SupportingFile("ResponseDeserializer-header.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.h")); // !! + supportingFiles.add(new SupportingFile("Sanitizer-body.mustache", coreFileFolder(), classPrefix + "Sanitizer.m")); // !! + supportingFiles.add(new SupportingFile("Sanitizer-header.mustache", coreFileFolder(), classPrefix + "Sanitizer.h")); // !! + supportingFiles.add(new SupportingFile("Logger-body.mustache", coreFileFolder(), classPrefix + "Logger.m")); // !! + supportingFiles.add(new SupportingFile("Logger-header.mustache", coreFileFolder(), classPrefix + "Logger.h")); // !! + supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-body.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.m")); + supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-header.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.h")); + supportingFiles.add(new SupportingFile("Configuration-body.mustache", coreFileFolder(), classPrefix + "Configuration.m")); // !! + supportingFiles.add(new SupportingFile("Configuration-header.mustache", coreFileFolder(), classPrefix + "Configuration.h")); // !! + supportingFiles.add(new SupportingFile("api-protocol.mustache", coreFileFolder(), classPrefix + "Api.h")); // !! + supportingFiles.add(new SupportingFile("podspec.mustache", "", podName + ".podspec")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); // !! + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); // !! + + if(generateCoreData) { + supportingFiles.add(new SupportingFile("xccurrentversion.mustache", (modelPackage() + "/" + modelFilesPath + "/").replace("/", File.separator) + classPrefix + "Model.xcdatamodeld", ".xccurrentversion")); + supportingFiles.add(new SupportingFile("Model.xcdatamodel.mustache",(modelPackage() + "/" + modelFilesPath + "/").replace("/", File.separator) + classPrefix + "Model.xcdatamodeld" + File.separator + classPrefix + "Model.xcdatamodel", "contents")); + } + + // is apiclient + //supportingFiles.add(new SupportingFile("ApiSessionManager-header.mustache", swaggerFolder, classPrefix + "ApiSessionManager.h")); + //supportingFiles.add(new SupportingFile("ApiSessionManager-body.mustache", swaggerFolder, classPrefix + "ApiSessionManager.m")); + + // protocol! + //supportingFiles.add(new SupportingFile("Configuration-protocol.mustache", swaggerFolder, classPrefix + "Configuration.h")); + //supportingFiles.add(new SupportingFile("DefaultConfiguration-body.mustache", swaggerFolder, classPrefix + "DefaultConfiguration.m")); + //supportingFiles.add(new SupportingFile("DefaultConfiguration-header.mustache", swaggerFolder, classPrefix + "DefaultConfiguration.h")); + + // missing! + //supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-header.mustache", swaggerFolder, classPrefix + "BasicAuthTokenProvider.h")); + //supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-body.mustache", swaggerFolder, classPrefix + "BasicAuthTokenProvider.m")); + } + + @Override + public String toInstantiationType(Property p) { + if (p instanceof MapProperty) { + return instantiationTypes.get("map"); + } else if (p instanceof ArrayProperty) { + return instantiationTypes.get("array"); + } else { + return null; + } + } + + @Override + public String getTypeDeclaration(String name) { + if (languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name)) { + return name; + } else { + return name + "*"; + } + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType.toLowerCase())) { + type = typeMapping.get(swaggerType.toLowerCase()); + if (languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type)) { + return toModelNameWithoutReservedWordCheck(type); + } + } else { + type = swaggerType; + } + return toModelNameWithoutReservedWordCheck(type); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + String innerTypeDeclaration = getTypeDeclaration(inner); + if (innerTypeDeclaration.endsWith("*")) { + innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); + } + // In this condition, type of property p is array of primitive, + // return container type with pointer, e.g. `NSArray**' + if (languageSpecificPrimitives.contains(innerTypeDeclaration)) { + return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*"; + } + // In this condition, type of property p is array of model, + // return container type combine inner type with pointer, e.g. `NSArray*' + else { + for (String sd : advancedMapingTypes) { + if(innerTypeDeclaration.startsWith(sd)) { + return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*"; + } + } + return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*"; + } + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + String innerTypeDeclaration = getTypeDeclaration(inner); + + if (innerTypeDeclaration.endsWith("*")) { + innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); + } + if (languageSpecificPrimitives.contains(innerTypeDeclaration)) { + return getSwaggerType(p) + "*"; + } else { + for (String s : advancedMapingTypes) { + if(innerTypeDeclaration.startsWith(s)) { + return getSwaggerType(p) + "*"; + } + } + return getSwaggerType(p) + "*"; + } + } else { + String swaggerType = getSwaggerType(p); + // In this condition, type of p is objective-c primitive type, e.g. `NSSNumber', + // return type of p with pointer, e.g. `NSNumber*' + if (languageSpecificPrimitives.contains(swaggerType) && + foundationClasses.contains(swaggerType)) { + return swaggerType + "*"; + } + // In this condition, type of p is c primitive type, e.g. `bool', + // return type of p, e.g. `bool' + else if (languageSpecificPrimitives.contains(swaggerType)) { + return swaggerType; + } + // In this condition, type of p is objective-c object type, e.g. `SWGPet', + // return type of p with pointer, e.g. `SWGPet*' + else { + return swaggerType + "*"; + } + } + } + + @Override + public boolean isDataTypeBinary(String dataType) { + return dataType.toLowerCase().startsWith("nsdata"); + } + + @Override + public String toModelName(String type) { + // model name cannot use reserved keyword + if (reservedWords.contains(type)) { + LOGGER.warn(type+ " (reserved word) cannot be used as model name. Renamed to " + ("model_" + type) + " before further processing"); + type = "model_" + type; // e.g. return => ModelReturn (after camelize) + } + + // model name starts with number + /* no need for the fix below as objc model starts with prefix (e.g. SWG) + if (type.matches("^\\d.*")) { + LOGGER.warn(type + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + type)); + type = "model_" + type; // e.g. 200Response => Model200Response (after camelize) + } + */ + + return toModelNameWithoutReservedWordCheck(type); + } + + /* + * Convert input to proper model name according to ObjC style guide + * without checking for reserved words + * + * @param type Model anme + * @return model Name in ObjC style guide + */ + public String toModelNameWithoutReservedWordCheck(String type) { + type = type.replaceAll("[^0-9a-zA-Z_]", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + + // language build-in classes + if (typeMapping.keySet().contains(type) || + foundationClasses.contains(type) || + importMapping.values().contains(type) || + defaultIncludes.contains(type) || + languageSpecificPrimitives.contains(type)) { + return camelize(type); + } + // custom classes + else { + if (!StringUtils.isEmpty(modelNameSuffix)) { // set model suffix + type = type + "_" + modelNameSuffix; + } + + if (!StringUtils.isEmpty(modelNamePrefix)) { // set model prefix + type = modelNamePrefix + "_" + type; + } + + return classPrefix + camelize(type); // add class prefix + } + } + + @Override + public String toModelFilename(String name) { + // should be the same as the model name + return toModelName(name); + } + + @Override + protected void setNonArrayMapProperty(CodegenProperty property, String type) { + super.setNonArrayMapProperty(property, type); + if ("NSDictionary".equals(type)) { + property.setter = "initWithDictionary"; + } else { + property.setter = "initWithValues"; + } + } + + @Override + public String toModelImport(String name) { + return name; + } + + @Override + public String apiDocFileFolder() { + return (outputFolder + "/" + apiDocPath).replace("/", File.separator); + } + + @Override + public String modelDocFileFolder() { + return (outputFolder + "/" + modelDocPath).replace("/", File.separator); + } + + @Override + public String toModelDocFilename(String name) { + return toModelName(name); + } + + @Override + public String toApiDocFilename(String name) { + return toApiName(name); + } + + @Override + public String apiFileFolder() { + return (outputFolder + "/"+ apiPackage() + "/" + apiFilesPath).replace("/", File.separator); + } + + @Override + public String modelFileFolder() { + return (outputFolder + "/"+ modelPackage() + "/" + modelFilesPath).replace("/", File.separator); + } + + public String coreFileFolder() { + return (apiPackage() + "/" + coreFilesPath).replace("/", File.separator); + } + + @Override + public String toApiName(String name) { + return classPrefix + camelize(name) + "Api"; + } + + @Override + public String toApiFilename(String name) { + return classPrefix + camelize(name) + "Api"; + } + + @Override + public String toVarName(String name) { + // sanitize name + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + + // if it's all upper case, do noting + if (name.matches("^[A-Z_]$")) { + return name; + } + + // if name starting with special word, escape with '_' + for(int i =0; i < specialWords.length; i++) { + if (name.matches("(?i:^" + specialWords[i] + ".*)")) + name = escapeSpecialWord(name); + } + + // camelize (lower first character) the variable name + // e.g. `pet_id` to `petId` + name = camelize(name, true); + + // for reserved word or word starting with number, prepend `_` + if (isReservedWord(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } + + + return name; + } + + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @SuppressWarnings("static-method") + public String escapeSpecialWord(String name) { + return "var_" + name; + } + + @Override + public String toOperationId(String operationId) { + // throw exception if method name is empty + if (StringUtils.isEmpty(operationId)) { + throw new RuntimeException("Empty method name (operationId) not allowed"); + } + + // method name cannot use reserved keyword, e.g. return + if (isReservedWord(operationId)) { + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId), true)); + operationId = "call_" + operationId; + } + + return camelize(sanitizeName(operationId), true); + } + + public void setClassPrefix(String classPrefix) { + this.classPrefix = classPrefix; + } + + public void setPodName(String podName) { + this.podName = podName; + } + + public void setPodVersion(String podVersion) { + this.podVersion = podVersion; + } + + public void setAuthorEmail(String authorEmail) { + this.authorEmail = authorEmail; + } + + public void setAuthorName(String authorName) { + this.authorName = authorName; + } + + public void setGitRepoURL(String gitRepoURL) { + this.gitRepoURL = gitRepoURL; + } + + public void setLicense(String license) { + this.license = license; + } + + @Override + public Map postProcessOperations(Map objs) { + Map operations = (Map) objs.get("operations"); + if (operations != null) { + List ops = (List) operations.get("operation"); + for (CodegenOperation operation : ops) { + if (!operation.allParams.isEmpty()) { + String firstParamName = operation.allParams.get(0).paramName; + operation.vendorExtensions.put("firstParamAltName", camelize(firstParamName)); + } + } + } + return objs; + } + + @Override + public void postProcessModelProperty(CodegenModel model, CodegenProperty property){ + super.postProcessModelProperty(model,property); + property.vendorExtensions.put("x-uppercaseName", camelize(property.name)); + } + + /** + * 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; + } + + @Override + public void setParameterExampleValue(CodegenParameter p) { + String example; + + if (p.defaultValue == null) { + example = p.example; + } else { + example = p.defaultValue; + } + + String type = p.baseType; + if (type == null) { + type = p.dataType; + } + + if ("NSString*".equalsIgnoreCase(type)) { + if (example == null) { + example = p.paramName + "_example"; + } + example = "@\"" + escapeText(example) + "\""; + } else if ("NSNumber*".equals(type)) { + if (example == null) { + example = "56"; + } + example = "@" + example; + /* OBJC uses NSNumber to represent both int, long, double and float + } else if ("Float".equalsIgnoreCase(type) || "Double".equalsIgnoreCase(type)) { + if (example == null) { + example = "3.4"; + } */ + } else if ("BOOLEAN".equalsIgnoreCase(type) || "bool".equalsIgnoreCase(type)) { + if (example == null) { + example = "True"; + } + } else if ("NSURL*".equalsIgnoreCase(type)) { + if (example == null) { + example = "/path/to/file"; + } + //[NSURL fileURLWithPath:@"path/to/file"] + example = "[NSURL fileURLWithPath:@\"" + escapeText(example) + "\"]"; + /*} else if ("NSDate".equalsIgnoreCase(type)) { + if (example == null) { + example = "2013-10-20"; + } + example = "'" + escapeText(example) + "'";*/ + } else if ("NSDate*".equalsIgnoreCase(type)) { + if (example == null) { + example = "2013-10-20T19:20:30+01:00"; + } + example = "@\"" + escapeText(example) + "\""; + } else if (!languageSpecificPrimitives.contains(type)) { + // type is a model class, e.g. User + type = type.replace("*", ""); + // e.g. [[SWGPet alloc] init + example = "[[" + type + " alloc] init]"; + } else { + LOGGER.warn("Type " + type + " not handled properly in setParameterExampleValue"); + } + + if (example == null) { + example = "NULL"; + } else if (Boolean.TRUE.equals(p.isListContainer)) { + example = "@[" + example + "]"; + } else if (Boolean.TRUE.equals(p.isMapContainer)) { + example = "@{@\"key\" : " + example + "}"; + } + + p.example = example; + } + + @Override + public String escapeQuotationMark(String input) { + // remove " to avoid code injection + return input.replace("\"", ""); + } + + @Override + public String escapeUnsafeCharacters(String input) { + return input.replace("*/", "*_/").replace("/*", "/_*"); + } + +} diff --git a/output/objcSessionManager_old/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/output/objcSessionManager_old/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig new file mode 100644 index 00000000000..e3cfa53811b --- /dev/null +++ b/output/objcSessionManager_old/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig @@ -0,0 +1 @@ +io.swagger.codegen.languages.ObjcSessionManagerClientCodegen \ No newline at end of file diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache new file mode 100644 index 00000000000..5e5ad41e2df --- /dev/null +++ b/output/objcSessionManager_old/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache @@ -0,0 +1,461 @@ +#import + +#import "{{classPrefix}}ApiSessionManager.h" +#import "{{classPrefix}}JSONRequestSerializer.h" +#import "{{classPrefix}}JSONResponseSerializer.h" +#import "{{classPrefix}}QueryParamCollection.h" +#import "{{classPrefix}}Object.h" +#import "{{classPrefix}}DefaultConfiguration.h" + + +NSString * const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}ResponseObject"; + + +static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) { + NSDictionary * headers = {{classPrefix}}__headerFieldsForResponse(response); + if(!headers[@"Content-Disposition"]) { + return [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]]; + } + NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?"; + NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern + options:NSRegularExpressionCaseInsensitive + error:nil]; + NSString *contentDispositionHeader = headers[@"Content-Disposition"]; + NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader + options:0 + range:NSMakeRange(0, [contentDispositionHeader length])]; + return [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]]; +} + + +@interface {{classPrefix}}ApiSessionManager () + +@property (nonatomic, strong, readwrite) id<{{classPrefix}}Configuration> configuration; + +@end + +@implementation {{classPrefix}}ApiSessionManager + +- (instancetype)init { + + return [self initWithConfiguration:[{{classPrefix}}DefaultConfiguration sharedConfiguration]]; +} + +- (instancetype)initWithBaseURL:(NSURL *)url { + + return [self initWithBaseURL:url + configuration:[{{classPrefix}}DefaultConfiguration sharedConfiguration]]; + +} + +- (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration { + + return [self initWithBaseURL:[NSURL URLWithString:configuration.host] configuration:configuration]; +} + +- (instancetype)initWithBaseURL:(NSURL *)url + configuration:(id<{{classPrefix}}Configuration>)configuration { + + self = [super initWithBaseURL:url]; + if (self) { + _configuration = configuration; + } + + return self; +} + +#pragma mark - Setter Methods + ++ (void) setOfflineState:(BOOL) state { + offlineState = state; +} + ++ (void) setCacheEnabled:(BOOL)enabled { + cacheEnabled = enabled; +} + ++(void) setReachabilityStatus:(AFNetworkReachabilityStatus)status { + reachabilityStatus = status; +} + +- (void)setHeaderValue:(NSString*) value forKey:(NSString*) forKey { + [self.requestSerializer setValue:value forHTTPHeaderField:forKey]; +} + +- (void)setRequestSerializer:(AFHTTPRequestSerializer *)requestSerializer { + [super setRequestSerializer:requestSerializer]; + requestSerializer.timeoutInterval = self.timeoutInterval; +} + +#pragma mark - Cache Methods + ++(void)clearCache { + [[NSURLCache sharedURLCache] removeAllCachedResponses]; +} + ++(void)configureCacheWithMemoryAndDiskCapacity: (unsigned long) memorySize + diskSize: (unsigned long) diskSize { + NSAssert(memorySize > 0, @"invalid in-memory cache size"); + NSAssert(diskSize >= 0, @"invalid disk cache size"); + + NSURLCache *cache = + [[NSURLCache alloc] + initWithMemoryCapacity:memorySize + diskCapacity:diskSize + diskPath:@"swagger_url_cache"]; + + [NSURLCache setSharedURLCache:cache]; +} + +#pragma mark - Reachability Methods + ++(AFNetworkReachabilityStatus) getReachabilityStatus { + return reachabilityStatus; +} + ++(BOOL) getOfflineState { + return offlineState; +} + ++(void) setReachabilityChangeBlock:(void(^)(int))changeBlock { + reachabilityChangeBlock = changeBlock; +} + +- (void) configureCacheReachibility { + [self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { + reachabilityStatus = status; + {{classPrefix}}DebugLog(@"reachability changed to %@",AFStringFromNetworkReachabilityStatus(status)); + [{{classPrefix}}ApiClient setOfflineState:status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable]; + + // call the reachability block, if configured + if (reachabilityChangeBlock != nil) { + reachabilityChangeBlock(status); + } + }]; + + [self.reachabilityManager startMonitoring]; +} + +#pragma mark - Task Methods + +- (NSURLSessionDataTask*) taskWithCompletionBlock: (NSURLRequest *)request + completionBlock: (void (^)(id, NSError *))completionBlock { + + NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { + {{classPrefix}}DebugLogResponse(response, responseObject,request,error); + + if(!error) { + completionBlock(responseObject, nil); + return; + } + + NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; + if (responseObject) { + // Add in the (parsed) response body. + userInfo[{{classPrefix}}ResponseObjectErrorKey] = responseObject; + } + NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; + completionBlock(nil, augmentedError); + }]; + + return task; +} + +- (NSURLSessionDownloadTask*) downloadTaskWithCompletionBlock: (NSURLRequest *)request + completionBlock: (void (^)(id, NSError *))completionBlock { + + id<{{classPrefix}}Configuration> config = self.configuration; + + NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + {{classPrefix}}DebugLogResponse(response, responseObject,request,error); + + if(error) { + NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; + if (responseObject) { + userInfo[{{classPrefix}}ResponseObjectErrorKey] = responseObject; + } + NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; + completionBlock(nil, augmentedError); + } + + NSString *directory = config.tempFolderPath ?: NSTemporaryDirectory(); + NSString *filename = {{classPrefix}}__fileNameForResponse(response); + + NSString *filepath = [directory stringByAppendingPathComponent:filename]; + NSURL *file = [NSURL fileURLWithPath:filepath]; + + [responseObject writeToURL:file atomically:YES]; + + completionBlock(file, nil); + }]; + + return task; +} + +#pragma mark - Perform Request Methods + +- (NSURLSessionTask*) requestWithPath: (NSString*) path + method: (NSString*) method + pathParams: (NSDictionary *) pathParams + queryParams: (NSDictionary*) queryParams + formParams: (NSDictionary *) formParams + files: (NSDictionary *) files + body: (id) body + headerParams: (NSDictionary*) headerParams + authSettings: (NSArray *) authSettings + requestContentType: (NSString*) requestContentType + responseContentType: (NSString*) responseContentType + responseType: (NSString *) responseType + completionBlock: (void (^)(id, NSError *))completionBlock { + + // setting request serializer + if ([requestContentType isEqualToString:@"application/json"]) { + self.requestSerializer = [{{classPrefix}}JSONRequestSerializer serializer]; + } + else if ([requestContentType isEqualToString:@"application/x-www-form-urlencoded"]) { + self.requestSerializer = [AFHTTPRequestSerializer serializer]; + } + else if ([requestContentType isEqualToString:@"multipart/form-data"]) { + self.requestSerializer = [AFHTTPRequestSerializer serializer]; + } + else { + self.requestSerializer = [AFHTTPRequestSerializer serializer]; + NSAssert(NO, @"Unsupported request type %@", requestContentType); + } + + // setting response serializer + if ([responseContentType isEqualToString:@"application/json"]) { + self.responseSerializer = [{{classPrefix}}JSONResponseSerializer serializer]; + } else { + self.responseSerializer = [AFHTTPResponseSerializer serializer]; + } + + // sanitize parameters + pathParams = [self.sanitizer sanitizeForSerialization:pathParams]; + queryParams = [self.sanitizer sanitizeForSerialization:queryParams]; + headerParams = [self.sanitizer sanitizeForSerialization:headerParams]; + formParams = [self.sanitizer sanitizeForSerialization:formParams]; + if(![body isKindOfClass:[NSData class]]) { + body = [self.sanitizer sanitizeForSerialization:body]; + } + + // auth setting + [self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings]; + + NSMutableString *resourcePath = [NSMutableString stringWithString:path]; + [pathParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + NSString * safeString = ([obj isKindOfClass:[NSString class]]) ? obj : [NSString stringWithFormat:@"%@", obj]; + safeString = {{classPrefix}}PercentEscapedStringFromString(safeString); + [resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"{%@}", key]] withString:safeString]; + }]; + + NSMutableURLRequest * request = nil; + + NSString* pathWithQueryParams = [self pathWithQueryParamsToString:resourcePath queryParams:queryParams]; + if ([pathWithQueryParams hasPrefix:@"/"]) { + pathWithQueryParams = [pathWithQueryParams substringFromIndex:1]; + } + + NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString]; + if (files.count > 0) { + __weak __typeof(self)weakSelf = self; + request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" + URLString:urlString + parameters:nil + constructingBodyWithBlock:^(id formData) { + [formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + NSString *objString = [weakSelf.sanitizer parameterToString:obj]; + NSData *data = [objString dataUsingEncoding:NSUTF8StringEncoding]; + [formData appendPartWithFormData:data name:key]; + }]; + [files enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + NSURL *filePath = (NSURL *)obj; + [formData appendPartWithFileURL:filePath name:key error:nil]; + }]; + } error:nil]; + } + else { + if (formParams) { + request = [self.requestSerializer requestWithMethod:method + URLString:urlString + parameters:formParams + error:nil]; + } + if (body) { + request = [self.requestSerializer requestWithMethod:method + URLString:urlString + parameters:body + error:nil]; + } + } + + // request cache + BOOL hasHeaderParams = [headerParams count] > 0; + if (offlineState) { + {{classPrefix}}DebugLog(@"%@ cache forced", resourcePath); + [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; + } + else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { + {{classPrefix}}DebugLog(@"%@ cache enabled", resourcePath); + [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; + } + else { + {{classPrefix}}DebugLog(@"%@ cache disabled", resourcePath); + [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; + } + + if (hasHeaderParams){ + for(NSString * key in [headerParams keyEnumerator]){ + [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; + } + } + [self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"]; + + [self postProcessRequest:request]; + + + NSURLSessionTask *task = nil + + if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) { + task = [self downloadTaskWithCompletionBlock:request completionBlock:^(id data, NSError *error) { + completionBlock(data, error); + }]; + } + else { + [self taskWithCompletionBlock:request completionBlock:^(id data, NSError *error) { + NSError * serializationError; + id response = [self.responseDeserializer deserialize:data class:responseType error:&serializationError]; + if(!response && !error){ + error = serializationError; + } + completionBlock(response, error); + }]; + } + + [task resume]; + + return task; +} + +// Added for easier override to modify request +- (void)postProcessRequest:(NSMutableURLRequest *)request { + // Always disable cookies! + [request setHTTPShouldHandleCookies:NO]; +} + +#pragma mark - + +- (NSString*)pathWithQueryParamsToString:(NSString*) path + queryParams:(NSDictionary*) queryParams { + if(queryParams.count == 0) { + return path; + } + NSString * separator = nil; + NSUInteger counter = 0; + + NSMutableString * requestUrl = [NSMutableString stringWithFormat:@"%@", path]; + + NSDictionary *separatorStyles = @{@"csv" : @",", + @"tsv" : @"\t", + @"pipes": @"|" + }; + for(NSString * key in [queryParams keyEnumerator]){ + if (counter == 0) { + separator = @"?"; + } else { + separator = @"&"; + } + id queryParam = [queryParams valueForKey:key]; + if(!queryParam) { + continue; + } + NSString *safeKey = {{classPrefix}}PercentEscapedStringFromString(key); + if ([queryParam isKindOfClass:[NSString class]]){ + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, {{classPrefix}}PercentEscapedStringFromString(queryParam)]]; + + } else if ([queryParam isKindOfClass:[{{classPrefix}}QueryParamCollection class]]){ + {{classPrefix}}QueryParamCollection * coll = ({{classPrefix}}QueryParamCollection*) queryParam; + NSArray* values = [coll values]; + NSString* format = [coll format]; + + if([format isEqualToString:@"multi"]) { + for(id obj in values) { + if (counter > 0) { + separator = @"&"; + } + NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([NSString stringWithFormat:@"%@",obj]); + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; + counter += 1; + } + continue; + } + NSString * separatorStyle = separatorStyles[format]; + NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([values componentsJoinedByString:separatorStyle]); + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; + } else { + NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([NSString stringWithFormat:@"%@",queryParam]); + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; + } + counter += 1; + } + return requestUrl; +} + +/** + * Update header and query params based on authentication settings + */ +- (void) updateHeaderParams:(NSDictionary *__autoreleasing *)headers + queryParams:(NSDictionary *__autoreleasing *)querys + WithAuthSettings:(NSArray *)authSettings { + + if (!authSettings || [authSettings count] == 0) { + return; + } + + NSMutableDictionary *headersWithAuth = [NSMutableDictionary dictionaryWithDictionary:*headers]; + NSMutableDictionary *querysWithAuth = [NSMutableDictionary dictionaryWithDictionary:*querys]; + + id<{{classPrefix}}Configuration> config = self.configuration; + for (NSString *auth in authSettings) { + NSDictionary *authSetting = config.authSettings[auth]; + + if(!authSetting) { // auth setting is set only if the key is non-empty + continue; + } + + NSString *type = authSetting[@"in"]; + NSString *key = authSetting[@"key"]; + NSString *value = authSetting[@"value"]; + if ([type isEqualToString:@"header"] && [key length] > 0 ) { + headersWithAuth[key] = value; + } else if ([type isEqualToString:@"query"] && [key length] != 0) { + querysWithAuth[key] = value; + } + } + + *headers = [NSDictionary dictionaryWithDictionary:headersWithAuth]; + *querys = [NSDictionary dictionaryWithDictionary:querysWithAuth]; +} + +- (AFSecurityPolicy *) customSecurityPolicy { + AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; + + id<{{classPrefix}}Configuration> config = self.configuration; + + if (config.sslCaCert) { + NSData *certData = [NSData dataWithContentsOfFile:config.sslCaCert]; + [securityPolicy setPinnedCertificates:@[certData]]; + } + + if (config.verifySSL) { + [securityPolicy setAllowInvalidCertificates:NO]; + } + else { + [securityPolicy setAllowInvalidCertificates:YES]; + [securityPolicy setValidatesDomainName:NO]; + } + + return securityPolicy; +} + +@end diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/ApiSessionManager-header.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/ApiSessionManager-header.mustache new file mode 100644 index 00000000000..010966b14a5 --- /dev/null +++ b/output/objcSessionManager_old/src/main/resources/objcSessionManager/ApiSessionManager-header.mustache @@ -0,0 +1,147 @@ +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + +#import +#import "{{classPrefix}}Configuration.h" + +/** + * A key for `NSError` user info dictionaries. + * + * The corresponding value is the parsed response body for an HTTP error. + */ +extern NSString *const {{classPrefix}}ResponseObjectErrorKey; + + +@interface {{classPrefix}}ApiSessionManager : AFHTTPSessionManager + +@property (nonatomic, strong, readonly) id<{{classPrefix}}Configuration> configuration; + +@property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy; +@property(nonatomic, assign) NSTimeInterval timeoutInterval; +@property(nonatomic, readonly) NSOperationQueue* queue; + +@property(nonatomic, strong) id<{{classPrefix}}ResponseDeserializer> responseDeserializer; + +@property(nonatomic, strong) id<{{classPrefix}}Sanitizer> sanitizer; + +/** + * Clears Cache + */ ++(void)clearCache; + +/** + * Turns on cache + * + * @param enabled If the cached is enable, must be `YES` or `NO` + */ ++(void)setCacheEnabled:(BOOL) enabled; + +/** + * Sets the client unreachable + * + * @param state off line state, must be `YES` or `NO` + */ ++(void) setOfflineState:(BOOL) state; + +/** + * Gets if the client is unreachable + * + * @return The client offline state + */ ++(BOOL) getOfflineState; + +/** + * Sets the client reachability, this may be overridden by the reachability manager if reachability changes + * + * @param The client reachability. + */ ++(void) setReachabilityStatus:(AFNetworkReachabilityStatus) status; + +/** + * Gets the client reachability + * + * @return The client reachability. + */ ++(AFNetworkReachabilityStatus) getReachabilityStatus; + +/** + * Customizes the behavior when the reachability changed + * + * @param changeBlock The block will be executed when the reachability changed. + */ ++(void) setReachabilityChangeBlock:(void(^)(int))changeBlock; + +/** + * Sets the api client reachability strategy + */ +- (void)configureCacheReachibility; + +/** + * Sets header for request + * + * @param value The header value + * @param forKey The header key + */ +-(void)setHeaderValue:(NSString*) value + forKey:(NSString*) forKey; + +/** + * Updates header parameters and query parameters for authentication + * + * @param headers The header parameter will be udpated, passed by pointer to pointer. + * @param querys The query parameters will be updated, passed by pointer to pointer. + * @param authSettings The authentication names NSArray. + */ +- (void) updateHeaderParams:(NSDictionary **)headers + queryParams:(NSDictionary **)querys + WithAuthSettings:(NSArray *)authSettings; + + +/** + * Initializes the session manager with a configuration. + * + * @param configuration The configuration implementation + */ +- (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration; + +/** + * Performs request + * + * @param path Request url. + * @param method Request method. + * @param pathParams Request path parameters. + * @param queryParams Request query parameters. + * @param body Request body. + * @param headerParams Request header parameters. + * @param authSettings Request authentication names. + * @param requestContentType Request content-type. + * @param responseContentType Response content-type. + * @param completionBlock The block will be executed when the request completed. + * + * @return The created session task. + */ +- (NSURLSessionTask *)requestWithCompletionBlock:(NSString*)path + method:(NSString*) method + pathParams:(NSDictionary *)pathParams + queryParams:(NSDictionary*)queryParams + formParams:(NSDictionary *)formParams + files:(NSDictionary *)files + body:(id)body + headerParams:(NSDictionary *)headerParams + authSettings: (NSArray *)authSettings + requestContentType:(NSString *)requestContentType + responseContentType:(NSString *)responseContentType + responseType:(NSString *)responseType + completionBlock:(void (^)(id, NSError *))completionBlock; + +/** + * Custom security policy + * + * @return AFSecurityPolicy + */ +- (AFSecurityPolicy *) customSecurityPolicy; + +@end diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/BasicAuthTokenProvider-body.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/BasicAuthTokenProvider-body.mustache new file mode 100644 index 00000000000..e2ba00badb7 --- /dev/null +++ b/output/objcSessionManager_old/src/main/resources/objcSessionManager/BasicAuthTokenProvider-body.mustache @@ -0,0 +1,14 @@ +#import "{{classPrefix}}BasicAuthTokenProvider.h" + +@implementation {{classPrefix}}BasicAuthTokenProvider + ++ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password { + + NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password]; + NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; + basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; + + return basicAuthCredentials; +} + +@end diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/BasicAuthTokenProvider-header.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/BasicAuthTokenProvider-header.mustache new file mode 100644 index 00000000000..dfb287568a0 --- /dev/null +++ b/output/objcSessionManager_old/src/main/resources/objcSessionManager/BasicAuthTokenProvider-header.mustache @@ -0,0 +1,14 @@ +/** The `{{classPrefix}}BasicAuthTokenProvider` class creates a basic auth token from username and password. + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + +#import + +@interface {{classPrefix}}BasicAuthTokenProvider : NSObject + ++ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password; + +@end \ No newline at end of file diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/Configuration-protocol.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/Configuration-protocol.mustache new file mode 100644 index 00000000000..db429a38150 --- /dev/null +++ b/output/objcSessionManager_old/src/main/resources/objcSessionManager/Configuration-protocol.mustache @@ -0,0 +1,75 @@ +#import +#import "{{classPrefix}}Logger.h" + +{{>licenceInfo}} + +@protocol {{classPrefix}}Configuration + +/** + * Api logger + */ +@property (readonly, nonatomic) {{classPrefix}}Logger *logger; + +/** + * Base url + */ +@property (readonly, nonatomic) NSString *host; + +/** + * Api key values for Api Key type Authentication + */ +@property (readonly, nonatomic) NSDictionary *apiKey; + +/** + * Api key prefix values to be prepend to the respective api key + */ +@property (readonly, nonatomic) NSDictionary *apiKeyPrefix; + +/** + * Username for HTTP Basic Authentication + */ +@property (readonly, nonatomic) NSString *username; + +/** + * Password for HTTP Basic Authentication + */ +@property (readonly, nonatomic) NSString *password; + +/** + * Access token for OAuth + */ +@property (readonly, nonatomic) NSString *accessToken; + +/** + * Temp folder for file download + */ +@property (readonly, nonatomic) NSString *tempFolderPath; + +/** + * Debug switch, default false + */ +@property (readonly, nonatomic) BOOL debug; + +/** + * SSL/TLS verification + * Set this to NO to skip verifying SSL certificate when calling API from https server + */ +@property (readonly, nonatomic) BOOL verifySSL; + +/** + * SSL/TLS verification + * Set this to customize the certificate file to verify the peer + */ +@property (readonly, nonatomic) NSString *sslCaCert; + +/** + * Authentication Settings + */ +@property (readonly, nonatomic) NSDictionary *authSettings; + +/** +* Default headers for all services +*/ +@property (readonly, nonatomic, strong) NSDictionary *defaultHeaders; + +@end \ No newline at end of file diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/DefaultConfiguration-body.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/DefaultConfiguration-body.mustache new file mode 100644 index 00000000000..a45eba7ba55 --- /dev/null +++ b/output/objcSessionManager_old/src/main/resources/objcSessionManager/DefaultConfiguration-body.mustache @@ -0,0 +1,157 @@ +#import "{{classPrefix}}DefaultConfiguration.h" + +@implementation {{classPrefix}}DefaultConfiguration + +#pragma mark - Singleton Methods + ++ (instancetype)sharedConfiguration { + + static {{classPrefix}}DefaultConfiguration *shardConfig = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + shardConfig = [[self alloc] init]; + }); + return shardConfig; +} + +#pragma mark - Initialize Methods + +- (instancetype)init { + self = [super init]; + if (self) { + _host = @"{{basePath}}"; + _username = @""; + _password = @""; + _accessToken= @""; + _verifySSL = YES; + _mutableApiKey = [NSMutableDictionary dictionary]; + _mutableApiKeyPrefix = [NSMutableDictionary dictionary]; + _mutableDefaultHeaders = [NSMutableDictionary dictionary]; + _mutableDefaultHeaders[@"User-Agent"] = {{#httpUserAgent}}@"{{httpUserAgent}}"{{/httpUserAgent}}{{^httpUserAgent}}[NSString stringWithFormat:@"Swagger-Codegen/{{version}}/objc (%@; iOS %@; Scale/%0.2f)",[[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]]{{/httpUserAgent}}; + _logger = [{{classPrefix}}Logger sharedLogger]; + } + return self; +} + +#pragma mark - Instance Methods + +- (NSString *) getApiKeyWithPrefix:(NSString *)key { + NSString *prefix = self.apiKeyPrefix[key]; + NSString *apiKey = self.apiKey[key]; + if (prefix && apiKey != (id)[NSNull null] && apiKey.length > 0) { // both api key prefix and api key are set + return [NSString stringWithFormat:@"%@ %@", prefix, apiKey]; + } + else if (apiKey != (id)[NSNull null] && apiKey.length > 0) { // only api key, no api key prefix + return [NSString stringWithFormat:@"%@", self.apiKey[key]]; + } + else { // return empty string if nothing is set + return @""; + } +} + +- (NSString *) getBasicAuthToken { + // return empty string if username and password are empty + if (self.username.length == 0 && self.password.length == 0){ + return @""; + } + + NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.username, self.password]; + NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; + basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; + + return basicAuthCredentials; +} + +- (NSString *) getAccessToken { + if (self.accessToken.length == 0) { // token not set, return empty string + return @""; + } else { + return [NSString stringWithFormat:@"Bearer %@", self.accessToken]; + } +} + +#pragma mark - Setter Methods + +- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString *)identifier { + [self.mutableApiKey setValue:apiKey forKey:identifier]; +} + +- (void) removeApiKey:(NSString *)identifier { + [self.mutableApiKey removeObjectForKey:identifier]; +} + +- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier { + [self.mutableApiKeyPrefix setValue:prefix forKey:identifier]; +} + +- (void) removeApiKeyPrefix:(NSString *)identifier { + [self.mutableApiKeyPrefix removeObjectForKey:identifier]; +} + +#pragma mark - + +- (NSDictionary *) authSettings { + return @{ +{{#authMethods}} +{{#isApiKey}} + @"{{name}}": + @{ + @"type": @"api_key", + @"in": {{#isKeyInHeader}}@"header"{{/isKeyInHeader}}{{#isKeyInQuery}}@"query"{{/isKeyInQuery}}, + @"key": @"{{keyParamName}}", + @"value": [self getApiKeyWithPrefix:@"{{keyParamName}}"] + }, +{{/isApiKey}} +{{#isBasic}} + @"{{name}}": + @{ + @"type": @"basic", + @"in": @"header", + @"key": @"Authorization", + @"value": [self getBasicAuthToken] + }, +{{/isBasic}} +{{#isOAuth}} + @"{{name}}": + @{ + @"type": @"oauth", + @"in": @"header", + @"key": @"Authorization", + @"value": [self getAccessToken] + }, +{{/isOAuth}} +{{/authMethods}} + }; +} + +-(BOOL)debug { + return self.logger.isEnabled; +} + +-(void)setDebug:(BOOL)debug { + self.logger.enabled = debug; +} + + + +- (void)setDefaultHeaderValue:(NSString *)value forKey:(NSString *)key { + if(!value) { + [self.mutableDefaultHeaders removeObjectForKey:key]; + return; + } + self.mutableDefaultHeaders[key] = value; +} + +-(void) removeDefaultHeaderForKey:(NSString*)key { + [self.mutableDefaultHeaders removeObjectForKey:key]; +} + +- (NSString *)defaultHeaderForKey:(NSString *)key { + return self.mutableDefaultHeaders[key]; +} + +- (NSDictionary *)defaultHeaders { + return [self.mutableDefaultHeaders copy]; +} + +@end diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/DefaultConfiguration-header.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/DefaultConfiguration-header.mustache new file mode 100644 index 00000000000..46f3b32fc93 --- /dev/null +++ b/output/objcSessionManager_old/src/main/resources/objcSessionManager/DefaultConfiguration-header.mustache @@ -0,0 +1,134 @@ +#import +#import "{{classPrefix}}Configuration.h" + +{{>licenceInfo}} + +@interface {{classPrefix}}DefaultConfiguration : NSObject <{{classPrefix}}Configuration> + ++ ({{classPrefix}}DefaultConfiguration *)sharedConfiguration; + +/** + * Default api logger + */ +@property (nonatomic, strong) {{classPrefix}}Logger * logger; + +/** + * Default api client + */ +@property (nonatomic) {{classPrefix}}ApiClient *apiClient; + +/** + * Default base url + */ +@property (nonatomic) NSString *host; + +/** + * Api key values for Api Key type Authentication + * + * To add or remove api key, use `setApiKey:forApiKeyIdentifier:`. + */ +@property (readonly, nonatomic, strong) NSDictionary *apiKey; + +/** + * Api key prefix values to be prepend to the respective api key + * + * To add or remove prefix, use `setApiKeyPrefix:forApiKeyPrefixIdentifier:`. + */ +@property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix; + +/** + * Username for HTTP Basic Authentication + */ + @property (nonatomic) NSString *username; + +/** + * Password for HTTP Basic Authentication + */ +@property (nonatomic) NSString *password; + +/** + * Access token for OAuth + */ +@property (nonatomic) NSString *accessToken; + +/** + * Temp folder for file download + */ +@property (nonatomic) NSString *tempFolderPath; + +/** + * Debug switch, default false + */ +@property (nonatomic) BOOL debug; + +/** + * SSL/TLS verification + * Set this to NO to skip verifying SSL certificate when calling API from https server + */ +@property (nonatomic) BOOL verifySSL; + +/** + * SSL/TLS verification + * Set this to customize the certificate file to verify the peer + */ +@property (nonatomic) NSString *sslCaCert; + +/** + * Sets API key + * + * To remove a apiKey for an identifier, just set the apiKey to nil. + * + * @param apiKey API key or token. + * @param identifier API key identifier (authentication schema). + * + */ +- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString*)identifier; + +/** + * Removes api key + * + * @param identifier API key identifier. + */ +- (void) removeApiKey:(NSString *)identifier; + +/** + * Sets the prefix for API key + * + * @param apiKeyPrefix API key prefix. + * @param identifier API key identifier. + */ +- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier; + +/** + * Removes api key prefix + * + * @param identifier API key identifier. + */ +- (void) removeApiKeyPrefix:(NSString *)identifier; + +/** +* Default headers for all services +*/ +@property (readonly, nonatomic, strong) NSDictionary *defaultHeaders; + +/** +* Removes header from defaultHeaders +* +* @param Header name. +*/ +-(void) removeDefaultHeaderForKey:(NSString*)key; + +/** +* Sets the header for key +* +* @param value Value for header name +* @param key Header name +*/ +-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key; + +/** +* @param Header key name. +*/ +-(NSString*) defaultHeaderForKey:(NSString*)key; + +@end \ No newline at end of file diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONRequestSerializer-body.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONRequestSerializer-body.mustache new file mode 100644 index 00000000000..63513335d9a --- /dev/null +++ b/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONRequestSerializer-body.mustache @@ -0,0 +1,37 @@ +#import "{{classPrefix}}JSONRequestSerializer.h" + +@implementation {{classPrefix}}JSONRequestSerializer + +/// +/// When customize a request serializer, +/// the serializer must conform the protocol `AFURLRequestSerialization` +/// and implements the protocol method `requestBySerializingRequest:withParameters:error:` +/// +/// @param request The original request. +/// @param parameters The parameters to be encoded. +/// @param error The error that occurred while attempting to encode the request parameters. +/// +/// @return A serialized request. +/// +- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request + withParameters:(id)parameters + error:(NSError *__autoreleasing *)error +{ + if (!parameters) { + return request; + } + // If the body data which will be serialized isn't NSArray or NSDictionary + // then put the data in the http request body directly. + if ([parameters isKindOfClass:[NSArray class]] || [parameters isKindOfClass:[NSDictionary class]]) { + return [super requestBySerializingRequest:request withParameters:parameters error:error]; + } + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + if([parameters isKindOfClass:[NSData class]]) { + [mutableRequest setHTTPBody:parameters]; + } else { + [mutableRequest setHTTPBody:[parameters dataUsingEncoding:self.stringEncoding]]; + } + return mutableRequest; +} + +@end diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONRequestSerializer-header.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONRequestSerializer-header.mustache new file mode 100644 index 00000000000..1259c5d1530 --- /dev/null +++ b/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONRequestSerializer-header.mustache @@ -0,0 +1,7 @@ +#import +#import + +{{>licenceInfo}} + +@interface {{classPrefix}}JSONRequestSerializer : AFJSONRequestSerializer +@end diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONResponseSerializer-body.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONResponseSerializer-body.mustache new file mode 100644 index 00000000000..7fa5e7b19e0 --- /dev/null +++ b/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONResponseSerializer-body.mustache @@ -0,0 +1,39 @@ +#import "{{classPrefix}}JSONResponseSerializer.h" + +@implementation {{classPrefix}}JSONResponseSerializer + +/// +/// When customize a response serializer, +/// the serializer must conform the protocol `AFURLResponseSerialization` +/// and implements the protocol method `responseObjectForResponse:error:` +/// +/// @param response The response to be processed. +/// @param data The response data to be decoded. +/// @param error The error that occurred while attempting to decode the response data. +/// +/// @return The object decoded from the specified response data. +/// +- (id) responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error { + NSDictionary *responseJson = [super responseObjectForResponse:response data:data error:error]; + + // if response data is not a valid json, return string of data. + if ([self isParseError:*error]) { + *error = nil; + NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; + return responseString; + } + + return responseJson; +} + +-(BOOL)isParseError:(NSError *)error { + return [error.domain isEqualToString:NSCocoaErrorDomain] && error.code == 3840; +} + ++ (instancetype)serializer { + return [self serializerWithReadingOptions:NSJSONReadingAllowFragments]; +} + +@end diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONResponseSerializer-header.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONResponseSerializer-header.mustache new file mode 100644 index 00000000000..360e4f9cdc5 --- /dev/null +++ b/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONResponseSerializer-header.mustache @@ -0,0 +1,8 @@ +#import +#import + +{{>licenceInfo}} + +@interface {{classPrefix}}JSONResponseSerializer : AFJSONResponseSerializer + +@end diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.h b/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.h new file mode 100644 index 00000000000..f621e7184a9 --- /dev/null +++ b/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.h @@ -0,0 +1,8 @@ +#import +#import + +{{>licenceInfo}} + +@interface JSONValueTransformer (ISO8601) + +@end diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.m b/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.m new file mode 100644 index 00000000000..b544a1dae58 --- /dev/null +++ b/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.m @@ -0,0 +1,11 @@ +#import +#import "JSONValueTransformer+ISO8601.h" + +@implementation JSONValueTransformer (ISO8601) + +- (NSDate *) NSDateFromNSString:(NSString *)string +{ + return [NSDate dateWithISO8601String:string]; +} + +@end diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/Object-body.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/Object-body.mustache new file mode 100644 index 00000000000..88df6d6c9ae --- /dev/null +++ b/output/objcSessionManager_old/src/main/resources/objcSessionManager/Object-body.mustache @@ -0,0 +1,42 @@ +#import "{{classPrefix}}Object.h" + +@implementation {{classPrefix}}Object + +/** + * Workaround for JSONModel multithreading issues + * https://github.com/icanzilb/JSONModel/issues/441 + */ +- (instancetype)initWithDictionary:(NSDictionary *)dict error:(NSError **)err { + static NSMutableSet *classNames; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + classNames = [NSMutableSet new]; + }); + + BOOL initSync; + @synchronized([self class]) + { + NSString *className = NSStringFromClass([self class]); + initSync = ![classNames containsObject:className]; + if(initSync) + { + [classNames addObject:className]; + self = [super initWithDictionary:dict error:err]; + } + } + if(!initSync) + { + self = [super initWithDictionary:dict error:err]; + } + return self; +} + +/** + * Gets the string presentation of the object. + * This method will be called when logging model object using `NSLog`. + */ +- (NSString *)description { + return [[self toDictionary] description]; +} + +@end diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/Object-header.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/Object-header.mustache new file mode 100644 index 00000000000..89da6a4d8b6 --- /dev/null +++ b/output/objcSessionManager_old/src/main/resources/objcSessionManager/Object-header.mustache @@ -0,0 +1,8 @@ +#import +#import + +{{>licenceInfo}} + +@interface {{classPrefix}}Object : JSONModel + +@end diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/QueryParamCollection-body.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/QueryParamCollection-body.mustache new file mode 100644 index 00000000000..b1c901dbffa --- /dev/null +++ b/output/objcSessionManager_old/src/main/resources/objcSessionManager/QueryParamCollection-body.mustache @@ -0,0 +1,20 @@ +#import "{{classPrefix}}QueryParamCollection.h" + +@implementation {{classPrefix}}QueryParamCollection + +@synthesize values = _values; +@synthesize format = _format; + +- (id)initWithValuesAndFormat:(NSArray *)values + format:(NSString *)format { + + self = [super init]; + if (self) { + _values = values; + _format = format; + } + + return self; +} + +@end diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/QueryParamCollection-header.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/QueryParamCollection-header.mustache new file mode 100644 index 00000000000..9729c182bd8 --- /dev/null +++ b/output/objcSessionManager_old/src/main/resources/objcSessionManager/QueryParamCollection-header.mustache @@ -0,0 +1,13 @@ +#import + +{{>licenceInfo}} + +@interface {{classPrefix}}QueryParamCollection : NSObject + +@property(nonatomic, readonly) NSArray* values; +@property(nonatomic, readonly) NSString* format; + +- (id) initWithValuesAndFormat: (NSArray*) values + format: (NSString*) format; + +@end diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/README.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/README.mustache new file mode 100644 index 00000000000..4355ecc1af5 --- /dev/null +++ b/output/objcSessionManager_old/src/main/resources/objcSessionManager/README.mustache @@ -0,0 +1,143 @@ +# {{podName}} + +{{#appDescription}} +{{{appDescription}}} +{{/appDescription}} + +This ObjC package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: + +- API version: {{appVersion}} +- Package version: {{artifactVersion}} +- Build date: {{generatedDate}} +- Build package: {{generatorClass}} +{{#infoUrl}} +For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + +## Requirements + +The SDK requires [**ARC (Automatic Reference Counting)**](http://stackoverflow.com/questions/7778356/how-to-enable-disable-automatic-reference-counting) to be enabled in the Xcode project. + +## Installation & Usage +### Install from Github using [CocoaPods](https://cocoapods.org/) + +Add the following to the Podfile: + +```ruby +pod '{{podName}}', :git => 'https://github.com/{{gitUserId}}/{{gitRepoId}}.git' +``` + +To specify a particular branch, append `, :branch => 'branch-name-here'` + +To specify a particular commit, append `, :commit => '11aa22'` + +### Install from local path using [CocoaPods](https://cocoapods.org/) + +Put the SDK under your project folder (e.g. /path/to/objc_project/Vendor/{{podName}}) and then add the following to the Podfile: + +```ruby +pod '{{podName}}', :path => 'Vendor/{{podName}}' +``` + +### Usage + +Import the following: + +```objc +#import <{{podName}}/{{{classPrefix}}}ApiClient.h> +#import <{{podName}}/{{{classPrefix}}}Configuration.h> +// load models +{{#models}}{{#model}}#import <{{podName}}/{{{classname}}}.h> +{{/model}}{{/models}}// load API classes for accessing endpoints +{{#apiInfo}}{{#apis}}#import <{{podName}}/{{{classname}}}.h> +{{/apis}}{{/apiInfo}} +``` + +## Recommendation + +It's recommended to create an instance of ApiClient per thread in a multi-threaded environment to avoid any potential issue. + +## Getting Started + +Please follow the [installation procedure](#installation--usage) and then run the following: + +```objc +{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}} +{{#hasAuthMethods}} +{{classPrefix}}Configuration *apiConfig = [{{classPrefix}}Configuration sharedConfig]; +{{#authMethods}}{{#isBasic}}// Configure HTTP basic authorization (authentication scheme: {{{name}}}) +[apiConfig setUsername:@"YOUR_USERNAME"]; +[apiConfig setPassword:@"YOUR_PASSWORD"]; +{{/isBasic}}{{#isApiKey}} +// Configure API key authorization: (authentication scheme: {{{name}}}) +[apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"{{{keyParamName}}}"]; +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +//[apiConfig setApiKeyPrefix:@"Bearer" forApiKeyIdentifier:@"{{{keyParamName}}}"]; +{{/isApiKey}}{{#isOAuth}} +// Configure OAuth2 access token for authorization: (authentication scheme: {{{name}}}) +[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; +{{/isOAuth}}{{/authMethods}} +{{/hasAuthMethods}} + +{{#allParams}}{{{dataType}}} *{{paramName}} = {{{example}}}; // {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} +{{/allParams}} + +{{classname}} *apiInstance = [[{{classname}} alloc] init]; + +{{#summary}}// {{{.}}} +{{/summary}}[apiInstance {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} + {{paramName}}{{/secondaryParam}}:{{paramName}}{{/allParams}} + {{#hasParams}}completionHandler: {{/hasParams}}^({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error) { +{{#returnType}} + if (output) { + NSLog(@"%@", output); + } +{{/returnType}} + if (error) { + NSLog(@"Error: %@", error); + } + }]; +{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} +``` + +## Documentation for API Endpoints + +All URIs are relative to *{{basePath}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + +## Documentation For Models + +{{#models}}{{#model}} - [{{{classname}}}]({{modelDocPath}}{{{classname}}}.md) +{{/model}}{{/models}} + +## Documentation For Authorization + +{{^authMethods}} All endpoints do not require authorization. +{{/authMethods}}{{#authMethods}}{{#last}} Authentication schemes defined for the API:{{/last}}{{/authMethods}} +{{#authMethods}}## {{{name}}} + +{{#isApiKey}}- **Type**: API key +- **API key parameter name**: {{{keyParamName}}} +- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} +{{/isApiKey}} +{{#isBasic}}- **Type**: HTTP basic authentication +{{/isBasic}} +{{#isOAuth}}- **Type**: OAuth +- **Flow**: {{{flow}}} +- **Authorization URL**: {{{authorizationUrl}}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - **{{{scope}}}**: {{{description}}} +{{/scopes}} +{{/isOAuth}} + +{{/authMethods}} + +## Author + +{{#apiInfo}}{{#apis}}{{^hasMore}}{{infoEmail}} +{{/hasMore}}{{/apis}}{{/apiInfo}} + diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/api-body.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/api-body.mustache new file mode 100644 index 00000000000..050368f9899 --- /dev/null +++ b/output/objcSessionManager_old/src/main/resources/objcSessionManager/api-body.mustache @@ -0,0 +1,161 @@ +{{#operations}} +#import "{{classname}}.h" +#import "{{classPrefix}}QueryParamCollection.h" +{{#imports}}#import "{{import}}.h" +{{/imports}} +{{newline}} + +@interface {{classname}} () + +@property (nonatomic, strong, readwrite) NSMutableDictionary *defaultHeaders; + +@end + +@implementation {{classname}} + +NSString* k{{classname}}ErrorDomain = @"{{classname}}ErrorDomain"; +NSInteger k{{classname}}MissingParamErrorCode = 234513; + +@synthesize sessionManager = _sessionManager; + +#pragma mark - Initialize methods + +- (id)initWithSessionManager:({{classPrefix}}ApiSessionManager *)sessionManager { + self = [super init]; + if (self) { + _sessionManager = sessionManager; + _defaultHeaders = [NSMutableDictionary dictionary]; + } + + return self; +} + +#pragma mark - + +-(NSString*) defaultHeaderForKey:(NSString*)key { + return self.defaultHeaders[key]; +} + +-(void) addHeader:(NSString*)value forKey:(NSString*)key { + [self setDefaultHeaderValue:value forKey:key]; +} + +-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key { + [self.defaultHeaders setValue:value forKey:key]; +} + +#pragma mark - Api Methods + +{{#operation}} +/// +/// {{{summary}}} +/// {{{notes}}} +/// {{#allParams}} @param {{paramName}} {{{description}}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} +/// +/// {{/allParams}} @returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} +/// +-(NSURLSessionTask*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} + {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}} + {{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler { + {{#allParams}} + {{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == nil) { + NSParameterAssert({{paramName}}); + if(handler) { + NSDictionary * userInfo = @{NSLocalizedDescriptionKey : [NSString stringWithFormat:NSLocalizedString(@"Missing required parameter '%@'", nil),@"{{paramName}}"] }; + NSError* error = [NSError errorWithDomain:k{{classname}}ErrorDomain code:k{{classname}}MissingParamErrorCode userInfo:userInfo]; + handler({{#returnType}}nil, {{/returnType}}error); + } + return nil; + } + + {{/required}} + {{/allParams}} + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"{{path}}"]; + + // remove format in URL if needed + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + {{#pathParams}} + if ({{paramName}} != nil) { + pathParams[@"{{baseName}}"] = {{paramName}}; + } + {{/pathParams}} + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + {{#queryParams}} + if ({{paramName}} != nil) { + {{#collectionFormat}} + queryParams[@"{{baseName}}"] = [[{{classPrefix}}QueryParamCollection alloc] initWithValuesAndFormat: {{paramName}} format: @"{{collectionFormat}}"]; + {{/collectionFormat}} + {{^collectionFormat}}queryParams[@"{{baseName}}"] = {{paramName}};{{/collectionFormat}} + } + {{/queryParams}} + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders]; + [headerParams addEntriesFromDictionary:self.defaultHeaders]; + {{#headerParams}} + if ({{paramName}} != nil) { + headerParams[@"{{baseName}}"] = {{paramName}}; + } + {{/headerParams}} + // HTTP header `Accept` + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[{{#produces}}@"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}}]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; + } + + // response content type + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; + + // request content type + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[{{#consumes}}@"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}]]; + + // Authentication setting + NSArray *authSettings = @[{{#authMethods}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; + + id bodyParam = nil; + NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; + {{#bodyParam}} + bodyParam = {{paramName}}; + {{/bodyParam}} + {{^bodyParam}} + {{#formParams}} + {{#notFile}} + if ({{paramName}}) { + formParams[@"{{baseName}}"] = {{paramName}}; + } + {{/notFile}} + {{#isFile}} + localVarFiles[@"{{paramName}}"] = {{paramName}}; + {{/isFile}} + {{/formParams}} + {{/bodyParam}} + + return [self.sessionManager requestWithPath: resourcePath + method: @"{{httpMethod}}" + pathParams: pathParams + queryParams: queryParams + formParams: formParams + files: localVarFiles + body: bodyParam + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + responseType: {{^returnType}}nil{{/returnType}}{{#returnType}}@"{{{ returnType }}}"{{/returnType}} + completionBlock: ^(id data, NSError *error) { + if(handler) { + handler({{#returnType}}({{{ returnType }}})data, {{/returnType}}error); + } + } + ]; +} + +{{/operation}} + +{{newline}} +{{/operations}} +@end diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/api-header.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/api-header.mustache new file mode 100644 index 00000000000..1b28b47c882 --- /dev/null +++ b/output/objcSessionManager_old/src/main/resources/objcSessionManager/api-header.mustache @@ -0,0 +1,34 @@ +#import +{{#imports}}#import "{{import}}.h" +{{/imports}} +#import "{{classPrefix}}ApiSessionManager.h" + +{{>licenceInfo}} + + +@interface {{classname}}: NSObject <{{classPrefix}}Api> + +extern NSString* k{{classname}}ErrorDomain; +extern NSInteger k{{classname}}MissingParamErrorCode; + ++(instancetype) sharedAPI; + +{{#operations}} +{{#operation}} +/// {{{summary}}} +/// {{#notes}}{{{notes}}}{{/notes}} +/// +/// {{#allParams}}@param {{paramName}} {{description}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} +/// {{/allParams}}{{#responses}} +/// code:{{{code}}} message:"{{{message}}}"{{#hasMore}},{{/hasMore}}{{/responses}} +/// +/// @return {{{returnType}}} +-(NSURLSessionTask*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} + {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}} + {{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler; + +{{newline}} +{{/operation}} +{{/operations}} + +@end diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/model-body.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/model-body.mustache new file mode 100644 index 00000000000..2a4a548458e --- /dev/null +++ b/output/objcSessionManager_old/src/main/resources/objcSessionManager/model-body.mustache @@ -0,0 +1,59 @@ +{{#models}} +{{#model}} +#import "{{classname}}.h" + +@implementation {{classname}} + +- (instancetype)init { + self = [super init]; + if (self) { + // initialize property's default value, if any + {{#vars}}{{#defaultValue}}self.{{name}} = {{{defaultValue}}}; + {{/defaultValue}}{{/vars}} + } + return self; +} +{{#vars}}{{^vendorExtensions.x-unique-id-key}}{{/vendorExtensions.x-unique-id-key}}{{#vendorExtensions.x-unique-id-key}} +-(NSString*)indexPropertyName { + return @"{{name}}"; +} +{{/vendorExtensions.x-unique-id-key}}{{/vars}} +{{#discriminator}} +/** + * Maps "discriminator" value to the sub-class name, so that inheritance is supported. + */ +- (id)initWithDictionary:(NSDictionary *)dict error:(NSError *__autoreleasing *)err { + NSString * discriminatedClassName = [dict valueForKey:@"{{discriminator}}"]; + if(discriminatedClassName == nil ){ + return [super initWithDictionary:dict error:err]; + } + Class class = NSClassFromString([@"{{classPrefix}}" stringByAppendingString:discriminatedClassName]); + if([self class ] == class) { + return [super initWithDictionary:dict error:err]; + } + return [[class alloc] initWithDictionary:dict error: err]; +} +{{/discriminator}} + +/** + * Maps json key to property name. + * This method is used by `JSONModel`. + */ ++ (JSONKeyMapper *)keyMapper { + return [[JSONKeyMapper alloc] initWithDictionary:@{ {{#vars}}@"{{baseName}}": @"{{name}}"{{#hasMore}}, {{/hasMore}}{{/vars}} }]; +} + +/** + * Indicates whether the property with the given name is optional. + * If `propertyName` is optional, then return `YES`, otherwise return `NO`. + * This method is used by `JSONModel`. + */ ++ (BOOL)propertyIsOptional:(NSString *)propertyName { + + NSArray *optionalProperties = @[{{#vars}}{{^required}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/required}}{{/vars}}]; + return [optionalProperties containsObject:propertyName]; +} + +{{/model}} +@end +{{/models}} diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/model-header.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/model-header.mustache new file mode 100644 index 00000000000..04570e71a2f --- /dev/null +++ b/output/objcSessionManager_old/src/main/resources/objcSessionManager/model-header.mustache @@ -0,0 +1,25 @@ +#import +#import "{{classPrefix}}Object.h" + +{{>licenceInfo}} + +{{#imports}}#import "{{import}}.h" +{{/imports}} +{{newline}} +{{#models}} +{{#model}} + +@protocol {{classname}} +@end + +@interface {{classname}} : {{#parent}}{{{parent}}}{{/parent}}{{^parent}}{{classPrefix}}Object{{/parent}} + +{{#vars}} +{{#description}}/* {{{description}}} {{^required}}[optional]{{/required}} + */{{/description}} +@property(nonatomic) {{{ datatype }}} {{name}}; +{{/vars}} + +@end +{{/model}} +{{/models}} diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/podspec.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/podspec.mustache new file mode 100644 index 00000000000..bd0bd9f328e --- /dev/null +++ b/output/objcSessionManager_old/src/main/resources/objcSessionManager/podspec.mustache @@ -0,0 +1,37 @@ +# +# Be sure to run `pod lib lint {{podName}}.podspec' to ensure this is a +# valid spec and remove all comments before submitting the spec. +# +# Any lines starting with a # are optional, but encouraged +# +# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html +# + +Pod::Spec.new do |s| + s.name = "{{podName}}" + s.version = "{{podVersion}}" +{{#apiInfo}}{{#apis}}{{^hasMore}} + s.summary = "{{appName}}" + s.description = <<-DESC + {{{appDescription}}} + DESC +{{/hasMore}}{{/apis}}{{/apiInfo}} + s.platform = :ios, '7.0' + s.requires_arc = true + + {{^useCoreData}}s.framework = 'SystemConfiguration'{{/useCoreData}}{{#useCoreData}}s.frameworks = 'SystemConfiguration', 'CoreData'{{/useCoreData}} + + s.homepage = "{{gitRepoURL}}" + s.license = "{{#license}}{{license}}{{/license}}{{^license}}Apache License, Version 2.0{{/license}}" + s.source = { :git => "{{gitRepoURL}}.git", :tag => "#{s.version}" } + s.author = { "{{authorName}}" => "{{authorEmail}}" } + + s.source_files = '{{podName}}/**/*.{m,h}' + s.public_header_files = '{{podName}}/**/*.h' +{{#useCoreData}} s.resources = '{{podName}}/**/*.{xcdatamodeld,xcdatamodel}'{{/useCoreData}} + + s.dependency 'AFNetworking', '~> 3' + s.dependency 'JSONModel', '~> 1.2' + s.dependency 'ISO8601', '~> 0.5' +end + From c49db091efcf7bc5904444dc22654b8ee81f8e78 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 15 Jul 2016 13:45:22 -0700 Subject: [PATCH 110/470] updated versions for release --- modules/swagger-codegen-cli/pom.xml | 2 +- modules/swagger-codegen-maven-plugin/pom.xml | 2 +- modules/swagger-codegen/pom.xml | 2 +- .../src/main/resources/Java/libraries/jersey2/pom.mustache | 2 +- .../src/main/resources/Java/libraries/retrofit/pom.mustache | 2 +- .../src/main/resources/JavaInflector/pom.mustache | 2 +- .../src/main/resources/JavaJaxRS/resteasy/pom.mustache | 2 +- .../src/main/resources/akka-scala/pom.mustache | 2 +- .../swagger-codegen/src/main/resources/android/pom.mustache | 2 +- modules/swagger-codegen/src/main/resources/scala/pom.mustache | 2 +- modules/swagger-generator/pom.xml | 2 +- pom.xml | 4 ++-- 12 files changed, 13 insertions(+), 13 deletions(-) diff --git a/modules/swagger-codegen-cli/pom.xml b/modules/swagger-codegen-cli/pom.xml index 92490778689..895984a3e35 100644 --- a/modules/swagger-codegen-cli/pom.xml +++ b/modules/swagger-codegen-cli/pom.xml @@ -3,7 +3,7 @@ io.swagger swagger-codegen-project - 2.2.0-SNAPSHOT + 2.2.0 ../.. 4.0.0 diff --git a/modules/swagger-codegen-maven-plugin/pom.xml b/modules/swagger-codegen-maven-plugin/pom.xml index 0b6885bf048..8777c6d6d22 100644 --- a/modules/swagger-codegen-maven-plugin/pom.xml +++ b/modules/swagger-codegen-maven-plugin/pom.xml @@ -6,7 +6,7 @@ io.swagger swagger-codegen-project - 2.2.0-SNAPSHOT + 2.2.0 ../.. swagger-codegen-maven-plugin diff --git a/modules/swagger-codegen/pom.xml b/modules/swagger-codegen/pom.xml index 8f7e98074de..042ba0c2a65 100644 --- a/modules/swagger-codegen/pom.xml +++ b/modules/swagger-codegen/pom.xml @@ -3,7 +3,7 @@ io.swagger swagger-codegen-project - 2.2.0-SNAPSHOT + 2.2.0 ../.. 4.0.0 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 ee55337e4b9..4978faba6e9 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 @@ -188,7 +188,7 @@ - 1.5.8 + 1.5.9 2.22.2 2.7.5 {{^java8}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pom.mustache index c9991c230e5..1be9703bad3 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pom.mustache @@ -142,7 +142,7 @@ - 1.5.8 + 1.5.9 1.9.0 2.7.5 2.9.3 diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/pom.mustache index a46b1960a67..5b6b7c0161d 100644 --- a/modules/swagger-codegen/src/main/resources/JavaInflector/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/pom.mustache @@ -111,7 +111,7 @@ 1.0.0 - 1.0.4 + 1.0.8 9.2.9.v20150224 1.0.1 4.8.2 diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pom.mustache index 3373c53b2ce..a98e1b68ad4 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pom.mustache @@ -145,7 +145,7 @@ - 1.5.8 + 1.5.9 9.2.9.v20150224 3.0.11.Final 1.6.3 diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache index b7bd04afffb..ea666198674 100644 --- a/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache @@ -217,7 +217,7 @@ 2.3.9 1.2 2.2 - 1.5.8 + 1.5.9 1.0.0 4.8.1 diff --git a/modules/swagger-codegen/src/main/resources/android/pom.mustache b/modules/swagger-codegen/src/main/resources/android/pom.mustache index bf11a6625c5..e073253123d 100644 --- a/modules/swagger-codegen/src/main/resources/android/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/android/pom.mustache @@ -145,7 +145,7 @@ - 1.5.8 + 1.5.9 2.3.1 4.8.1 1.0.0 diff --git a/modules/swagger-codegen/src/main/resources/scala/pom.mustache b/modules/swagger-codegen/src/main/resources/scala/pom.mustache index 51256c42491..e6d80631460 100644 --- a/modules/swagger-codegen/src/main/resources/scala/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/scala/pom.mustache @@ -210,7 +210,7 @@ 1.2 2.2 1.19 - 1.5.8 + 1.5.9 1.0.5 1.0.0 2.4.2 diff --git a/modules/swagger-generator/pom.xml b/modules/swagger-generator/pom.xml index 7304fdd04bc..5616a41af8b 100644 --- a/modules/swagger-generator/pom.xml +++ b/modules/swagger-generator/pom.xml @@ -4,7 +4,7 @@ io.swagger swagger-codegen-project - 2.2.0-SNAPSHOT + 2.2.0 ../.. swagger-generator diff --git a/pom.xml b/pom.xml index f31a7c230d9..4c199723a04 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ swagger-codegen-project pom swagger-codegen-project - 2.2.0-SNAPSHOT + 2.2.0 https://github.com/swagger-api/swagger-codegen scm:git:git@github.com:swagger-api/swagger-codegen.git @@ -704,7 +704,7 @@ - 1.0.19 + 1.0.21 2.11.1 2.3.4 1.5.9 From d9aa1dd98518b09aa9f8db4433fc065ee8c97bf4 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 15 Jul 2016 13:46:47 -0700 Subject: [PATCH 111/470] updated readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e5be5de59f7..853a9a3b488 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ The OpenAPI Specification has undergone 3 revisions since initial creation in 20 Swagger Codegen Version | Release Date | OpenAPI Spec compatibility | Notes -------------------------- | ------------ | -------------------------- | ----- -2.2.0-SNAPSHOT | | 1.0, 1.1, 1.2, 2.0 | [master](https://github.com/swagger-api/swagger-codegen) +2.2.0 | 2016-07-15 | 1.0, 1.1, 1.2, 2.0 | [tag v2.2.0](https://github.com/swagger-api/swagger-codegen/tree/v2.2.0) 2.1.6 (**current stable**) | 2016-04-06 | 1.0, 1.1, 1.2, 2.0 | [tag v2.1.6](https://github.com/swagger-api/swagger-codegen/tree/v2.1.6) 2.0.17 | 2014-08-22 | 1.1, 1.2 | [tag v2.0.17](https://github.com/swagger-api/swagger-codegen/tree/v2.0.17) 1.0.4 | 2012-04-12 | 1.0, 1.1 | [tag v1.0.4](https://github.com/swagger-api/swagger-codegen/tree/swagger-codegen_2.9.1-1.1) From 3346388056f82b9c9df37de92f7991c7a9deb6c9 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 15 Jul 2016 21:39:58 -0700 Subject: [PATCH 112/470] null check --- .../src/main/java/io/swagger/codegen/DefaultGenerator.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index b0a2fd34292..20b6acca907 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -259,7 +259,10 @@ private int getInheritanceDepth(Model model) { private Model getParent(Model model) { if (model instanceof ComposedModel) { - return definitions.get(((ComposedModel) model).getParent().getReference()); + Model parent = ((ComposedModel) model).getParent(); + if(parent != null) { + return definitions.get(parent.getReference()); + } } return null; From 8740b4d0ea68f9de2bd2849a501e33a5010a11d3 Mon Sep 17 00:00:00 2001 From: cbornet Date: Mon, 30 May 2016 18:44:44 +0200 Subject: [PATCH 113/470] set interface with discriminator as parent If a composed model (allOf) doesn't have any parent and one of its interface has a discriminator field, then set this interface as parent. See #2096 See https://github.com/swagger-api/swagger-parser/pull/246 --- .../io/swagger/codegen/DefaultCodegen.java | 49 ++++++++++++------- .../codegen/java/JavaInheritanceTest.java | 28 ++++++++++- .../javascript/JavaScriptInheritanceTest.java | 4 +- 3 files changed, 59 insertions(+), 22 deletions(-) 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 1eceabdd973..47df8cded35 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 @@ -1195,7 +1195,35 @@ public CodegenModel fromModel(String name, Model model, Map allDe allRequired = null; } // parent model - final RefModel parent = (RefModel) composed.getParent(); + RefModel parent = (RefModel) composed.getParent(); + + // interfaces (intermediate models) + if (composed.getInterfaces() != null) { + if (m.interfaces == null) + m.interfaces = new ArrayList(); + for (RefModel _interface : composed.getInterfaces()) { + Model interfaceModel = null; + if (allDefinitions != null) { + interfaceModel = allDefinitions.get(_interface.getSimpleRef()); + } + // set first interface with discriminator found as parent + if (parent == null && interfaceModel instanceof ModelImpl && ((ModelImpl) interfaceModel).getDiscriminator() != null) { + parent = _interface; + } else { + final String interfaceRef = toModelName(_interface.getSimpleRef()); + m.interfaces.add(interfaceRef); + addImport(m, interfaceRef); + if (allDefinitions != null) { + if (supportsInheritance) { + addProperties(allProperties, allRequired, interfaceModel, allDefinitions); + } else { + addProperties(properties, required, interfaceModel, allDefinitions); + } + } + } + } + } + if (parent != null) { final String parentRef = parent.getSimpleRef(); m.parentSchema = parentRef; @@ -1210,24 +1238,7 @@ public CodegenModel fromModel(String name, Model model, Map allDe } } } - // interfaces (intermediate models) - if (composed.getInterfaces() != null) { - if (m.interfaces == null) - m.interfaces = new ArrayList(); - for (RefModel _interface : composed.getInterfaces()) { - final String interfaceRef = toModelName(_interface.getSimpleRef()); - m.interfaces.add(interfaceRef); - addImport(m, interfaceRef); - if (allDefinitions != null) { - final Model interfaceModel = allDefinitions.get(_interface.getSimpleRef()); - if (supportsInheritance) { - addProperties(allProperties, allRequired, interfaceModel, allDefinitions); - } else { - addProperties(properties, required, interfaceModel, allDefinitions); - } - } - } - } + // child model (properties owned by the model itself) Model child = composed.getChild(); if (child != null && child instanceof RefModel && allDefinitions != null) { diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaInheritanceTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaInheritanceTest.java index dcd87b4d700..a4cb27db756 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaInheritanceTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaInheritanceTest.java @@ -13,10 +13,14 @@ import org.testng.Assert; import org.testng.annotations.Test; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + public class JavaInheritanceTest { @SuppressWarnings("static-method") - @Test(description = "convert a composed model") + @Test(description = "convert a composed model with parent") public void javaInheritanceTest() { final Model model = new ComposedModel().parent(new RefModel("Base")) .child(new ModelImpl().additionalProperties(new StringProperty())); @@ -29,4 +33,26 @@ public void javaInheritanceTest() { Assert.assertEquals(cm.parent, "Base"); Assert.assertEquals(cm.imports, Sets.newHashSet("Base")); } + + @SuppressWarnings("static-method") + @Test(description = "convert a composed model with discriminator") + public void javaInheritanceWithDiscriminatorTest() { + ModelImpl base = new ModelImpl(); + base.setDiscriminator("disc"); + + final Model model = new ComposedModel() + .interfaces(Arrays.asList(new RefModel("Base"))) + .child(new ModelImpl().additionalProperties(new StringProperty())); + + final Map allDefinitions = new HashMap(); + allDefinitions.put("Base", base); + + final DefaultCodegen codegen = new JavaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model, allDefinitions); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.parent, "Base"); + Assert.assertEquals(cm.imports, Sets.newHashSet("Base")); + } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptInheritanceTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptInheritanceTest.java index 94285e46888..592a9e2ae58 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptInheritanceTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptInheritanceTest.java @@ -51,7 +51,7 @@ public void javascriptInheritanceTest() { Assert.assertEquals(cm.vars.size(), 1); Assert.assertEquals(cm.vars.get(0).name, "childProp"); Assert.assertEquals(cm.allVars.size(), 4); - String[] allVars = {"baseProp", "intf1Prop", "intf2Prop", "childProp"}; + String[] allVars = {"intf1Prop", "intf2Prop", "baseProp", "childProp"}; for (int i = 0; i < allVars.length; i++) { Assert.assertEquals(cm.allVars.get(i).name, allVars[i]); } @@ -91,7 +91,7 @@ public void javascriptNoInheritanceTest() { Assert.assertEquals(cm.imports, Sets.newHashSet("Base", "Interface1", "Interface2")); Assert.assertEquals(cm.vars.size(), 4); Assert.assertEquals(cm.allVars.size(), 4); - String[] allVars = {"baseProp", "intf1Prop", "intf2Prop", "childProp"}; + String[] allVars = {"intf1Prop", "intf2Prop", "baseProp", "childProp"}; for (int i = 0; i < allVars.length; i++) { Assert.assertEquals(cm.vars.get(i).name, allVars[i]); Assert.assertEquals(cm.allVars.get(i).name, allVars[i]); From 39cb6a24dbb5610ca9bb89f80eb62037aafabe59 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Sun, 17 Jul 2016 15:43:30 -0700 Subject: [PATCH 114/470] updated dev versions --- README.md | 4 ++-- modules/swagger-codegen-cli/pom.xml | 2 +- modules/swagger-codegen-maven-plugin/pom.xml | 2 +- modules/swagger-codegen/pom.xml | 2 +- modules/swagger-generator/pom.xml | 2 +- pom.xml | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 853a9a3b488..52caa16287f 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,7 @@ Swagger Codegen Version | Release Date | OpenAPI Spec compatibility | Notes If you're looking for the latest stable version, you can grab it directly from maven central (you'll need java 7 runtime at a minimum): ``` -wget http://repo1.maven.org/maven2/io/swagger/swagger-codegen-cli/2.1.6/swagger-codegen-cli-2.1.6.jar -O swagger-codegen-cli.jar +wget http://repo1.maven.org/maven2/io/swagger/swagger-codegen-cli/2.1.6/swagger-codegen-cli-2.2.0.jar -O swagger-codegen-cli.jar java -jar swagger-codegen-cli.jar help ``` @@ -148,7 +148,7 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ ``` (if you're on Windows, replace the last command with `java -jar modules\swagger-codegen-cli\target\swagger-codegen-cli.jar generate -i http://petstore.swagger.io/v2/swagger.json -l php -o c:\temp\php_api_client`) -You can also download the JAR (latest relesae) directly from [maven.org]( http://central.maven.org/maven2/io/swagger/swagger-codegen/2.1.6/swagger-codegen-2.1.6.jar) +You can also download the JAR (latest relesae) directly from [maven.org]( http://central.maven.org/maven2/io/swagger/swagger-codegen/2.1.6/swagger-codegen-2.2.0.jar) To get a list of **general** options available, please run `java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar help generate` diff --git a/modules/swagger-codegen-cli/pom.xml b/modules/swagger-codegen-cli/pom.xml index 895984a3e35..fa1ddefa72a 100644 --- a/modules/swagger-codegen-cli/pom.xml +++ b/modules/swagger-codegen-cli/pom.xml @@ -3,7 +3,7 @@ io.swagger swagger-codegen-project - 2.2.0 + 2.2.1-SNAPSHOT ../.. 4.0.0 diff --git a/modules/swagger-codegen-maven-plugin/pom.xml b/modules/swagger-codegen-maven-plugin/pom.xml index 8777c6d6d22..8850b8ee7ea 100644 --- a/modules/swagger-codegen-maven-plugin/pom.xml +++ b/modules/swagger-codegen-maven-plugin/pom.xml @@ -6,7 +6,7 @@ io.swagger swagger-codegen-project - 2.2.0 + 2.2.1-SNAPSHOT ../.. swagger-codegen-maven-plugin diff --git a/modules/swagger-codegen/pom.xml b/modules/swagger-codegen/pom.xml index 042ba0c2a65..16b89d6a5ba 100644 --- a/modules/swagger-codegen/pom.xml +++ b/modules/swagger-codegen/pom.xml @@ -3,7 +3,7 @@ io.swagger swagger-codegen-project - 2.2.0 + 2.2.1-SNAPSHOT ../.. 4.0.0 diff --git a/modules/swagger-generator/pom.xml b/modules/swagger-generator/pom.xml index 5616a41af8b..29d4e25c2b3 100644 --- a/modules/swagger-generator/pom.xml +++ b/modules/swagger-generator/pom.xml @@ -4,7 +4,7 @@ io.swagger swagger-codegen-project - 2.2.0 + 2.2.1-SNAPSHOT ../.. swagger-generator diff --git a/pom.xml b/pom.xml index 4c199723a04..be3a7f8c5e6 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ swagger-codegen-project pom swagger-codegen-project - 2.2.0 + 2.2.1-SNAPSHOT https://github.com/swagger-api/swagger-codegen scm:git:git@github.com:swagger-api/swagger-codegen.git From e077e80dcb27d60c161116683fbf6decf15b6505 Mon Sep 17 00:00:00 2001 From: Wolfgang Berger Date: Mon, 18 Jul 2016 10:45:22 +0200 Subject: [PATCH 115/470] add missing assignment to task --- .../objcSessionManager/ApiSessionManager-body.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache index 31382dc7b2f..aa285a4d10f 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache @@ -344,7 +344,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) }]; } else { - [self taskWithCompletionBlock:request completionBlock:^(id data, NSError *error) { + task = [self taskWithCompletionBlock:request completionBlock:^(id data, NSError *error) { NSError * serializationError; id response = [self.responseDeserializer deserialize:data class:responseType error:&serializationError]; if(!response && !error){ From 07d2e7245e24096a5b59c472a43040cb96559097 Mon Sep 17 00:00:00 2001 From: Wolfgang Berger Date: Mon, 18 Jul 2016 11:20:29 +0200 Subject: [PATCH 116/470] updates iso lib version requirement --- .../src/main/resources/objcSessionManager/podspec.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/podspec.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/podspec.mustache index bd0bd9f328e..7a2b22bea28 100644 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/podspec.mustache +++ b/output/objcSessionManager/src/main/resources/objcSessionManager/podspec.mustache @@ -32,6 +32,6 @@ Pod::Spec.new do |s| s.dependency 'AFNetworking', '~> 3' s.dependency 'JSONModel', '~> 1.2' - s.dependency 'ISO8601', '~> 0.5' + s.dependency 'ISO8601', '~> 0.6' end From e6f08df30ce904692069254889bbe240996b3e28 Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 18 Jul 2016 17:32:29 +0800 Subject: [PATCH 117/470] update JAR URL to 2.2.0 --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 52caa16287f..d3d19f7c63a 100644 --- a/README.md +++ b/README.md @@ -59,8 +59,8 @@ The OpenAPI Specification has undergone 3 revisions since initial creation in 20 Swagger Codegen Version | Release Date | OpenAPI Spec compatibility | Notes -------------------------- | ------------ | -------------------------- | ----- -2.2.0 | 2016-07-15 | 1.0, 1.1, 1.2, 2.0 | [tag v2.2.0](https://github.com/swagger-api/swagger-codegen/tree/v2.2.0) -2.1.6 (**current stable**) | 2016-04-06 | 1.0, 1.1, 1.2, 2.0 | [tag v2.1.6](https://github.com/swagger-api/swagger-codegen/tree/v2.1.6) +2.2.0 (**current stable**) | 2016-07-15 | 1.0, 1.1, 1.2, 2.0 | [tag v2.2.0](https://github.com/swagger-api/swagger-codegen/tree/v2.2.0) +2.1.6 | 2016-04-06 | 1.0, 1.1, 1.2, 2.0 | [tag v2.1.6](https://github.com/swagger-api/swagger-codegen/tree/v2.1.6) 2.0.17 | 2014-08-22 | 1.1, 1.2 | [tag v2.0.17](https://github.com/swagger-api/swagger-codegen/tree/v2.0.17) 1.0.4 | 2012-04-12 | 1.0, 1.1 | [tag v1.0.4](https://github.com/swagger-api/swagger-codegen/tree/swagger-codegen_2.9.1-1.1) @@ -69,7 +69,7 @@ Swagger Codegen Version | Release Date | OpenAPI Spec compatibility | Notes If you're looking for the latest stable version, you can grab it directly from maven central (you'll need java 7 runtime at a minimum): ``` -wget http://repo1.maven.org/maven2/io/swagger/swagger-codegen-cli/2.1.6/swagger-codegen-cli-2.2.0.jar -O swagger-codegen-cli.jar +wget http://repo1.maven.org/maven2/io/swagger/swagger-codegen-cli/2.2.0/swagger-codegen-cli-2.2.0.jar -O swagger-codegen-cli.jar java -jar swagger-codegen-cli.jar help ``` @@ -148,7 +148,7 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ ``` (if you're on Windows, replace the last command with `java -jar modules\swagger-codegen-cli\target\swagger-codegen-cli.jar generate -i http://petstore.swagger.io/v2/swagger.json -l php -o c:\temp\php_api_client`) -You can also download the JAR (latest relesae) directly from [maven.org]( http://central.maven.org/maven2/io/swagger/swagger-codegen/2.1.6/swagger-codegen-2.2.0.jar) +You can also download the JAR (latest relesae) directly from [maven.org]( http://central.maven.org/maven2/io/swagger/swagger-codegen/2.2.0/swagger-codegen-2.2.0.jar) To get a list of **general** options available, please run `java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar help generate` From 749a17d292e3cc9c8e764b86b31596bc98cac809 Mon Sep 17 00:00:00 2001 From: Wolfgang Berger Date: Mon, 18 Jul 2016 12:00:22 +0200 Subject: [PATCH 118/470] cleanup --- .../ObjcSessionManagerClientCodegen.java | 37 ++++++------------- 1 file changed, 11 insertions(+), 26 deletions(-) diff --git a/output/objcSessionManager/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerClientCodegen.java b/output/objcSessionManager/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerClientCodegen.java index e74eda786d0..77ce74430d7 100644 --- a/output/objcSessionManager/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerClientCodegen.java +++ b/output/objcSessionManager/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerClientCodegen.java @@ -245,50 +245,35 @@ public void processOpts() { supportingFiles.add(new SupportingFile("Object-body.mustache", coreFileFolder(), classPrefix + "Object.m")); supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.h")); supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.m")); - supportingFiles.add(new SupportingFile("ApiSessionManager-header.mustache", coreFileFolder(), classPrefix + "ApiSessionManager.h")); // !! - supportingFiles.add(new SupportingFile("ApiSessionManager-body.mustache", coreFileFolder(), classPrefix + "ApiSessionManager.m")); // !! + supportingFiles.add(new SupportingFile("ApiSessionManager-header.mustache", coreFileFolder(), classPrefix + "ApiSessionManager.h")); + supportingFiles.add(new SupportingFile("ApiSessionManager-body.mustache", coreFileFolder(), classPrefix + "ApiSessionManager.m")); supportingFiles.add(new SupportingFile("JSONResponseSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.h")); supportingFiles.add(new SupportingFile("JSONResponseSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.m")); supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.m")); supportingFiles.add(new SupportingFile("JSONRequestSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.h")); - supportingFiles.add(new SupportingFile("ResponseDeserializer-body.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.m")); // !! - supportingFiles.add(new SupportingFile("ResponseDeserializer-header.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.h")); // !! - supportingFiles.add(new SupportingFile("Sanitizer-body.mustache", coreFileFolder(), classPrefix + "Sanitizer.m")); // !! - supportingFiles.add(new SupportingFile("Sanitizer-header.mustache", coreFileFolder(), classPrefix + "Sanitizer.h")); // !! - supportingFiles.add(new SupportingFile("Logger-body.mustache", coreFileFolder(), classPrefix + "Logger.m")); // !! - supportingFiles.add(new SupportingFile("Logger-header.mustache", coreFileFolder(), classPrefix + "Logger.h")); // !! + supportingFiles.add(new SupportingFile("ResponseDeserializer-body.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.m")); + supportingFiles.add(new SupportingFile("ResponseDeserializer-header.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.h")); + supportingFiles.add(new SupportingFile("Sanitizer-body.mustache", coreFileFolder(), classPrefix + "Sanitizer.m")); + supportingFiles.add(new SupportingFile("Sanitizer-header.mustache", coreFileFolder(), classPrefix + "Sanitizer.h")); + supportingFiles.add(new SupportingFile("Logger-body.mustache", coreFileFolder(), classPrefix + "Logger.m")); + supportingFiles.add(new SupportingFile("Logger-header.mustache", coreFileFolder(), classPrefix + "Logger.h")); supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-body.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.m")); supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-header.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.h")); - //supportingFiles.add(new SupportingFile("Configuration-body.mustache", coreFileFolder(), classPrefix + "Configuration.m")); // !! - //supportingFiles.add(new SupportingFile("Configuration-header.mustache", coreFileFolder(), classPrefix + "Configuration.h")); // !! supportingFiles.add(new SupportingFile("Configuration-protocol.mustache", coreFileFolder(), classPrefix + "Configuration.h")); supportingFiles.add(new SupportingFile("DefaultConfiguration-body.mustache", coreFileFolder(), classPrefix + "DefaultConfiguration.m")); supportingFiles.add(new SupportingFile("DefaultConfiguration-header.mustache", coreFileFolder(), classPrefix + "DefaultConfiguration.h")); supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-header.mustache", coreFileFolder(), classPrefix + "BasicAuthTokenProvider.h")); supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-body.mustache", coreFileFolder(), classPrefix + "BasicAuthTokenProvider.m")); - supportingFiles.add(new SupportingFile("api-protocol.mustache", coreFileFolder(), classPrefix + "Api.h")); // !! + supportingFiles.add(new SupportingFile("api-protocol.mustache", coreFileFolder(), classPrefix + "Api.h")); supportingFiles.add(new SupportingFile("podspec.mustache", "", podName + ".podspec")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); // !! - supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); // !! + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); if(generateCoreData) { supportingFiles.add(new SupportingFile("xccurrentversion.mustache", (modelPackage() + "/" + modelFilesPath + "/").replace("/", File.separator) + classPrefix + "Model.xcdatamodeld", ".xccurrentversion")); supportingFiles.add(new SupportingFile("Model.xcdatamodel.mustache",(modelPackage() + "/" + modelFilesPath + "/").replace("/", File.separator) + classPrefix + "Model.xcdatamodeld" + File.separator + classPrefix + "Model.xcdatamodel", "contents")); } - - // is apiclient - //supportingFiles.add(new SupportingFile("ApiSessionManager-header.mustache", swaggerFolder, classPrefix + "ApiSessionManager.h")); - //supportingFiles.add(new SupportingFile("ApiSessionManager-body.mustache", swaggerFolder, classPrefix + "ApiSessionManager.m")); - - // protocol! - //supportingFiles.add(new SupportingFile("Configuration-protocol.mustache", swaggerFolder, classPrefix + "Configuration.h")); - //supportingFiles.add(new SupportingFile("DefaultConfiguration-body.mustache", swaggerFolder, classPrefix + "DefaultConfiguration.m")); - //supportingFiles.add(new SupportingFile("DefaultConfiguration-header.mustache", swaggerFolder, classPrefix + "DefaultConfiguration.h")); - - // missing! - //supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-header.mustache", swaggerFolder, classPrefix + "BasicAuthTokenProvider.h")); - //supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-body.mustache", swaggerFolder, classPrefix + "BasicAuthTokenProvider.m")); } @Override From f37bd4ab49d6044e1bf1893e51cf4bd87a80b890 Mon Sep 17 00:00:00 2001 From: Wolfgang Berger Date: Mon, 18 Jul 2016 13:01:57 +0200 Subject: [PATCH 119/470] rename ApiClient to ApiSessionManager, return cancellable tasks instead of request IDs which greatly reduces state while offering real cancellation, change to a protocol-based configuration with a default implementation, include a workarount for current JSONModel concurrency issues, add missing super call in QueryParamCollection initWithValuesAndFormat --- .../codegen/languages/ObjcClientCodegen.java | 11 +- ...stache => ApiSessionManager-body.mustache} | 198 ++++++++---------- ...ache => ApiSessionManager-header.mustache} | 92 +++----- .../objc/BasicAuthTokenProvider-body.mustache | 19 ++ .../BasicAuthTokenProvider-header.mustache | 14 ++ .../objc/Configuration-protocol.mustache | 75 +++++++ ...che => DefaultConfiguration-body.mustache} | 41 ++-- ...e => DefaultConfiguration-header.mustache} | 11 +- ...JSONValueTransformer+ISO8601-body.mustache | 1 + ...ONValueTransformer+ISO8601-header.mustache | 1 - .../main/resources/objc/Object-body.mustache | 29 +++ .../objc/QueryParamCollection-body.mustache | 12 +- .../src/main/resources/objc/api-body.mustache | 77 +++---- .../main/resources/objc/api-header.mustache | 4 +- .../main/resources/objc/api-protocol.mustache | 8 +- .../src/main/resources/objc/podspec.mustache | 2 +- 16 files changed, 316 insertions(+), 279 deletions(-) rename modules/swagger-codegen/src/main/resources/objc/{ApiClient-body.mustache => ApiSessionManager-body.mustache} (76%) rename modules/swagger-codegen/src/main/resources/objc/{ApiClient-header.mustache => ApiSessionManager-header.mustache} (59%) create mode 100644 modules/swagger-codegen/src/main/resources/objc/BasicAuthTokenProvider-body.mustache create mode 100644 modules/swagger-codegen/src/main/resources/objc/BasicAuthTokenProvider-header.mustache create mode 100644 modules/swagger-codegen/src/main/resources/objc/Configuration-protocol.mustache rename modules/swagger-codegen/src/main/resources/objc/{Configuration-body.mustache => DefaultConfiguration-body.mustache} (76%) rename modules/swagger-codegen/src/main/resources/objc/{Configuration-header.mustache => DefaultConfiguration-header.mustache} (92%) 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 e028083a74b..a8522f403d2 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 @@ -245,8 +245,8 @@ public void processOpts() { supportingFiles.add(new SupportingFile("Object-body.mustache", coreFileFolder(), classPrefix + "Object.m")); supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.h")); supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.m")); - supportingFiles.add(new SupportingFile("ApiClient-header.mustache", coreFileFolder(), classPrefix + "ApiClient.h")); - supportingFiles.add(new SupportingFile("ApiClient-body.mustache", coreFileFolder(), classPrefix + "ApiClient.m")); + supportingFiles.add(new SupportingFile("ApiSessionManager-header.mustache", coreFileFolder(), classPrefix + "ApiSessionManager.h")); + supportingFiles.add(new SupportingFile("ApiSessionManager-body.mustache", coreFileFolder(), classPrefix + "ApiSessionManager.m")); supportingFiles.add(new SupportingFile("JSONResponseSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.h")); supportingFiles.add(new SupportingFile("JSONResponseSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.m")); supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.m")); @@ -259,8 +259,11 @@ public void processOpts() { supportingFiles.add(new SupportingFile("Logger-header.mustache", coreFileFolder(), classPrefix + "Logger.h")); supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-body.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.m")); supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-header.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.h")); - supportingFiles.add(new SupportingFile("Configuration-body.mustache", coreFileFolder(), classPrefix + "Configuration.m")); - supportingFiles.add(new SupportingFile("Configuration-header.mustache", coreFileFolder(), classPrefix + "Configuration.h")); + supportingFiles.add(new SupportingFile("Configuration-protocol.mustache", coreFileFolder(), classPrefix + "Configuration.h")); + supportingFiles.add(new SupportingFile("DefaultConfiguration-body.mustache", coreFileFolder(), classPrefix + "DefaultConfiguration.m")); + supportingFiles.add(new SupportingFile("DefaultConfiguration-header.mustache", coreFileFolder(), classPrefix + "DefaultConfiguration.h")); + supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-header.mustache", coreFileFolder(), classPrefix + "BasicAuthTokenProvider.h")); + supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-body.mustache", coreFileFolder(), classPrefix + "BasicAuthTokenProvider.m")); supportingFiles.add(new SupportingFile("api-protocol.mustache", coreFileFolder(), classPrefix + "Api.h")); supportingFiles.add(new SupportingFile("podspec.mustache", "", podName + ".podspec")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiSessionManager-body.mustache similarity index 76% rename from modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache rename to modules/swagger-codegen/src/main/resources/objc/ApiSessionManager-body.mustache index 10cb6528d86..6b454063ada 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiSessionManager-body.mustache @@ -1,10 +1,16 @@ -#import "{{classPrefix}}ApiClient.h" +#import + +#import "{{classPrefix}}ApiSessionManager.h" +#import "{{classPrefix}}JSONRequestSerializer.h" +#import "{{classPrefix}}JSONResponseSerializer.h" +#import "{{classPrefix}}QueryParamCollection.h" +#import "{{classPrefix}}DefaultConfiguration.h" + + NSString *const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}ResponseObject"; -static NSUInteger requestId = 0; static bool offlineState = false; -static NSMutableSet * queuedRequests = nil; static bool cacheEnabled = false; static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilityStatusNotReachable; static void (^reachabilityChangeBlock)(int); @@ -34,40 +40,50 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) } -@interface {{classPrefix}}ApiClient () +@interface {{classPrefix}}ApiSessionManager () -@property (nonatomic, strong) NSDictionary* HTTPResponseHeaders; +@property (nonatomic, strong, readwrite) id<{{classPrefix}}Configuration> configuration; @end -@implementation {{classPrefix}}ApiClient +@implementation {{classPrefix}}ApiSessionManager - (instancetype)init { - NSString *baseUrl = [[{{classPrefix}}Configuration sharedConfig] host]; - return [self initWithBaseURL:[NSURL URLWithString:baseUrl]]; + + return [self initWithConfiguration:[{{classPrefix}}DefaultConfiguration sharedConfig]]; } - (instancetype)initWithBaseURL:(NSURL *)url { + + return [self initWithBaseURL:url + configuration:[{{classPrefix}}DefaultConfiguration sharedConfig]]; + +} + +- (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration { + + return [self initWithBaseURL:[NSURL URLWithString:configuration.host] configuration:configuration]; +} + +- (instancetype)initWithBaseURL:(NSURL *)url + configuration:(id<{{classPrefix}}Configuration>)configuration { + self = [super initWithBaseURL:url]; if (self) { - self.timeoutInterval = 60; + _configuration = configuration; + _timeoutInterval = 60; + _responseDeserializer = [[{{classPrefix}}ResponseDeserializer alloc] init]; + _sanitizer = [[{{classPrefix}}Sanitizer alloc] init]; + self.requestSerializer = [AFJSONRequestSerializer serializer]; self.responseSerializer = [AFJSONResponseSerializer serializer]; self.securityPolicy = [self customSecurityPolicy]; - self.responseDeserializer = [[{{classPrefix}}ResponseDeserializer alloc] init]; - self.sanitizer = [[{{classPrefix}}Sanitizer alloc] init]; + // configure reachability [self configureCacheReachibility]; } - return self; -} -+ (void)initialize { - if (self == [{{classPrefix}}ApiClient class]) { - queuedRequests = [[NSMutableSet alloc] init]; - // initialize URL cache - [self configureCacheWithMemoryAndDiskCapacity:4*1024*1024 diskSize:32*1024*1024]; - } + return self; } #pragma mark - Setter Methods @@ -113,43 +129,6 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) [NSURLCache setSharedURLCache:cache]; } -#pragma mark - Request Methods - -+(NSUInteger)requestQueueSize { - return [queuedRequests count]; -} - -+(NSNumber*) nextRequestId { - @synchronized(self) { - return @(++requestId); - } -} - -+(NSNumber*) queueRequest { - NSNumber* requestId = [[self class] nextRequestId]; - {{classPrefix}}DebugLog(@"added %@ to request queue", requestId); - [queuedRequests addObject:requestId]; - return requestId; -} - -+(void) cancelRequest:(NSNumber*)requestId { - [queuedRequests removeObject:requestId]; -} - --(Boolean) executeRequestWithId:(NSNumber*) requestId { - NSSet* matchingItems = [queuedRequests objectsPassingTest:^BOOL(id obj, BOOL *stop) { - return [obj intValue] == [requestId intValue]; - }]; - - if (matchingItems.count == 1) { - {{classPrefix}}DebugLog(@"removed request id %@", requestId); - [queuedRequests removeObject:requestId]; - return YES; - } else { - return NO; - } -} - #pragma mark - Reachability Methods +(AFNetworkReachabilityStatus) getReachabilityStatus { @@ -168,7 +147,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) [self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { reachabilityStatus = status; {{classPrefix}}DebugLog(@"reachability changed to %@",AFStringFromNetworkReachabilityStatus(status)); - [{{classPrefix}}ApiClient setOfflineState:status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable]; + [{{classPrefix}}ApiSessionManager setOfflineState:status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable]; // call the reachability block, if configured if (reachabilityChangeBlock != nil) { @@ -179,23 +158,19 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) [self.reachabilityManager startMonitoring]; } -#pragma mark - Operation Methods +#pragma mark - Task Methods -- (void) operationWithCompletionBlock: (NSURLRequest *)request - requestId: (NSNumber *) requestId - completionBlock: (void (^)(id, NSError *))completionBlock { - __weak __typeof(self)weakSelf = self; - NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { - __strong __typeof(weakSelf)strongSelf = weakSelf; - if (![strongSelf executeRequestWithId:requestId]) { - return; - } +- (NSURLSessionDataTask*) taskWithCompletionBlock: (NSURLRequest *)request + completionBlock: (void (^)(id, NSError *))completionBlock { + + NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { {{classPrefix}}DebugLogResponse(response, responseObject,request,error); - strongSelf.HTTPResponseHeaders = {{classPrefix}}__headerFieldsForResponse(response); + if(!error) { completionBlock(responseObject, nil); return; } + NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; if (responseObject) { // Add in the (parsed) response body. @@ -204,20 +179,18 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; completionBlock(nil, augmentedError); }]; - [op resume]; + + return task; } -- (void) downloadOperationWithCompletionBlock: (NSURLRequest *)request - requestId: (NSNumber *) requestId - completionBlock: (void (^)(id, NSError *))completionBlock { - __weak __typeof(self)weakSelf = self; - NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { - __strong __typeof(weakSelf)strongSelf = weakSelf; - if (![strongSelf executeRequestWithId:requestId]) { - return; - } - strongSelf.HTTPResponseHeaders = {{classPrefix}}__headerFieldsForResponse(response); +- (NSURLSessionDataTask*) downloadTaskWithCompletionBlock: (NSURLRequest *)request + completionBlock: (void (^)(id, NSError *))completionBlock { + + id<{{classPrefix}}Configuration> config = self.configuration; + + NSURLSessionDataTask* task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { {{classPrefix}}DebugLogResponse(response, responseObject,request,error); + if(error) { NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; if (responseObject) { @@ -226,8 +199,9 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; completionBlock(nil, augmentedError); } - NSString *directory = [self configuration].tempFolderPath ?: NSTemporaryDirectory(); - NSString * filename = {{classPrefix}}__fileNameForResponse(response); + + NSString *directory = config.tempFolderPath ?: NSTemporaryDirectory(); + NSString *filename = {{classPrefix}}__fileNameForResponse(response); NSString *filepath = [directory stringByAppendingPathComponent:filename]; NSURL *file = [NSURL fileURLWithPath:filepath]; @@ -236,24 +210,26 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) completionBlock(file, nil); }]; - [op resume]; + + return task; } -#pragma mark - Perform Request Methods - --(NSNumber*) requestWithPath: (NSString*) path - method: (NSString*) method - pathParams: (NSDictionary *) pathParams - queryParams: (NSDictionary*) queryParams - formParams: (NSDictionary *) formParams - files: (NSDictionary *) files - body: (id) body - headerParams: (NSDictionary*) headerParams - authSettings: (NSArray *) authSettings - requestContentType: (NSString*) requestContentType - responseContentType: (NSString*) responseContentType - responseType: (NSString *) responseType - completionBlock: (void (^)(id, NSError *))completionBlock { +#pragma mark - Perform Request Methods + +- (NSURLSessionTask*) requestWithPath: (NSString*) path + method: (NSString*) method + pathParams: (NSDictionary *) pathParams + queryParams: (NSDictionary*) queryParams + formParams: (NSDictionary *) formParams + files: (NSDictionary *) files + body: (id) body + headerParams: (NSDictionary*) headerParams + authSettings: (NSArray *) authSettings + requestContentType: (NSString*) requestContentType + responseContentType: (NSString*) responseContentType + responseType: (NSString *) responseType + completionBlock: (void (^)(id, NSError *))completionBlock { + // setting request serializer if ([requestContentType isEqualToString:@"application/json"]) { self.requestSerializer = [{{classPrefix}}JSONRequestSerializer serializer]; @@ -359,14 +335,16 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) [self postProcessRequest:request]; - NSNumber* requestId = [{{classPrefix}}ApiClient queueRequest]; + + NSURLSessionTask *task = nil; + if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) { - [self downloadOperationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { + task = [self downloadTaskWithCompletionBlock:request completionBlock:^(id data, NSError *error) { completionBlock(data, error); }]; } else { - [self operationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { + task = [self taskWithCompletionBlock:request completionBlock:^(id data, NSError *error) { NSError * serializationError; id response = [self.responseDeserializer deserialize:data class:responseType error:&serializationError]; if(!response && !error){ @@ -375,7 +353,10 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) completionBlock(response, error); }]; } - return requestId; + + [task resume]; + + return task; } //Added for easier override to modify request @@ -455,10 +436,11 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) NSMutableDictionary *headersWithAuth = [NSMutableDictionary dictionaryWithDictionary:*headers]; NSMutableDictionary *querysWithAuth = [NSMutableDictionary dictionaryWithDictionary:*querys]; - - NSDictionary* configurationAuthSettings = [[self configuration] authSettings]; + + id<{{classPrefix}}Configuration> config = self.configuration; for (NSString *auth in authSettings) { - NSDictionary *authSetting = configurationAuthSettings[auth]; + NSDictionary *authSetting = config.authSettings[auth]; + if(!authSetting) { // auth setting is set only if the key is non-empty continue; } @@ -479,11 +461,11 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) - (AFSecurityPolicy *) customSecurityPolicy { AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; - {{classPrefix}}Configuration *config = [self configuration]; + id<{{classPrefix}}Configuration> config = self.configuration; if (config.sslCaCert) { NSData *certData = [NSData dataWithContentsOfFile:config.sslCaCert]; - [securityPolicy setPinnedCertificates:@[certData]]; + [securityPolicy setPinnedCertificates:[NSSet setWithObject:certData]]; } if (config.verifySSL) { @@ -497,8 +479,4 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) return securityPolicy; } -- ({{classPrefix}}Configuration*) configuration { - return [{{classPrefix}}Configuration sharedConfig]; -} - @end diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiSessionManager-header.mustache similarity index 59% rename from modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache rename to modules/swagger-codegen/src/main/resources/objc/ApiSessionManager-header.mustache index be5eba32ee0..ef3a10a55ed 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiSessionManager-header.mustache @@ -1,22 +1,10 @@ -#import -#import #import -#import "{{classPrefix}}JSONResponseSerializer.h" -#import "{{classPrefix}}JSONRequestSerializer.h" -#import "{{classPrefix}}QueryParamCollection.h" #import "{{classPrefix}}Configuration.h" #import "{{classPrefix}}ResponseDeserializer.h" #import "{{classPrefix}}Sanitizer.h" -#import "{{classPrefix}}Logger.h" {{>licenceInfo}} -{{#models}}{{#model}}#import "{{classname}}.h" -{{/model}}{{/models}} -{{^models}}#import "{{classPrefix}}Object.h"{{/models}} - -@class {{classPrefix}}Configuration; - /** * A key for `NSError` user info dictionaries. * @@ -24,15 +12,15 @@ */ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; -@interface {{classPrefix}}ApiClient : AFHTTPSessionManager + +@interface {{classPrefix}}ApiSessionManager : AFHTTPSessionManager + +@property (nonatomic, strong, readonly) id<{{classPrefix}}Configuration> configuration; @property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy; @property(nonatomic, assign) NSTimeInterval timeoutInterval; @property(nonatomic, readonly) NSOperationQueue* queue; -/// In order to ensure the HTTPResponseHeaders are correct, it is recommended to initialize one {{classPrefix}}ApiClient instance per thread. -@property(nonatomic, readonly) NSDictionary* HTTPResponseHeaders; - @property(nonatomic, strong) id<{{classPrefix}}ResponseDeserializer> responseDeserializer; @property(nonatomic, strong) id<{{classPrefix}}Sanitizer> sanitizer; @@ -48,13 +36,6 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; */ +(void)setCacheEnabled:(BOOL) enabled; -/** - * Gets the request queue size - * - * @return The size of `queuedRequests` static variable. - */ -+(NSUInteger)requestQueueSize; - /** * Sets the client unreachable * @@ -83,27 +64,6 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; */ +(AFNetworkReachabilityStatus) getReachabilityStatus; -/** - * Gets the next request id - * - * @return The next executed request id. - */ -+(NSNumber*) nextRequestId; - -/** - * Generates request id and add it to the queue - * - * @return The next executed request id. - */ -+(NSNumber*) queueRequest; - -/** - * Removes request id from the queue - * - * @param requestId The request which will be removed. - */ -+(void) cancelRequest:(NSNumber*)requestId; - /** * Customizes the behavior when the reachability changed * @@ -136,6 +96,14 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; queryParams:(NSDictionary **)querys WithAuthSettings:(NSArray *)authSettings; + +/** + * Initializes the session manager with a configuration. + * + * @param configuration The configuration implementation + */ +- (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration; + /** * Performs request * @@ -150,21 +118,21 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; * @param responseContentType Response content-type. * @param completionBlock The block will be executed when the request completed. * - * @return The request id. + * @return The created session task. */ --(NSNumber*) requestWithPath:(NSString*) path - method:(NSString*) method - pathParams:(NSDictionary *) pathParams - queryParams:(NSDictionary*) queryParams - formParams:(NSDictionary *) formParams - files:(NSDictionary *) files - body:(id) body - headerParams:(NSDictionary*) headerParams - authSettings:(NSArray *) authSettings - requestContentType:(NSString*) requestContentType - responseContentType:(NSString*) responseContentType - responseType:(NSString *) responseType - completionBlock:(void (^)(id, NSError *))completionBlock; +- (NSURLSessionTask*) requestWithPath: (NSString*) path + method: (NSString*) method + pathParams: (NSDictionary *) pathParams + queryParams: (NSDictionary*) queryParams + formParams: (NSDictionary *) formParams + files: (NSDictionary *) files + body: (id) body + headerParams: (NSDictionary*) headerParams + authSettings: (NSArray *) authSettings + requestContentType: (NSString*) requestContentType + responseContentType: (NSString*) responseContentType + responseType: (NSString *) responseType + completionBlock: (void (^)(id, NSError *))completionBlock; /** * Custom security policy @@ -173,12 +141,4 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; */ - (AFSecurityPolicy *) customSecurityPolicy; -/** - * {{classPrefix}}Configuration return sharedConfig - * - * @return {{classPrefix}}Configuration - */ -- ({{classPrefix}}Configuration*) configuration; - - @end diff --git a/modules/swagger-codegen/src/main/resources/objc/BasicAuthTokenProvider-body.mustache b/modules/swagger-codegen/src/main/resources/objc/BasicAuthTokenProvider-body.mustache new file mode 100644 index 00000000000..a928e5e8f4e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/BasicAuthTokenProvider-body.mustache @@ -0,0 +1,19 @@ +#import "{{classPrefix}}BasicAuthTokenProvider.h" + +@implementation {{classPrefix}}BasicAuthTokenProvider + ++ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password { + + // return empty string if username and password are empty + if (username.length == 0 && password.length == 0){ + return @""; + } + + NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password]; + NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; + basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; + + return basicAuthCredentials; +} + +@end diff --git a/modules/swagger-codegen/src/main/resources/objc/BasicAuthTokenProvider-header.mustache b/modules/swagger-codegen/src/main/resources/objc/BasicAuthTokenProvider-header.mustache new file mode 100644 index 00000000000..dfb287568a0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/BasicAuthTokenProvider-header.mustache @@ -0,0 +1,14 @@ +/** The `{{classPrefix}}BasicAuthTokenProvider` class creates a basic auth token from username and password. + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + +#import + +@interface {{classPrefix}}BasicAuthTokenProvider : NSObject + ++ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password; + +@end \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/objc/Configuration-protocol.mustache b/modules/swagger-codegen/src/main/resources/objc/Configuration-protocol.mustache new file mode 100644 index 00000000000..db429a38150 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/Configuration-protocol.mustache @@ -0,0 +1,75 @@ +#import +#import "{{classPrefix}}Logger.h" + +{{>licenceInfo}} + +@protocol {{classPrefix}}Configuration + +/** + * Api logger + */ +@property (readonly, nonatomic) {{classPrefix}}Logger *logger; + +/** + * Base url + */ +@property (readonly, nonatomic) NSString *host; + +/** + * Api key values for Api Key type Authentication + */ +@property (readonly, nonatomic) NSDictionary *apiKey; + +/** + * Api key prefix values to be prepend to the respective api key + */ +@property (readonly, nonatomic) NSDictionary *apiKeyPrefix; + +/** + * Username for HTTP Basic Authentication + */ +@property (readonly, nonatomic) NSString *username; + +/** + * Password for HTTP Basic Authentication + */ +@property (readonly, nonatomic) NSString *password; + +/** + * Access token for OAuth + */ +@property (readonly, nonatomic) NSString *accessToken; + +/** + * Temp folder for file download + */ +@property (readonly, nonatomic) NSString *tempFolderPath; + +/** + * Debug switch, default false + */ +@property (readonly, nonatomic) BOOL debug; + +/** + * SSL/TLS verification + * Set this to NO to skip verifying SSL certificate when calling API from https server + */ +@property (readonly, nonatomic) BOOL verifySSL; + +/** + * SSL/TLS verification + * Set this to customize the certificate file to verify the peer + */ +@property (readonly, nonatomic) NSString *sslCaCert; + +/** + * Authentication Settings + */ +@property (readonly, nonatomic) NSDictionary *authSettings; + +/** +* Default headers for all services +*/ +@property (readonly, nonatomic, strong) NSDictionary *defaultHeaders; + +@end \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache b/modules/swagger-codegen/src/main/resources/objc/DefaultConfiguration-body.mustache similarity index 76% rename from modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache rename to modules/swagger-codegen/src/main/resources/objc/DefaultConfiguration-body.mustache index c1819d7fe19..7c2b6cda20b 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/DefaultConfiguration-body.mustache @@ -1,6 +1,7 @@ -#import "{{classPrefix}}Configuration.h" +#import "{{classPrefix}}DefaultConfiguration.h" +#import "{{classPrefix}}BasicAuthTokenProvider.h" -@interface {{classPrefix}}Configuration () +@interface {{classPrefix}}DefaultConfiguration () @property (nonatomic, strong) NSMutableDictionary *mutableDefaultHeaders; @property (nonatomic, strong) NSMutableDictionary *mutableApiKey; @@ -8,12 +9,12 @@ @end -@implementation {{classPrefix}}Configuration +@implementation {{classPrefix}}DefaultConfiguration #pragma mark - Singleton Methods + (instancetype) sharedConfig { - static {{classPrefix}}Configuration *shardConfig = nil; + static {{classPrefix}}DefaultConfiguration *shardConfig = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ shardConfig = [[self alloc] init]; @@ -26,17 +27,16 @@ - (instancetype) init { self = [super init]; if (self) { - self.apiClient = nil; - self.host = @"{{basePath}}"; - self.username = @""; - self.password = @""; - self.accessToken= @""; - self.verifySSL = YES; - self.mutableApiKey = [NSMutableDictionary dictionary]; - self.mutableApiKeyPrefix = [NSMutableDictionary dictionary]; - self.mutableDefaultHeaders = [NSMutableDictionary dictionary]; - {{#httpUserAgent}}self.mutableDefaultHeaders[@"User-Agent"] = @"{{httpUserAgent}}"{{/httpUserAgent}}; - self.logger = [{{classPrefix}}Logger sharedLogger]; + _host = @"{{basePath}}"; + _username = @""; + _password = @""; + _accessToken= @""; + _verifySSL = YES; + _mutableApiKey = [NSMutableDictionary dictionary]; + _mutableApiKeyPrefix = [NSMutableDictionary dictionary]; + _mutableDefaultHeaders = [NSMutableDictionary dictionary]; + {{#httpUserAgent}}_mutableDefaultHeaders[@"User-Agent"] = @"{{httpUserAgent}}"{{/httpUserAgent}}; + _logger = [{{classPrefix}}Logger sharedLogger]; } return self; } @@ -58,16 +58,9 @@ } - (NSString *) getBasicAuthToken { - // return empty string if username and password are empty - if (self.username.length == 0 && self.password.length == 0){ - return @""; - } - - NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.username, self.password]; - NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; - basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; - return basicAuthCredentials; + NSString *basicAuthToken = [{{classPrefix}}BasicAuthTokenProvider createBasicAuthTokenWithUsername:self.username password:self.password]; + return basicAuthToken; } - (NSString *) getAccessToken { diff --git a/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache b/modules/swagger-codegen/src/main/resources/objc/DefaultConfiguration-header.mustache similarity index 92% rename from modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache rename to modules/swagger-codegen/src/main/resources/objc/DefaultConfiguration-header.mustache index e727942a4f2..f93c864ecfe 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/DefaultConfiguration-header.mustache @@ -1,23 +1,16 @@ #import -#import "{{classPrefix}}ApiClient.h" -#import "{{classPrefix}}Logger.h" +#import "{{classPrefix}}Configuration.h" {{>licenceInfo}} -@class {{classPrefix}}ApiClient; +@interface {{classPrefix}}DefaultConfiguration : NSObject <{{classPrefix}}Configuration> -@interface {{classPrefix}}Configuration : NSObject /** * Default api logger */ @property (nonatomic, strong) {{classPrefix}}Logger * logger; -/** - * Default api client - */ -@property (nonatomic) {{classPrefix}}ApiClient *apiClient; - /** * Default base url */ diff --git a/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601-body.mustache b/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601-body.mustache index cec8bdeea27..b544a1dae58 100644 --- a/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601-body.mustache @@ -1,3 +1,4 @@ +#import #import "JSONValueTransformer+ISO8601.h" @implementation JSONValueTransformer (ISO8601) diff --git a/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601-header.mustache b/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601-header.mustache index 2a8d5b0c9e7..f621e7184a9 100644 --- a/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601-header.mustache @@ -1,5 +1,4 @@ #import -#import #import {{>licenceInfo}} diff --git a/modules/swagger-codegen/src/main/resources/objc/Object-body.mustache b/modules/swagger-codegen/src/main/resources/objc/Object-body.mustache index b4599c34f3f..88df6d6c9ae 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Object-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Object-body.mustache @@ -2,6 +2,35 @@ @implementation {{classPrefix}}Object +/** + * Workaround for JSONModel multithreading issues + * https://github.com/icanzilb/JSONModel/issues/441 + */ +- (instancetype)initWithDictionary:(NSDictionary *)dict error:(NSError **)err { + static NSMutableSet *classNames; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + classNames = [NSMutableSet new]; + }); + + BOOL initSync; + @synchronized([self class]) + { + NSString *className = NSStringFromClass([self class]); + initSync = ![classNames containsObject:className]; + if(initSync) + { + [classNames addObject:className]; + self = [super initWithDictionary:dict error:err]; + } + } + if(!initSync) + { + self = [super initWithDictionary:dict error:err]; + } + return self; +} + /** * Gets the string presentation of the object. * This method will be called when logging model object using `NSLog`. diff --git a/modules/swagger-codegen/src/main/resources/objc/QueryParamCollection-body.mustache b/modules/swagger-codegen/src/main/resources/objc/QueryParamCollection-body.mustache index 23d0c8eaa86..b1c901dbffa 100644 --- a/modules/swagger-codegen/src/main/resources/objc/QueryParamCollection-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/QueryParamCollection-body.mustache @@ -5,11 +5,15 @@ @synthesize values = _values; @synthesize format = _format; -- (id) initWithValuesAndFormat: (NSArray*) values - format: (NSString*) format { - _values = values; - _format = format; +- (id)initWithValuesAndFormat:(NSArray *)values + format:(NSString *)format { + self = [super init]; + if (self) { + _values = values; + _format = format; + } + return self; } 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 57fdc4ae6a7..d5354954668 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache @@ -7,7 +7,7 @@ @interface {{classname}} () -@property (nonatomic, strong) NSMutableDictionary *defaultHeaders; +@property (nonatomic, strong, readwrite) NSMutableDictionary *defaultHeaders; @end @@ -16,27 +16,14 @@ NSString* k{{classname}}ErrorDomain = @"{{classname}}ErrorDomain"; NSInteger k{{classname}}MissingParamErrorCode = 234513; -@synthesize apiClient = _apiClient; +@synthesize apiSessionManager = _apiSessionManager; #pragma mark - Initialize methods -- (instancetype) init { +-(instancetype) initWithApiSessionManager:({{classPrefix}}ApiSessionManager *)apiSessionManager { self = [super init]; if (self) { - {{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig]; - if (config.apiClient == nil) { - config.apiClient = [[{{classPrefix}}ApiClient alloc] init]; - } - _apiClient = config.apiClient; - _defaultHeaders = [NSMutableDictionary dictionary]; - } - return self; -} - -- (id) initWithApiClient:({{classPrefix}}ApiClient *)apiClient { - self = [super init]; - if (self) { - _apiClient = apiClient; + _apiSessionManager = apiSessionManager; _defaultHeaders = [NSMutableDictionary dictionary]; } return self; @@ -44,15 +31,6 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513; #pragma mark - -+ (instancetype)sharedAPI { - static {{classname}} *sharedAPI; - static dispatch_once_t once; - dispatch_once(&once, ^{ - sharedAPI = [[self alloc] init]; - }); - return sharedAPI; -} - -(NSString*) defaultHeaderForKey:(NSString*)key { return self.defaultHeaders[key]; } @@ -65,10 +43,6 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513; [self.defaultHeaders setValue:value forKey:key]; } --(NSUInteger) requestQueueSize { - return [{{classPrefix}}ApiClient requestQueueSize]; -} - #pragma mark - Api Methods {{#operation}} @@ -79,7 +53,7 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513; /// /// {{/allParams}} @returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} /// --(NSNumber*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} +-(NSURLSessionTask*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}} {{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler { {{#allParams}} @@ -118,7 +92,7 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513; {{^collectionFormat}}queryParams[@"{{baseName}}"] = {{paramName}};{{/collectionFormat}} } {{/queryParams}} - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders]; + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiSessionManager.configuration.defaultHeaders]; [headerParams addEntriesFromDictionary:self.defaultHeaders]; {{#headerParams}} if ({{paramName}} != nil) { @@ -126,7 +100,7 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513; } {{/headerParams}} // HTTP header `Accept` - NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[{{#produces}}@"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}}]]; + NSString *acceptHeader = [self.apiSessionManager.sanitizer selectHeaderAccept:@[{{#produces}}@"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}}]]; if(acceptHeader.length > 0) { headerParams[@"Accept"] = acceptHeader; } @@ -135,7 +109,7 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513; NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[{{#consumes}}@"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}]]; + NSString *requestContentType = [self.apiSessionManager.sanitizer selectHeaderContentType:@[{{#consumes}}@"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}]]; // Authentication setting NSArray *authSettings = @[{{#authMethods}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; @@ -159,24 +133,23 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513; {{/formParams}} {{/bodyParam}} - return [self.apiClient requestWithPath: resourcePath - method: @"{{httpMethod}}" - pathParams: pathParams - queryParams: queryParams - formParams: formParams - files: localVarFiles - body: bodyParam - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - responseType: {{^returnType}}nil{{/returnType}}{{#returnType}}@"{{{ returnType }}}"{{/returnType}} - completionBlock: ^(id data, NSError *error) { - if(handler) { - handler({{#returnType}}({{{ returnType }}})data, {{/returnType}}error); - } - } - ]; + return [self.apiSessionManager requestWithPath: resourcePath + method: @"{{httpMethod}}" + pathParams: pathParams + queryParams: queryParams + formParams: formParams + files: localVarFiles + body: bodyParam + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + responseType: {{^returnType}}nil{{/returnType}}{{#returnType}}@"{{{ returnType }}}"{{/returnType}} + completionBlock: ^(id data, NSError *error) { + if(handler) { + handler({{#returnType}}({{{ returnType }}})data, {{/returnType}}error); + } + }]; } {{/operation}} diff --git a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache index abe4cf64eb0..12fe8c7b954 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache @@ -11,8 +11,6 @@ extern NSString* k{{classname}}ErrorDomain; extern NSInteger k{{classname}}MissingParamErrorCode; -+(instancetype) sharedAPI; - {{#operations}} {{#operation}} /// {{{summary}}} @@ -23,7 +21,7 @@ extern NSInteger k{{classname}}MissingParamErrorCode; /// code:{{{code}}} message:"{{{message}}}"{{#hasMore}},{{/hasMore}}{{/responses}} /// /// @return {{{returnType}}} --(NSNumber*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} +-(NSURLSessionTask*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}} {{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler; diff --git a/modules/swagger-codegen/src/main/resources/objc/api-protocol.mustache b/modules/swagger-codegen/src/main/resources/objc/api-protocol.mustache index da87a712fa2..79c9da59ce4 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-protocol.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-protocol.mustache @@ -1,20 +1,18 @@ #import #import "{{classPrefix}}Object.h" -#import "{{classPrefix}}ApiClient.h" +#import "{{classPrefix}}ApiSessionManager.h" {{>licenceInfo}} @protocol {{classPrefix}}Api -@property(nonatomic, assign) {{classPrefix}}ApiClient *apiClient; +@property(readonly, nonatomic, strong) {{classPrefix}}ApiSessionManager *apiSessionManager; --(id) initWithApiClient:({{classPrefix}}ApiClient *)apiClient; +-(instancetype) initWithApiSessionManager:({{classPrefix}}ApiSessionManager *)apiSessionManager; -(void) addHeader:(NSString*)value forKey:(NSString*)key DEPRECATED_MSG_ATTRIBUTE("setDefaultHeaderValue:forKey:"); -(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key; -(NSString*) defaultHeaderForKey:(NSString*)key; --(NSUInteger) requestQueueSize; - @end diff --git a/modules/swagger-codegen/src/main/resources/objc/podspec.mustache b/modules/swagger-codegen/src/main/resources/objc/podspec.mustache index bd0bd9f328e..7a2b22bea28 100644 --- a/modules/swagger-codegen/src/main/resources/objc/podspec.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/podspec.mustache @@ -32,6 +32,6 @@ Pod::Spec.new do |s| s.dependency 'AFNetworking', '~> 3' s.dependency 'JSONModel', '~> 1.2' - s.dependency 'ISO8601', '~> 0.5' + s.dependency 'ISO8601', '~> 0.6' end From d4611e46450b2824644acf6a5a38a05ee36f1a89 Mon Sep 17 00:00:00 2001 From: Wolfgang Berger Date: Mon, 18 Jul 2016 13:05:07 +0200 Subject: [PATCH 120/470] remove custom codegen --- output/objcSessionManager/README.md | 74 -- output/objcSessionManager/pom.xml | 102 --- .../ObjcSessionManagerClientCodegen.java | 740 ----------------- .../services/io.swagger.codegen.CodegenConfig | 1 - .../ApiSessionManager-body.mustache | 483 ----------- .../ApiSessionManager-header.mustache | 149 ---- .../BasicAuthTokenProvider-body.mustache | 19 - .../BasicAuthTokenProvider-header.mustache | 14 - .../Configuration-protocol.mustache | 75 -- .../DefaultConfiguration-body.mustache | 159 ---- .../DefaultConfiguration-header.mustache | 129 --- .../JSONRequestSerializer-body.mustache | 37 - .../JSONRequestSerializer-header.mustache | 7 - .../JSONResponseSerializer-body.mustache | 39 - .../JSONResponseSerializer-header.mustache | 8 - ...JSONValueTransformer+ISO8601-body.mustache | 11 - ...ONValueTransformer+ISO8601-header.mustache | 8 - .../objcSessionManager/Logger-body.mustache | 74 -- .../objcSessionManager/Logger-header.mustache | 50 -- .../Model.xcdatamodel.mustache | 12 - .../NSManagedObject-body.mustache | 20 - .../NSManagedObject-header.mustache | 49 -- .../NSManagedObjectBuilder-body.mustache | 89 --- .../NSManagedObjectBuilder-header.mustache | 31 - .../objcSessionManager/Object-body.mustache | 42 - .../objcSessionManager/Object-header.mustache | 8 - .../QueryParamCollection-body.mustache | 20 - .../QueryParamCollection-header.mustache | 13 - .../objcSessionManager/README.mustache | 143 ---- .../ResponseDeserializer-body.mustache | 231 ------ .../ResponseDeserializer-header.mustache | 46 -- .../Sanitizer-body.mustache | 168 ---- .../Sanitizer-header.mustache | 45 -- .../objcSessionManager/api-body.mustache | 160 ---- .../objcSessionManager/api-header.mustache | 32 - .../objcSessionManager/api-protocol.mustache | 18 - .../objcSessionManager/api_doc.mustache | 85 -- .../objcSessionManager/git_push.sh.mustache | 52 -- .../objcSessionManager/gitignore.mustache | 53 -- .../objcSessionManager/licenceInfo.mustache | 23 - .../objcSessionManager/model-body.mustache | 59 -- .../objcSessionManager/model-header.mustache | 25 - .../objcSessionManager/model_doc.mustache | 11 - .../objcSessionManager/podspec.mustache | 37 - .../xccurrentversion.mustache | 8 - output/objcSessionManager_notasold/README.md | 74 -- output/objcSessionManager_notasold/pom.xml | 102 --- .../ObjcSessionManagerClientCodegen.java | 750 ------------------ .../services/io.swagger.codegen.CodegenConfig | 1 - .../ApiSessionManager-body.mustache | 461 ----------- .../ApiSessionManager-header.mustache | 147 ---- .../BasicAuthTokenProvider-body.mustache | 14 - .../BasicAuthTokenProvider-header.mustache | 14 - .../Configuration-protocol.mustache | 75 -- .../DefaultConfiguration-body.mustache | 157 ---- .../DefaultConfiguration-header.mustache | 134 ---- .../JSONRequestSerializer-body.mustache | 37 - .../JSONRequestSerializer-header.mustache | 7 - .../JSONResponseSerializer-body.mustache | 39 - .../JSONResponseSerializer-header.mustache | 8 - .../JSONValueTransformer+ISO8601.h | 8 - .../JSONValueTransformer+ISO8601.m | 11 - .../objcSessionManager/Object-body.mustache | 42 - .../objcSessionManager/Object-header.mustache | 8 - .../QueryParamCollection-body.mustache | 20 - .../QueryParamCollection-header.mustache | 13 - .../objcSessionManager/README.mustache | 143 ---- .../objcSessionManager/api-body.mustache | 161 ---- .../objcSessionManager/api-header.mustache | 34 - .../objcSessionManager/model-body.mustache | 59 -- .../objcSessionManager/model-header.mustache | 25 - .../objcSessionManager/podspec.mustache | 37 - output/objcSessionManager_old/README.md | 74 -- output/objcSessionManager_old/pom.xml | 102 --- .../ObjcSessionManagerClientCodegen.java | 750 ------------------ .../services/io.swagger.codegen.CodegenConfig | 1 - .../ApiSessionManager-body.mustache | 461 ----------- .../ApiSessionManager-header.mustache | 147 ---- .../BasicAuthTokenProvider-body.mustache | 14 - .../BasicAuthTokenProvider-header.mustache | 14 - .../Configuration-protocol.mustache | 75 -- .../DefaultConfiguration-body.mustache | 157 ---- .../DefaultConfiguration-header.mustache | 134 ---- .../JSONRequestSerializer-body.mustache | 37 - .../JSONRequestSerializer-header.mustache | 7 - .../JSONResponseSerializer-body.mustache | 39 - .../JSONResponseSerializer-header.mustache | 8 - .../JSONValueTransformer+ISO8601.h | 8 - .../JSONValueTransformer+ISO8601.m | 11 - .../objcSessionManager/Object-body.mustache | 42 - .../objcSessionManager/Object-header.mustache | 8 - .../QueryParamCollection-body.mustache | 20 - .../QueryParamCollection-header.mustache | 13 - .../objcSessionManager/README.mustache | 143 ---- .../objcSessionManager/api-body.mustache | 161 ---- .../objcSessionManager/api-header.mustache | 34 - .../objcSessionManager/model-body.mustache | 59 -- .../objcSessionManager/model-header.mustache | 25 - .../objcSessionManager/podspec.mustache | 37 - 99 files changed, 8821 deletions(-) delete mode 100644 output/objcSessionManager/README.md delete mode 100644 output/objcSessionManager/pom.xml delete mode 100644 output/objcSessionManager/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerClientCodegen.java delete mode 100644 output/objcSessionManager/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-header.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/BasicAuthTokenProvider-body.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/BasicAuthTokenProvider-header.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/Configuration-protocol.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/DefaultConfiguration-body.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/DefaultConfiguration-header.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/JSONRequestSerializer-body.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/JSONRequestSerializer-header.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/JSONResponseSerializer-body.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/JSONResponseSerializer-header.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601-body.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601-header.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/Logger-body.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/Logger-header.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/Model.xcdatamodel.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/NSManagedObject-body.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/NSManagedObject-header.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/NSManagedObjectBuilder-body.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/NSManagedObjectBuilder-header.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/Object-body.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/Object-header.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/QueryParamCollection-body.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/QueryParamCollection-header.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/README.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/ResponseDeserializer-body.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/ResponseDeserializer-header.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/Sanitizer-body.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/Sanitizer-header.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/api-body.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/api-header.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/api-protocol.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/api_doc.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/git_push.sh.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/gitignore.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/licenceInfo.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/model-body.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/model-header.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/model_doc.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/podspec.mustache delete mode 100644 output/objcSessionManager/src/main/resources/objcSessionManager/xccurrentversion.mustache delete mode 100644 output/objcSessionManager_notasold/README.md delete mode 100644 output/objcSessionManager_notasold/pom.xml delete mode 100644 output/objcSessionManager_notasold/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerClientCodegen.java delete mode 100644 output/objcSessionManager_notasold/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig delete mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache delete mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/ApiSessionManager-header.mustache delete mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/BasicAuthTokenProvider-body.mustache delete mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/BasicAuthTokenProvider-header.mustache delete mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/Configuration-protocol.mustache delete mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/DefaultConfiguration-body.mustache delete mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/DefaultConfiguration-header.mustache delete mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONRequestSerializer-body.mustache delete mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONRequestSerializer-header.mustache delete mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONResponseSerializer-body.mustache delete mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONResponseSerializer-header.mustache delete mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.h delete mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.m delete mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/Object-body.mustache delete mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/Object-header.mustache delete mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/QueryParamCollection-body.mustache delete mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/QueryParamCollection-header.mustache delete mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/README.mustache delete mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/api-body.mustache delete mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/api-header.mustache delete mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/model-body.mustache delete mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/model-header.mustache delete mode 100644 output/objcSessionManager_notasold/src/main/resources/objcSessionManager/podspec.mustache delete mode 100644 output/objcSessionManager_old/README.md delete mode 100644 output/objcSessionManager_old/pom.xml delete mode 100644 output/objcSessionManager_old/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerClientCodegen.java delete mode 100644 output/objcSessionManager_old/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig delete mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache delete mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/ApiSessionManager-header.mustache delete mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/BasicAuthTokenProvider-body.mustache delete mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/BasicAuthTokenProvider-header.mustache delete mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/Configuration-protocol.mustache delete mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/DefaultConfiguration-body.mustache delete mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/DefaultConfiguration-header.mustache delete mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONRequestSerializer-body.mustache delete mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONRequestSerializer-header.mustache delete mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONResponseSerializer-body.mustache delete mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONResponseSerializer-header.mustache delete mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.h delete mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.m delete mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/Object-body.mustache delete mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/Object-header.mustache delete mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/QueryParamCollection-body.mustache delete mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/QueryParamCollection-header.mustache delete mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/README.mustache delete mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/api-body.mustache delete mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/api-header.mustache delete mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/model-body.mustache delete mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/model-header.mustache delete mode 100644 output/objcSessionManager_old/src/main/resources/objcSessionManager/podspec.mustache diff --git a/output/objcSessionManager/README.md b/output/objcSessionManager/README.md deleted file mode 100644 index f70096077f0..00000000000 --- a/output/objcSessionManager/README.md +++ /dev/null @@ -1,74 +0,0 @@ -# Swagger Codegen for the objc-SessionManager library - -## Overview -This is a boiler-plate project to generate your own client library with Swagger. It's goal is -to get you started with the basic plumbing so you can put in your own logic. It won't work without -your changes applied. - -## What's Swagger? -The goal of Swagger™ is to define a standard, language-agnostic interface to REST APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined via Swagger, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. Similar to what interfaces have done for lower-level programming, Swagger removes the guesswork in calling the service. - - -Check out [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) for additional information about the Swagger project, including additional libraries with support for other languages and more. - -## How do I use this? -At this point, you've likely generated a client setup. It will include something along these lines: - -``` -. -|- README.md // this file -|- pom.xml // build script -|-- src -|--- main -|---- java -|----- io.swagger.codegen.languages.ObjcSessionmanagerGenerator.java // generator file -|---- resources -|----- objc-SessionManager // template files -|----- META-INF -|------ services -|------- io.swagger.codegen.CodegenConfig -``` - -You _will_ need to make changes in at least the following: - -`ObjcSessionmanagerGenerator.java` - -Templates in this folder: - -`src/main/resources/objc-SessionManager` - -Once modified, you can run this: - -``` -mvn package -``` - -In your generator project. A single jar file will be produced in `target`. You can now use that with codegen: - -``` -java -cp /path/to/swagger-codegen-distribution:/path/to/your/jar io.swagger.codegen.Codegen -l objc-SessionManager -o ./test -``` - -Now your templates are available to the client generator and you can write output values - -## But how do I modify this? -The `ObjcSessionmanagerGenerator.java` has comments in it--lots of comments. There is no good substitute -for reading the code more, though. See how the `ObjcSessionmanagerGenerator` implements `CodegenConfig`. -That class has the signature of all values that can be overridden. - -For the templates themselves, you have a number of values available to you for generation. -You can execute the `java` command from above while passing different debug flags to show -the object you have available during client generation: - -``` -# The following additional debug options are available for all codegen targets: -# -DdebugSwagger prints the OpenAPI Specification as interpreted by the codegen -# -DdebugModels prints models passed to the template engine -# -DdebugOperations prints operations passed to the template engine -# -DdebugSupportingFiles prints additional data passed to the template engine - -java -DdebugOperations -cp /path/to/swagger-codegen-distribution:/path/to/your/jar io.swagger.codegen.Codegen -l objc-SessionManager -o ./test -``` - -Will, for example, output the debug info for operations. You can use this info -in the `api.mustache` file. \ No newline at end of file diff --git a/output/objcSessionManager/pom.xml b/output/objcSessionManager/pom.xml deleted file mode 100644 index d4545ae9dec..00000000000 --- a/output/objcSessionManager/pom.xml +++ /dev/null @@ -1,102 +0,0 @@ - - 4.0.0 - io.swagger - objc-SessionManager-swagger-codegen - jar - objc-SessionManager-swagger-codegen - 1.0.0 - - 2.2.0 - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.12 - - - - loggerPath - conf/log4j.properties - - - -Xms512m -Xmx1500m - methods - pertest - - - - - - 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-codegen - ${swagger-codegen-version} - provided - - - - 2.2.0-SNAPSHOT - 1.0.0 - 4.8.1 - - diff --git a/output/objcSessionManager/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerClientCodegen.java b/output/objcSessionManager/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerClientCodegen.java deleted file mode 100644 index 77ce74430d7..00000000000 --- a/output/objcSessionManager/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerClientCodegen.java +++ /dev/null @@ -1,740 +0,0 @@ -package io.swagger.codegen.languages; - -import io.swagger.codegen.*; -import io.swagger.models.ArrayModel; -import io.swagger.models.Model; -import io.swagger.models.properties.*; - -import java.io.File; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.lang3.StringUtils; - -public class ObjcSessionManagerClientCodegen extends DefaultCodegen implements CodegenConfig { - public static final String CLASS_PREFIX = "classPrefix"; - public static final String POD_NAME = "podName"; - public static final String AUTHOR_NAME = "authorName"; - public static final String AUTHOR_EMAIL = "authorEmail"; - public static final String LICENSE = "license"; - public static final String GIT_REPO_URL = "gitRepoURL"; - public static final String DEFAULT_LICENSE = "Apache License, Version 2.0"; - public static final String CORE_DATA = "coreData"; - - protected Set foundationClasses = new HashSet(); - protected String podName = "SwaggerClient"; - protected String podVersion = "1.0.0"; - protected String classPrefix = "SWG"; - protected String authorName = "Swagger"; - protected String authorEmail = "apiteam@swagger.io"; - protected String license = DEFAULT_LICENSE; - protected String gitRepoURL = "https://github.com/swagger-api/swagger-codegen"; - protected String[] specialWords = {"new", "copy"}; - protected String apiDocPath = "docs/"; - protected String modelDocPath = "docs/"; - protected String modelFilesPath = "Model/"; - protected String coreFilesPath = "Core/"; - protected String apiFilesPath = "Api/"; - - protected boolean generateCoreData = false; - - protected Set advancedMapingTypes = new HashSet(); - - public ObjcSessionManagerClientCodegen() { - super(); - - outputFolder = "generated-code" + File.separator + "objcSessionManager"; - modelTemplateFiles.put("model-header.mustache", ".h"); - modelTemplateFiles.put("model-body.mustache", ".m"); - apiTemplateFiles.put("api-header.mustache", ".h"); - apiTemplateFiles.put("api-body.mustache", ".m"); - embeddedTemplateDir = templateDir = "objcSessionManager"; - modelDocTemplateFiles.put("model_doc.mustache", ".md"); - apiDocTemplateFiles.put("api_doc.mustache", ".md"); - - defaultIncludes.clear(); - defaultIncludes.add("bool"); - defaultIncludes.add("BOOL"); - defaultIncludes.add("int"); - defaultIncludes.add("NSURL"); - defaultIncludes.add("NSString"); - defaultIncludes.add("NSObject"); - defaultIncludes.add("NSArray"); - defaultIncludes.add("NSNumber"); - defaultIncludes.add("NSDate"); - defaultIncludes.add("NSDictionary"); - defaultIncludes.add("NSMutableArray"); - defaultIncludes.add("NSMutableDictionary"); - defaultIncludes.add("NSManagedObject"); - defaultIncludes.add("NSData"); - - advancedMapingTypes.add("NSDictionary"); - advancedMapingTypes.add("NSArray"); - advancedMapingTypes.add("NSMutableArray"); - advancedMapingTypes.add("NSMutableDictionary"); - advancedMapingTypes.add("NSObject"); - advancedMapingTypes.add("NSNumber"); - advancedMapingTypes.add("NSURL"); - advancedMapingTypes.add("NSString"); - advancedMapingTypes.add("NSDate"); - - languageSpecificPrimitives.clear(); - languageSpecificPrimitives.add("NSNumber"); - languageSpecificPrimitives.add("NSString"); - languageSpecificPrimitives.add("NSObject"); - languageSpecificPrimitives.add("NSDate"); - languageSpecificPrimitives.add("NSData"); - languageSpecificPrimitives.add("NSURL"); - languageSpecificPrimitives.add("bool"); - languageSpecificPrimitives.add("BOOL"); - - typeMapping.clear(); - typeMapping.put("enum", "NSString"); - typeMapping.put("date", "NSDate"); - typeMapping.put("datetime", "NSDate"); - typeMapping.put("boolean", "NSNumber"); - typeMapping.put("string", "NSString"); - typeMapping.put("integer", "NSNumber"); - typeMapping.put("int", "NSNumber"); - typeMapping.put("float", "NSNumber"); - typeMapping.put("long", "NSNumber"); - typeMapping.put("double", "NSNumber"); - typeMapping.put("array", "NSArray"); - typeMapping.put("map", "NSDictionary"); - typeMapping.put("number", "NSNumber"); - typeMapping.put("bigdecimal", "NSNumber"); - typeMapping.put("List", "NSArray"); - typeMapping.put("object", "NSObject"); - typeMapping.put("file", "NSURL"); - typeMapping.put("binary", "NSData"); - typeMapping.put("bytearray", "NSData"); - typeMapping.put("byte", "NSData"); - typeMapping.put("uuid", "NSString"); - typeMapping.put("password", "NSString"); - - // ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm - setReservedWordsLowerCase( - Arrays.asList( - // local variable names in API methods (endpoints) - "resourcePath", "pathParams", "queryParams", "headerParams", - "responseContentType", "requestContentType", "authSettings", - "formParams", "localVarFiles", "bodyParam", - // objc reserved words - "auto", "else", "long", "switch", - "break", "enum", "register", "typedef", - "case", "extern", "return", "union", - "char", "float", "short", "unsigned", - "const", "for", "signed", "void", - "continue", "goto", "sizeof", "volatile", - "default", "if", "id", "static", "while", - "do", "int", "struct", "_Packed", - "double", "protocol", "interface", "implementation", - "NSObject", "NSInteger", "NSNumber", "CGFloat", - "property", "nonatomic", "retain", "strong", - "weak", "unsafe_unretained", "readwrite", "readonly", - "description" - )); - - importMapping = new HashMap(); - - foundationClasses = new HashSet( - Arrays.asList( - "NSNumber", - "NSObject", - "NSString", - "NSDate", - "NSData", - "NSURL", - "NSDictionary") - ); - - instantiationTypes.put("array", "NSMutableArray"); - instantiationTypes.put("map", "NSMutableDictionary"); - - cliOptions.clear(); - cliOptions.add(new CliOption(CORE_DATA, "Should generate core data models").defaultValue("false")); - cliOptions.add(new CliOption(CLASS_PREFIX, "prefix for generated classes (convention: Abbreviation of pod name e.g. `HN` for `HackerNews`).`") - .defaultValue("SWG")); - cliOptions.add(new CliOption(POD_NAME, "cocoapods package name (convention: CameCase).") - .defaultValue("SwaggerClient")); - cliOptions.add(new CliOption(CodegenConstants.POD_VERSION, "cocoapods package version.") - .defaultValue("1.0.0")); - cliOptions.add(new CliOption(AUTHOR_NAME, "Name to use in the podspec file.").defaultValue("Swagger")); - cliOptions.add(new CliOption(AUTHOR_EMAIL, "Email to use in the podspec file.").defaultValue("apiteam@swagger.io")); - cliOptions.add(new CliOption(GIT_REPO_URL, "URL for the git repo where this podspec should point to.") - .defaultValue("https://github.com/swagger-api/swagger-codegen")); - } - - @Override - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - @Override - public String getName() { - return "objc-SessionManager"; - } - - @Override - public String getHelp() { - return "Generates an Objective-C client library."; - } - - @Override - public void processOpts() { - super.processOpts(); - - if (additionalProperties.containsKey(POD_NAME)) { - setPodName((String) additionalProperties.get(POD_NAME)); - } - - if (additionalProperties.containsKey(CodegenConstants.POD_VERSION)) { - setPodVersion((String) additionalProperties.get(CodegenConstants.POD_VERSION)); - } - - if (additionalProperties.containsKey(CORE_DATA)) { - Object coreData = additionalProperties.get(CORE_DATA); - if(((String)coreData).equalsIgnoreCase("true")) { - generateCoreData = true; - } - } - if (additionalProperties.containsKey(CLASS_PREFIX)) { - setClassPrefix((String) additionalProperties.get(CLASS_PREFIX)); - } - - if (additionalProperties.containsKey(AUTHOR_NAME)) { - setAuthorName((String) additionalProperties.get(AUTHOR_NAME)); - } - - if (additionalProperties.containsKey(AUTHOR_EMAIL)) { - setAuthorEmail((String) additionalProperties.get(AUTHOR_EMAIL)); - } - - if (additionalProperties.containsKey(GIT_REPO_URL)) { - setGitRepoURL((String) additionalProperties.get(GIT_REPO_URL)); - } - - if(generateCoreData) { - modelTemplateFiles.put("NSManagedObject-header.mustache", "ManagedObject.h"); - modelTemplateFiles.put("NSManagedObject-body.mustache", "ManagedObject.m"); - modelTemplateFiles.put("NSManagedObjectBuilder-header.mustache", "ManagedObjectBuilder.h"); - modelTemplateFiles.put("NSManagedObjectBuilder-body.mustache", "ManagedObjectBuilder.m"); - } - - additionalProperties.put(POD_NAME, podName); - additionalProperties.put(CodegenConstants.POD_VERSION, podVersion); - additionalProperties.put(CLASS_PREFIX, classPrefix); - additionalProperties.put(AUTHOR_NAME, authorName); - additionalProperties.put(AUTHOR_EMAIL, authorEmail); - additionalProperties.put(GIT_REPO_URL, gitRepoURL); - additionalProperties.put(LICENSE, license); - - // make api and model doc path available in mustache template - additionalProperties.put("apiDocPath", apiDocPath); - additionalProperties.put("modelDocPath", modelDocPath); - additionalProperties.put("useCoreData", generateCoreData); - - modelPackage = podName; - apiPackage = podName; - - supportingFiles.add(new SupportingFile("Object-header.mustache", coreFileFolder(), classPrefix + "Object.h")); - supportingFiles.add(new SupportingFile("Object-body.mustache", coreFileFolder(), classPrefix + "Object.m")); - supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.h")); - supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.m")); - supportingFiles.add(new SupportingFile("ApiSessionManager-header.mustache", coreFileFolder(), classPrefix + "ApiSessionManager.h")); - supportingFiles.add(new SupportingFile("ApiSessionManager-body.mustache", coreFileFolder(), classPrefix + "ApiSessionManager.m")); - supportingFiles.add(new SupportingFile("JSONResponseSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.h")); - supportingFiles.add(new SupportingFile("JSONResponseSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.m")); - supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.m")); - supportingFiles.add(new SupportingFile("JSONRequestSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.h")); - supportingFiles.add(new SupportingFile("ResponseDeserializer-body.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.m")); - supportingFiles.add(new SupportingFile("ResponseDeserializer-header.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.h")); - supportingFiles.add(new SupportingFile("Sanitizer-body.mustache", coreFileFolder(), classPrefix + "Sanitizer.m")); - supportingFiles.add(new SupportingFile("Sanitizer-header.mustache", coreFileFolder(), classPrefix + "Sanitizer.h")); - supportingFiles.add(new SupportingFile("Logger-body.mustache", coreFileFolder(), classPrefix + "Logger.m")); - supportingFiles.add(new SupportingFile("Logger-header.mustache", coreFileFolder(), classPrefix + "Logger.h")); - supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-body.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.m")); - supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-header.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.h")); - supportingFiles.add(new SupportingFile("Configuration-protocol.mustache", coreFileFolder(), classPrefix + "Configuration.h")); - supportingFiles.add(new SupportingFile("DefaultConfiguration-body.mustache", coreFileFolder(), classPrefix + "DefaultConfiguration.m")); - supportingFiles.add(new SupportingFile("DefaultConfiguration-header.mustache", coreFileFolder(), classPrefix + "DefaultConfiguration.h")); - supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-header.mustache", coreFileFolder(), classPrefix + "BasicAuthTokenProvider.h")); - supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-body.mustache", coreFileFolder(), classPrefix + "BasicAuthTokenProvider.m")); - supportingFiles.add(new SupportingFile("api-protocol.mustache", coreFileFolder(), classPrefix + "Api.h")); - supportingFiles.add(new SupportingFile("podspec.mustache", "", podName + ".podspec")); - supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); - supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); - - if(generateCoreData) { - supportingFiles.add(new SupportingFile("xccurrentversion.mustache", (modelPackage() + "/" + modelFilesPath + "/").replace("/", File.separator) + classPrefix + "Model.xcdatamodeld", ".xccurrentversion")); - supportingFiles.add(new SupportingFile("Model.xcdatamodel.mustache",(modelPackage() + "/" + modelFilesPath + "/").replace("/", File.separator) + classPrefix + "Model.xcdatamodeld" + File.separator + classPrefix + "Model.xcdatamodel", "contents")); - } - } - - @Override - public String toInstantiationType(Property p) { - if (p instanceof MapProperty) { - return instantiationTypes.get("map"); - } else if (p instanceof ArrayProperty) { - return instantiationTypes.get("array"); - } else { - return null; - } - } - - @Override - public String getTypeDeclaration(String name) { - if (languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name)) { - return name; - } else { - return name + "*"; - } - } - - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if (typeMapping.containsKey(swaggerType.toLowerCase())) { - type = typeMapping.get(swaggerType.toLowerCase()); - if (languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type)) { - return toModelNameWithoutReservedWordCheck(type); - } - } else { - type = swaggerType; - } - return toModelNameWithoutReservedWordCheck(type); - } - - @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - String innerTypeDeclaration = getTypeDeclaration(inner); - if (innerTypeDeclaration.endsWith("*")) { - innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); - } - // In this condition, type of property p is array of primitive, - // return container type with pointer, e.g. `NSArray**' - if (languageSpecificPrimitives.contains(innerTypeDeclaration)) { - return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*"; - } - // In this condition, type of property p is array of model, - // return container type combine inner type with pointer, e.g. `NSArray*' - else { - for (String sd : advancedMapingTypes) { - if(innerTypeDeclaration.startsWith(sd)) { - return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*"; - } - } - return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*"; - } - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - - String innerTypeDeclaration = getTypeDeclaration(inner); - - if (innerTypeDeclaration.endsWith("*")) { - innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); - } - if (languageSpecificPrimitives.contains(innerTypeDeclaration)) { - return getSwaggerType(p) + "*"; - } else { - for (String s : advancedMapingTypes) { - if(innerTypeDeclaration.startsWith(s)) { - return getSwaggerType(p) + "*"; - } - } - return getSwaggerType(p) + "*"; - } - } else { - String swaggerType = getSwaggerType(p); - // In this condition, type of p is objective-c primitive type, e.g. `NSSNumber', - // return type of p with pointer, e.g. `NSNumber*' - if (languageSpecificPrimitives.contains(swaggerType) && - foundationClasses.contains(swaggerType)) { - return swaggerType + "*"; - } - // In this condition, type of p is c primitive type, e.g. `bool', - // return type of p, e.g. `bool' - else if (languageSpecificPrimitives.contains(swaggerType)) { - return swaggerType; - } - // In this condition, type of p is objective-c object type, e.g. `SWGPet', - // return type of p with pointer, e.g. `SWGPet*' - else { - return swaggerType + "*"; - } - } - } - - @Override - public boolean isDataTypeBinary(String dataType) { - return dataType.toLowerCase().startsWith("nsdata"); - } - - @Override - public String toModelName(String type) { - // model name cannot use reserved keyword - if (reservedWords.contains(type)) { - LOGGER.warn(type+ " (reserved word) cannot be used as model name. Renamed to " + ("model_" + type) + " before further processing"); - type = "model_" + type; // e.g. return => ModelReturn (after camelize) - } - - // model name starts with number - /* no need for the fix below as objc model starts with prefix (e.g. SWG) - if (type.matches("^\\d.*")) { - LOGGER.warn(type + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + type)); - type = "model_" + type; // e.g. 200Response => Model200Response (after camelize) - } - */ - - return toModelNameWithoutReservedWordCheck(type); - } - - /* - * Convert input to proper model name according to ObjC style guide - * without checking for reserved words - * - * @param type Model anme - * @return model Name in ObjC style guide - */ - public String toModelNameWithoutReservedWordCheck(String type) { - type = type.replaceAll("[^0-9a-zA-Z_]", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - - // language build-in classes - if (typeMapping.keySet().contains(type) || - foundationClasses.contains(type) || - importMapping.values().contains(type) || - defaultIncludes.contains(type) || - languageSpecificPrimitives.contains(type)) { - return camelize(type); - } - // custom classes - else { - if (!StringUtils.isEmpty(modelNameSuffix)) { // set model suffix - type = type + "_" + modelNameSuffix; - } - - if (!StringUtils.isEmpty(modelNamePrefix)) { // set model prefix - type = modelNamePrefix + "_" + type; - } - - return classPrefix + camelize(type); // add class prefix - } - } - - @Override - public String toModelFilename(String name) { - // should be the same as the model name - return toModelName(name); - } - - @Override - protected void setNonArrayMapProperty(CodegenProperty property, String type) { - super.setNonArrayMapProperty(property, type); - if ("NSDictionary".equals(type)) { - property.setter = "initWithDictionary"; - } else { - property.setter = "initWithValues"; - } - } - - @Override - public String toModelImport(String name) { - return name; - } - - @Override - public String apiDocFileFolder() { - return (outputFolder + "/" + apiDocPath).replace("/", File.separator); - } - - @Override - public String modelDocFileFolder() { - return (outputFolder + "/" + modelDocPath).replace("/", File.separator); - } - - @Override - public String toModelDocFilename(String name) { - return toModelName(name); - } - - @Override - public String toApiDocFilename(String name) { - return toApiName(name); - } - - @Override - public String apiFileFolder() { - return (outputFolder + "/"+ apiPackage() + "/" + apiFilesPath).replace("/", File.separator); - } - - @Override - public String modelFileFolder() { - return (outputFolder + "/"+ modelPackage() + "/" + modelFilesPath).replace("/", File.separator); - } - - public String coreFileFolder() { - return (apiPackage() + "/" + coreFilesPath).replace("/", File.separator); - } - - @Override - public String toApiName(String name) { - return classPrefix + camelize(name) + "Api"; - } - - @Override - public String toApiFilename(String name) { - return classPrefix + camelize(name) + "Api"; - } - - @Override - public String toVarName(String name) { - // sanitize name - name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - - // if it's all upper case, do noting - if (name.matches("^[A-Z_]$")) { - return name; - } - - // if name starting with special word, escape with '_' - for(int i =0; i < specialWords.length; i++) { - if (name.matches("(?i:^" + specialWords[i] + ".*)")) - name = escapeSpecialWord(name); - } - - // camelize (lower first character) the variable name - // e.g. `pet_id` to `petId` - name = camelize(name, true); - - // for reserved word or word starting with number, prepend `_` - if (isReservedWord(name) || name.matches("^\\d.*")) { - name = escapeReservedWord(name); - } - - - return name; - } - - @Override - public String toParamName(String name) { - // should be the same as variable name - return toVarName(name); - } - - @Override - public String escapeReservedWord(String name) { - return "_" + name; - } - - @SuppressWarnings("static-method") - public String escapeSpecialWord(String name) { - return "var_" + name; - } - - @Override - public String toOperationId(String operationId) { - // throw exception if method name is empty - if (StringUtils.isEmpty(operationId)) { - throw new RuntimeException("Empty method name (operationId) not allowed"); - } - - // method name cannot use reserved keyword, e.g. return - if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId), true)); - operationId = "call_" + operationId; - } - - return camelize(sanitizeName(operationId), true); - } - - public void setClassPrefix(String classPrefix) { - this.classPrefix = classPrefix; - } - - public void setPodName(String podName) { - this.podName = podName; - } - - public void setPodVersion(String podVersion) { - this.podVersion = podVersion; - } - - public void setAuthorEmail(String authorEmail) { - this.authorEmail = authorEmail; - } - - public void setAuthorName(String authorName) { - this.authorName = authorName; - } - - public void setGitRepoURL(String gitRepoURL) { - this.gitRepoURL = gitRepoURL; - } - - public void setLicense(String license) { - this.license = license; - } - - @Override - public Map postProcessOperations(Map objs) { - Map operations = (Map) objs.get("operations"); - if (operations != null) { - List ops = (List) operations.get("operation"); - for (CodegenOperation operation : ops) { - if (!operation.allParams.isEmpty()) { - String firstParamName = operation.allParams.get(0).paramName; - operation.vendorExtensions.put("firstParamAltName", camelize(firstParamName)); - } - } - } - return objs; - } - - @Override - public void postProcessModelProperty(CodegenModel model, CodegenProperty property){ - super.postProcessModelProperty(model,property); - property.vendorExtensions.put("x-uppercaseName", camelize(property.name)); - } - - /** - * 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; - } - - @Override - public void setParameterExampleValue(CodegenParameter p) { - String example; - - if (p.defaultValue == null) { - example = p.example; - } else { - example = p.defaultValue; - } - - String type = p.baseType; - if (type == null) { - type = p.dataType; - } - - if ("NSString*".equalsIgnoreCase(type)) { - if (example == null) { - example = p.paramName + "_example"; - } - example = "@\"" + escapeText(example) + "\""; - } else if ("NSNumber*".equals(type)) { - if (example == null) { - example = "56"; - } - example = "@" + example; - /* OBJC uses NSNumber to represent both int, long, double and float - } else if ("Float".equalsIgnoreCase(type) || "Double".equalsIgnoreCase(type)) { - if (example == null) { - example = "3.4"; - } */ - } else if ("BOOLEAN".equalsIgnoreCase(type) || "bool".equalsIgnoreCase(type)) { - if (example == null) { - example = "True"; - } - } else if ("NSURL*".equalsIgnoreCase(type)) { - if (example == null) { - example = "/path/to/file"; - } - //[NSURL fileURLWithPath:@"path/to/file"] - example = "[NSURL fileURLWithPath:@\"" + escapeText(example) + "\"]"; - /*} else if ("NSDate".equalsIgnoreCase(type)) { - if (example == null) { - example = "2013-10-20"; - } - example = "'" + escapeText(example) + "'";*/ - } else if ("NSDate*".equalsIgnoreCase(type)) { - if (example == null) { - example = "2013-10-20T19:20:30+01:00"; - } - example = "@\"" + escapeText(example) + "\""; - } else if (!languageSpecificPrimitives.contains(type)) { - // type is a model class, e.g. User - type = type.replace("*", ""); - // e.g. [[SWGPet alloc] init - example = "[[" + type + " alloc] init]"; - } else { - LOGGER.warn("Type " + type + " not handled properly in setParameterExampleValue"); - } - - if (example == null) { - example = "NULL"; - } else if (Boolean.TRUE.equals(p.isListContainer)) { - example = "@[" + example + "]"; - } else if (Boolean.TRUE.equals(p.isMapContainer)) { - example = "@{@\"key\" : " + example + "}"; - } - - p.example = example; - } - - @Override - public String escapeQuotationMark(String input) { - // remove " to avoid code injection - return input.replace("\"", ""); - } - - @Override - public String escapeUnsafeCharacters(String input) { - return input.replace("*/", "*_/").replace("/*", "/_*"); - } - -} diff --git a/output/objcSessionManager/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/output/objcSessionManager/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig deleted file mode 100644 index e3cfa53811b..00000000000 --- a/output/objcSessionManager/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig +++ /dev/null @@ -1 +0,0 @@ -io.swagger.codegen.languages.ObjcSessionManagerClientCodegen \ No newline at end of file diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache deleted file mode 100644 index aa285a4d10f..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache +++ /dev/null @@ -1,483 +0,0 @@ -#import - -#import "{{classPrefix}}ApiSessionManager.h" -#import "{{classPrefix}}JSONRequestSerializer.h" -#import "{{classPrefix}}JSONResponseSerializer.h" -#import "{{classPrefix}}QueryParamCollection.h" -#import "{{classPrefix}}DefaultConfiguration.h" - - -NSString * const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}ResponseObject"; - - -static bool offlineState = false; -static bool cacheEnabled = false; -static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilityStatusNotReachable; -static void (^reachabilityChangeBlock)(int); - - -static NSDictionary * {{classPrefix}}__headerFieldsForResponse(NSURLResponse *response) { - if(![response isKindOfClass:[NSHTTPURLResponse class]]) { - return nil; - } - return ((NSHTTPURLResponse*)response).allHeaderFields; -} - -static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) { - NSDictionary * headers = {{classPrefix}}__headerFieldsForResponse(response); - if(!headers[@"Content-Disposition"]) { - return [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]]; - } - NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?"; - NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern - options:NSRegularExpressionCaseInsensitive - error:nil]; - NSString *contentDispositionHeader = headers[@"Content-Disposition"]; - NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader - options:0 - range:NSMakeRange(0, [contentDispositionHeader length])]; - return [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]]; -} - - -@interface {{classPrefix}}ApiSessionManager () - -@property (nonatomic, strong, readwrite) id<{{classPrefix}}Configuration> configuration; - -@end - -@implementation {{classPrefix}}ApiSessionManager - -- (instancetype)init { - - return [self initWithConfiguration:[{{classPrefix}}DefaultConfiguration sharedConfiguration]]; -} - -- (instancetype)initWithBaseURL:(NSURL *)url { - - return [self initWithBaseURL:url - configuration:[{{classPrefix}}DefaultConfiguration sharedConfiguration]]; - -} - -- (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration { - - return [self initWithBaseURL:[NSURL URLWithString:configuration.host] configuration:configuration]; -} - -- (instancetype)initWithBaseURL:(NSURL *)url - configuration:(id<{{classPrefix}}Configuration>)configuration { - - self = [super initWithBaseURL:url]; - if (self) { - _configuration = configuration; - _timeoutInterval = 60; - _responseDeserializer = [[{{classPrefix}}ResponseDeserializer alloc] init]; - _sanitizer = [[{{classPrefix}}Sanitizer alloc] init]; - - self.requestSerializer = [AFJSONRequestSerializer serializer]; - self.responseSerializer = [AFJSONResponseSerializer serializer]; - self.securityPolicy = [self customSecurityPolicy]; - - // configure reachability - [self configureCacheReachibility]; - } - - return self; -} - -#pragma mark - Setter Methods - -+ (void) setOfflineState:(BOOL) state { - offlineState = state; -} - -+ (void) setCacheEnabled:(BOOL)enabled { - cacheEnabled = enabled; -} - -+(void) setReachabilityStatus:(AFNetworkReachabilityStatus)status { - reachabilityStatus = status; -} - -- (void)setHeaderValue:(NSString*) value forKey:(NSString*) forKey { - [self.requestSerializer setValue:value forHTTPHeaderField:forKey]; -} - -- (void)setRequestSerializer:(AFHTTPRequestSerializer *)requestSerializer { - [super setRequestSerializer:requestSerializer]; - requestSerializer.timeoutInterval = self.timeoutInterval; -} - -#pragma mark - Cache Methods - -+(void)clearCache { - [[NSURLCache sharedURLCache] removeAllCachedResponses]; -} - -+(void)configureCacheWithMemoryAndDiskCapacity: (unsigned long) memorySize - diskSize: (unsigned long) diskSize { - NSAssert(memorySize > 0, @"invalid in-memory cache size"); - NSAssert(diskSize >= 0, @"invalid disk cache size"); - - NSURLCache *cache = - [[NSURLCache alloc] - initWithMemoryCapacity:memorySize - diskCapacity:diskSize - diskPath:@"swagger_url_cache"]; - - [NSURLCache setSharedURLCache:cache]; -} - -#pragma mark - Reachability Methods - -+(AFNetworkReachabilityStatus) getReachabilityStatus { - return reachabilityStatus; -} - -+(BOOL) getOfflineState { - return offlineState; -} - -+(void) setReachabilityChangeBlock:(void(^)(int))changeBlock { - reachabilityChangeBlock = changeBlock; -} - -- (void) configureCacheReachibility { - [self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { - reachabilityStatus = status; - {{classPrefix}}DebugLog(@"reachability changed to %@",AFStringFromNetworkReachabilityStatus(status)); - [{{classPrefix}}ApiSessionManager setOfflineState:status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable]; - - // call the reachability block, if configured - if (reachabilityChangeBlock != nil) { - reachabilityChangeBlock(status); - } - }]; - - [self.reachabilityManager startMonitoring]; -} - -#pragma mark - Task Methods - -- (NSURLSessionDataTask*) taskWithCompletionBlock: (NSURLRequest *)request - completionBlock: (void (^)(id, NSError *))completionBlock { - - NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { - {{classPrefix}}DebugLogResponse(response, responseObject,request,error); - - if(!error) { - completionBlock(responseObject, nil); - return; - } - - NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; - if (responseObject) { - // Add in the (parsed) response body. - userInfo[{{classPrefix}}ResponseObjectErrorKey] = responseObject; - } - NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; - completionBlock(nil, augmentedError); - }]; - - return task; -} - -- (NSURLSessionDataTask*) downloadTaskWithCompletionBlock: (NSURLRequest *)request - completionBlock: (void (^)(id, NSError *))completionBlock { - - id<{{classPrefix}}Configuration> config = self.configuration; - - NSURLSessionDataTask* task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { - {{classPrefix}}DebugLogResponse(response, responseObject,request,error); - - if(error) { - NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; - if (responseObject) { - userInfo[{{classPrefix}}ResponseObjectErrorKey] = responseObject; - } - NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; - completionBlock(nil, augmentedError); - } - - NSString *directory = config.tempFolderPath ?: NSTemporaryDirectory(); - NSString *filename = {{classPrefix}}__fileNameForResponse(response); - - NSString *filepath = [directory stringByAppendingPathComponent:filename]; - NSURL *file = [NSURL fileURLWithPath:filepath]; - - [responseObject writeToURL:file atomically:YES]; - - completionBlock(file, nil); - }]; - - return task; -} - -#pragma mark - Perform Request Methods - -- (NSURLSessionTask*) requestWithPath: (NSString*) path - method: (NSString*) method - pathParams: (NSDictionary *) pathParams - queryParams: (NSDictionary*) queryParams - formParams: (NSDictionary *) formParams - files: (NSDictionary *) files - body: (id) body - headerParams: (NSDictionary*) headerParams - authSettings: (NSArray *) authSettings - requestContentType: (NSString*) requestContentType - responseContentType: (NSString*) responseContentType - responseType: (NSString *) responseType - completionBlock: (void (^)(id, NSError *))completionBlock { - - // setting request serializer - if ([requestContentType isEqualToString:@"application/json"]) { - self.requestSerializer = [{{classPrefix}}JSONRequestSerializer serializer]; - } - else if ([requestContentType isEqualToString:@"application/x-www-form-urlencoded"]) { - self.requestSerializer = [AFHTTPRequestSerializer serializer]; - } - else if ([requestContentType isEqualToString:@"multipart/form-data"]) { - self.requestSerializer = [AFHTTPRequestSerializer serializer]; - } - else { - self.requestSerializer = [AFHTTPRequestSerializer serializer]; - NSAssert(NO, @"Unsupported request type %@", requestContentType); - } - - // setting response serializer - if ([responseContentType isEqualToString:@"application/json"]) { - self.responseSerializer = [{{classPrefix}}JSONResponseSerializer serializer]; - } else { - self.responseSerializer = [AFHTTPResponseSerializer serializer]; - } - - // sanitize parameters - pathParams = [self.sanitizer sanitizeForSerialization:pathParams]; - queryParams = [self.sanitizer sanitizeForSerialization:queryParams]; - headerParams = [self.sanitizer sanitizeForSerialization:headerParams]; - formParams = [self.sanitizer sanitizeForSerialization:formParams]; - if(![body isKindOfClass:[NSData class]]) { - body = [self.sanitizer sanitizeForSerialization:body]; - } - - // auth setting - [self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings]; - - NSMutableString *resourcePath = [NSMutableString stringWithString:path]; - [pathParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - NSString * safeString = ([obj isKindOfClass:[NSString class]]) ? obj : [NSString stringWithFormat:@"%@", obj]; - safeString = {{classPrefix}}PercentEscapedStringFromString(safeString); - [resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"{%@}", key]] withString:safeString]; - }]; - - NSMutableURLRequest * request = nil; - - NSString* pathWithQueryParams = [self pathWithQueryParamsToString:resourcePath queryParams:queryParams]; - if ([pathWithQueryParams hasPrefix:@"/"]) { - pathWithQueryParams = [pathWithQueryParams substringFromIndex:1]; - } - - NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString]; - if (files.count > 0) { - __weak __typeof(self)weakSelf = self; - request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" - URLString:urlString - parameters:nil - constructingBodyWithBlock:^(id formData) { - [formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - NSString *objString = [weakSelf.sanitizer parameterToString:obj]; - NSData *data = [objString dataUsingEncoding:NSUTF8StringEncoding]; - [formData appendPartWithFormData:data name:key]; - }]; - [files enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - NSURL *filePath = (NSURL *)obj; - [formData appendPartWithFileURL:filePath name:key error:nil]; - }]; - } error:nil]; - } - else { - if (formParams) { - request = [self.requestSerializer requestWithMethod:method - URLString:urlString - parameters:formParams - error:nil]; - } - if (body) { - request = [self.requestSerializer requestWithMethod:method - URLString:urlString - parameters:body - error:nil]; - } - } - - // request cache - BOOL hasHeaderParams = [headerParams count] > 0; - if (offlineState) { - {{classPrefix}}DebugLog(@"%@ cache forced", resourcePath); - [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; - } - else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { - {{classPrefix}}DebugLog(@"%@ cache enabled", resourcePath); - [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; - } - else { - {{classPrefix}}DebugLog(@"%@ cache disabled", resourcePath); - [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; - } - - if (hasHeaderParams){ - for(NSString * key in [headerParams keyEnumerator]){ - [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; - } - } - [self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"]; - - [self postProcessRequest:request]; - - - NSURLSessionTask *task = nil; - - if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) { - task = [self downloadTaskWithCompletionBlock:request completionBlock:^(id data, NSError *error) { - completionBlock(data, error); - }]; - } - else { - task = [self taskWithCompletionBlock:request completionBlock:^(id data, NSError *error) { - NSError * serializationError; - id response = [self.responseDeserializer deserialize:data class:responseType error:&serializationError]; - if(!response && !error){ - error = serializationError; - } - completionBlock(response, error); - }]; - } - - [task resume]; - - return task; -} - -// Added for easier override to modify request -- (void)postProcessRequest:(NSMutableURLRequest *)request { - // Always disable cookies! - [request setHTTPShouldHandleCookies:NO]; -} - -#pragma mark - - -- (NSString*)pathWithQueryParamsToString:(NSString*) path - queryParams:(NSDictionary*) queryParams { - if(queryParams.count == 0) { - return path; - } - NSString * separator = nil; - NSUInteger counter = 0; - - NSMutableString * requestUrl = [NSMutableString stringWithFormat:@"%@", path]; - - NSDictionary *separatorStyles = @{@"csv" : @",", - @"tsv" : @"\t", - @"pipes": @"|" - }; - for(NSString * key in [queryParams keyEnumerator]){ - if (counter == 0) { - separator = @"?"; - } else { - separator = @"&"; - } - id queryParam = [queryParams valueForKey:key]; - if(!queryParam) { - continue; - } - NSString *safeKey = {{classPrefix}}PercentEscapedStringFromString(key); - if ([queryParam isKindOfClass:[NSString class]]){ - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, {{classPrefix}}PercentEscapedStringFromString(queryParam)]]; - - } else if ([queryParam isKindOfClass:[{{classPrefix}}QueryParamCollection class]]){ - {{classPrefix}}QueryParamCollection * coll = ({{classPrefix}}QueryParamCollection*) queryParam; - NSArray* values = [coll values]; - NSString* format = [coll format]; - - if([format isEqualToString:@"multi"]) { - for(id obj in values) { - if (counter > 0) { - separator = @"&"; - } - NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([NSString stringWithFormat:@"%@",obj]); - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; - counter += 1; - } - continue; - } - NSString * separatorStyle = separatorStyles[format]; - NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([values componentsJoinedByString:separatorStyle]); - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; - } else { - NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([NSString stringWithFormat:@"%@",queryParam]); - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; - } - counter += 1; - } - return requestUrl; -} - -/** - * Update header and query params based on authentication settings - */ -- (void) updateHeaderParams:(NSDictionary *__autoreleasing *)headers - queryParams:(NSDictionary *__autoreleasing *)querys - WithAuthSettings:(NSArray *)authSettings { - - if (!authSettings || [authSettings count] == 0) { - return; - } - - NSMutableDictionary *headersWithAuth = [NSMutableDictionary dictionaryWithDictionary:*headers]; - NSMutableDictionary *querysWithAuth = [NSMutableDictionary dictionaryWithDictionary:*querys]; - - id<{{classPrefix}}Configuration> config = self.configuration; - for (NSString *auth in authSettings) { - NSDictionary *authSetting = config.authSettings[auth]; - - if(!authSetting) { // auth setting is set only if the key is non-empty - continue; - } - - NSString *type = authSetting[@"in"]; - NSString *key = authSetting[@"key"]; - NSString *value = authSetting[@"value"]; - if ([type isEqualToString:@"header"] && [key length] > 0 ) { - headersWithAuth[key] = value; - } else if ([type isEqualToString:@"query"] && [key length] != 0) { - querysWithAuth[key] = value; - } - } - - *headers = [NSDictionary dictionaryWithDictionary:headersWithAuth]; - *querys = [NSDictionary dictionaryWithDictionary:querysWithAuth]; -} - -- (AFSecurityPolicy *) customSecurityPolicy { - AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; - - id<{{classPrefix}}Configuration> config = self.configuration; - - if (config.sslCaCert) { - NSData *certData = [NSData dataWithContentsOfFile:config.sslCaCert]; - [securityPolicy setPinnedCertificates:[NSSet setWithObject:certData]]; - } - - if (config.verifySSL) { - [securityPolicy setAllowInvalidCertificates:NO]; - } - else { - [securityPolicy setAllowInvalidCertificates:YES]; - [securityPolicy setValidatesDomainName:NO]; - } - - return securityPolicy; -} - -@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-header.mustache deleted file mode 100644 index f94d680375e..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/ApiSessionManager-header.mustache +++ /dev/null @@ -1,149 +0,0 @@ -/** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ - -#import -#import "{{classPrefix}}Configuration.h" -#import "{{classPrefix}}ResponseDeserializer.h" -#import "{{classPrefix}}Sanitizer.h" - -/** - * A key for `NSError` user info dictionaries. - * - * The corresponding value is the parsed response body for an HTTP error. - */ -extern NSString *const {{classPrefix}}ResponseObjectErrorKey; - - -@interface {{classPrefix}}ApiSessionManager : AFHTTPSessionManager - -@property (nonatomic, strong, readonly) id<{{classPrefix}}Configuration> configuration; - -@property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy; -@property(nonatomic, assign) NSTimeInterval timeoutInterval; -@property(nonatomic, readonly) NSOperationQueue* queue; - -@property(nonatomic, strong) id<{{classPrefix}}ResponseDeserializer> responseDeserializer; - -@property(nonatomic, strong) id<{{classPrefix}}Sanitizer> sanitizer; - -/** - * Clears Cache - */ -+(void)clearCache; - -/** - * Turns on cache - * - * @param enabled If the cached is enable, must be `YES` or `NO` - */ -+(void)setCacheEnabled:(BOOL) enabled; - -/** - * Sets the client unreachable - * - * @param state off line state, must be `YES` or `NO` - */ -+(void) setOfflineState:(BOOL) state; - -/** - * Gets if the client is unreachable - * - * @return The client offline state - */ -+(BOOL) getOfflineState; - -/** - * Sets the client reachability, this may be overridden by the reachability manager if reachability changes - * - * @param The client reachability. - */ -+(void) setReachabilityStatus:(AFNetworkReachabilityStatus) status; - -/** - * Gets the client reachability - * - * @return The client reachability. - */ -+(AFNetworkReachabilityStatus) getReachabilityStatus; - -/** - * Customizes the behavior when the reachability changed - * - * @param changeBlock The block will be executed when the reachability changed. - */ -+(void) setReachabilityChangeBlock:(void(^)(int))changeBlock; - -/** - * Sets the api client reachability strategy - */ -- (void)configureCacheReachibility; - -/** - * Sets header for request - * - * @param value The header value - * @param forKey The header key - */ --(void)setHeaderValue:(NSString*) value - forKey:(NSString*) forKey; - -/** - * Updates header parameters and query parameters for authentication - * - * @param headers The header parameter will be udpated, passed by pointer to pointer. - * @param querys The query parameters will be updated, passed by pointer to pointer. - * @param authSettings The authentication names NSArray. - */ -- (void) updateHeaderParams:(NSDictionary **)headers - queryParams:(NSDictionary **)querys - WithAuthSettings:(NSArray *)authSettings; - - -/** - * Initializes the session manager with a configuration. - * - * @param configuration The configuration implementation - */ -- (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration; - -/** - * Performs request - * - * @param path Request url. - * @param method Request method. - * @param pathParams Request path parameters. - * @param queryParams Request query parameters. - * @param body Request body. - * @param headerParams Request header parameters. - * @param authSettings Request authentication names. - * @param requestContentType Request content-type. - * @param responseContentType Response content-type. - * @param completionBlock The block will be executed when the request completed. - * - * @return The created session task. - */ -- (NSURLSessionTask*) requestWithPath: (NSString*) path - method: (NSString*) method - pathParams: (NSDictionary *) pathParams - queryParams: (NSDictionary*) queryParams - formParams: (NSDictionary *) formParams - files: (NSDictionary *) files - body: (id) body - headerParams: (NSDictionary*) headerParams - authSettings: (NSArray *) authSettings - requestContentType: (NSString*) requestContentType - responseContentType: (NSString*) responseContentType - responseType: (NSString *) responseType - completionBlock: (void (^)(id, NSError *))completionBlock; - -/** - * Custom security policy - * - * @return AFSecurityPolicy - */ -- (AFSecurityPolicy *) customSecurityPolicy; - -@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/BasicAuthTokenProvider-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/BasicAuthTokenProvider-body.mustache deleted file mode 100644 index a928e5e8f4e..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/BasicAuthTokenProvider-body.mustache +++ /dev/null @@ -1,19 +0,0 @@ -#import "{{classPrefix}}BasicAuthTokenProvider.h" - -@implementation {{classPrefix}}BasicAuthTokenProvider - -+ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password { - - // return empty string if username and password are empty - if (username.length == 0 && password.length == 0){ - return @""; - } - - NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password]; - NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; - basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; - - return basicAuthCredentials; -} - -@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/BasicAuthTokenProvider-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/BasicAuthTokenProvider-header.mustache deleted file mode 100644 index dfb287568a0..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/BasicAuthTokenProvider-header.mustache +++ /dev/null @@ -1,14 +0,0 @@ -/** The `{{classPrefix}}BasicAuthTokenProvider` class creates a basic auth token from username and password. - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ - -#import - -@interface {{classPrefix}}BasicAuthTokenProvider : NSObject - -+ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password; - -@end \ No newline at end of file diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/Configuration-protocol.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/Configuration-protocol.mustache deleted file mode 100644 index db429a38150..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/Configuration-protocol.mustache +++ /dev/null @@ -1,75 +0,0 @@ -#import -#import "{{classPrefix}}Logger.h" - -{{>licenceInfo}} - -@protocol {{classPrefix}}Configuration - -/** - * Api logger - */ -@property (readonly, nonatomic) {{classPrefix}}Logger *logger; - -/** - * Base url - */ -@property (readonly, nonatomic) NSString *host; - -/** - * Api key values for Api Key type Authentication - */ -@property (readonly, nonatomic) NSDictionary *apiKey; - -/** - * Api key prefix values to be prepend to the respective api key - */ -@property (readonly, nonatomic) NSDictionary *apiKeyPrefix; - -/** - * Username for HTTP Basic Authentication - */ -@property (readonly, nonatomic) NSString *username; - -/** - * Password for HTTP Basic Authentication - */ -@property (readonly, nonatomic) NSString *password; - -/** - * Access token for OAuth - */ -@property (readonly, nonatomic) NSString *accessToken; - -/** - * Temp folder for file download - */ -@property (readonly, nonatomic) NSString *tempFolderPath; - -/** - * Debug switch, default false - */ -@property (readonly, nonatomic) BOOL debug; - -/** - * SSL/TLS verification - * Set this to NO to skip verifying SSL certificate when calling API from https server - */ -@property (readonly, nonatomic) BOOL verifySSL; - -/** - * SSL/TLS verification - * Set this to customize the certificate file to verify the peer - */ -@property (readonly, nonatomic) NSString *sslCaCert; - -/** - * Authentication Settings - */ -@property (readonly, nonatomic) NSDictionary *authSettings; - -/** -* Default headers for all services -*/ -@property (readonly, nonatomic, strong) NSDictionary *defaultHeaders; - -@end \ No newline at end of file diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/DefaultConfiguration-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/DefaultConfiguration-body.mustache deleted file mode 100644 index 7d99c336a94..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/DefaultConfiguration-body.mustache +++ /dev/null @@ -1,159 +0,0 @@ -#import "{{classPrefix}}DefaultConfiguration.h" -#import "{{classPrefix}}BasicAuthTokenProvider.h" - -@interface {{classPrefix}}DefaultConfiguration () - -@property (nonatomic, strong) NSMutableDictionary *mutableDefaultHeaders; -@property (nonatomic, strong) NSMutableDictionary *mutableApiKey; -@property (nonatomic, strong) NSMutableDictionary *mutableApiKeyPrefix; - -@end - -@implementation {{classPrefix}}DefaultConfiguration - -#pragma mark - Singleton Methods - -+ (instancetype)sharedConfiguration { - - static {{classPrefix}}DefaultConfiguration *shardConfig = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - shardConfig = [[self alloc] init]; - }); - return shardConfig; -} - -#pragma mark - Initialize Methods - -- (instancetype)init { - self = [super init]; - if (self) { - _host = @"{{basePath}}"; - _username = @""; - _password = @""; - _accessToken= @""; - _verifySSL = YES; - _mutableApiKey = [NSMutableDictionary dictionary]; - _mutableApiKeyPrefix = [NSMutableDictionary dictionary]; - _mutableDefaultHeaders = [NSMutableDictionary dictionary]; - {{#httpUserAgent}}_mutableDefaultHeaders[@"User-Agent"] = @"{{httpUserAgent}}"{{/httpUserAgent}}; - _logger = [{{classPrefix}}Logger sharedLogger]; - } - return self; -} - -#pragma mark - Instance Methods - -- (NSString *) getApiKeyWithPrefix:(NSString *)key { - NSString *prefix = self.apiKeyPrefix[key]; - NSString *apiKey = self.apiKey[key]; - if (prefix && apiKey != (id)[NSNull null] && apiKey.length > 0) { // both api key prefix and api key are set - return [NSString stringWithFormat:@"%@ %@", prefix, apiKey]; - } - else if (apiKey != (id)[NSNull null] && apiKey.length > 0) { // only api key, no api key prefix - return [NSString stringWithFormat:@"%@", self.apiKey[key]]; - } - else { // return empty string if nothing is set - return @""; - } -} - -- (NSString *) getBasicAuthToken { - - NSString *basicAuthToken = [{{classPrefix}}BasicAuthTokenProvider createBasicAuthTokenWithUsername:self.username password:self.password]; - return basicAuthToken; -} - -- (NSString *) getAccessToken { - if (self.accessToken.length == 0) { // token not set, return empty string - return @""; - } else { - return [NSString stringWithFormat:@"Bearer %@", self.accessToken]; - } -} - -#pragma mark - Setter Methods - -- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString *)identifier { - [self.mutableApiKey setValue:apiKey forKey:identifier]; -} - -- (void) removeApiKey:(NSString *)identifier { - [self.mutableApiKey removeObjectForKey:identifier]; -} - -- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier { - [self.mutableApiKeyPrefix setValue:prefix forKey:identifier]; -} - -- (void) removeApiKeyPrefix:(NSString *)identifier { - [self.mutableApiKeyPrefix removeObjectForKey:identifier]; -} - -#pragma mark - - -- (NSDictionary *) authSettings { - return @{ -{{#authMethods}} -{{#isApiKey}} - @"{{name}}": - @{ - @"type": @"api_key", - @"in": {{#isKeyInHeader}}@"header"{{/isKeyInHeader}}{{#isKeyInQuery}}@"query"{{/isKeyInQuery}}, - @"key": @"{{keyParamName}}", - @"value": [self getApiKeyWithPrefix:@"{{keyParamName}}"] - }, -{{/isApiKey}} -{{#isBasic}} - @"{{name}}": - @{ - @"type": @"basic", - @"in": @"header", - @"key": @"Authorization", - @"value": [self getBasicAuthToken] - }, -{{/isBasic}} -{{#isOAuth}} - @"{{name}}": - @{ - @"type": @"oauth", - @"in": @"header", - @"key": @"Authorization", - @"value": [self getAccessToken] - }, -{{/isOAuth}} -{{/authMethods}} - }; -} - --(BOOL)debug { - return self.logger.isEnabled; -} - --(void)setDebug:(BOOL)debug { - self.logger.enabled = debug; -} - - - -- (void)setDefaultHeaderValue:(NSString *)value forKey:(NSString *)key { - if(!value) { - [self.mutableDefaultHeaders removeObjectForKey:key]; - return; - } - self.mutableDefaultHeaders[key] = value; -} - --(void) removeDefaultHeaderForKey:(NSString*)key { - [self.mutableDefaultHeaders removeObjectForKey:key]; -} - -- (NSString *)defaultHeaderForKey:(NSString *)key { - return self.mutableDefaultHeaders[key]; -} - -- (NSDictionary *)defaultHeaders { - return [self.mutableDefaultHeaders copy]; -} - -@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/DefaultConfiguration-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/DefaultConfiguration-header.mustache deleted file mode 100644 index 3d74bceb2b6..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/DefaultConfiguration-header.mustache +++ /dev/null @@ -1,129 +0,0 @@ -#import -#import "{{classPrefix}}Configuration.h" - -{{>licenceInfo}} - -@interface {{classPrefix}}DefaultConfiguration : NSObject <{{classPrefix}}Configuration> - -+ ({{classPrefix}}DefaultConfiguration *)sharedConfiguration; - -/** - * Default api logger - */ -@property (nonatomic, strong) {{classPrefix}}Logger * logger; - -/** - * Default base url - */ -@property (nonatomic) NSString *host; - -/** - * Api key values for Api Key type Authentication - * - * To add or remove api key, use `setApiKey:forApiKeyIdentifier:`. - */ -@property (readonly, nonatomic, strong) NSDictionary *apiKey; - -/** - * Api key prefix values to be prepend to the respective api key - * - * To add or remove prefix, use `setApiKeyPrefix:forApiKeyPrefixIdentifier:`. - */ -@property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix; - -/** - * Username for HTTP Basic Authentication - */ - @property (nonatomic) NSString *username; - -/** - * Password for HTTP Basic Authentication - */ -@property (nonatomic) NSString *password; - -/** - * Access token for OAuth - */ -@property (nonatomic) NSString *accessToken; - -/** - * Temp folder for file download - */ -@property (nonatomic) NSString *tempFolderPath; - -/** - * Debug switch, default false - */ -@property (nonatomic) BOOL debug; - -/** - * SSL/TLS verification - * Set this to NO to skip verifying SSL certificate when calling API from https server - */ -@property (nonatomic) BOOL verifySSL; - -/** - * SSL/TLS verification - * Set this to customize the certificate file to verify the peer - */ -@property (nonatomic) NSString *sslCaCert; - -/** - * Sets API key - * - * To remove a apiKey for an identifier, just set the apiKey to nil. - * - * @param apiKey API key or token. - * @param identifier API key identifier (authentication schema). - * - */ -- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString*)identifier; - -/** - * Removes api key - * - * @param identifier API key identifier. - */ -- (void) removeApiKey:(NSString *)identifier; - -/** - * Sets the prefix for API key - * - * @param apiKeyPrefix API key prefix. - * @param identifier API key identifier. - */ -- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier; - -/** - * Removes api key prefix - * - * @param identifier API key identifier. - */ -- (void) removeApiKeyPrefix:(NSString *)identifier; - -/** -* Default headers for all services -*/ -@property (readonly, nonatomic, strong) NSDictionary *defaultHeaders; - -/** -* Removes header from defaultHeaders -* -* @param Header name. -*/ --(void) removeDefaultHeaderForKey:(NSString*)key; - -/** -* Sets the header for key -* -* @param value Value for header name -* @param key Header name -*/ --(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key; - -/** -* @param Header key name. -*/ --(NSString*) defaultHeaderForKey:(NSString*)key; - -@end \ No newline at end of file diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONRequestSerializer-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONRequestSerializer-body.mustache deleted file mode 100644 index 63513335d9a..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONRequestSerializer-body.mustache +++ /dev/null @@ -1,37 +0,0 @@ -#import "{{classPrefix}}JSONRequestSerializer.h" - -@implementation {{classPrefix}}JSONRequestSerializer - -/// -/// When customize a request serializer, -/// the serializer must conform the protocol `AFURLRequestSerialization` -/// and implements the protocol method `requestBySerializingRequest:withParameters:error:` -/// -/// @param request The original request. -/// @param parameters The parameters to be encoded. -/// @param error The error that occurred while attempting to encode the request parameters. -/// -/// @return A serialized request. -/// -- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request - withParameters:(id)parameters - error:(NSError *__autoreleasing *)error -{ - if (!parameters) { - return request; - } - // If the body data which will be serialized isn't NSArray or NSDictionary - // then put the data in the http request body directly. - if ([parameters isKindOfClass:[NSArray class]] || [parameters isKindOfClass:[NSDictionary class]]) { - return [super requestBySerializingRequest:request withParameters:parameters error:error]; - } - NSMutableURLRequest *mutableRequest = [request mutableCopy]; - if([parameters isKindOfClass:[NSData class]]) { - [mutableRequest setHTTPBody:parameters]; - } else { - [mutableRequest setHTTPBody:[parameters dataUsingEncoding:self.stringEncoding]]; - } - return mutableRequest; -} - -@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONRequestSerializer-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONRequestSerializer-header.mustache deleted file mode 100644 index 1259c5d1530..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONRequestSerializer-header.mustache +++ /dev/null @@ -1,7 +0,0 @@ -#import -#import - -{{>licenceInfo}} - -@interface {{classPrefix}}JSONRequestSerializer : AFJSONRequestSerializer -@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONResponseSerializer-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONResponseSerializer-body.mustache deleted file mode 100644 index 7fa5e7b19e0..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONResponseSerializer-body.mustache +++ /dev/null @@ -1,39 +0,0 @@ -#import "{{classPrefix}}JSONResponseSerializer.h" - -@implementation {{classPrefix}}JSONResponseSerializer - -/// -/// When customize a response serializer, -/// the serializer must conform the protocol `AFURLResponseSerialization` -/// and implements the protocol method `responseObjectForResponse:error:` -/// -/// @param response The response to be processed. -/// @param data The response data to be decoded. -/// @param error The error that occurred while attempting to decode the response data. -/// -/// @return The object decoded from the specified response data. -/// -- (id) responseObjectForResponse:(NSURLResponse *)response - data:(NSData *)data - error:(NSError *__autoreleasing *)error { - NSDictionary *responseJson = [super responseObjectForResponse:response data:data error:error]; - - // if response data is not a valid json, return string of data. - if ([self isParseError:*error]) { - *error = nil; - NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; - return responseString; - } - - return responseJson; -} - --(BOOL)isParseError:(NSError *)error { - return [error.domain isEqualToString:NSCocoaErrorDomain] && error.code == 3840; -} - -+ (instancetype)serializer { - return [self serializerWithReadingOptions:NSJSONReadingAllowFragments]; -} - -@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONResponseSerializer-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONResponseSerializer-header.mustache deleted file mode 100644 index 360e4f9cdc5..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONResponseSerializer-header.mustache +++ /dev/null @@ -1,8 +0,0 @@ -#import -#import - -{{>licenceInfo}} - -@interface {{classPrefix}}JSONResponseSerializer : AFJSONResponseSerializer - -@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601-body.mustache deleted file mode 100644 index b544a1dae58..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601-body.mustache +++ /dev/null @@ -1,11 +0,0 @@ -#import -#import "JSONValueTransformer+ISO8601.h" - -@implementation JSONValueTransformer (ISO8601) - -- (NSDate *) NSDateFromNSString:(NSString *)string -{ - return [NSDate dateWithISO8601String:string]; -} - -@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601-header.mustache deleted file mode 100644 index f621e7184a9..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601-header.mustache +++ /dev/null @@ -1,8 +0,0 @@ -#import -#import - -{{>licenceInfo}} - -@interface JSONValueTransformer (ISO8601) - -@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/Logger-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/Logger-body.mustache deleted file mode 100644 index 9a8f7de2418..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/Logger-body.mustache +++ /dev/null @@ -1,74 +0,0 @@ -#import "{{classPrefix}}Logger.h" - -@interface {{classPrefix}}Logger () - -@end - -@implementation {{classPrefix}}Logger - -+ (instancetype) sharedLogger { - static {{classPrefix}}Logger *shardLogger = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - shardLogger = [[self alloc] init]; - }); - return shardLogger; -} - -#pragma mark - Log Methods - -- (void)debugLog:(NSString *)method - message:(NSString *)format, ... { - if (!self.isEnabled) { - return; - } - - NSMutableString *message = [NSMutableString stringWithCapacity:1]; - - if (method) { - [message appendFormat:@"%@: ", method]; - } - - va_list args; - va_start(args, format); - - [message appendString:[[NSString alloc] initWithFormat:format arguments:args]]; - - // If set logging file handler, log into file, - // otherwise log into console. - if (self.loggingFileHandler) { - [self.loggingFileHandler seekToEndOfFile]; - [self.loggingFileHandler writeData:[message dataUsingEncoding:NSUTF8StringEncoding]]; - } else { - NSLog(@"%@", message); - } - - va_end(args); -} - -- (void)logResponse:(NSURLResponse *)response responseObject:(id)responseObject request:(NSURLRequest *)request error:(NSError *)error { - NSString *message = [NSString stringWithFormat:@"\n[DEBUG] HTTP request body \n~BEGIN~\n %@\n~END~\n"\ - "[DEBUG] HTTP response body \n~BEGIN~\n %@\n~END~\n", - [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding], - responseObject]; - - {{classPrefix}}DebugLog(message); -} - -- (void) setLoggingFile:(NSString *)loggingFile { - if(_loggingFile == loggingFile) { - return; - } - // close old file handler - if ([self.loggingFileHandler isKindOfClass:[NSFileHandle class]]) { - [self.loggingFileHandler closeFile]; - } - _loggingFile = loggingFile; - _loggingFileHandler = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; - if (_loggingFileHandler == nil) { - [[NSFileManager defaultManager] createFileAtPath:_loggingFile contents:nil attributes:nil]; - _loggingFileHandler = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; - } -} - -@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/Logger-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/Logger-header.mustache deleted file mode 100644 index 37afea41a09..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/Logger-header.mustache +++ /dev/null @@ -1,50 +0,0 @@ -#import - -{{>licenceInfo}} - -#ifndef {{classPrefix}}DebugLogResponse -#define {{classPrefix}}DebugLogResponse(response, responseObject,request, error) [[{{classPrefix}}Logger sharedLogger] logResponse:response responseObject:responseObject request:request error:error]; -#endif - -/** - * Log debug message macro - */ -#ifndef {{classPrefix}}DebugLog -#define {{classPrefix}}DebugLog(format, ...) [[{{classPrefix}}Logger sharedLogger] debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__]; -#endif - -@interface {{classPrefix}}Logger : NSObject - -+(instancetype)sharedLogger; - -/** - * Enabled switch, default NO - default set by {{classPrefix}}Configuration debug property - */ -@property (nonatomic, assign, getter=isEnabled) BOOL enabled; - -/** - * Debug file location, default log in console - */ -@property (nonatomic, strong) NSString *loggingFile; - -/** - * Log file handler, this property is used by sdk internally. - */ -@property (nonatomic, strong, readonly) NSFileHandle *loggingFileHandler; - -/** - * Log debug message - */ --(void)debugLog:(NSString *)method message:(NSString *)format, ...; - -/** - * Logs request and response - * - * @param response NSURLResponse for the HTTP request. - * @param responseObject response object of the HTTP request. - * @param request The HTTP request. - * @param error The error of the HTTP request. - */ -- (void)logResponse:(NSURLResponse *)response responseObject:(id)responseObject request:(NSURLRequest *)request error:(NSError *)error; - -@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/Model.xcdatamodel.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/Model.xcdatamodel.mustache deleted file mode 100644 index 90dcd63e3d9..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/Model.xcdatamodel.mustache +++ /dev/null @@ -1,12 +0,0 @@ - - - - {{#models}}{{#model}} -{{#isArrayModel}} -{{/isArrayModel}}{{^isArrayModel}}{{#vars}}{{#complexType}} {{/complexType}}{{^complexType}} {{/complexType}}{{#vendorExtensions.x-is-unique}} - {{/vendorExtensions.x-is-unique}} -{{/vars}} -{{/isArrayModel}} - - {{/model}}{{/models}} - \ No newline at end of file diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/NSManagedObject-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/NSManagedObject-body.mustache deleted file mode 100644 index 205a692af5e..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/NSManagedObject-body.mustache +++ /dev/null @@ -1,20 +0,0 @@ -{{#models}} -{{#model}} -#import "{{classname}}ManagedObject.h" - -/** -* NOTE: This class is auto generated by the swagger code generator program. -* https://github.com/swagger-api/swagger-codegen -* Do not edit the class manually. -*/ -@implementation {{classname}}ManagedObject -{{#isArrayModel}} - -@dynamic entries; - -{{/isArrayModel}}{{^isArrayModel}}{{#vars}} -@dynamic {{name}};{{/vars}} -{{/isArrayModel}} -{{/model}} -@end -{{/models}} diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/NSManagedObject-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/NSManagedObject-header.mustache deleted file mode 100644 index 53bc9172472..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/NSManagedObject-header.mustache +++ /dev/null @@ -1,49 +0,0 @@ -#import -#import - -{{>licenceInfo}} - -{{#imports}}#import "{{import}}ManagedObject.h" -{{/imports}} -{{newline}} -{{#models}} -{{#model}} - -NS_ASSUME_NONNULL_BEGIN -{{#isArrayModel}} - -@interface {{classname}}ManagedObject : NSManagedObject - -@property (nullable, nonatomic, retain) NSSet<{{{arrayModelType}}}ManagedObject*>* entries; - -{{/isArrayModel}}{{^isArrayModel}} -@interface {{classname}}ManagedObject : {{#parent}}{{{parent}}}ManagedObject{{/parent}}{{^parent}}NSManagedObject{{/parent}} - -{{#vars}} -{{#description}}/* {{{description}}} {{^required}}[optional]{{/required}} - */{{/description}} -@property (nullable, nonatomic, retain) {{^complexType}}{{{ datatype }}}{{/complexType}}{{#complexType}}{{#isListContainer}}NSSet<{{{complexType}}}ManagedObject*>*{{/isListContainer}}{{^isListContainer}}{{#isMapContainer}}{{{ datatype }}}{{/isMapContainer}}{{^isMapContainer}}{{{complexType}}}ManagedObject*{{/isMapContainer}}{{/isListContainer}}{{/complexType}} {{name}}; -{{/vars}} -{{/isArrayModel}} -@end - -@interface {{classname}}ManagedObject (GeneratedAccessors) -{{#isArrayModel}} -- (void)addEntriesObject:({{arrayModelType}}ManagedObject *)value; -- (void)removeEntriesObject:({{arrayModelType}}ManagedObject *)value; -- (void)addEntries:(NSSet<{{{arrayModelType}}}ManagedObject*> *)values; -- (void)removeEntries:(NSSet<{{{arrayModelType}}}ManagedObject*> *)values; -{{/isArrayModel}} -{{^isArrayModel}} -{{#vars}}{{#isListContainer}}{{#complexType}}- (void)add{{vendorExtensions.x-uppercaseName}}Object:({{complexType}}ManagedObject *)value; -- (void)remove{{vendorExtensions.x-uppercaseName}}Object:({{complexType}}ManagedObject *)value; -- (void)add{{vendorExtensions.x-uppercaseName}}:(NSSet<{{{complexType}}}ManagedObject*> *)values; -- (void)remove{{vendorExtensions.x-uppercaseName}}:(NSSet<{{{complexType}}}ManagedObject*> *)values; -{{/complexType}}{{/isListContainer}}{{/vars}} -{{/isArrayModel}} -@end - - -NS_ASSUME_NONNULL_END -{{/model}} -{{/models}} \ No newline at end of file diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/NSManagedObjectBuilder-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/NSManagedObjectBuilder-body.mustache deleted file mode 100644 index b6b69135286..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/NSManagedObjectBuilder-body.mustache +++ /dev/null @@ -1,89 +0,0 @@ - -{{#models}}{{#model}} -#import "{{classname}}ManagedObjectBuilder.h" - -/** -* NOTE: This class is auto generated by the swagger code generator program. -* https://github.com/swagger-api/swagger-codegen -* Do not edit the class manually. -*/ - -@implementation {{classname}}ManagedObjectBuilder - --(instancetype)init { - self = [super init]; - if (self != nil) { -{{#isArrayModel}} _entriesBuilder = [[{{arrayModelType}}ManagedObjectBuilder alloc] init]; -{{/isArrayModel}}{{#vars}}{{#complexType}}{{^isMapContainer}} _{{name}}Builder = [[{{complexType}}ManagedObjectBuilder alloc] init]; -{{/isMapContainer}}{{/complexType}}{{/vars}} } - return self; -} - --({{classname}}ManagedObject*)createNew{{classname}}ManagedObjectInContext:(NSManagedObjectContext*)context { - {{classname}}ManagedObject *managedObject = [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([{{classname}}ManagedObject class]) inManagedObjectContext:context]; - return managedObject; -} - --({{classname}}ManagedObject*){{classname}}ManagedObjectFrom{{classname}}:({{classname}}*)object context:(NSManagedObjectContext*)context { - {{classname}}ManagedObject* new{{classname}} = [self createNew{{{classname}}}ManagedObjectInContext:context]; - [self update{{classname}}ManagedObject:new{{classname}} with{{classname}}:object]; - return new{{classname}}; -} - --(void)update{{classname}}ManagedObject:({{classname}}ManagedObject*)managedObject with{{classname}}:({{classname}}*)object { - if(!managedObject || !object) { - return; - } -{{#vars}}{{^complexType}} managedObject.{{name}} = [object.{{name}} copy];{{/complexType}}{{#complexType}}{{#isListContainer}} if(object.{{name}}) { - NSMutableSet * convertedObjs = [NSMutableSet set]; - for (id innerObject in object.{{name}}) { - id convertedObj = [self.{{name}}Builder {{complexType}}ManagedObjectFrom{{complexType}}:innerObject context:managedObject.managedObjectContext]; - [convertedObjs addObject:convertedObj]; - } - managedObject.{{name}} = convertedObjs; - }{{/isListContainer}}{{^isListContainer}}{{^isMapContainer}} - if(!managedObject.{{name}}) { - managedObject.{{name}} = [self.{{name}}Builder {{complexType}}ManagedObjectFrom{{complexType}}:object.{{name}} context:managedObject.managedObjectContext]; - } else { - [self.{{name}}Builder update{{complexType}}ManagedObject:managedObject.{{name}} with{{complexType}}:object.{{name}}]; - }{{/isMapContainer}}{{#isMapContainer}}managedObject.{{name}} = [object.{{name}} copy];{{/isMapContainer}}{{/isListContainer}}{{/complexType}} -{{/vars}}{{#isArrayModel}} NSMutableSet * convertedObjs = [NSMutableSet set]; - for (id innerObject in object) { - id convertedObj = [self.entriesBuilder {{arrayModelType}}ManagedObjectFrom{{arrayModelType}}:innerObject context:managedObject.managedObjectContext]; - [convertedObjs addObject:convertedObj]; - } - managedObject.entries = convertedObjs;{{/isArrayModel}} -} - --({{classname}}*){{classname}}From{{classname}}ManagedObject:({{classname}}ManagedObject*)obj { - if(!obj) { - return nil; - } - {{classname}}* new{{classname}} = [[{{classname}} alloc] init]; - [self update{{classname}}:new{{classname}} with{{classname}}ManagedObject:obj]; - return new{{classname}}; -} - --(void)update{{classname}}:({{classname}}*)new{{classname}} with{{classname}}ManagedObject:({{classname}}ManagedObject*)obj { -{{#isArrayModel}} [new{{classname}} removeAllObjects]; - NSMutableArray* convertedObjs = [NSMutableArray array]; - for (id innerObject in obj.entries) { - id convertedObj = [self.entriesBuilder {{arrayModelType}}From{{arrayModelType}}ManagedObject:innerObject]; - [convertedObjs addObject:convertedObj]; - } - [new{{classname}} addObjectsFromArray:convertedObjs]; -{{/isArrayModel}}{{#vars}}{{^complexType}} new{{classname}}.{{name}} = [obj.{{name}} copy];{{/complexType}}{{#complexType}}{{#isListContainer}} if(obj.{{name}} != nil) { - NSMutableArray* convertedObjs = [NSMutableArray array]; - for (id innerObject in obj.{{name}}) { - id convertedObj = [self.{{name}}Builder {{complexType}}From{{complexType}}ManagedObject:innerObject]; - [convertedObjs addObject:convertedObj]; - } - new{{classname}}.{{name}} = ({{{ datatype }}})convertedObjs; - } - {{/isListContainer}}{{^isListContainer}} new{{classname}}.{{name}} = [self.{{name}}Builder {{complexType}}From{{complexType}}ManagedObject:obj.{{name}}];{{/isListContainer}}{{/complexType}} - {{/vars}} -} - -@end -{{/model}} -{{/models}} \ No newline at end of file diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/NSManagedObjectBuilder-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/NSManagedObjectBuilder-header.mustache deleted file mode 100644 index 15778de3217..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/NSManagedObjectBuilder-header.mustache +++ /dev/null @@ -1,31 +0,0 @@ -#import -#import - -{{#imports}}#import "{{import}}ManagedObjectBuilder.h" -{{/imports}} -{{#models}} -{{#model}} - -#import "{{classname}}ManagedObject.h" -#import "{{classname}}.h" - -{{>licenceInfo}} - -@interface {{classname}}ManagedObjectBuilder : NSObject - -{{#isArrayModel}}@property (nonatomic, strong) {{arrayModelType}}ManagedObjectBuilder * entriesBuilder;{{/isArrayModel}}{{#vars}}{{#complexType}}@property (nonatomic, strong) {{complexType}}ManagedObjectBuilder * {{name}}Builder; -{{/complexType}}{{/vars}} - --({{classname}}ManagedObject*)createNew{{classname}}ManagedObjectInContext:(NSManagedObjectContext*)context; - --({{classname}}ManagedObject*){{classname}}ManagedObjectFrom{{classname}}:({{classname}}*)object context:(NSManagedObjectContext*)context; - --(void)update{{classname}}ManagedObject:({{classname}}ManagedObject*)object with{{classname}}:({{classname}}*)object2; - --({{classname}}*){{classname}}From{{classname}}ManagedObject:({{classname}}ManagedObject*)obj; - --(void)update{{classname}}:({{classname}}*)object with{{classname}}ManagedObject:({{classname}}ManagedObject*)object2; - -@end -{{/model}} -{{/models}} diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/Object-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/Object-body.mustache deleted file mode 100644 index 88df6d6c9ae..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/Object-body.mustache +++ /dev/null @@ -1,42 +0,0 @@ -#import "{{classPrefix}}Object.h" - -@implementation {{classPrefix}}Object - -/** - * Workaround for JSONModel multithreading issues - * https://github.com/icanzilb/JSONModel/issues/441 - */ -- (instancetype)initWithDictionary:(NSDictionary *)dict error:(NSError **)err { - static NSMutableSet *classNames; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - classNames = [NSMutableSet new]; - }); - - BOOL initSync; - @synchronized([self class]) - { - NSString *className = NSStringFromClass([self class]); - initSync = ![classNames containsObject:className]; - if(initSync) - { - [classNames addObject:className]; - self = [super initWithDictionary:dict error:err]; - } - } - if(!initSync) - { - self = [super initWithDictionary:dict error:err]; - } - return self; -} - -/** - * Gets the string presentation of the object. - * This method will be called when logging model object using `NSLog`. - */ -- (NSString *)description { - return [[self toDictionary] description]; -} - -@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/Object-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/Object-header.mustache deleted file mode 100644 index 89da6a4d8b6..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/Object-header.mustache +++ /dev/null @@ -1,8 +0,0 @@ -#import -#import - -{{>licenceInfo}} - -@interface {{classPrefix}}Object : JSONModel - -@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/QueryParamCollection-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/QueryParamCollection-body.mustache deleted file mode 100644 index b1c901dbffa..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/QueryParamCollection-body.mustache +++ /dev/null @@ -1,20 +0,0 @@ -#import "{{classPrefix}}QueryParamCollection.h" - -@implementation {{classPrefix}}QueryParamCollection - -@synthesize values = _values; -@synthesize format = _format; - -- (id)initWithValuesAndFormat:(NSArray *)values - format:(NSString *)format { - - self = [super init]; - if (self) { - _values = values; - _format = format; - } - - return self; -} - -@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/QueryParamCollection-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/QueryParamCollection-header.mustache deleted file mode 100644 index 9729c182bd8..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/QueryParamCollection-header.mustache +++ /dev/null @@ -1,13 +0,0 @@ -#import - -{{>licenceInfo}} - -@interface {{classPrefix}}QueryParamCollection : NSObject - -@property(nonatomic, readonly) NSArray* values; -@property(nonatomic, readonly) NSString* format; - -- (id) initWithValuesAndFormat: (NSArray*) values - format: (NSString*) format; - -@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/README.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/README.mustache deleted file mode 100644 index 4355ecc1af5..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/README.mustache +++ /dev/null @@ -1,143 +0,0 @@ -# {{podName}} - -{{#appDescription}} -{{{appDescription}}} -{{/appDescription}} - -This ObjC package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: - -- API version: {{appVersion}} -- Package version: {{artifactVersion}} -- Build date: {{generatedDate}} -- Build package: {{generatorClass}} -{{#infoUrl}} -For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) -{{/infoUrl}} - -## Requirements - -The SDK requires [**ARC (Automatic Reference Counting)**](http://stackoverflow.com/questions/7778356/how-to-enable-disable-automatic-reference-counting) to be enabled in the Xcode project. - -## Installation & Usage -### Install from Github using [CocoaPods](https://cocoapods.org/) - -Add the following to the Podfile: - -```ruby -pod '{{podName}}', :git => 'https://github.com/{{gitUserId}}/{{gitRepoId}}.git' -``` - -To specify a particular branch, append `, :branch => 'branch-name-here'` - -To specify a particular commit, append `, :commit => '11aa22'` - -### Install from local path using [CocoaPods](https://cocoapods.org/) - -Put the SDK under your project folder (e.g. /path/to/objc_project/Vendor/{{podName}}) and then add the following to the Podfile: - -```ruby -pod '{{podName}}', :path => 'Vendor/{{podName}}' -``` - -### Usage - -Import the following: - -```objc -#import <{{podName}}/{{{classPrefix}}}ApiClient.h> -#import <{{podName}}/{{{classPrefix}}}Configuration.h> -// load models -{{#models}}{{#model}}#import <{{podName}}/{{{classname}}}.h> -{{/model}}{{/models}}// load API classes for accessing endpoints -{{#apiInfo}}{{#apis}}#import <{{podName}}/{{{classname}}}.h> -{{/apis}}{{/apiInfo}} -``` - -## Recommendation - -It's recommended to create an instance of ApiClient per thread in a multi-threaded environment to avoid any potential issue. - -## Getting Started - -Please follow the [installation procedure](#installation--usage) and then run the following: - -```objc -{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}} -{{#hasAuthMethods}} -{{classPrefix}}Configuration *apiConfig = [{{classPrefix}}Configuration sharedConfig]; -{{#authMethods}}{{#isBasic}}// Configure HTTP basic authorization (authentication scheme: {{{name}}}) -[apiConfig setUsername:@"YOUR_USERNAME"]; -[apiConfig setPassword:@"YOUR_PASSWORD"]; -{{/isBasic}}{{#isApiKey}} -// Configure API key authorization: (authentication scheme: {{{name}}}) -[apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"{{{keyParamName}}}"]; -// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed -//[apiConfig setApiKeyPrefix:@"Bearer" forApiKeyIdentifier:@"{{{keyParamName}}}"]; -{{/isApiKey}}{{#isOAuth}} -// Configure OAuth2 access token for authorization: (authentication scheme: {{{name}}}) -[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; -{{/isOAuth}}{{/authMethods}} -{{/hasAuthMethods}} - -{{#allParams}}{{{dataType}}} *{{paramName}} = {{{example}}}; // {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} -{{/allParams}} - -{{classname}} *apiInstance = [[{{classname}} alloc] init]; - -{{#summary}}// {{{.}}} -{{/summary}}[apiInstance {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} - {{paramName}}{{/secondaryParam}}:{{paramName}}{{/allParams}} - {{#hasParams}}completionHandler: {{/hasParams}}^({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error) { -{{#returnType}} - if (output) { - NSLog(@"%@", output); - } -{{/returnType}} - if (error) { - NSLog(@"Error: %@", error); - } - }]; -{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} -``` - -## Documentation for API Endpoints - -All URIs are relative to *{{basePath}}* - -Class | Method | HTTP request | Description ------------- | ------------- | ------------- | ------------- -{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} -{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} - -## Documentation For Models - -{{#models}}{{#model}} - [{{{classname}}}]({{modelDocPath}}{{{classname}}}.md) -{{/model}}{{/models}} - -## Documentation For Authorization - -{{^authMethods}} All endpoints do not require authorization. -{{/authMethods}}{{#authMethods}}{{#last}} Authentication schemes defined for the API:{{/last}}{{/authMethods}} -{{#authMethods}}## {{{name}}} - -{{#isApiKey}}- **Type**: API key -- **API key parameter name**: {{{keyParamName}}} -- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} -{{/isApiKey}} -{{#isBasic}}- **Type**: HTTP basic authentication -{{/isBasic}} -{{#isOAuth}}- **Type**: OAuth -- **Flow**: {{{flow}}} -- **Authorization URL**: {{{authorizationUrl}}} -- **Scopes**: {{^scopes}}N/A{{/scopes}} -{{#scopes}} - **{{{scope}}}**: {{{description}}} -{{/scopes}} -{{/isOAuth}} - -{{/authMethods}} - -## Author - -{{#apiInfo}}{{#apis}}{{^hasMore}}{{infoEmail}} -{{/hasMore}}{{/apis}}{{/apiInfo}} - diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/ResponseDeserializer-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/ResponseDeserializer-body.mustache deleted file mode 100644 index 812ed061c04..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/ResponseDeserializer-body.mustache +++ /dev/null @@ -1,231 +0,0 @@ -#import "{{classPrefix}}ResponseDeserializer.h" -#import -#import - -NSString *const {{classPrefix}}DeserializationErrorDomainKey = @"{{classPrefix}}DeserializationErrorDomainKey"; - -NSInteger const {{classPrefix}}TypeMismatchErrorCode = 143553; - -NSInteger const {{classPrefix}}EmptyValueOccurredErrorCode = 143509; - -NSInteger const {{classPrefix}}UnknownResponseObjectErrorCode = 143528; - - -@interface {{classPrefix}}ResponseDeserializer () - -@property (nonatomic, strong) NSNumberFormatter* numberFormatter; -@property (nonatomic, strong) NSArray *primitiveTypes; -@property (nonatomic, strong) NSArray *basicReturnTypes; - -@property (nonatomic, strong) NSRegularExpression* arrayOfModelsPatExpression; -@property (nonatomic, strong) NSRegularExpression* arrayOfPrimitivesPatExpression; -@property (nonatomic, strong) NSRegularExpression* dictPatExpression; -@property (nonatomic, strong) NSRegularExpression* dictModelsPatExpression; - -@end - -@implementation {{classPrefix}}ResponseDeserializer - -- (instancetype)init { - self = [super init]; - if (self) { - NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; - formatter.numberStyle = NSNumberFormatterDecimalStyle; - _numberFormatter = formatter; - _primitiveTypes = @[@"NSString", @"NSDate", @"NSNumber"]; - _basicReturnTypes = @[@"NSObject", @"id", @"NSData"]; - _arrayOfModelsPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSArray<(.+)>" - options:NSRegularExpressionCaseInsensitive - error:nil]; - _arrayOfPrimitivesPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSArray\\* /\\* (.+) \\*/" - options:NSRegularExpressionCaseInsensitive - error:nil]; - _dictPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSDictionary\\* /\\* (.+?), (.+) \\*/" - options:NSRegularExpressionCaseInsensitive - error:nil]; - _dictModelsPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSDictionary\\<(.+?), (.+)*\\>" - options:NSRegularExpressionCaseInsensitive - error:nil]; - } - return self; -} - -#pragma mark - Deserialize methods - -- (id) deserialize:(id) data class:(NSString *) className error:(NSError **) error { - // return nil if data is nil or className is nil - if (!data || !className || [data isKindOfClass:[NSNull class]]) { - return nil; - } - - // remove "*" from className, if ends with "*" - if ([className hasSuffix:@"*"]) { - className = [className substringToIndex:[className length] - 1]; - } - // pure object - if ([self.basicReturnTypes containsObject:className]) { - return data; - } - - // primitives - if ([self.primitiveTypes containsObject:className]) { - return [self deserializePrimitiveValue:data class:className error:error]; - } - - NSTextCheckingResult *match = nil; - NSRange range = NSMakeRange(0, [className length]); - // list of models - match = [self.arrayOfModelsPatExpression firstMatchInString:className options:0 range:range]; - if (match) { - NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]]; - return [self deserializeArrayValue:data innerType:innerType error:error]; - } - - // list of primitives - match = [self.arrayOfPrimitivesPatExpression firstMatchInString:className options:0 range:range]; - if (match) { - NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]]; - return [self deserializeArrayValue:data innerType:innerType error:error]; - } - - // map - match = [self.dictPatExpression firstMatchInString:className options:0 range:range]; - if (match) { - NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]]; - return [self deserializeDictionaryValue:data valueType:valueType error:error]; - } - - match = [self.dictModelsPatExpression firstMatchInString:className options:0 range:range]; - if (match) { - NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]]; - return [self deserializeDictionaryValue:data valueType:valueType error:error]; - } - - // model - Class ModelClass = NSClassFromString(className); - if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) { - return [(JSONModel *) [ModelClass alloc] initWithDictionary:data error:error]; - } - - if(error) { - *error = [self unknownResponseErrorWithExpectedType:className data:data]; - } - return nil; -} - -- (id) deserializeDictionaryValue:(id) data valueType:(NSString *) valueType error:(NSError**)error { - if(![data isKindOfClass: [NSDictionary class]]) { - if(error) { - *error = [self typeMismatchErrorWithExpectedType:NSStringFromClass([NSDictionary class]) data:data]; - } - return nil; - } - __block NSMutableDictionary *resultDict = [NSMutableDictionary dictionaryWithCapacity:[data count]]; - for (id key in [data allKeys]) { - id obj = [data valueForKey:key]; - id dicObj = [self deserialize:obj class:valueType error:error]; - if(dicObj) { - [resultDict setValue:dicObj forKey:key]; - } else if([obj isKindOfClass:[NSNull class]]) { - if(self.treatNullAsError) { - if (error) { - *error = [self emptyValueOccurredError]; - } - resultDict = nil; - break; - } - } else { - resultDict = nil; - break; - } - } - return resultDict; -} - -- (id) deserializeArrayValue:(id) data innerType:(NSString *) innerType error:(NSError**)error { - if(![data isKindOfClass: [NSArray class]]) { - if(error) { - *error = [self typeMismatchErrorWithExpectedType:NSStringFromClass([NSArray class]) data:data]; - } - return nil; - } - NSMutableArray* resultArray = [NSMutableArray arrayWithCapacity:[data count]]; - for (id obj in data) { - id arrObj = [self deserialize:obj class:innerType error:error]; - if(arrObj) { - [resultArray addObject:arrObj]; - } else if([obj isKindOfClass:[NSNull class]]) { - if(self.treatNullAsError) { - if (error) { - *error = [self emptyValueOccurredError]; - } - resultArray = nil; - break; - } - } else { - resultArray = nil; - break; - } - } - return resultArray; -}; - -- (id) deserializePrimitiveValue:(id) data class:(NSString *) className error:(NSError**)error { - if ([className isEqualToString:@"NSString"]) { - return [NSString stringWithString:data]; - } - else if ([className isEqualToString:@"NSDate"]) { - return [self deserializeDateValue:data error:error]; - } - else if ([className isEqualToString:@"NSNumber"]) { - // NSNumber from NSNumber - if ([data isKindOfClass:[NSNumber class]]) { - return data; - } - else if ([data isKindOfClass:[NSString class]]) { - // NSNumber (NSCFBoolean) from NSString - if ([[data lowercaseString] isEqualToString:@"true"] || [[data lowercaseString] isEqualToString:@"false"]) { - return @([data boolValue]); - // NSNumber from NSString - } else { - NSNumber* formattedValue = [self.numberFormatter numberFromString:data]; - if(!formattedValue && [data length] > 0 && error) { - *error = [self typeMismatchErrorWithExpectedType:className data:data]; - } - return formattedValue; - } - } - } - if(error) { - *error = [self typeMismatchErrorWithExpectedType:className data:data]; - } - return nil; -} - -- (id) deserializeDateValue:(id) data error:(NSError**)error { - NSDate *date =[NSDate dateWithISO8601String:data]; - if(!date && [data length] > 0 && error) { - *error = [self typeMismatchErrorWithExpectedType:NSStringFromClass([NSDate class]) data:data]; - } - return date; -}; - --(NSError *)typeMismatchErrorWithExpectedType:(NSString *)expected data:(id)data { - NSString * message = [NSString stringWithFormat:NSLocalizedString(@"Received response [%@] is not an object of type %@",nil),data, expected]; - NSDictionary * userInfo = @{NSLocalizedDescriptionKey : message}; - return [NSError errorWithDomain:{{classPrefix}}DeserializationErrorDomainKey code:{{classPrefix}}TypeMismatchErrorCode userInfo:userInfo]; -} - --(NSError *)emptyValueOccurredError { - NSString * message = NSLocalizedString(@"Received response contains null value in dictionary or array response",nil); - NSDictionary * userInfo = @{NSLocalizedDescriptionKey : message}; - return [NSError errorWithDomain:{{classPrefix}}DeserializationErrorDomainKey code:{{classPrefix}}EmptyValueOccurredErrorCode userInfo:userInfo]; -} - --(NSError *)unknownResponseErrorWithExpectedType:(NSString *)expected data:(id)data { - NSString * message = [NSString stringWithFormat:NSLocalizedString(@"Unknown response expected type %@ [reponse: %@]",nil),expected,data]; - NSDictionary * userInfo = @{NSLocalizedDescriptionKey : message}; - return [NSError errorWithDomain:{{classPrefix}}DeserializationErrorDomainKey code:{{classPrefix}}UnknownResponseObjectErrorCode userInfo:userInfo]; -} - -@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/ResponseDeserializer-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/ResponseDeserializer-header.mustache deleted file mode 100644 index 90aa174d7c4..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/ResponseDeserializer-header.mustache +++ /dev/null @@ -1,46 +0,0 @@ -#import - -{{>licenceInfo}} - -/** - * A key for deserialization ErrorDomain - */ -extern NSString *const {{classPrefix}}DeserializationErrorDomainKey; - -/** - * Code for deserialization type mismatch error - */ -extern NSInteger const {{classPrefix}}TypeMismatchErrorCode; - -/** - * Code for deserialization empty value error - */ -extern NSInteger const {{classPrefix}}EmptyValueOccurredErrorCode; - -/** - * Error code for unknown response - */ -extern NSInteger const {{classPrefix}}UnknownResponseObjectErrorCode; - -@protocol {{classPrefix}}ResponseDeserializer - -/** - * Deserializes the given data to Objective-C object. - * - * @param data The data will be deserialized. - * @param class The type of objective-c object. - * @param error The error - */ -- (id) deserialize:(id) data class:(NSString *) className error:(NSError**)error; - -@end - -@interface {{classPrefix}}ResponseDeserializer : NSObject <{{classPrefix}}ResponseDeserializer> - -/** - * If an null value occurs in dictionary or array if set to YES whole response will be invalid else will be ignored - * @default NO - */ -@property (nonatomic, assign) BOOL treatNullAsError; - -@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/Sanitizer-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/Sanitizer-body.mustache deleted file mode 100644 index 00d74aaa1f7..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/Sanitizer-body.mustache +++ /dev/null @@ -1,168 +0,0 @@ -#import "{{classPrefix}}Sanitizer.h" -#import "{{classPrefix}}Object.h" -#import "{{classPrefix}}QueryParamCollection.h" -#import - -NSString * {{classPrefix}}PercentEscapedStringFromString(NSString *string) { - static NSString * const k{{classPrefix}}CharactersGeneralDelimitersToEncode = @":#[]@"; - static NSString * const k{{classPrefix}}CharactersSubDelimitersToEncode = @"!$&'()*+,;="; - - NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy]; - [allowedCharacterSet removeCharactersInString:[k{{classPrefix}}CharactersGeneralDelimitersToEncode stringByAppendingString:k{{classPrefix}}CharactersSubDelimitersToEncode]]; - - static NSUInteger const batchSize = 50; - - NSUInteger index = 0; - NSMutableString *escaped = @"".mutableCopy; - - while (index < string.length) { - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wgnu" - NSUInteger length = MIN(string.length - index, batchSize); - #pragma GCC diagnostic pop - NSRange range = NSMakeRange(index, length); - - // To avoid breaking up character sequences such as 👴🏻👮🏽 - range = [string rangeOfComposedCharacterSequencesForRange:range]; - - NSString *substring = [string substringWithRange:range]; - NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet]; - [escaped appendString:encoded]; - - index += range.length; - } - - return escaped; -} - -@interface {{classPrefix}}Sanitizer () - -@property (nonatomic, strong) NSRegularExpression* jsonHeaderTypeExpression; - -@end - -@implementation {{classPrefix}}Sanitizer - -static NSString * kApplicationJSONType = @"application/json"; - --(instancetype)init { - self = [super init]; - if ( !self ) { - return nil; - } - _jsonHeaderTypeExpression = [NSRegularExpression regularExpressionWithPattern:@"(.*)application(.*)json(.*)" options:NSRegularExpressionCaseInsensitive error:nil]; - return self; -} - - -- (id) sanitizeForSerialization:(id) object { - if (object == nil) { - return nil; - } - else if ([object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSNumber class]] || [object isKindOfClass:[{{classPrefix}}QueryParamCollection class]]) { - return object; - } - else if ([object isKindOfClass:[NSDate class]]) { - return [self dateParameterToString:object]; - } - else if ([object isKindOfClass:[NSArray class]]) { - NSArray *objectArray = object; - NSMutableArray *sanitizedObjs = [NSMutableArray arrayWithCapacity:[objectArray count]]; - [object enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - id sanitizedObj = [self sanitizeForSerialization:obj]; - if (sanitizedObj) { - [sanitizedObjs addObject:sanitizedObj]; - } - }]; - return sanitizedObjs; - } - else if ([object isKindOfClass:[NSDictionary class]]) { - NSDictionary *objectDict = object; - NSMutableDictionary *sanitizedObjs = [NSMutableDictionary dictionaryWithCapacity:[objectDict count]]; - [object enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - id sanitizedObj = [self sanitizeForSerialization:obj]; - if (sanitizedObj) { - sanitizedObjs[key] = sanitizedObj; - } - }]; - return sanitizedObjs; - } - else if ([object isKindOfClass:[{{classPrefix}}Object class]]) { - return [object toDictionary]; - } - else { - NSException *e = [NSException - exceptionWithName:@"InvalidObjectArgumentException" - reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", object] - userInfo:nil]; - @throw e; - } -} - -- (NSString *) parameterToString:(id)param { - if ([param isKindOfClass:[NSString class]]) { - return param; - } - else if ([param isKindOfClass:[NSNumber class]]) { - return [param stringValue]; - } - else if ([param isKindOfClass:[NSDate class]]) { - return [self dateParameterToString:param]; - } - else if ([param isKindOfClass:[NSArray class]]) { - NSMutableArray *mutableParam = [NSMutableArray array]; - [param enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - [mutableParam addObject:[self parameterToString:obj]]; - }]; - return [mutableParam componentsJoinedByString:@","]; - } - else { - NSException *e = [NSException - exceptionWithName:@"InvalidObjectArgumentException" - reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", param] - userInfo:nil]; - @throw e; - } -} - -- (NSString *)dateParameterToString:(id)param { - return [param ISO8601String]; -} - -#pragma mark - Utility Methods - -/* - * Detect `Accept` from accepts - */ -- (NSString *) selectHeaderAccept:(NSArray *)accepts { - if (accepts.count == 0) { - return @""; - } - NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]]; - for (NSString *string in accepts) { - if ([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0) { - return kApplicationJSONType; - } - [lowerAccepts addObject:[string lowercaseString]]; - } - return [lowerAccepts componentsJoinedByString:@", "]; -} - -/* - * Detect `Content-Type` from contentTypes - */ -- (NSString *) selectHeaderContentType:(NSArray *)contentTypes { - if (contentTypes.count == 0) { - return kApplicationJSONType; - } - NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]]; - for (NSString *string in contentTypes) { - if([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0){ - return kApplicationJSONType; - } - [lowerContentTypes addObject:[string lowercaseString]]; - } - return [lowerContentTypes firstObject]; -} - -@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/Sanitizer-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/Sanitizer-header.mustache deleted file mode 100644 index f975018a020..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/Sanitizer-header.mustache +++ /dev/null @@ -1,45 +0,0 @@ -#import - -{{>licenceInfo}} - -extern NSString * {{classPrefix}}PercentEscapedStringFromString(NSString *string); - -@protocol {{classPrefix}}Sanitizer - -/** - * Sanitize object for request - * - * @param object The query/path/header/form/body param to be sanitized. - */ -- (id) sanitizeForSerialization:(id) object; - -/** - * Convert parameter to NSString - */ -- (NSString *) parameterToString: (id) param; - -/** - * Detects Accept header from accepts NSArray - * - * @param accepts NSArray of header - * - * @return The Accept header - */ --(NSString *) selectHeaderAccept:(NSArray *)accepts; - -/** - * Detects Content-Type header from contentTypes NSArray - * - * @param contentTypes NSArray of header - * - * @return The Content-Type header - */ --(NSString *) selectHeaderContentType:(NSArray *)contentTypes; - -@end - -@interface {{classPrefix}}Sanitizer : NSObject <{{classPrefix}}Sanitizer> - - - -@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/api-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/api-body.mustache deleted file mode 100644 index ff9b42d38d4..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/api-body.mustache +++ /dev/null @@ -1,160 +0,0 @@ -{{#operations}} -#import "{{classname}}.h" -#import "{{classPrefix}}QueryParamCollection.h" -{{#imports}}#import "{{import}}.h" -{{/imports}} -{{newline}} - -@interface {{classname}} () - -@property (nonatomic, strong, readwrite) NSMutableDictionary *defaultHeaders; - -@end - -@implementation {{classname}} - -NSString* k{{classname}}ErrorDomain = @"{{classname}}ErrorDomain"; -NSInteger k{{classname}}MissingParamErrorCode = 234513; - -@synthesize apiSessionManager = _apiSessionManager; - -#pragma mark - Initialize methods - --(instancetype) initWithApiSessionManager:({{classPrefix}}ApiSessionManager *)apiSessionManager { - self = [super init]; - if (self) { - _apiSessionManager = apiSessionManager; - _defaultHeaders = [NSMutableDictionary dictionary]; - } - - return self; -} - -#pragma mark - - --(NSString*) defaultHeaderForKey:(NSString*)key { - return self.defaultHeaders[key]; -} - --(void) addHeader:(NSString*)value forKey:(NSString*)key { - [self setDefaultHeaderValue:value forKey:key]; -} - --(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key { - [self.defaultHeaders setValue:value forKey:key]; -} - -#pragma mark - Api Methods - -{{#operation}} -/// -/// {{{summary}}} -/// {{{notes}}} -/// {{#allParams}} @param {{paramName}} {{{description}}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} -/// -/// {{/allParams}} @returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} -/// --(NSURLSessionTask*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} - {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}} - {{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler { - {{#allParams}} - {{#required}} - // verify the required parameter '{{paramName}}' is set - if ({{paramName}} == nil) { - NSParameterAssert({{paramName}}); - if(handler) { - NSDictionary * userInfo = @{NSLocalizedDescriptionKey : [NSString stringWithFormat:NSLocalizedString(@"Missing required parameter '%@'", nil),@"{{paramName}}"] }; - NSError* error = [NSError errorWithDomain:k{{classname}}ErrorDomain code:k{{classname}}MissingParamErrorCode userInfo:userInfo]; - handler({{#returnType}}nil, {{/returnType}}error); - } - return nil; - } - - {{/required}} - {{/allParams}} - NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"{{path}}"]; - - // remove format in URL if needed - [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; - - NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; - {{#pathParams}} - if ({{paramName}} != nil) { - pathParams[@"{{baseName}}"] = {{paramName}}; - } - {{/pathParams}} - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - {{#queryParams}} - if ({{paramName}} != nil) { - {{#collectionFormat}} - queryParams[@"{{baseName}}"] = [[{{classPrefix}}QueryParamCollection alloc] initWithValuesAndFormat: {{paramName}} format: @"{{collectionFormat}}"]; - {{/collectionFormat}} - {{^collectionFormat}}queryParams[@"{{baseName}}"] = {{paramName}};{{/collectionFormat}} - } - {{/queryParams}} - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiSessionManager.configuration.defaultHeaders]; - [headerParams addEntriesFromDictionary:self.defaultHeaders]; - {{#headerParams}} - if ({{paramName}} != nil) { - headerParams[@"{{baseName}}"] = {{paramName}}; - } - {{/headerParams}} - // HTTP header `Accept` - NSString *acceptHeader = [self.apiSessionManager.sanitizer selectHeaderAccept:@[{{#produces}}@"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}}]]; - if(acceptHeader.length > 0) { - headerParams[@"Accept"] = acceptHeader; - } - - // response content type - NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; - - // request content type - NSString *requestContentType = [self.apiSessionManager.sanitizer selectHeaderContentType:@[{{#consumes}}@"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}]]; - - // Authentication setting - NSArray *authSettings = @[{{#authMethods}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; - - id bodyParam = nil; - NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; - {{#bodyParam}} - bodyParam = {{paramName}}; - {{/bodyParam}} - {{^bodyParam}} - {{#formParams}} - {{#notFile}} - if ({{paramName}}) { - formParams[@"{{baseName}}"] = {{paramName}}; - } - {{/notFile}} - {{#isFile}} - localVarFiles[@"{{paramName}}"] = {{paramName}}; - {{/isFile}} - {{/formParams}} - {{/bodyParam}} - - return [self.apiSessionManager requestWithPath: resourcePath - method: @"{{httpMethod}}" - pathParams: pathParams - queryParams: queryParams - formParams: formParams - files: localVarFiles - body: bodyParam - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - responseType: {{^returnType}}nil{{/returnType}}{{#returnType}}@"{{{ returnType }}}"{{/returnType}} - completionBlock: ^(id data, NSError *error) { - if(handler) { - handler({{#returnType}}({{{ returnType }}})data, {{/returnType}}error); - } - }]; -} - -{{/operation}} - -{{newline}} -{{/operations}} -@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/api-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/api-header.mustache deleted file mode 100644 index 12fe8c7b954..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/api-header.mustache +++ /dev/null @@ -1,32 +0,0 @@ -#import -{{#imports}}#import "{{import}}.h" -{{/imports}} -#import "{{classPrefix}}Api.h" - -{{>licenceInfo}} - - -@interface {{classname}}: NSObject <{{classPrefix}}Api> - -extern NSString* k{{classname}}ErrorDomain; -extern NSInteger k{{classname}}MissingParamErrorCode; - -{{#operations}} -{{#operation}} -/// {{{summary}}} -/// {{#notes}}{{{notes}}}{{/notes}} -/// -/// {{#allParams}}@param {{paramName}} {{description}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} -/// {{/allParams}}{{#responses}} -/// code:{{{code}}} message:"{{{message}}}"{{#hasMore}},{{/hasMore}}{{/responses}} -/// -/// @return {{{returnType}}} --(NSURLSessionTask*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} - {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}} - {{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler; - -{{newline}} -{{/operation}} -{{/operations}} - -@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/api-protocol.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/api-protocol.mustache deleted file mode 100644 index 79c9da59ce4..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/api-protocol.mustache +++ /dev/null @@ -1,18 +0,0 @@ -#import -#import "{{classPrefix}}Object.h" -#import "{{classPrefix}}ApiSessionManager.h" - -{{>licenceInfo}} - -@protocol {{classPrefix}}Api - -@property(readonly, nonatomic, strong) {{classPrefix}}ApiSessionManager *apiSessionManager; - --(instancetype) initWithApiSessionManager:({{classPrefix}}ApiSessionManager *)apiSessionManager; - --(void) addHeader:(NSString*)value forKey:(NSString*)key DEPRECATED_MSG_ATTRIBUTE("setDefaultHeaderValue:forKey:"); - --(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key; --(NSString*) defaultHeaderForKey:(NSString*)key; - -@end diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/api_doc.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/api_doc.mustache deleted file mode 100644 index 44fe31d6404..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/api_doc.mustache +++ /dev/null @@ -1,85 +0,0 @@ -# {{classname}}{{#description}} -{{description}}{{/description}} - -All URIs are relative to *{{basePath}}* - -Method | HTTP request | Description -------------- | ------------- | ------------- -{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} -{{/operation}}{{/operations}} - -{{#operations}} -{{#operation}} -# **{{{operationId}}}** -```objc --(NSNumber*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} - {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}} - {{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler; -``` - -{{{summary}}}{{#notes}} - -{{{notes}}}{{/notes}} - -### Example -```objc -{{#hasAuthMethods}} -{{classPrefix}}Configuration *apiConfig = [{{classPrefix}}Configuration sharedConfig]; -{{#authMethods}}{{#isBasic}}// Configure HTTP basic authorization (authentication scheme: {{{name}}}) -[apiConfig setUsername:@"YOUR_USERNAME"]; -[apiConfig setPassword:@"YOUR_PASSWORD"]; -{{/isBasic}}{{#isApiKey}} -// Configure API key authorization: (authentication scheme: {{{name}}}) -[apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"{{{keyParamName}}}"]; -// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed -//[apiConfig setApiKeyPrefix:@"Bearer" forApiKeyIdentifier:@"{{{keyParamName}}}"]; -{{/isApiKey}}{{#isOAuth}} -// Configure OAuth2 access token for authorization: (authentication scheme: {{{name}}}) -[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; -{{/isOAuth}}{{/authMethods}} -{{/hasAuthMethods}} - -{{#allParams}}{{{dataType}}} {{paramName}} = {{{example}}}; // {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} -{{/allParams}} - -{{classname}}*apiInstance = [[{{classname}} alloc] init]; - -{{#summary}}// {{{.}}} -{{/summary}}[apiInstance {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} - {{paramName}}{{/secondaryParam}}:{{paramName}}{{/allParams}} - {{#hasParams}}completionHandler: {{/hasParams}}^({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error) { -{{#returnType}} - if (output) { - NSLog(@"%@", output); - } -{{/returnType}} - if (error) { - NSLog(@"Error calling {{classname}}->{{operationId}}: %@", error); - } - }]; -``` - -### Parameters -{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} -Name | Type | Description | Notes -------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} -{{#allParams}} **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} -{{/allParams}} - -### Return type - -{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void (empty response body){{/returnType}} - -### Authorization - -{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{{name}}}](../README.md#{{{name}}}){{^-last}}, {{/-last}}{{/authMethods}} - -### HTTP request headers - - - **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} - - **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -{{/operation}} -{{/operations}} diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/git_push.sh.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/git_push.sh.mustache deleted file mode 100644 index e153ce23ecf..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/git_push.sh.mustache +++ /dev/null @@ -1,52 +0,0 @@ -#!/bin/sh -# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ -# -# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" - -git_user_id=$1 -git_repo_id=$2 -release_note=$3 - -if [ "$git_user_id" = "" ]; then - git_user_id="{{{gitUserId}}}" - echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" -fi - -if [ "$git_repo_id" = "" ]; then - git_repo_id="{{{gitRepoId}}}" - echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" -fi - -if [ "$release_note" = "" ]; then - release_note="{{{releaseNote}}}" - echo "[INFO] No command line input provided. Set \$release_note to $release_note" -fi - -# Initialize the local directory as a Git repository -git init - -# Adds the files in the local repository and stages them for commit. -git add . - -# Commits the tracked changes and prepares them to be pushed to a remote repository. -git commit -m "$release_note" - -# Sets the new remote -git_remote=`git remote` -if [ "$git_remote" = "" ]; then # git remote not defined - - if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." - git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git - else - git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git - fi - -fi - -git pull origin master - -# Pushes (Forces) the changes in the local repository up to the remote repository -echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" -git push origin master 2>&1 | grep -v 'To https' - diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/gitignore.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/gitignore.mustache deleted file mode 100644 index 79d9331b6d4..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/gitignore.mustache +++ /dev/null @@ -1,53 +0,0 @@ -# Xcode -# -# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore - -## Build generated -build/ -DerivedData - -## Various settings -*.pbxuser -!default.pbxuser -*.mode1v3 -!default.mode1v3 -*.mode2v3 -!default.mode2v3 -*.perspectivev3 -!default.perspectivev3 -xcuserdata - -## Other -*.xccheckout -*.moved-aside -*.xcuserstate -*.xcscmblueprint - -## Obj-C/Swift specific -*.hmap -*.ipa - -# CocoaPods -# -# We recommend against adding the Pods directory to your .gitignore. However -# you should judge for yourself, the pros and cons are mentioned at: -# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control -# -# Pods/ - -# Carthage -# -# Add this line if you want to avoid checking in source code from Carthage dependencies. -# Carthage/Checkouts - -Carthage/Build - -# fastlane -# -# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the -# screenshots whenever they are needed. -# For more information about the recommended setup visit: -# https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md - -fastlane/report.xml -fastlane/screenshots diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/licenceInfo.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/licenceInfo.mustache deleted file mode 100644 index 2f0f1940e89..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/licenceInfo.mustache +++ /dev/null @@ -1,23 +0,0 @@ -/** -* {{{appName}}} -* {{{appDescription}}} -* -* {{#version}}OpenAPI spec version: {{{version}}}{{/version}} -* {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} -* -* NOTE: This class is auto generated by the swagger code generator program. -* https://github.com/swagger-api/swagger-codegen.git -* Do not edit the class manually. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ \ No newline at end of file diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/model-body.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/model-body.mustache deleted file mode 100644 index 2a4a548458e..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/model-body.mustache +++ /dev/null @@ -1,59 +0,0 @@ -{{#models}} -{{#model}} -#import "{{classname}}.h" - -@implementation {{classname}} - -- (instancetype)init { - self = [super init]; - if (self) { - // initialize property's default value, if any - {{#vars}}{{#defaultValue}}self.{{name}} = {{{defaultValue}}}; - {{/defaultValue}}{{/vars}} - } - return self; -} -{{#vars}}{{^vendorExtensions.x-unique-id-key}}{{/vendorExtensions.x-unique-id-key}}{{#vendorExtensions.x-unique-id-key}} --(NSString*)indexPropertyName { - return @"{{name}}"; -} -{{/vendorExtensions.x-unique-id-key}}{{/vars}} -{{#discriminator}} -/** - * Maps "discriminator" value to the sub-class name, so that inheritance is supported. - */ -- (id)initWithDictionary:(NSDictionary *)dict error:(NSError *__autoreleasing *)err { - NSString * discriminatedClassName = [dict valueForKey:@"{{discriminator}}"]; - if(discriminatedClassName == nil ){ - return [super initWithDictionary:dict error:err]; - } - Class class = NSClassFromString([@"{{classPrefix}}" stringByAppendingString:discriminatedClassName]); - if([self class ] == class) { - return [super initWithDictionary:dict error:err]; - } - return [[class alloc] initWithDictionary:dict error: err]; -} -{{/discriminator}} - -/** - * Maps json key to property name. - * This method is used by `JSONModel`. - */ -+ (JSONKeyMapper *)keyMapper { - return [[JSONKeyMapper alloc] initWithDictionary:@{ {{#vars}}@"{{baseName}}": @"{{name}}"{{#hasMore}}, {{/hasMore}}{{/vars}} }]; -} - -/** - * Indicates whether the property with the given name is optional. - * If `propertyName` is optional, then return `YES`, otherwise return `NO`. - * This method is used by `JSONModel`. - */ -+ (BOOL)propertyIsOptional:(NSString *)propertyName { - - NSArray *optionalProperties = @[{{#vars}}{{^required}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/required}}{{/vars}}]; - return [optionalProperties containsObject:propertyName]; -} - -{{/model}} -@end -{{/models}} diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/model-header.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/model-header.mustache deleted file mode 100644 index 04570e71a2f..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/model-header.mustache +++ /dev/null @@ -1,25 +0,0 @@ -#import -#import "{{classPrefix}}Object.h" - -{{>licenceInfo}} - -{{#imports}}#import "{{import}}.h" -{{/imports}} -{{newline}} -{{#models}} -{{#model}} - -@protocol {{classname}} -@end - -@interface {{classname}} : {{#parent}}{{{parent}}}{{/parent}}{{^parent}}{{classPrefix}}Object{{/parent}} - -{{#vars}} -{{#description}}/* {{{description}}} {{^required}}[optional]{{/required}} - */{{/description}} -@property(nonatomic) {{{ datatype }}} {{name}}; -{{/vars}} - -@end -{{/model}} -{{/models}} diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/model_doc.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/model_doc.mustache deleted file mode 100644 index 569550df372..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/model_doc.mustache +++ /dev/null @@ -1,11 +0,0 @@ -{{#models}}{{#model}}# {{classname}} - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{datatype}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{datatype}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#readOnly}}[readonly] {{/readOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}} -{{/vars}} - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - -{{/model}}{{/models}} diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/podspec.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/podspec.mustache deleted file mode 100644 index 7a2b22bea28..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/podspec.mustache +++ /dev/null @@ -1,37 +0,0 @@ -# -# Be sure to run `pod lib lint {{podName}}.podspec' to ensure this is a -# valid spec and remove all comments before submitting the spec. -# -# Any lines starting with a # are optional, but encouraged -# -# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html -# - -Pod::Spec.new do |s| - s.name = "{{podName}}" - s.version = "{{podVersion}}" -{{#apiInfo}}{{#apis}}{{^hasMore}} - s.summary = "{{appName}}" - s.description = <<-DESC - {{{appDescription}}} - DESC -{{/hasMore}}{{/apis}}{{/apiInfo}} - s.platform = :ios, '7.0' - s.requires_arc = true - - {{^useCoreData}}s.framework = 'SystemConfiguration'{{/useCoreData}}{{#useCoreData}}s.frameworks = 'SystemConfiguration', 'CoreData'{{/useCoreData}} - - s.homepage = "{{gitRepoURL}}" - s.license = "{{#license}}{{license}}{{/license}}{{^license}}Apache License, Version 2.0{{/license}}" - s.source = { :git => "{{gitRepoURL}}.git", :tag => "#{s.version}" } - s.author = { "{{authorName}}" => "{{authorEmail}}" } - - s.source_files = '{{podName}}/**/*.{m,h}' - s.public_header_files = '{{podName}}/**/*.h' -{{#useCoreData}} s.resources = '{{podName}}/**/*.{xcdatamodeld,xcdatamodel}'{{/useCoreData}} - - s.dependency 'AFNetworking', '~> 3' - s.dependency 'JSONModel', '~> 1.2' - s.dependency 'ISO8601', '~> 0.6' -end - diff --git a/output/objcSessionManager/src/main/resources/objcSessionManager/xccurrentversion.mustache b/output/objcSessionManager/src/main/resources/objcSessionManager/xccurrentversion.mustache deleted file mode 100644 index 528b389e3ef..00000000000 --- a/output/objcSessionManager/src/main/resources/objcSessionManager/xccurrentversion.mustache +++ /dev/null @@ -1,8 +0,0 @@ - - - - - _XCCurrentVersionName - {{classPrefix}}Model.xcdatamodel - - diff --git a/output/objcSessionManager_notasold/README.md b/output/objcSessionManager_notasold/README.md deleted file mode 100644 index 40c3ef4fd44..00000000000 --- a/output/objcSessionManager_notasold/README.md +++ /dev/null @@ -1,74 +0,0 @@ -# Swagger Codegen for the ObjcSessionManagerClientCodegen library - -## Overview -This is a boiler-plate project to generate your own client library with Swagger. It's goal is -to get you started with the basic plumbing so you can put in your own logic. It won't work without -your changes applied. - -## What's Swagger? -The goal of Swagger™ is to define a standard, language-agnostic interface to REST APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined via Swagger, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. Similar to what interfaces have done for lower-level programming, Swagger removes the guesswork in calling the service. - - -Check out [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) for additional information about the Swagger project, including additional libraries with support for other languages and more. - -## How do I use this? -At this point, you've likely generated a client setup. It will include something along these lines: - -``` -. -|- README.md // this file -|- pom.xml // build script -|-- src -|--- main -|---- java -|----- io.swagger.codegen.languages.ObjcsessionmanagerclientcodegenGenerator.java // generator file -|---- resources -|----- ObjcSessionManagerClientCodegen // template files -|----- META-INF -|------ services -|------- io.swagger.codegen.CodegenConfig -``` - -You _will_ need to make changes in at least the following: - -`ObjcsessionmanagerclientcodegenGenerator.java` - -Templates in this folder: - -`src/main/resources/ObjcSessionManagerClientCodegen` - -Once modified, you can run this: - -``` -mvn package -``` - -In your generator project. A single jar file will be produced in `target`. You can now use that with codegen: - -``` -java -cp /path/to/swagger-codegen-distribution:/path/to/your/jar io.swagger.codegen.Codegen -l ObjcSessionManagerClientCodegen -o ./test -``` - -Now your templates are available to the client generator and you can write output values - -## But how do I modify this? -The `ObjcsessionmanagerclientcodegenGenerator.java` has comments in it--lots of comments. There is no good substitute -for reading the code more, though. See how the `ObjcsessionmanagerclientcodegenGenerator` implements `CodegenConfig`. -That class has the signature of all values that can be overridden. - -For the templates themselves, you have a number of values available to you for generation. -You can execute the `java` command from above while passing different debug flags to show -the object you have available during client generation: - -``` -# The following additional debug options are available for all codegen targets: -# -DdebugSwagger prints the OpenAPI Specification as interpreted by the codegen -# -DdebugModels prints models passed to the template engine -# -DdebugOperations prints operations passed to the template engine -# -DdebugSupportingFiles prints additional data passed to the template engine - -java -DdebugOperations -cp /path/to/swagger-codegen-distribution:/path/to/your/jar io.swagger.codegen.Codegen -l ObjcSessionManagerClientCodegen -o ./test -``` - -Will, for example, output the debug info for operations. You can use this info -in the `api.mustache` file. \ No newline at end of file diff --git a/output/objcSessionManager_notasold/pom.xml b/output/objcSessionManager_notasold/pom.xml deleted file mode 100644 index ddbd6e88190..00000000000 --- a/output/objcSessionManager_notasold/pom.xml +++ /dev/null @@ -1,102 +0,0 @@ - - 4.0.0 - io.swagger - ObjcSessionManager-swagger-codegen - jar - ObjcSessionManager-swagger-codegen - 1.0.0 - - 2.2.0 - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.12 - - - - loggerPath - conf/log4j.properties - - - -Xms512m -Xmx1500m - methods - pertest - - - - - - 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-codegen - ${swagger-codegen-version} - provided - - - - 2.2.0-SNAPSHOT - 1.0.0 - 4.8.1 - - diff --git a/output/objcSessionManager_notasold/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerClientCodegen.java b/output/objcSessionManager_notasold/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerClientCodegen.java deleted file mode 100644 index 4fd59986fb7..00000000000 --- a/output/objcSessionManager_notasold/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerClientCodegen.java +++ /dev/null @@ -1,750 +0,0 @@ -package io.swagger.codegen.languages; - -import io.swagger.codegen.*; -import io.swagger.models.ArrayModel; -import io.swagger.models.Model; -import io.swagger.models.properties.*; - -import java.io.File; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.lang3.StringUtils; - -public class ObjcSessionManagerClientCodegen extends DefaultCodegen implements CodegenConfig { - public static final String CLASS_PREFIX = "classPrefix"; - public static final String POD_NAME = "podName"; - public static final String AUTHOR_NAME = "authorName"; - public static final String AUTHOR_EMAIL = "authorEmail"; - public static final String LICENSE = "license"; - public static final String GIT_REPO_URL = "gitRepoURL"; - public static final String DEFAULT_LICENSE = "Apache License, Version 2.0"; - public static final String CORE_DATA = "coreData"; - - protected Set foundationClasses = new HashSet(); - protected String podName = "SwaggerClient"; - protected String podVersion = "1.0.0"; - protected String classPrefix = "SWG"; - protected String authorName = "Swagger"; - protected String authorEmail = "apiteam@swagger.io"; - protected String license = DEFAULT_LICENSE; - protected String gitRepoURL = "https://github.com/swagger-api/swagger-codegen"; - protected String[] specialWords = {"new", "copy"}; - protected String apiDocPath = "docs/"; - protected String modelDocPath = "docs/"; - protected String modelFilesPath = "Model/"; - protected String coreFilesPath = "Core/"; - protected String apiFilesPath = "Api/"; - - protected boolean generateCoreData = false; - - protected Set advancedMapingTypes = new HashSet(); - - public ObjcSessionManagerClientCodegen() { - super(); - - outputFolder = "generated-code" + File.separator + "objcSessionManager"; - modelTemplateFiles.put("model-header.mustache", ".h"); - modelTemplateFiles.put("model-body.mustache", ".m"); - apiTemplateFiles.put("api-header.mustache", ".h"); - apiTemplateFiles.put("api-body.mustache", ".m"); - embeddedTemplateDir = templateDir = "objcSessionManager"; - modelDocTemplateFiles.put("model_doc.mustache", ".md"); - apiDocTemplateFiles.put("api_doc.mustache", ".md"); - - defaultIncludes.clear(); - defaultIncludes.add("bool"); - defaultIncludes.add("BOOL"); - defaultIncludes.add("int"); - defaultIncludes.add("NSURL"); - defaultIncludes.add("NSString"); - defaultIncludes.add("NSObject"); - defaultIncludes.add("NSArray"); - defaultIncludes.add("NSNumber"); - defaultIncludes.add("NSDate"); - defaultIncludes.add("NSDictionary"); - defaultIncludes.add("NSMutableArray"); - defaultIncludes.add("NSMutableDictionary"); - defaultIncludes.add("NSManagedObject"); - defaultIncludes.add("NSData"); - - advancedMapingTypes.add("NSDictionary"); - advancedMapingTypes.add("NSArray"); - advancedMapingTypes.add("NSMutableArray"); - advancedMapingTypes.add("NSMutableDictionary"); - advancedMapingTypes.add("NSObject"); - advancedMapingTypes.add("NSNumber"); - advancedMapingTypes.add("NSURL"); - advancedMapingTypes.add("NSString"); - advancedMapingTypes.add("NSDate"); - - languageSpecificPrimitives.clear(); - languageSpecificPrimitives.add("NSNumber"); - languageSpecificPrimitives.add("NSString"); - languageSpecificPrimitives.add("NSObject"); - languageSpecificPrimitives.add("NSDate"); - languageSpecificPrimitives.add("NSData"); - languageSpecificPrimitives.add("NSURL"); - languageSpecificPrimitives.add("bool"); - languageSpecificPrimitives.add("BOOL"); - - typeMapping.clear(); - typeMapping.put("enum", "NSString"); - typeMapping.put("date", "NSDate"); - typeMapping.put("datetime", "NSDate"); - typeMapping.put("boolean", "NSNumber"); - typeMapping.put("string", "NSString"); - typeMapping.put("integer", "NSNumber"); - typeMapping.put("int", "NSNumber"); - typeMapping.put("float", "NSNumber"); - typeMapping.put("long", "NSNumber"); - typeMapping.put("double", "NSNumber"); - typeMapping.put("array", "NSArray"); - typeMapping.put("map", "NSDictionary"); - typeMapping.put("number", "NSNumber"); - typeMapping.put("bigdecimal", "NSNumber"); - typeMapping.put("List", "NSArray"); - typeMapping.put("object", "NSObject"); - typeMapping.put("file", "NSURL"); - typeMapping.put("binary", "NSData"); - typeMapping.put("bytearray", "NSData"); - typeMapping.put("byte", "NSData"); - typeMapping.put("uuid", "NSString"); - typeMapping.put("password", "NSString"); - - // ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm - setReservedWordsLowerCase( - Arrays.asList( - // local variable names in API methods (endpoints) - "resourcePath", "pathParams", "queryParams", "headerParams", - "responseContentType", "requestContentType", "authSettings", - "formParams", "localVarFiles", "bodyParam", - // objc reserved words - "auto", "else", "long", "switch", - "break", "enum", "register", "typedef", - "case", "extern", "return", "union", - "char", "float", "short", "unsigned", - "const", "for", "signed", "void", - "continue", "goto", "sizeof", "volatile", - "default", "if", "id", "static", "while", - "do", "int", "struct", "_Packed", - "double", "protocol", "interface", "implementation", - "NSObject", "NSInteger", "NSNumber", "CGFloat", - "property", "nonatomic", "retain", "strong", - "weak", "unsafe_unretained", "readwrite", "readonly", - "description" - )); - - importMapping = new HashMap(); - - foundationClasses = new HashSet( - Arrays.asList( - "NSNumber", - "NSObject", - "NSString", - "NSDate", - "NSData", - "NSURL", - "NSDictionary") - ); - - instantiationTypes.put("array", "NSMutableArray"); - instantiationTypes.put("map", "NSMutableDictionary"); - - cliOptions.clear(); - cliOptions.add(new CliOption(CORE_DATA, "Should generate core data models").defaultValue("false")); - cliOptions.add(new CliOption(CLASS_PREFIX, "prefix for generated classes (convention: Abbreviation of pod name e.g. `HN` for `HackerNews`).`") - .defaultValue("SWG")); - cliOptions.add(new CliOption(POD_NAME, "cocoapods package name (convention: CameCase).") - .defaultValue("SwaggerClient")); - cliOptions.add(new CliOption(CodegenConstants.POD_VERSION, "cocoapods package version.") - .defaultValue("1.0.0")); - cliOptions.add(new CliOption(AUTHOR_NAME, "Name to use in the podspec file.").defaultValue("Swagger")); - cliOptions.add(new CliOption(AUTHOR_EMAIL, "Email to use in the podspec file.").defaultValue("apiteam@swagger.io")); - cliOptions.add(new CliOption(GIT_REPO_URL, "URL for the git repo where this podspec should point to.") - .defaultValue("https://github.com/swagger-api/swagger-codegen")); - } - - @Override - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - @Override - public String getName() { - return "objc"; - } - - @Override - public String getHelp() { - return "Generates an Objective-C client library."; - } - - @Override - public void processOpts() { - super.processOpts(); - - if (additionalProperties.containsKey(POD_NAME)) { - setPodName((String) additionalProperties.get(POD_NAME)); - } - - if (additionalProperties.containsKey(CodegenConstants.POD_VERSION)) { - setPodVersion((String) additionalProperties.get(CodegenConstants.POD_VERSION)); - } - - if (additionalProperties.containsKey(CORE_DATA)) { - Object coreData = additionalProperties.get(CORE_DATA); - if(((String)coreData).equalsIgnoreCase("true")) { - generateCoreData = true; - } - } - if (additionalProperties.containsKey(CLASS_PREFIX)) { - setClassPrefix((String) additionalProperties.get(CLASS_PREFIX)); - } - - if (additionalProperties.containsKey(AUTHOR_NAME)) { - setAuthorName((String) additionalProperties.get(AUTHOR_NAME)); - } - - if (additionalProperties.containsKey(AUTHOR_EMAIL)) { - setAuthorEmail((String) additionalProperties.get(AUTHOR_EMAIL)); - } - - if (additionalProperties.containsKey(GIT_REPO_URL)) { - setGitRepoURL((String) additionalProperties.get(GIT_REPO_URL)); - } - - if(generateCoreData) { - modelTemplateFiles.put("NSManagedObject-header.mustache", "ManagedObject.h"); - modelTemplateFiles.put("NSManagedObject-body.mustache", "ManagedObject.m"); - modelTemplateFiles.put("NSManagedObjectBuilder-header.mustache", "ManagedObjectBuilder.h"); - modelTemplateFiles.put("NSManagedObjectBuilder-body.mustache", "ManagedObjectBuilder.m"); - } - - additionalProperties.put(POD_NAME, podName); - additionalProperties.put(CodegenConstants.POD_VERSION, podVersion); - additionalProperties.put(CLASS_PREFIX, classPrefix); - additionalProperties.put(AUTHOR_NAME, authorName); - additionalProperties.put(AUTHOR_EMAIL, authorEmail); - additionalProperties.put(GIT_REPO_URL, gitRepoURL); - additionalProperties.put(LICENSE, license); - - // make api and model doc path available in mustache template - additionalProperties.put("apiDocPath", apiDocPath); - additionalProperties.put("modelDocPath", modelDocPath); - additionalProperties.put("useCoreData", generateCoreData); - - modelPackage = podName; - apiPackage = podName; - - supportingFiles.add(new SupportingFile("Object-header.mustache", coreFileFolder(), classPrefix + "Object.h")); - supportingFiles.add(new SupportingFile("Object-body.mustache", coreFileFolder(), classPrefix + "Object.m")); - supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.h")); - supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.m")); - supportingFiles.add(new SupportingFile("ApiClient-header.mustache", coreFileFolder(), classPrefix + "ApiClient.h")); // !! - supportingFiles.add(new SupportingFile("ApiClient-body.mustache", coreFileFolder(), classPrefix + "ApiClient.m")); // !! - supportingFiles.add(new SupportingFile("JSONResponseSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.h")); - supportingFiles.add(new SupportingFile("JSONResponseSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.m")); - supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.m")); - supportingFiles.add(new SupportingFile("JSONRequestSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.h")); - supportingFiles.add(new SupportingFile("ResponseDeserializer-body.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.m")); // !! - supportingFiles.add(new SupportingFile("ResponseDeserializer-header.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.h")); // !! - supportingFiles.add(new SupportingFile("Sanitizer-body.mustache", coreFileFolder(), classPrefix + "Sanitizer.m")); // !! - supportingFiles.add(new SupportingFile("Sanitizer-header.mustache", coreFileFolder(), classPrefix + "Sanitizer.h")); // !! - supportingFiles.add(new SupportingFile("Logger-body.mustache", coreFileFolder(), classPrefix + "Logger.m")); // !! - supportingFiles.add(new SupportingFile("Logger-header.mustache", coreFileFolder(), classPrefix + "Logger.h")); // !! - supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-body.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.m")); - supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-header.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.h")); - supportingFiles.add(new SupportingFile("Configuration-body.mustache", coreFileFolder(), classPrefix + "Configuration.m")); // !! - supportingFiles.add(new SupportingFile("Configuration-header.mustache", coreFileFolder(), classPrefix + "Configuration.h")); // !! - supportingFiles.add(new SupportingFile("api-protocol.mustache", coreFileFolder(), classPrefix + "Api.h")); // !! - supportingFiles.add(new SupportingFile("podspec.mustache", "", podName + ".podspec")); - supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); // !! - supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); // !! - - if(generateCoreData) { - supportingFiles.add(new SupportingFile("xccurrentversion.mustache", (modelPackage() + "/" + modelFilesPath + "/").replace("/", File.separator) + classPrefix + "Model.xcdatamodeld", ".xccurrentversion")); - supportingFiles.add(new SupportingFile("Model.xcdatamodel.mustache",(modelPackage() + "/" + modelFilesPath + "/").replace("/", File.separator) + classPrefix + "Model.xcdatamodeld" + File.separator + classPrefix + "Model.xcdatamodel", "contents")); - } - - // is apiclient - //supportingFiles.add(new SupportingFile("ApiSessionManager-header.mustache", swaggerFolder, classPrefix + "ApiSessionManager.h")); - //supportingFiles.add(new SupportingFile("ApiSessionManager-body.mustache", swaggerFolder, classPrefix + "ApiSessionManager.m")); - - // protocol! - //supportingFiles.add(new SupportingFile("Configuration-protocol.mustache", swaggerFolder, classPrefix + "Configuration.h")); - //supportingFiles.add(new SupportingFile("DefaultConfiguration-body.mustache", swaggerFolder, classPrefix + "DefaultConfiguration.m")); - //supportingFiles.add(new SupportingFile("DefaultConfiguration-header.mustache", swaggerFolder, classPrefix + "DefaultConfiguration.h")); - - // missing! - //supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-header.mustache", swaggerFolder, classPrefix + "BasicAuthTokenProvider.h")); - //supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-body.mustache", swaggerFolder, classPrefix + "BasicAuthTokenProvider.m")); - } - - @Override - public String toInstantiationType(Property p) { - if (p instanceof MapProperty) { - return instantiationTypes.get("map"); - } else if (p instanceof ArrayProperty) { - return instantiationTypes.get("array"); - } else { - return null; - } - } - - @Override - public String getTypeDeclaration(String name) { - if (languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name)) { - return name; - } else { - return name + "*"; - } - } - - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if (typeMapping.containsKey(swaggerType.toLowerCase())) { - type = typeMapping.get(swaggerType.toLowerCase()); - if (languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type)) { - return toModelNameWithoutReservedWordCheck(type); - } - } else { - type = swaggerType; - } - return toModelNameWithoutReservedWordCheck(type); - } - - @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - String innerTypeDeclaration = getTypeDeclaration(inner); - if (innerTypeDeclaration.endsWith("*")) { - innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); - } - // In this condition, type of property p is array of primitive, - // return container type with pointer, e.g. `NSArray**' - if (languageSpecificPrimitives.contains(innerTypeDeclaration)) { - return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*"; - } - // In this condition, type of property p is array of model, - // return container type combine inner type with pointer, e.g. `NSArray*' - else { - for (String sd : advancedMapingTypes) { - if(innerTypeDeclaration.startsWith(sd)) { - return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*"; - } - } - return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*"; - } - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - - String innerTypeDeclaration = getTypeDeclaration(inner); - - if (innerTypeDeclaration.endsWith("*")) { - innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); - } - if (languageSpecificPrimitives.contains(innerTypeDeclaration)) { - return getSwaggerType(p) + "*"; - } else { - for (String s : advancedMapingTypes) { - if(innerTypeDeclaration.startsWith(s)) { - return getSwaggerType(p) + "*"; - } - } - return getSwaggerType(p) + "*"; - } - } else { - String swaggerType = getSwaggerType(p); - // In this condition, type of p is objective-c primitive type, e.g. `NSSNumber', - // return type of p with pointer, e.g. `NSNumber*' - if (languageSpecificPrimitives.contains(swaggerType) && - foundationClasses.contains(swaggerType)) { - return swaggerType + "*"; - } - // In this condition, type of p is c primitive type, e.g. `bool', - // return type of p, e.g. `bool' - else if (languageSpecificPrimitives.contains(swaggerType)) { - return swaggerType; - } - // In this condition, type of p is objective-c object type, e.g. `SWGPet', - // return type of p with pointer, e.g. `SWGPet*' - else { - return swaggerType + "*"; - } - } - } - - @Override - public boolean isDataTypeBinary(String dataType) { - return dataType.toLowerCase().startsWith("nsdata"); - } - - @Override - public String toModelName(String type) { - // model name cannot use reserved keyword - if (reservedWords.contains(type)) { - LOGGER.warn(type+ " (reserved word) cannot be used as model name. Renamed to " + ("model_" + type) + " before further processing"); - type = "model_" + type; // e.g. return => ModelReturn (after camelize) - } - - // model name starts with number - /* no need for the fix below as objc model starts with prefix (e.g. SWG) - if (type.matches("^\\d.*")) { - LOGGER.warn(type + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + type)); - type = "model_" + type; // e.g. 200Response => Model200Response (after camelize) - } - */ - - return toModelNameWithoutReservedWordCheck(type); - } - - /* - * Convert input to proper model name according to ObjC style guide - * without checking for reserved words - * - * @param type Model anme - * @return model Name in ObjC style guide - */ - public String toModelNameWithoutReservedWordCheck(String type) { - type = type.replaceAll("[^0-9a-zA-Z_]", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - - // language build-in classes - if (typeMapping.keySet().contains(type) || - foundationClasses.contains(type) || - importMapping.values().contains(type) || - defaultIncludes.contains(type) || - languageSpecificPrimitives.contains(type)) { - return camelize(type); - } - // custom classes - else { - if (!StringUtils.isEmpty(modelNameSuffix)) { // set model suffix - type = type + "_" + modelNameSuffix; - } - - if (!StringUtils.isEmpty(modelNamePrefix)) { // set model prefix - type = modelNamePrefix + "_" + type; - } - - return classPrefix + camelize(type); // add class prefix - } - } - - @Override - public String toModelFilename(String name) { - // should be the same as the model name - return toModelName(name); - } - - @Override - protected void setNonArrayMapProperty(CodegenProperty property, String type) { - super.setNonArrayMapProperty(property, type); - if ("NSDictionary".equals(type)) { - property.setter = "initWithDictionary"; - } else { - property.setter = "initWithValues"; - } - } - - @Override - public String toModelImport(String name) { - return name; - } - - @Override - public String apiDocFileFolder() { - return (outputFolder + "/" + apiDocPath).replace("/", File.separator); - } - - @Override - public String modelDocFileFolder() { - return (outputFolder + "/" + modelDocPath).replace("/", File.separator); - } - - @Override - public String toModelDocFilename(String name) { - return toModelName(name); - } - - @Override - public String toApiDocFilename(String name) { - return toApiName(name); - } - - @Override - public String apiFileFolder() { - return (outputFolder + "/"+ apiPackage() + "/" + apiFilesPath).replace("/", File.separator); - } - - @Override - public String modelFileFolder() { - return (outputFolder + "/"+ modelPackage() + "/" + modelFilesPath).replace("/", File.separator); - } - - public String coreFileFolder() { - return (apiPackage() + "/" + coreFilesPath).replace("/", File.separator); - } - - @Override - public String toApiName(String name) { - return classPrefix + camelize(name) + "Api"; - } - - @Override - public String toApiFilename(String name) { - return classPrefix + camelize(name) + "Api"; - } - - @Override - public String toVarName(String name) { - // sanitize name - name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - - // if it's all upper case, do noting - if (name.matches("^[A-Z_]$")) { - return name; - } - - // if name starting with special word, escape with '_' - for(int i =0; i < specialWords.length; i++) { - if (name.matches("(?i:^" + specialWords[i] + ".*)")) - name = escapeSpecialWord(name); - } - - // camelize (lower first character) the variable name - // e.g. `pet_id` to `petId` - name = camelize(name, true); - - // for reserved word or word starting with number, prepend `_` - if (isReservedWord(name) || name.matches("^\\d.*")) { - name = escapeReservedWord(name); - } - - - return name; - } - - @Override - public String toParamName(String name) { - // should be the same as variable name - return toVarName(name); - } - - @Override - public String escapeReservedWord(String name) { - return "_" + name; - } - - @SuppressWarnings("static-method") - public String escapeSpecialWord(String name) { - return "var_" + name; - } - - @Override - public String toOperationId(String operationId) { - // throw exception if method name is empty - if (StringUtils.isEmpty(operationId)) { - throw new RuntimeException("Empty method name (operationId) not allowed"); - } - - // method name cannot use reserved keyword, e.g. return - if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId), true)); - operationId = "call_" + operationId; - } - - return camelize(sanitizeName(operationId), true); - } - - public void setClassPrefix(String classPrefix) { - this.classPrefix = classPrefix; - } - - public void setPodName(String podName) { - this.podName = podName; - } - - public void setPodVersion(String podVersion) { - this.podVersion = podVersion; - } - - public void setAuthorEmail(String authorEmail) { - this.authorEmail = authorEmail; - } - - public void setAuthorName(String authorName) { - this.authorName = authorName; - } - - public void setGitRepoURL(String gitRepoURL) { - this.gitRepoURL = gitRepoURL; - } - - public void setLicense(String license) { - this.license = license; - } - - @Override - public Map postProcessOperations(Map objs) { - Map operations = (Map) objs.get("operations"); - if (operations != null) { - List ops = (List) operations.get("operation"); - for (CodegenOperation operation : ops) { - if (!operation.allParams.isEmpty()) { - String firstParamName = operation.allParams.get(0).paramName; - operation.vendorExtensions.put("firstParamAltName", camelize(firstParamName)); - } - } - } - return objs; - } - - @Override - public void postProcessModelProperty(CodegenModel model, CodegenProperty property){ - super.postProcessModelProperty(model,property); - property.vendorExtensions.put("x-uppercaseName", camelize(property.name)); - } - - /** - * 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; - } - - @Override - public void setParameterExampleValue(CodegenParameter p) { - String example; - - if (p.defaultValue == null) { - example = p.example; - } else { - example = p.defaultValue; - } - - String type = p.baseType; - if (type == null) { - type = p.dataType; - } - - if ("NSString*".equalsIgnoreCase(type)) { - if (example == null) { - example = p.paramName + "_example"; - } - example = "@\"" + escapeText(example) + "\""; - } else if ("NSNumber*".equals(type)) { - if (example == null) { - example = "56"; - } - example = "@" + example; - /* OBJC uses NSNumber to represent both int, long, double and float - } else if ("Float".equalsIgnoreCase(type) || "Double".equalsIgnoreCase(type)) { - if (example == null) { - example = "3.4"; - } */ - } else if ("BOOLEAN".equalsIgnoreCase(type) || "bool".equalsIgnoreCase(type)) { - if (example == null) { - example = "True"; - } - } else if ("NSURL*".equalsIgnoreCase(type)) { - if (example == null) { - example = "/path/to/file"; - } - //[NSURL fileURLWithPath:@"path/to/file"] - example = "[NSURL fileURLWithPath:@\"" + escapeText(example) + "\"]"; - /*} else if ("NSDate".equalsIgnoreCase(type)) { - if (example == null) { - example = "2013-10-20"; - } - example = "'" + escapeText(example) + "'";*/ - } else if ("NSDate*".equalsIgnoreCase(type)) { - if (example == null) { - example = "2013-10-20T19:20:30+01:00"; - } - example = "@\"" + escapeText(example) + "\""; - } else if (!languageSpecificPrimitives.contains(type)) { - // type is a model class, e.g. User - type = type.replace("*", ""); - // e.g. [[SWGPet alloc] init - example = "[[" + type + " alloc] init]"; - } else { - LOGGER.warn("Type " + type + " not handled properly in setParameterExampleValue"); - } - - if (example == null) { - example = "NULL"; - } else if (Boolean.TRUE.equals(p.isListContainer)) { - example = "@[" + example + "]"; - } else if (Boolean.TRUE.equals(p.isMapContainer)) { - example = "@{@\"key\" : " + example + "}"; - } - - p.example = example; - } - - @Override - public String escapeQuotationMark(String input) { - // remove " to avoid code injection - return input.replace("\"", ""); - } - - @Override - public String escapeUnsafeCharacters(String input) { - return input.replace("*/", "*_/").replace("/*", "/_*"); - } - -} diff --git a/output/objcSessionManager_notasold/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/output/objcSessionManager_notasold/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig deleted file mode 100644 index e3cfa53811b..00000000000 --- a/output/objcSessionManager_notasold/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig +++ /dev/null @@ -1 +0,0 @@ -io.swagger.codegen.languages.ObjcSessionManagerClientCodegen \ No newline at end of file diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache deleted file mode 100644 index 5e5ad41e2df..00000000000 --- a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache +++ /dev/null @@ -1,461 +0,0 @@ -#import - -#import "{{classPrefix}}ApiSessionManager.h" -#import "{{classPrefix}}JSONRequestSerializer.h" -#import "{{classPrefix}}JSONResponseSerializer.h" -#import "{{classPrefix}}QueryParamCollection.h" -#import "{{classPrefix}}Object.h" -#import "{{classPrefix}}DefaultConfiguration.h" - - -NSString * const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}ResponseObject"; - - -static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) { - NSDictionary * headers = {{classPrefix}}__headerFieldsForResponse(response); - if(!headers[@"Content-Disposition"]) { - return [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]]; - } - NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?"; - NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern - options:NSRegularExpressionCaseInsensitive - error:nil]; - NSString *contentDispositionHeader = headers[@"Content-Disposition"]; - NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader - options:0 - range:NSMakeRange(0, [contentDispositionHeader length])]; - return [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]]; -} - - -@interface {{classPrefix}}ApiSessionManager () - -@property (nonatomic, strong, readwrite) id<{{classPrefix}}Configuration> configuration; - -@end - -@implementation {{classPrefix}}ApiSessionManager - -- (instancetype)init { - - return [self initWithConfiguration:[{{classPrefix}}DefaultConfiguration sharedConfiguration]]; -} - -- (instancetype)initWithBaseURL:(NSURL *)url { - - return [self initWithBaseURL:url - configuration:[{{classPrefix}}DefaultConfiguration sharedConfiguration]]; - -} - -- (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration { - - return [self initWithBaseURL:[NSURL URLWithString:configuration.host] configuration:configuration]; -} - -- (instancetype)initWithBaseURL:(NSURL *)url - configuration:(id<{{classPrefix}}Configuration>)configuration { - - self = [super initWithBaseURL:url]; - if (self) { - _configuration = configuration; - } - - return self; -} - -#pragma mark - Setter Methods - -+ (void) setOfflineState:(BOOL) state { - offlineState = state; -} - -+ (void) setCacheEnabled:(BOOL)enabled { - cacheEnabled = enabled; -} - -+(void) setReachabilityStatus:(AFNetworkReachabilityStatus)status { - reachabilityStatus = status; -} - -- (void)setHeaderValue:(NSString*) value forKey:(NSString*) forKey { - [self.requestSerializer setValue:value forHTTPHeaderField:forKey]; -} - -- (void)setRequestSerializer:(AFHTTPRequestSerializer *)requestSerializer { - [super setRequestSerializer:requestSerializer]; - requestSerializer.timeoutInterval = self.timeoutInterval; -} - -#pragma mark - Cache Methods - -+(void)clearCache { - [[NSURLCache sharedURLCache] removeAllCachedResponses]; -} - -+(void)configureCacheWithMemoryAndDiskCapacity: (unsigned long) memorySize - diskSize: (unsigned long) diskSize { - NSAssert(memorySize > 0, @"invalid in-memory cache size"); - NSAssert(diskSize >= 0, @"invalid disk cache size"); - - NSURLCache *cache = - [[NSURLCache alloc] - initWithMemoryCapacity:memorySize - diskCapacity:diskSize - diskPath:@"swagger_url_cache"]; - - [NSURLCache setSharedURLCache:cache]; -} - -#pragma mark - Reachability Methods - -+(AFNetworkReachabilityStatus) getReachabilityStatus { - return reachabilityStatus; -} - -+(BOOL) getOfflineState { - return offlineState; -} - -+(void) setReachabilityChangeBlock:(void(^)(int))changeBlock { - reachabilityChangeBlock = changeBlock; -} - -- (void) configureCacheReachibility { - [self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { - reachabilityStatus = status; - {{classPrefix}}DebugLog(@"reachability changed to %@",AFStringFromNetworkReachabilityStatus(status)); - [{{classPrefix}}ApiClient setOfflineState:status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable]; - - // call the reachability block, if configured - if (reachabilityChangeBlock != nil) { - reachabilityChangeBlock(status); - } - }]; - - [self.reachabilityManager startMonitoring]; -} - -#pragma mark - Task Methods - -- (NSURLSessionDataTask*) taskWithCompletionBlock: (NSURLRequest *)request - completionBlock: (void (^)(id, NSError *))completionBlock { - - NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { - {{classPrefix}}DebugLogResponse(response, responseObject,request,error); - - if(!error) { - completionBlock(responseObject, nil); - return; - } - - NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; - if (responseObject) { - // Add in the (parsed) response body. - userInfo[{{classPrefix}}ResponseObjectErrorKey] = responseObject; - } - NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; - completionBlock(nil, augmentedError); - }]; - - return task; -} - -- (NSURLSessionDownloadTask*) downloadTaskWithCompletionBlock: (NSURLRequest *)request - completionBlock: (void (^)(id, NSError *))completionBlock { - - id<{{classPrefix}}Configuration> config = self.configuration; - - NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { - {{classPrefix}}DebugLogResponse(response, responseObject,request,error); - - if(error) { - NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; - if (responseObject) { - userInfo[{{classPrefix}}ResponseObjectErrorKey] = responseObject; - } - NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; - completionBlock(nil, augmentedError); - } - - NSString *directory = config.tempFolderPath ?: NSTemporaryDirectory(); - NSString *filename = {{classPrefix}}__fileNameForResponse(response); - - NSString *filepath = [directory stringByAppendingPathComponent:filename]; - NSURL *file = [NSURL fileURLWithPath:filepath]; - - [responseObject writeToURL:file atomically:YES]; - - completionBlock(file, nil); - }]; - - return task; -} - -#pragma mark - Perform Request Methods - -- (NSURLSessionTask*) requestWithPath: (NSString*) path - method: (NSString*) method - pathParams: (NSDictionary *) pathParams - queryParams: (NSDictionary*) queryParams - formParams: (NSDictionary *) formParams - files: (NSDictionary *) files - body: (id) body - headerParams: (NSDictionary*) headerParams - authSettings: (NSArray *) authSettings - requestContentType: (NSString*) requestContentType - responseContentType: (NSString*) responseContentType - responseType: (NSString *) responseType - completionBlock: (void (^)(id, NSError *))completionBlock { - - // setting request serializer - if ([requestContentType isEqualToString:@"application/json"]) { - self.requestSerializer = [{{classPrefix}}JSONRequestSerializer serializer]; - } - else if ([requestContentType isEqualToString:@"application/x-www-form-urlencoded"]) { - self.requestSerializer = [AFHTTPRequestSerializer serializer]; - } - else if ([requestContentType isEqualToString:@"multipart/form-data"]) { - self.requestSerializer = [AFHTTPRequestSerializer serializer]; - } - else { - self.requestSerializer = [AFHTTPRequestSerializer serializer]; - NSAssert(NO, @"Unsupported request type %@", requestContentType); - } - - // setting response serializer - if ([responseContentType isEqualToString:@"application/json"]) { - self.responseSerializer = [{{classPrefix}}JSONResponseSerializer serializer]; - } else { - self.responseSerializer = [AFHTTPResponseSerializer serializer]; - } - - // sanitize parameters - pathParams = [self.sanitizer sanitizeForSerialization:pathParams]; - queryParams = [self.sanitizer sanitizeForSerialization:queryParams]; - headerParams = [self.sanitizer sanitizeForSerialization:headerParams]; - formParams = [self.sanitizer sanitizeForSerialization:formParams]; - if(![body isKindOfClass:[NSData class]]) { - body = [self.sanitizer sanitizeForSerialization:body]; - } - - // auth setting - [self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings]; - - NSMutableString *resourcePath = [NSMutableString stringWithString:path]; - [pathParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - NSString * safeString = ([obj isKindOfClass:[NSString class]]) ? obj : [NSString stringWithFormat:@"%@", obj]; - safeString = {{classPrefix}}PercentEscapedStringFromString(safeString); - [resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"{%@}", key]] withString:safeString]; - }]; - - NSMutableURLRequest * request = nil; - - NSString* pathWithQueryParams = [self pathWithQueryParamsToString:resourcePath queryParams:queryParams]; - if ([pathWithQueryParams hasPrefix:@"/"]) { - pathWithQueryParams = [pathWithQueryParams substringFromIndex:1]; - } - - NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString]; - if (files.count > 0) { - __weak __typeof(self)weakSelf = self; - request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" - URLString:urlString - parameters:nil - constructingBodyWithBlock:^(id formData) { - [formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - NSString *objString = [weakSelf.sanitizer parameterToString:obj]; - NSData *data = [objString dataUsingEncoding:NSUTF8StringEncoding]; - [formData appendPartWithFormData:data name:key]; - }]; - [files enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - NSURL *filePath = (NSURL *)obj; - [formData appendPartWithFileURL:filePath name:key error:nil]; - }]; - } error:nil]; - } - else { - if (formParams) { - request = [self.requestSerializer requestWithMethod:method - URLString:urlString - parameters:formParams - error:nil]; - } - if (body) { - request = [self.requestSerializer requestWithMethod:method - URLString:urlString - parameters:body - error:nil]; - } - } - - // request cache - BOOL hasHeaderParams = [headerParams count] > 0; - if (offlineState) { - {{classPrefix}}DebugLog(@"%@ cache forced", resourcePath); - [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; - } - else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { - {{classPrefix}}DebugLog(@"%@ cache enabled", resourcePath); - [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; - } - else { - {{classPrefix}}DebugLog(@"%@ cache disabled", resourcePath); - [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; - } - - if (hasHeaderParams){ - for(NSString * key in [headerParams keyEnumerator]){ - [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; - } - } - [self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"]; - - [self postProcessRequest:request]; - - - NSURLSessionTask *task = nil - - if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) { - task = [self downloadTaskWithCompletionBlock:request completionBlock:^(id data, NSError *error) { - completionBlock(data, error); - }]; - } - else { - [self taskWithCompletionBlock:request completionBlock:^(id data, NSError *error) { - NSError * serializationError; - id response = [self.responseDeserializer deserialize:data class:responseType error:&serializationError]; - if(!response && !error){ - error = serializationError; - } - completionBlock(response, error); - }]; - } - - [task resume]; - - return task; -} - -// Added for easier override to modify request -- (void)postProcessRequest:(NSMutableURLRequest *)request { - // Always disable cookies! - [request setHTTPShouldHandleCookies:NO]; -} - -#pragma mark - - -- (NSString*)pathWithQueryParamsToString:(NSString*) path - queryParams:(NSDictionary*) queryParams { - if(queryParams.count == 0) { - return path; - } - NSString * separator = nil; - NSUInteger counter = 0; - - NSMutableString * requestUrl = [NSMutableString stringWithFormat:@"%@", path]; - - NSDictionary *separatorStyles = @{@"csv" : @",", - @"tsv" : @"\t", - @"pipes": @"|" - }; - for(NSString * key in [queryParams keyEnumerator]){ - if (counter == 0) { - separator = @"?"; - } else { - separator = @"&"; - } - id queryParam = [queryParams valueForKey:key]; - if(!queryParam) { - continue; - } - NSString *safeKey = {{classPrefix}}PercentEscapedStringFromString(key); - if ([queryParam isKindOfClass:[NSString class]]){ - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, {{classPrefix}}PercentEscapedStringFromString(queryParam)]]; - - } else if ([queryParam isKindOfClass:[{{classPrefix}}QueryParamCollection class]]){ - {{classPrefix}}QueryParamCollection * coll = ({{classPrefix}}QueryParamCollection*) queryParam; - NSArray* values = [coll values]; - NSString* format = [coll format]; - - if([format isEqualToString:@"multi"]) { - for(id obj in values) { - if (counter > 0) { - separator = @"&"; - } - NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([NSString stringWithFormat:@"%@",obj]); - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; - counter += 1; - } - continue; - } - NSString * separatorStyle = separatorStyles[format]; - NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([values componentsJoinedByString:separatorStyle]); - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; - } else { - NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([NSString stringWithFormat:@"%@",queryParam]); - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; - } - counter += 1; - } - return requestUrl; -} - -/** - * Update header and query params based on authentication settings - */ -- (void) updateHeaderParams:(NSDictionary *__autoreleasing *)headers - queryParams:(NSDictionary *__autoreleasing *)querys - WithAuthSettings:(NSArray *)authSettings { - - if (!authSettings || [authSettings count] == 0) { - return; - } - - NSMutableDictionary *headersWithAuth = [NSMutableDictionary dictionaryWithDictionary:*headers]; - NSMutableDictionary *querysWithAuth = [NSMutableDictionary dictionaryWithDictionary:*querys]; - - id<{{classPrefix}}Configuration> config = self.configuration; - for (NSString *auth in authSettings) { - NSDictionary *authSetting = config.authSettings[auth]; - - if(!authSetting) { // auth setting is set only if the key is non-empty - continue; - } - - NSString *type = authSetting[@"in"]; - NSString *key = authSetting[@"key"]; - NSString *value = authSetting[@"value"]; - if ([type isEqualToString:@"header"] && [key length] > 0 ) { - headersWithAuth[key] = value; - } else if ([type isEqualToString:@"query"] && [key length] != 0) { - querysWithAuth[key] = value; - } - } - - *headers = [NSDictionary dictionaryWithDictionary:headersWithAuth]; - *querys = [NSDictionary dictionaryWithDictionary:querysWithAuth]; -} - -- (AFSecurityPolicy *) customSecurityPolicy { - AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; - - id<{{classPrefix}}Configuration> config = self.configuration; - - if (config.sslCaCert) { - NSData *certData = [NSData dataWithContentsOfFile:config.sslCaCert]; - [securityPolicy setPinnedCertificates:@[certData]]; - } - - if (config.verifySSL) { - [securityPolicy setAllowInvalidCertificates:NO]; - } - else { - [securityPolicy setAllowInvalidCertificates:YES]; - [securityPolicy setValidatesDomainName:NO]; - } - - return securityPolicy; -} - -@end diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/ApiSessionManager-header.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/ApiSessionManager-header.mustache deleted file mode 100644 index 010966b14a5..00000000000 --- a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/ApiSessionManager-header.mustache +++ /dev/null @@ -1,147 +0,0 @@ -/** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ - -#import -#import "{{classPrefix}}Configuration.h" - -/** - * A key for `NSError` user info dictionaries. - * - * The corresponding value is the parsed response body for an HTTP error. - */ -extern NSString *const {{classPrefix}}ResponseObjectErrorKey; - - -@interface {{classPrefix}}ApiSessionManager : AFHTTPSessionManager - -@property (nonatomic, strong, readonly) id<{{classPrefix}}Configuration> configuration; - -@property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy; -@property(nonatomic, assign) NSTimeInterval timeoutInterval; -@property(nonatomic, readonly) NSOperationQueue* queue; - -@property(nonatomic, strong) id<{{classPrefix}}ResponseDeserializer> responseDeserializer; - -@property(nonatomic, strong) id<{{classPrefix}}Sanitizer> sanitizer; - -/** - * Clears Cache - */ -+(void)clearCache; - -/** - * Turns on cache - * - * @param enabled If the cached is enable, must be `YES` or `NO` - */ -+(void)setCacheEnabled:(BOOL) enabled; - -/** - * Sets the client unreachable - * - * @param state off line state, must be `YES` or `NO` - */ -+(void) setOfflineState:(BOOL) state; - -/** - * Gets if the client is unreachable - * - * @return The client offline state - */ -+(BOOL) getOfflineState; - -/** - * Sets the client reachability, this may be overridden by the reachability manager if reachability changes - * - * @param The client reachability. - */ -+(void) setReachabilityStatus:(AFNetworkReachabilityStatus) status; - -/** - * Gets the client reachability - * - * @return The client reachability. - */ -+(AFNetworkReachabilityStatus) getReachabilityStatus; - -/** - * Customizes the behavior when the reachability changed - * - * @param changeBlock The block will be executed when the reachability changed. - */ -+(void) setReachabilityChangeBlock:(void(^)(int))changeBlock; - -/** - * Sets the api client reachability strategy - */ -- (void)configureCacheReachibility; - -/** - * Sets header for request - * - * @param value The header value - * @param forKey The header key - */ --(void)setHeaderValue:(NSString*) value - forKey:(NSString*) forKey; - -/** - * Updates header parameters and query parameters for authentication - * - * @param headers The header parameter will be udpated, passed by pointer to pointer. - * @param querys The query parameters will be updated, passed by pointer to pointer. - * @param authSettings The authentication names NSArray. - */ -- (void) updateHeaderParams:(NSDictionary **)headers - queryParams:(NSDictionary **)querys - WithAuthSettings:(NSArray *)authSettings; - - -/** - * Initializes the session manager with a configuration. - * - * @param configuration The configuration implementation - */ -- (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration; - -/** - * Performs request - * - * @param path Request url. - * @param method Request method. - * @param pathParams Request path parameters. - * @param queryParams Request query parameters. - * @param body Request body. - * @param headerParams Request header parameters. - * @param authSettings Request authentication names. - * @param requestContentType Request content-type. - * @param responseContentType Response content-type. - * @param completionBlock The block will be executed when the request completed. - * - * @return The created session task. - */ -- (NSURLSessionTask *)requestWithCompletionBlock:(NSString*)path - method:(NSString*) method - pathParams:(NSDictionary *)pathParams - queryParams:(NSDictionary*)queryParams - formParams:(NSDictionary *)formParams - files:(NSDictionary *)files - body:(id)body - headerParams:(NSDictionary *)headerParams - authSettings: (NSArray *)authSettings - requestContentType:(NSString *)requestContentType - responseContentType:(NSString *)responseContentType - responseType:(NSString *)responseType - completionBlock:(void (^)(id, NSError *))completionBlock; - -/** - * Custom security policy - * - * @return AFSecurityPolicy - */ -- (AFSecurityPolicy *) customSecurityPolicy; - -@end diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/BasicAuthTokenProvider-body.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/BasicAuthTokenProvider-body.mustache deleted file mode 100644 index e2ba00badb7..00000000000 --- a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/BasicAuthTokenProvider-body.mustache +++ /dev/null @@ -1,14 +0,0 @@ -#import "{{classPrefix}}BasicAuthTokenProvider.h" - -@implementation {{classPrefix}}BasicAuthTokenProvider - -+ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password { - - NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password]; - NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; - basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; - - return basicAuthCredentials; -} - -@end diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/BasicAuthTokenProvider-header.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/BasicAuthTokenProvider-header.mustache deleted file mode 100644 index dfb287568a0..00000000000 --- a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/BasicAuthTokenProvider-header.mustache +++ /dev/null @@ -1,14 +0,0 @@ -/** The `{{classPrefix}}BasicAuthTokenProvider` class creates a basic auth token from username and password. - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ - -#import - -@interface {{classPrefix}}BasicAuthTokenProvider : NSObject - -+ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password; - -@end \ No newline at end of file diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/Configuration-protocol.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/Configuration-protocol.mustache deleted file mode 100644 index db429a38150..00000000000 --- a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/Configuration-protocol.mustache +++ /dev/null @@ -1,75 +0,0 @@ -#import -#import "{{classPrefix}}Logger.h" - -{{>licenceInfo}} - -@protocol {{classPrefix}}Configuration - -/** - * Api logger - */ -@property (readonly, nonatomic) {{classPrefix}}Logger *logger; - -/** - * Base url - */ -@property (readonly, nonatomic) NSString *host; - -/** - * Api key values for Api Key type Authentication - */ -@property (readonly, nonatomic) NSDictionary *apiKey; - -/** - * Api key prefix values to be prepend to the respective api key - */ -@property (readonly, nonatomic) NSDictionary *apiKeyPrefix; - -/** - * Username for HTTP Basic Authentication - */ -@property (readonly, nonatomic) NSString *username; - -/** - * Password for HTTP Basic Authentication - */ -@property (readonly, nonatomic) NSString *password; - -/** - * Access token for OAuth - */ -@property (readonly, nonatomic) NSString *accessToken; - -/** - * Temp folder for file download - */ -@property (readonly, nonatomic) NSString *tempFolderPath; - -/** - * Debug switch, default false - */ -@property (readonly, nonatomic) BOOL debug; - -/** - * SSL/TLS verification - * Set this to NO to skip verifying SSL certificate when calling API from https server - */ -@property (readonly, nonatomic) BOOL verifySSL; - -/** - * SSL/TLS verification - * Set this to customize the certificate file to verify the peer - */ -@property (readonly, nonatomic) NSString *sslCaCert; - -/** - * Authentication Settings - */ -@property (readonly, nonatomic) NSDictionary *authSettings; - -/** -* Default headers for all services -*/ -@property (readonly, nonatomic, strong) NSDictionary *defaultHeaders; - -@end \ No newline at end of file diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/DefaultConfiguration-body.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/DefaultConfiguration-body.mustache deleted file mode 100644 index a45eba7ba55..00000000000 --- a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/DefaultConfiguration-body.mustache +++ /dev/null @@ -1,157 +0,0 @@ -#import "{{classPrefix}}DefaultConfiguration.h" - -@implementation {{classPrefix}}DefaultConfiguration - -#pragma mark - Singleton Methods - -+ (instancetype)sharedConfiguration { - - static {{classPrefix}}DefaultConfiguration *shardConfig = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - shardConfig = [[self alloc] init]; - }); - return shardConfig; -} - -#pragma mark - Initialize Methods - -- (instancetype)init { - self = [super init]; - if (self) { - _host = @"{{basePath}}"; - _username = @""; - _password = @""; - _accessToken= @""; - _verifySSL = YES; - _mutableApiKey = [NSMutableDictionary dictionary]; - _mutableApiKeyPrefix = [NSMutableDictionary dictionary]; - _mutableDefaultHeaders = [NSMutableDictionary dictionary]; - _mutableDefaultHeaders[@"User-Agent"] = {{#httpUserAgent}}@"{{httpUserAgent}}"{{/httpUserAgent}}{{^httpUserAgent}}[NSString stringWithFormat:@"Swagger-Codegen/{{version}}/objc (%@; iOS %@; Scale/%0.2f)",[[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]]{{/httpUserAgent}}; - _logger = [{{classPrefix}}Logger sharedLogger]; - } - return self; -} - -#pragma mark - Instance Methods - -- (NSString *) getApiKeyWithPrefix:(NSString *)key { - NSString *prefix = self.apiKeyPrefix[key]; - NSString *apiKey = self.apiKey[key]; - if (prefix && apiKey != (id)[NSNull null] && apiKey.length > 0) { // both api key prefix and api key are set - return [NSString stringWithFormat:@"%@ %@", prefix, apiKey]; - } - else if (apiKey != (id)[NSNull null] && apiKey.length > 0) { // only api key, no api key prefix - return [NSString stringWithFormat:@"%@", self.apiKey[key]]; - } - else { // return empty string if nothing is set - return @""; - } -} - -- (NSString *) getBasicAuthToken { - // return empty string if username and password are empty - if (self.username.length == 0 && self.password.length == 0){ - return @""; - } - - NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.username, self.password]; - NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; - basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; - - return basicAuthCredentials; -} - -- (NSString *) getAccessToken { - if (self.accessToken.length == 0) { // token not set, return empty string - return @""; - } else { - return [NSString stringWithFormat:@"Bearer %@", self.accessToken]; - } -} - -#pragma mark - Setter Methods - -- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString *)identifier { - [self.mutableApiKey setValue:apiKey forKey:identifier]; -} - -- (void) removeApiKey:(NSString *)identifier { - [self.mutableApiKey removeObjectForKey:identifier]; -} - -- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier { - [self.mutableApiKeyPrefix setValue:prefix forKey:identifier]; -} - -- (void) removeApiKeyPrefix:(NSString *)identifier { - [self.mutableApiKeyPrefix removeObjectForKey:identifier]; -} - -#pragma mark - - -- (NSDictionary *) authSettings { - return @{ -{{#authMethods}} -{{#isApiKey}} - @"{{name}}": - @{ - @"type": @"api_key", - @"in": {{#isKeyInHeader}}@"header"{{/isKeyInHeader}}{{#isKeyInQuery}}@"query"{{/isKeyInQuery}}, - @"key": @"{{keyParamName}}", - @"value": [self getApiKeyWithPrefix:@"{{keyParamName}}"] - }, -{{/isApiKey}} -{{#isBasic}} - @"{{name}}": - @{ - @"type": @"basic", - @"in": @"header", - @"key": @"Authorization", - @"value": [self getBasicAuthToken] - }, -{{/isBasic}} -{{#isOAuth}} - @"{{name}}": - @{ - @"type": @"oauth", - @"in": @"header", - @"key": @"Authorization", - @"value": [self getAccessToken] - }, -{{/isOAuth}} -{{/authMethods}} - }; -} - --(BOOL)debug { - return self.logger.isEnabled; -} - --(void)setDebug:(BOOL)debug { - self.logger.enabled = debug; -} - - - -- (void)setDefaultHeaderValue:(NSString *)value forKey:(NSString *)key { - if(!value) { - [self.mutableDefaultHeaders removeObjectForKey:key]; - return; - } - self.mutableDefaultHeaders[key] = value; -} - --(void) removeDefaultHeaderForKey:(NSString*)key { - [self.mutableDefaultHeaders removeObjectForKey:key]; -} - -- (NSString *)defaultHeaderForKey:(NSString *)key { - return self.mutableDefaultHeaders[key]; -} - -- (NSDictionary *)defaultHeaders { - return [self.mutableDefaultHeaders copy]; -} - -@end diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/DefaultConfiguration-header.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/DefaultConfiguration-header.mustache deleted file mode 100644 index 46f3b32fc93..00000000000 --- a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/DefaultConfiguration-header.mustache +++ /dev/null @@ -1,134 +0,0 @@ -#import -#import "{{classPrefix}}Configuration.h" - -{{>licenceInfo}} - -@interface {{classPrefix}}DefaultConfiguration : NSObject <{{classPrefix}}Configuration> - -+ ({{classPrefix}}DefaultConfiguration *)sharedConfiguration; - -/** - * Default api logger - */ -@property (nonatomic, strong) {{classPrefix}}Logger * logger; - -/** - * Default api client - */ -@property (nonatomic) {{classPrefix}}ApiClient *apiClient; - -/** - * Default base url - */ -@property (nonatomic) NSString *host; - -/** - * Api key values for Api Key type Authentication - * - * To add or remove api key, use `setApiKey:forApiKeyIdentifier:`. - */ -@property (readonly, nonatomic, strong) NSDictionary *apiKey; - -/** - * Api key prefix values to be prepend to the respective api key - * - * To add or remove prefix, use `setApiKeyPrefix:forApiKeyPrefixIdentifier:`. - */ -@property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix; - -/** - * Username for HTTP Basic Authentication - */ - @property (nonatomic) NSString *username; - -/** - * Password for HTTP Basic Authentication - */ -@property (nonatomic) NSString *password; - -/** - * Access token for OAuth - */ -@property (nonatomic) NSString *accessToken; - -/** - * Temp folder for file download - */ -@property (nonatomic) NSString *tempFolderPath; - -/** - * Debug switch, default false - */ -@property (nonatomic) BOOL debug; - -/** - * SSL/TLS verification - * Set this to NO to skip verifying SSL certificate when calling API from https server - */ -@property (nonatomic) BOOL verifySSL; - -/** - * SSL/TLS verification - * Set this to customize the certificate file to verify the peer - */ -@property (nonatomic) NSString *sslCaCert; - -/** - * Sets API key - * - * To remove a apiKey for an identifier, just set the apiKey to nil. - * - * @param apiKey API key or token. - * @param identifier API key identifier (authentication schema). - * - */ -- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString*)identifier; - -/** - * Removes api key - * - * @param identifier API key identifier. - */ -- (void) removeApiKey:(NSString *)identifier; - -/** - * Sets the prefix for API key - * - * @param apiKeyPrefix API key prefix. - * @param identifier API key identifier. - */ -- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier; - -/** - * Removes api key prefix - * - * @param identifier API key identifier. - */ -- (void) removeApiKeyPrefix:(NSString *)identifier; - -/** -* Default headers for all services -*/ -@property (readonly, nonatomic, strong) NSDictionary *defaultHeaders; - -/** -* Removes header from defaultHeaders -* -* @param Header name. -*/ --(void) removeDefaultHeaderForKey:(NSString*)key; - -/** -* Sets the header for key -* -* @param value Value for header name -* @param key Header name -*/ --(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key; - -/** -* @param Header key name. -*/ --(NSString*) defaultHeaderForKey:(NSString*)key; - -@end \ No newline at end of file diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONRequestSerializer-body.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONRequestSerializer-body.mustache deleted file mode 100644 index 63513335d9a..00000000000 --- a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONRequestSerializer-body.mustache +++ /dev/null @@ -1,37 +0,0 @@ -#import "{{classPrefix}}JSONRequestSerializer.h" - -@implementation {{classPrefix}}JSONRequestSerializer - -/// -/// When customize a request serializer, -/// the serializer must conform the protocol `AFURLRequestSerialization` -/// and implements the protocol method `requestBySerializingRequest:withParameters:error:` -/// -/// @param request The original request. -/// @param parameters The parameters to be encoded. -/// @param error The error that occurred while attempting to encode the request parameters. -/// -/// @return A serialized request. -/// -- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request - withParameters:(id)parameters - error:(NSError *__autoreleasing *)error -{ - if (!parameters) { - return request; - } - // If the body data which will be serialized isn't NSArray or NSDictionary - // then put the data in the http request body directly. - if ([parameters isKindOfClass:[NSArray class]] || [parameters isKindOfClass:[NSDictionary class]]) { - return [super requestBySerializingRequest:request withParameters:parameters error:error]; - } - NSMutableURLRequest *mutableRequest = [request mutableCopy]; - if([parameters isKindOfClass:[NSData class]]) { - [mutableRequest setHTTPBody:parameters]; - } else { - [mutableRequest setHTTPBody:[parameters dataUsingEncoding:self.stringEncoding]]; - } - return mutableRequest; -} - -@end diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONRequestSerializer-header.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONRequestSerializer-header.mustache deleted file mode 100644 index 1259c5d1530..00000000000 --- a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONRequestSerializer-header.mustache +++ /dev/null @@ -1,7 +0,0 @@ -#import -#import - -{{>licenceInfo}} - -@interface {{classPrefix}}JSONRequestSerializer : AFJSONRequestSerializer -@end diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONResponseSerializer-body.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONResponseSerializer-body.mustache deleted file mode 100644 index 7fa5e7b19e0..00000000000 --- a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONResponseSerializer-body.mustache +++ /dev/null @@ -1,39 +0,0 @@ -#import "{{classPrefix}}JSONResponseSerializer.h" - -@implementation {{classPrefix}}JSONResponseSerializer - -/// -/// When customize a response serializer, -/// the serializer must conform the protocol `AFURLResponseSerialization` -/// and implements the protocol method `responseObjectForResponse:error:` -/// -/// @param response The response to be processed. -/// @param data The response data to be decoded. -/// @param error The error that occurred while attempting to decode the response data. -/// -/// @return The object decoded from the specified response data. -/// -- (id) responseObjectForResponse:(NSURLResponse *)response - data:(NSData *)data - error:(NSError *__autoreleasing *)error { - NSDictionary *responseJson = [super responseObjectForResponse:response data:data error:error]; - - // if response data is not a valid json, return string of data. - if ([self isParseError:*error]) { - *error = nil; - NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; - return responseString; - } - - return responseJson; -} - --(BOOL)isParseError:(NSError *)error { - return [error.domain isEqualToString:NSCocoaErrorDomain] && error.code == 3840; -} - -+ (instancetype)serializer { - return [self serializerWithReadingOptions:NSJSONReadingAllowFragments]; -} - -@end diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONResponseSerializer-header.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONResponseSerializer-header.mustache deleted file mode 100644 index 360e4f9cdc5..00000000000 --- a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONResponseSerializer-header.mustache +++ /dev/null @@ -1,8 +0,0 @@ -#import -#import - -{{>licenceInfo}} - -@interface {{classPrefix}}JSONResponseSerializer : AFJSONResponseSerializer - -@end diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.h b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.h deleted file mode 100644 index f621e7184a9..00000000000 --- a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.h +++ /dev/null @@ -1,8 +0,0 @@ -#import -#import - -{{>licenceInfo}} - -@interface JSONValueTransformer (ISO8601) - -@end diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.m b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.m deleted file mode 100644 index b544a1dae58..00000000000 --- a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.m +++ /dev/null @@ -1,11 +0,0 @@ -#import -#import "JSONValueTransformer+ISO8601.h" - -@implementation JSONValueTransformer (ISO8601) - -- (NSDate *) NSDateFromNSString:(NSString *)string -{ - return [NSDate dateWithISO8601String:string]; -} - -@end diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/Object-body.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/Object-body.mustache deleted file mode 100644 index 88df6d6c9ae..00000000000 --- a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/Object-body.mustache +++ /dev/null @@ -1,42 +0,0 @@ -#import "{{classPrefix}}Object.h" - -@implementation {{classPrefix}}Object - -/** - * Workaround for JSONModel multithreading issues - * https://github.com/icanzilb/JSONModel/issues/441 - */ -- (instancetype)initWithDictionary:(NSDictionary *)dict error:(NSError **)err { - static NSMutableSet *classNames; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - classNames = [NSMutableSet new]; - }); - - BOOL initSync; - @synchronized([self class]) - { - NSString *className = NSStringFromClass([self class]); - initSync = ![classNames containsObject:className]; - if(initSync) - { - [classNames addObject:className]; - self = [super initWithDictionary:dict error:err]; - } - } - if(!initSync) - { - self = [super initWithDictionary:dict error:err]; - } - return self; -} - -/** - * Gets the string presentation of the object. - * This method will be called when logging model object using `NSLog`. - */ -- (NSString *)description { - return [[self toDictionary] description]; -} - -@end diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/Object-header.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/Object-header.mustache deleted file mode 100644 index 89da6a4d8b6..00000000000 --- a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/Object-header.mustache +++ /dev/null @@ -1,8 +0,0 @@ -#import -#import - -{{>licenceInfo}} - -@interface {{classPrefix}}Object : JSONModel - -@end diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/QueryParamCollection-body.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/QueryParamCollection-body.mustache deleted file mode 100644 index b1c901dbffa..00000000000 --- a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/QueryParamCollection-body.mustache +++ /dev/null @@ -1,20 +0,0 @@ -#import "{{classPrefix}}QueryParamCollection.h" - -@implementation {{classPrefix}}QueryParamCollection - -@synthesize values = _values; -@synthesize format = _format; - -- (id)initWithValuesAndFormat:(NSArray *)values - format:(NSString *)format { - - self = [super init]; - if (self) { - _values = values; - _format = format; - } - - return self; -} - -@end diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/QueryParamCollection-header.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/QueryParamCollection-header.mustache deleted file mode 100644 index 9729c182bd8..00000000000 --- a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/QueryParamCollection-header.mustache +++ /dev/null @@ -1,13 +0,0 @@ -#import - -{{>licenceInfo}} - -@interface {{classPrefix}}QueryParamCollection : NSObject - -@property(nonatomic, readonly) NSArray* values; -@property(nonatomic, readonly) NSString* format; - -- (id) initWithValuesAndFormat: (NSArray*) values - format: (NSString*) format; - -@end diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/README.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/README.mustache deleted file mode 100644 index 4355ecc1af5..00000000000 --- a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/README.mustache +++ /dev/null @@ -1,143 +0,0 @@ -# {{podName}} - -{{#appDescription}} -{{{appDescription}}} -{{/appDescription}} - -This ObjC package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: - -- API version: {{appVersion}} -- Package version: {{artifactVersion}} -- Build date: {{generatedDate}} -- Build package: {{generatorClass}} -{{#infoUrl}} -For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) -{{/infoUrl}} - -## Requirements - -The SDK requires [**ARC (Automatic Reference Counting)**](http://stackoverflow.com/questions/7778356/how-to-enable-disable-automatic-reference-counting) to be enabled in the Xcode project. - -## Installation & Usage -### Install from Github using [CocoaPods](https://cocoapods.org/) - -Add the following to the Podfile: - -```ruby -pod '{{podName}}', :git => 'https://github.com/{{gitUserId}}/{{gitRepoId}}.git' -``` - -To specify a particular branch, append `, :branch => 'branch-name-here'` - -To specify a particular commit, append `, :commit => '11aa22'` - -### Install from local path using [CocoaPods](https://cocoapods.org/) - -Put the SDK under your project folder (e.g. /path/to/objc_project/Vendor/{{podName}}) and then add the following to the Podfile: - -```ruby -pod '{{podName}}', :path => 'Vendor/{{podName}}' -``` - -### Usage - -Import the following: - -```objc -#import <{{podName}}/{{{classPrefix}}}ApiClient.h> -#import <{{podName}}/{{{classPrefix}}}Configuration.h> -// load models -{{#models}}{{#model}}#import <{{podName}}/{{{classname}}}.h> -{{/model}}{{/models}}// load API classes for accessing endpoints -{{#apiInfo}}{{#apis}}#import <{{podName}}/{{{classname}}}.h> -{{/apis}}{{/apiInfo}} -``` - -## Recommendation - -It's recommended to create an instance of ApiClient per thread in a multi-threaded environment to avoid any potential issue. - -## Getting Started - -Please follow the [installation procedure](#installation--usage) and then run the following: - -```objc -{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}} -{{#hasAuthMethods}} -{{classPrefix}}Configuration *apiConfig = [{{classPrefix}}Configuration sharedConfig]; -{{#authMethods}}{{#isBasic}}// Configure HTTP basic authorization (authentication scheme: {{{name}}}) -[apiConfig setUsername:@"YOUR_USERNAME"]; -[apiConfig setPassword:@"YOUR_PASSWORD"]; -{{/isBasic}}{{#isApiKey}} -// Configure API key authorization: (authentication scheme: {{{name}}}) -[apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"{{{keyParamName}}}"]; -// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed -//[apiConfig setApiKeyPrefix:@"Bearer" forApiKeyIdentifier:@"{{{keyParamName}}}"]; -{{/isApiKey}}{{#isOAuth}} -// Configure OAuth2 access token for authorization: (authentication scheme: {{{name}}}) -[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; -{{/isOAuth}}{{/authMethods}} -{{/hasAuthMethods}} - -{{#allParams}}{{{dataType}}} *{{paramName}} = {{{example}}}; // {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} -{{/allParams}} - -{{classname}} *apiInstance = [[{{classname}} alloc] init]; - -{{#summary}}// {{{.}}} -{{/summary}}[apiInstance {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} - {{paramName}}{{/secondaryParam}}:{{paramName}}{{/allParams}} - {{#hasParams}}completionHandler: {{/hasParams}}^({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error) { -{{#returnType}} - if (output) { - NSLog(@"%@", output); - } -{{/returnType}} - if (error) { - NSLog(@"Error: %@", error); - } - }]; -{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} -``` - -## Documentation for API Endpoints - -All URIs are relative to *{{basePath}}* - -Class | Method | HTTP request | Description ------------- | ------------- | ------------- | ------------- -{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} -{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} - -## Documentation For Models - -{{#models}}{{#model}} - [{{{classname}}}]({{modelDocPath}}{{{classname}}}.md) -{{/model}}{{/models}} - -## Documentation For Authorization - -{{^authMethods}} All endpoints do not require authorization. -{{/authMethods}}{{#authMethods}}{{#last}} Authentication schemes defined for the API:{{/last}}{{/authMethods}} -{{#authMethods}}## {{{name}}} - -{{#isApiKey}}- **Type**: API key -- **API key parameter name**: {{{keyParamName}}} -- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} -{{/isApiKey}} -{{#isBasic}}- **Type**: HTTP basic authentication -{{/isBasic}} -{{#isOAuth}}- **Type**: OAuth -- **Flow**: {{{flow}}} -- **Authorization URL**: {{{authorizationUrl}}} -- **Scopes**: {{^scopes}}N/A{{/scopes}} -{{#scopes}} - **{{{scope}}}**: {{{description}}} -{{/scopes}} -{{/isOAuth}} - -{{/authMethods}} - -## Author - -{{#apiInfo}}{{#apis}}{{^hasMore}}{{infoEmail}} -{{/hasMore}}{{/apis}}{{/apiInfo}} - diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/api-body.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/api-body.mustache deleted file mode 100644 index 050368f9899..00000000000 --- a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/api-body.mustache +++ /dev/null @@ -1,161 +0,0 @@ -{{#operations}} -#import "{{classname}}.h" -#import "{{classPrefix}}QueryParamCollection.h" -{{#imports}}#import "{{import}}.h" -{{/imports}} -{{newline}} - -@interface {{classname}} () - -@property (nonatomic, strong, readwrite) NSMutableDictionary *defaultHeaders; - -@end - -@implementation {{classname}} - -NSString* k{{classname}}ErrorDomain = @"{{classname}}ErrorDomain"; -NSInteger k{{classname}}MissingParamErrorCode = 234513; - -@synthesize sessionManager = _sessionManager; - -#pragma mark - Initialize methods - -- (id)initWithSessionManager:({{classPrefix}}ApiSessionManager *)sessionManager { - self = [super init]; - if (self) { - _sessionManager = sessionManager; - _defaultHeaders = [NSMutableDictionary dictionary]; - } - - return self; -} - -#pragma mark - - --(NSString*) defaultHeaderForKey:(NSString*)key { - return self.defaultHeaders[key]; -} - --(void) addHeader:(NSString*)value forKey:(NSString*)key { - [self setDefaultHeaderValue:value forKey:key]; -} - --(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key { - [self.defaultHeaders setValue:value forKey:key]; -} - -#pragma mark - Api Methods - -{{#operation}} -/// -/// {{{summary}}} -/// {{{notes}}} -/// {{#allParams}} @param {{paramName}} {{{description}}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} -/// -/// {{/allParams}} @returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} -/// --(NSURLSessionTask*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} - {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}} - {{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler { - {{#allParams}} - {{#required}} - // verify the required parameter '{{paramName}}' is set - if ({{paramName}} == nil) { - NSParameterAssert({{paramName}}); - if(handler) { - NSDictionary * userInfo = @{NSLocalizedDescriptionKey : [NSString stringWithFormat:NSLocalizedString(@"Missing required parameter '%@'", nil),@"{{paramName}}"] }; - NSError* error = [NSError errorWithDomain:k{{classname}}ErrorDomain code:k{{classname}}MissingParamErrorCode userInfo:userInfo]; - handler({{#returnType}}nil, {{/returnType}}error); - } - return nil; - } - - {{/required}} - {{/allParams}} - NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"{{path}}"]; - - // remove format in URL if needed - [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; - - NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; - {{#pathParams}} - if ({{paramName}} != nil) { - pathParams[@"{{baseName}}"] = {{paramName}}; - } - {{/pathParams}} - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - {{#queryParams}} - if ({{paramName}} != nil) { - {{#collectionFormat}} - queryParams[@"{{baseName}}"] = [[{{classPrefix}}QueryParamCollection alloc] initWithValuesAndFormat: {{paramName}} format: @"{{collectionFormat}}"]; - {{/collectionFormat}} - {{^collectionFormat}}queryParams[@"{{baseName}}"] = {{paramName}};{{/collectionFormat}} - } - {{/queryParams}} - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders]; - [headerParams addEntriesFromDictionary:self.defaultHeaders]; - {{#headerParams}} - if ({{paramName}} != nil) { - headerParams[@"{{baseName}}"] = {{paramName}}; - } - {{/headerParams}} - // HTTP header `Accept` - NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[{{#produces}}@"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}}]]; - if(acceptHeader.length > 0) { - headerParams[@"Accept"] = acceptHeader; - } - - // response content type - NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; - - // request content type - NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[{{#consumes}}@"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}]]; - - // Authentication setting - NSArray *authSettings = @[{{#authMethods}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; - - id bodyParam = nil; - NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; - {{#bodyParam}} - bodyParam = {{paramName}}; - {{/bodyParam}} - {{^bodyParam}} - {{#formParams}} - {{#notFile}} - if ({{paramName}}) { - formParams[@"{{baseName}}"] = {{paramName}}; - } - {{/notFile}} - {{#isFile}} - localVarFiles[@"{{paramName}}"] = {{paramName}}; - {{/isFile}} - {{/formParams}} - {{/bodyParam}} - - return [self.sessionManager requestWithPath: resourcePath - method: @"{{httpMethod}}" - pathParams: pathParams - queryParams: queryParams - formParams: formParams - files: localVarFiles - body: bodyParam - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - responseType: {{^returnType}}nil{{/returnType}}{{#returnType}}@"{{{ returnType }}}"{{/returnType}} - completionBlock: ^(id data, NSError *error) { - if(handler) { - handler({{#returnType}}({{{ returnType }}})data, {{/returnType}}error); - } - } - ]; -} - -{{/operation}} - -{{newline}} -{{/operations}} -@end diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/api-header.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/api-header.mustache deleted file mode 100644 index 1b28b47c882..00000000000 --- a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/api-header.mustache +++ /dev/null @@ -1,34 +0,0 @@ -#import -{{#imports}}#import "{{import}}.h" -{{/imports}} -#import "{{classPrefix}}ApiSessionManager.h" - -{{>licenceInfo}} - - -@interface {{classname}}: NSObject <{{classPrefix}}Api> - -extern NSString* k{{classname}}ErrorDomain; -extern NSInteger k{{classname}}MissingParamErrorCode; - -+(instancetype) sharedAPI; - -{{#operations}} -{{#operation}} -/// {{{summary}}} -/// {{#notes}}{{{notes}}}{{/notes}} -/// -/// {{#allParams}}@param {{paramName}} {{description}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} -/// {{/allParams}}{{#responses}} -/// code:{{{code}}} message:"{{{message}}}"{{#hasMore}},{{/hasMore}}{{/responses}} -/// -/// @return {{{returnType}}} --(NSURLSessionTask*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} - {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}} - {{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler; - -{{newline}} -{{/operation}} -{{/operations}} - -@end diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/model-body.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/model-body.mustache deleted file mode 100644 index 2a4a548458e..00000000000 --- a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/model-body.mustache +++ /dev/null @@ -1,59 +0,0 @@ -{{#models}} -{{#model}} -#import "{{classname}}.h" - -@implementation {{classname}} - -- (instancetype)init { - self = [super init]; - if (self) { - // initialize property's default value, if any - {{#vars}}{{#defaultValue}}self.{{name}} = {{{defaultValue}}}; - {{/defaultValue}}{{/vars}} - } - return self; -} -{{#vars}}{{^vendorExtensions.x-unique-id-key}}{{/vendorExtensions.x-unique-id-key}}{{#vendorExtensions.x-unique-id-key}} --(NSString*)indexPropertyName { - return @"{{name}}"; -} -{{/vendorExtensions.x-unique-id-key}}{{/vars}} -{{#discriminator}} -/** - * Maps "discriminator" value to the sub-class name, so that inheritance is supported. - */ -- (id)initWithDictionary:(NSDictionary *)dict error:(NSError *__autoreleasing *)err { - NSString * discriminatedClassName = [dict valueForKey:@"{{discriminator}}"]; - if(discriminatedClassName == nil ){ - return [super initWithDictionary:dict error:err]; - } - Class class = NSClassFromString([@"{{classPrefix}}" stringByAppendingString:discriminatedClassName]); - if([self class ] == class) { - return [super initWithDictionary:dict error:err]; - } - return [[class alloc] initWithDictionary:dict error: err]; -} -{{/discriminator}} - -/** - * Maps json key to property name. - * This method is used by `JSONModel`. - */ -+ (JSONKeyMapper *)keyMapper { - return [[JSONKeyMapper alloc] initWithDictionary:@{ {{#vars}}@"{{baseName}}": @"{{name}}"{{#hasMore}}, {{/hasMore}}{{/vars}} }]; -} - -/** - * Indicates whether the property with the given name is optional. - * If `propertyName` is optional, then return `YES`, otherwise return `NO`. - * This method is used by `JSONModel`. - */ -+ (BOOL)propertyIsOptional:(NSString *)propertyName { - - NSArray *optionalProperties = @[{{#vars}}{{^required}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/required}}{{/vars}}]; - return [optionalProperties containsObject:propertyName]; -} - -{{/model}} -@end -{{/models}} diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/model-header.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/model-header.mustache deleted file mode 100644 index 04570e71a2f..00000000000 --- a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/model-header.mustache +++ /dev/null @@ -1,25 +0,0 @@ -#import -#import "{{classPrefix}}Object.h" - -{{>licenceInfo}} - -{{#imports}}#import "{{import}}.h" -{{/imports}} -{{newline}} -{{#models}} -{{#model}} - -@protocol {{classname}} -@end - -@interface {{classname}} : {{#parent}}{{{parent}}}{{/parent}}{{^parent}}{{classPrefix}}Object{{/parent}} - -{{#vars}} -{{#description}}/* {{{description}}} {{^required}}[optional]{{/required}} - */{{/description}} -@property(nonatomic) {{{ datatype }}} {{name}}; -{{/vars}} - -@end -{{/model}} -{{/models}} diff --git a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/podspec.mustache b/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/podspec.mustache deleted file mode 100644 index bd0bd9f328e..00000000000 --- a/output/objcSessionManager_notasold/src/main/resources/objcSessionManager/podspec.mustache +++ /dev/null @@ -1,37 +0,0 @@ -# -# Be sure to run `pod lib lint {{podName}}.podspec' to ensure this is a -# valid spec and remove all comments before submitting the spec. -# -# Any lines starting with a # are optional, but encouraged -# -# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html -# - -Pod::Spec.new do |s| - s.name = "{{podName}}" - s.version = "{{podVersion}}" -{{#apiInfo}}{{#apis}}{{^hasMore}} - s.summary = "{{appName}}" - s.description = <<-DESC - {{{appDescription}}} - DESC -{{/hasMore}}{{/apis}}{{/apiInfo}} - s.platform = :ios, '7.0' - s.requires_arc = true - - {{^useCoreData}}s.framework = 'SystemConfiguration'{{/useCoreData}}{{#useCoreData}}s.frameworks = 'SystemConfiguration', 'CoreData'{{/useCoreData}} - - s.homepage = "{{gitRepoURL}}" - s.license = "{{#license}}{{license}}{{/license}}{{^license}}Apache License, Version 2.0{{/license}}" - s.source = { :git => "{{gitRepoURL}}.git", :tag => "#{s.version}" } - s.author = { "{{authorName}}" => "{{authorEmail}}" } - - s.source_files = '{{podName}}/**/*.{m,h}' - s.public_header_files = '{{podName}}/**/*.h' -{{#useCoreData}} s.resources = '{{podName}}/**/*.{xcdatamodeld,xcdatamodel}'{{/useCoreData}} - - s.dependency 'AFNetworking', '~> 3' - s.dependency 'JSONModel', '~> 1.2' - s.dependency 'ISO8601', '~> 0.5' -end - diff --git a/output/objcSessionManager_old/README.md b/output/objcSessionManager_old/README.md deleted file mode 100644 index 2bd0d9b256e..00000000000 --- a/output/objcSessionManager_old/README.md +++ /dev/null @@ -1,74 +0,0 @@ -# Swagger Codegen for the ObjcSessionManager library - -## Overview -This is a boiler-plate project to generate your own client library with Swagger. It's goal is -to get you started with the basic plumbing so you can put in your own logic. It won't work without -your changes applied. - -## What's Swagger? -The goal of Swagger™ is to define a standard, language-agnostic interface to REST APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined via Swagger, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. Similar to what interfaces have done for lower-level programming, Swagger removes the guesswork in calling the service. - - -Check out [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) for additional information about the Swagger project, including additional libraries with support for other languages and more. - -## How do I use this? -At this point, you've likely generated a client setup. It will include something along these lines: - -``` -. -|- README.md // this file -|- pom.xml // build script -|-- src -|--- main -|---- java -|----- io.swagger.codegen.languages.ObjcsessionmanagerGenerator.java // generator file -|---- resources -|----- ObjcSessionManager // template files -|----- META-INF -|------ services -|------- io.swagger.codegen.CodegenConfig -``` - -You _will_ need to make changes in at least the following: - -`ObjcsessionmanagerGenerator.java` - -Templates in this folder: - -`src/main/resources/ObjcSessionManager` - -Once modified, you can run this: - -``` -mvn package -``` - -In your generator project. A single jar file will be produced in `target`. You can now use that with codegen: - -``` -java -cp /path/to/swagger-codegen-distribution:/path/to/your/jar io.swagger.codegen.Codegen -l ObjcSessionManager -o ./test -``` - -Now your templates are available to the client generator and you can write output values - -## But how do I modify this? -The `ObjcsessionmanagerGenerator.java` has comments in it--lots of comments. There is no good substitute -for reading the code more, though. See how the `ObjcsessionmanagerGenerator` implements `CodegenConfig`. -That class has the signature of all values that can be overridden. - -For the templates themselves, you have a number of values available to you for generation. -You can execute the `java` command from above while passing different debug flags to show -the object you have available during client generation: - -``` -# The following additional debug options are available for all codegen targets: -# -DdebugSwagger prints the OpenAPI Specification as interpreted by the codegen -# -DdebugModels prints models passed to the template engine -# -DdebugOperations prints operations passed to the template engine -# -DdebugSupportingFiles prints additional data passed to the template engine - -java -DdebugOperations -cp /path/to/swagger-codegen-distribution:/path/to/your/jar io.swagger.codegen.Codegen -l ObjcSessionManager -o ./test -``` - -Will, for example, output the debug info for operations. You can use this info -in the `api.mustache` file. \ No newline at end of file diff --git a/output/objcSessionManager_old/pom.xml b/output/objcSessionManager_old/pom.xml deleted file mode 100644 index 6ec6fe8a8fb..00000000000 --- a/output/objcSessionManager_old/pom.xml +++ /dev/null @@ -1,102 +0,0 @@ - - 4.0.0 - io.swagger - ObjcSessionManager-swagger-codegen - jar - ObjcSessionManager-swagger-codegen - 1.0.0 - - 2.2.0 - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.12 - - - - loggerPath - conf/log4j.properties - - - -Xms512m -Xmx1500m - methods - pertest - - - - - - 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-codegen - ${swagger-codegen-version} - provided - - - - 2.1.5 - 1.0.0 - 4.8.1 - - diff --git a/output/objcSessionManager_old/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerClientCodegen.java b/output/objcSessionManager_old/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerClientCodegen.java deleted file mode 100644 index 4fd59986fb7..00000000000 --- a/output/objcSessionManager_old/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerClientCodegen.java +++ /dev/null @@ -1,750 +0,0 @@ -package io.swagger.codegen.languages; - -import io.swagger.codegen.*; -import io.swagger.models.ArrayModel; -import io.swagger.models.Model; -import io.swagger.models.properties.*; - -import java.io.File; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.lang3.StringUtils; - -public class ObjcSessionManagerClientCodegen extends DefaultCodegen implements CodegenConfig { - public static final String CLASS_PREFIX = "classPrefix"; - public static final String POD_NAME = "podName"; - public static final String AUTHOR_NAME = "authorName"; - public static final String AUTHOR_EMAIL = "authorEmail"; - public static final String LICENSE = "license"; - public static final String GIT_REPO_URL = "gitRepoURL"; - public static final String DEFAULT_LICENSE = "Apache License, Version 2.0"; - public static final String CORE_DATA = "coreData"; - - protected Set foundationClasses = new HashSet(); - protected String podName = "SwaggerClient"; - protected String podVersion = "1.0.0"; - protected String classPrefix = "SWG"; - protected String authorName = "Swagger"; - protected String authorEmail = "apiteam@swagger.io"; - protected String license = DEFAULT_LICENSE; - protected String gitRepoURL = "https://github.com/swagger-api/swagger-codegen"; - protected String[] specialWords = {"new", "copy"}; - protected String apiDocPath = "docs/"; - protected String modelDocPath = "docs/"; - protected String modelFilesPath = "Model/"; - protected String coreFilesPath = "Core/"; - protected String apiFilesPath = "Api/"; - - protected boolean generateCoreData = false; - - protected Set advancedMapingTypes = new HashSet(); - - public ObjcSessionManagerClientCodegen() { - super(); - - outputFolder = "generated-code" + File.separator + "objcSessionManager"; - modelTemplateFiles.put("model-header.mustache", ".h"); - modelTemplateFiles.put("model-body.mustache", ".m"); - apiTemplateFiles.put("api-header.mustache", ".h"); - apiTemplateFiles.put("api-body.mustache", ".m"); - embeddedTemplateDir = templateDir = "objcSessionManager"; - modelDocTemplateFiles.put("model_doc.mustache", ".md"); - apiDocTemplateFiles.put("api_doc.mustache", ".md"); - - defaultIncludes.clear(); - defaultIncludes.add("bool"); - defaultIncludes.add("BOOL"); - defaultIncludes.add("int"); - defaultIncludes.add("NSURL"); - defaultIncludes.add("NSString"); - defaultIncludes.add("NSObject"); - defaultIncludes.add("NSArray"); - defaultIncludes.add("NSNumber"); - defaultIncludes.add("NSDate"); - defaultIncludes.add("NSDictionary"); - defaultIncludes.add("NSMutableArray"); - defaultIncludes.add("NSMutableDictionary"); - defaultIncludes.add("NSManagedObject"); - defaultIncludes.add("NSData"); - - advancedMapingTypes.add("NSDictionary"); - advancedMapingTypes.add("NSArray"); - advancedMapingTypes.add("NSMutableArray"); - advancedMapingTypes.add("NSMutableDictionary"); - advancedMapingTypes.add("NSObject"); - advancedMapingTypes.add("NSNumber"); - advancedMapingTypes.add("NSURL"); - advancedMapingTypes.add("NSString"); - advancedMapingTypes.add("NSDate"); - - languageSpecificPrimitives.clear(); - languageSpecificPrimitives.add("NSNumber"); - languageSpecificPrimitives.add("NSString"); - languageSpecificPrimitives.add("NSObject"); - languageSpecificPrimitives.add("NSDate"); - languageSpecificPrimitives.add("NSData"); - languageSpecificPrimitives.add("NSURL"); - languageSpecificPrimitives.add("bool"); - languageSpecificPrimitives.add("BOOL"); - - typeMapping.clear(); - typeMapping.put("enum", "NSString"); - typeMapping.put("date", "NSDate"); - typeMapping.put("datetime", "NSDate"); - typeMapping.put("boolean", "NSNumber"); - typeMapping.put("string", "NSString"); - typeMapping.put("integer", "NSNumber"); - typeMapping.put("int", "NSNumber"); - typeMapping.put("float", "NSNumber"); - typeMapping.put("long", "NSNumber"); - typeMapping.put("double", "NSNumber"); - typeMapping.put("array", "NSArray"); - typeMapping.put("map", "NSDictionary"); - typeMapping.put("number", "NSNumber"); - typeMapping.put("bigdecimal", "NSNumber"); - typeMapping.put("List", "NSArray"); - typeMapping.put("object", "NSObject"); - typeMapping.put("file", "NSURL"); - typeMapping.put("binary", "NSData"); - typeMapping.put("bytearray", "NSData"); - typeMapping.put("byte", "NSData"); - typeMapping.put("uuid", "NSString"); - typeMapping.put("password", "NSString"); - - // ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm - setReservedWordsLowerCase( - Arrays.asList( - // local variable names in API methods (endpoints) - "resourcePath", "pathParams", "queryParams", "headerParams", - "responseContentType", "requestContentType", "authSettings", - "formParams", "localVarFiles", "bodyParam", - // objc reserved words - "auto", "else", "long", "switch", - "break", "enum", "register", "typedef", - "case", "extern", "return", "union", - "char", "float", "short", "unsigned", - "const", "for", "signed", "void", - "continue", "goto", "sizeof", "volatile", - "default", "if", "id", "static", "while", - "do", "int", "struct", "_Packed", - "double", "protocol", "interface", "implementation", - "NSObject", "NSInteger", "NSNumber", "CGFloat", - "property", "nonatomic", "retain", "strong", - "weak", "unsafe_unretained", "readwrite", "readonly", - "description" - )); - - importMapping = new HashMap(); - - foundationClasses = new HashSet( - Arrays.asList( - "NSNumber", - "NSObject", - "NSString", - "NSDate", - "NSData", - "NSURL", - "NSDictionary") - ); - - instantiationTypes.put("array", "NSMutableArray"); - instantiationTypes.put("map", "NSMutableDictionary"); - - cliOptions.clear(); - cliOptions.add(new CliOption(CORE_DATA, "Should generate core data models").defaultValue("false")); - cliOptions.add(new CliOption(CLASS_PREFIX, "prefix for generated classes (convention: Abbreviation of pod name e.g. `HN` for `HackerNews`).`") - .defaultValue("SWG")); - cliOptions.add(new CliOption(POD_NAME, "cocoapods package name (convention: CameCase).") - .defaultValue("SwaggerClient")); - cliOptions.add(new CliOption(CodegenConstants.POD_VERSION, "cocoapods package version.") - .defaultValue("1.0.0")); - cliOptions.add(new CliOption(AUTHOR_NAME, "Name to use in the podspec file.").defaultValue("Swagger")); - cliOptions.add(new CliOption(AUTHOR_EMAIL, "Email to use in the podspec file.").defaultValue("apiteam@swagger.io")); - cliOptions.add(new CliOption(GIT_REPO_URL, "URL for the git repo where this podspec should point to.") - .defaultValue("https://github.com/swagger-api/swagger-codegen")); - } - - @Override - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - @Override - public String getName() { - return "objc"; - } - - @Override - public String getHelp() { - return "Generates an Objective-C client library."; - } - - @Override - public void processOpts() { - super.processOpts(); - - if (additionalProperties.containsKey(POD_NAME)) { - setPodName((String) additionalProperties.get(POD_NAME)); - } - - if (additionalProperties.containsKey(CodegenConstants.POD_VERSION)) { - setPodVersion((String) additionalProperties.get(CodegenConstants.POD_VERSION)); - } - - if (additionalProperties.containsKey(CORE_DATA)) { - Object coreData = additionalProperties.get(CORE_DATA); - if(((String)coreData).equalsIgnoreCase("true")) { - generateCoreData = true; - } - } - if (additionalProperties.containsKey(CLASS_PREFIX)) { - setClassPrefix((String) additionalProperties.get(CLASS_PREFIX)); - } - - if (additionalProperties.containsKey(AUTHOR_NAME)) { - setAuthorName((String) additionalProperties.get(AUTHOR_NAME)); - } - - if (additionalProperties.containsKey(AUTHOR_EMAIL)) { - setAuthorEmail((String) additionalProperties.get(AUTHOR_EMAIL)); - } - - if (additionalProperties.containsKey(GIT_REPO_URL)) { - setGitRepoURL((String) additionalProperties.get(GIT_REPO_URL)); - } - - if(generateCoreData) { - modelTemplateFiles.put("NSManagedObject-header.mustache", "ManagedObject.h"); - modelTemplateFiles.put("NSManagedObject-body.mustache", "ManagedObject.m"); - modelTemplateFiles.put("NSManagedObjectBuilder-header.mustache", "ManagedObjectBuilder.h"); - modelTemplateFiles.put("NSManagedObjectBuilder-body.mustache", "ManagedObjectBuilder.m"); - } - - additionalProperties.put(POD_NAME, podName); - additionalProperties.put(CodegenConstants.POD_VERSION, podVersion); - additionalProperties.put(CLASS_PREFIX, classPrefix); - additionalProperties.put(AUTHOR_NAME, authorName); - additionalProperties.put(AUTHOR_EMAIL, authorEmail); - additionalProperties.put(GIT_REPO_URL, gitRepoURL); - additionalProperties.put(LICENSE, license); - - // make api and model doc path available in mustache template - additionalProperties.put("apiDocPath", apiDocPath); - additionalProperties.put("modelDocPath", modelDocPath); - additionalProperties.put("useCoreData", generateCoreData); - - modelPackage = podName; - apiPackage = podName; - - supportingFiles.add(new SupportingFile("Object-header.mustache", coreFileFolder(), classPrefix + "Object.h")); - supportingFiles.add(new SupportingFile("Object-body.mustache", coreFileFolder(), classPrefix + "Object.m")); - supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.h")); - supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.m")); - supportingFiles.add(new SupportingFile("ApiClient-header.mustache", coreFileFolder(), classPrefix + "ApiClient.h")); // !! - supportingFiles.add(new SupportingFile("ApiClient-body.mustache", coreFileFolder(), classPrefix + "ApiClient.m")); // !! - supportingFiles.add(new SupportingFile("JSONResponseSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.h")); - supportingFiles.add(new SupportingFile("JSONResponseSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.m")); - supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.m")); - supportingFiles.add(new SupportingFile("JSONRequestSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.h")); - supportingFiles.add(new SupportingFile("ResponseDeserializer-body.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.m")); // !! - supportingFiles.add(new SupportingFile("ResponseDeserializer-header.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.h")); // !! - supportingFiles.add(new SupportingFile("Sanitizer-body.mustache", coreFileFolder(), classPrefix + "Sanitizer.m")); // !! - supportingFiles.add(new SupportingFile("Sanitizer-header.mustache", coreFileFolder(), classPrefix + "Sanitizer.h")); // !! - supportingFiles.add(new SupportingFile("Logger-body.mustache", coreFileFolder(), classPrefix + "Logger.m")); // !! - supportingFiles.add(new SupportingFile("Logger-header.mustache", coreFileFolder(), classPrefix + "Logger.h")); // !! - supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-body.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.m")); - supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-header.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.h")); - supportingFiles.add(new SupportingFile("Configuration-body.mustache", coreFileFolder(), classPrefix + "Configuration.m")); // !! - supportingFiles.add(new SupportingFile("Configuration-header.mustache", coreFileFolder(), classPrefix + "Configuration.h")); // !! - supportingFiles.add(new SupportingFile("api-protocol.mustache", coreFileFolder(), classPrefix + "Api.h")); // !! - supportingFiles.add(new SupportingFile("podspec.mustache", "", podName + ".podspec")); - supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); // !! - supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); // !! - - if(generateCoreData) { - supportingFiles.add(new SupportingFile("xccurrentversion.mustache", (modelPackage() + "/" + modelFilesPath + "/").replace("/", File.separator) + classPrefix + "Model.xcdatamodeld", ".xccurrentversion")); - supportingFiles.add(new SupportingFile("Model.xcdatamodel.mustache",(modelPackage() + "/" + modelFilesPath + "/").replace("/", File.separator) + classPrefix + "Model.xcdatamodeld" + File.separator + classPrefix + "Model.xcdatamodel", "contents")); - } - - // is apiclient - //supportingFiles.add(new SupportingFile("ApiSessionManager-header.mustache", swaggerFolder, classPrefix + "ApiSessionManager.h")); - //supportingFiles.add(new SupportingFile("ApiSessionManager-body.mustache", swaggerFolder, classPrefix + "ApiSessionManager.m")); - - // protocol! - //supportingFiles.add(new SupportingFile("Configuration-protocol.mustache", swaggerFolder, classPrefix + "Configuration.h")); - //supportingFiles.add(new SupportingFile("DefaultConfiguration-body.mustache", swaggerFolder, classPrefix + "DefaultConfiguration.m")); - //supportingFiles.add(new SupportingFile("DefaultConfiguration-header.mustache", swaggerFolder, classPrefix + "DefaultConfiguration.h")); - - // missing! - //supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-header.mustache", swaggerFolder, classPrefix + "BasicAuthTokenProvider.h")); - //supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-body.mustache", swaggerFolder, classPrefix + "BasicAuthTokenProvider.m")); - } - - @Override - public String toInstantiationType(Property p) { - if (p instanceof MapProperty) { - return instantiationTypes.get("map"); - } else if (p instanceof ArrayProperty) { - return instantiationTypes.get("array"); - } else { - return null; - } - } - - @Override - public String getTypeDeclaration(String name) { - if (languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name)) { - return name; - } else { - return name + "*"; - } - } - - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if (typeMapping.containsKey(swaggerType.toLowerCase())) { - type = typeMapping.get(swaggerType.toLowerCase()); - if (languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type)) { - return toModelNameWithoutReservedWordCheck(type); - } - } else { - type = swaggerType; - } - return toModelNameWithoutReservedWordCheck(type); - } - - @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - String innerTypeDeclaration = getTypeDeclaration(inner); - if (innerTypeDeclaration.endsWith("*")) { - innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); - } - // In this condition, type of property p is array of primitive, - // return container type with pointer, e.g. `NSArray**' - if (languageSpecificPrimitives.contains(innerTypeDeclaration)) { - return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*"; - } - // In this condition, type of property p is array of model, - // return container type combine inner type with pointer, e.g. `NSArray*' - else { - for (String sd : advancedMapingTypes) { - if(innerTypeDeclaration.startsWith(sd)) { - return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*"; - } - } - return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*"; - } - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - - String innerTypeDeclaration = getTypeDeclaration(inner); - - if (innerTypeDeclaration.endsWith("*")) { - innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); - } - if (languageSpecificPrimitives.contains(innerTypeDeclaration)) { - return getSwaggerType(p) + "*"; - } else { - for (String s : advancedMapingTypes) { - if(innerTypeDeclaration.startsWith(s)) { - return getSwaggerType(p) + "*"; - } - } - return getSwaggerType(p) + "*"; - } - } else { - String swaggerType = getSwaggerType(p); - // In this condition, type of p is objective-c primitive type, e.g. `NSSNumber', - // return type of p with pointer, e.g. `NSNumber*' - if (languageSpecificPrimitives.contains(swaggerType) && - foundationClasses.contains(swaggerType)) { - return swaggerType + "*"; - } - // In this condition, type of p is c primitive type, e.g. `bool', - // return type of p, e.g. `bool' - else if (languageSpecificPrimitives.contains(swaggerType)) { - return swaggerType; - } - // In this condition, type of p is objective-c object type, e.g. `SWGPet', - // return type of p with pointer, e.g. `SWGPet*' - else { - return swaggerType + "*"; - } - } - } - - @Override - public boolean isDataTypeBinary(String dataType) { - return dataType.toLowerCase().startsWith("nsdata"); - } - - @Override - public String toModelName(String type) { - // model name cannot use reserved keyword - if (reservedWords.contains(type)) { - LOGGER.warn(type+ " (reserved word) cannot be used as model name. Renamed to " + ("model_" + type) + " before further processing"); - type = "model_" + type; // e.g. return => ModelReturn (after camelize) - } - - // model name starts with number - /* no need for the fix below as objc model starts with prefix (e.g. SWG) - if (type.matches("^\\d.*")) { - LOGGER.warn(type + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + type)); - type = "model_" + type; // e.g. 200Response => Model200Response (after camelize) - } - */ - - return toModelNameWithoutReservedWordCheck(type); - } - - /* - * Convert input to proper model name according to ObjC style guide - * without checking for reserved words - * - * @param type Model anme - * @return model Name in ObjC style guide - */ - public String toModelNameWithoutReservedWordCheck(String type) { - type = type.replaceAll("[^0-9a-zA-Z_]", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - - // language build-in classes - if (typeMapping.keySet().contains(type) || - foundationClasses.contains(type) || - importMapping.values().contains(type) || - defaultIncludes.contains(type) || - languageSpecificPrimitives.contains(type)) { - return camelize(type); - } - // custom classes - else { - if (!StringUtils.isEmpty(modelNameSuffix)) { // set model suffix - type = type + "_" + modelNameSuffix; - } - - if (!StringUtils.isEmpty(modelNamePrefix)) { // set model prefix - type = modelNamePrefix + "_" + type; - } - - return classPrefix + camelize(type); // add class prefix - } - } - - @Override - public String toModelFilename(String name) { - // should be the same as the model name - return toModelName(name); - } - - @Override - protected void setNonArrayMapProperty(CodegenProperty property, String type) { - super.setNonArrayMapProperty(property, type); - if ("NSDictionary".equals(type)) { - property.setter = "initWithDictionary"; - } else { - property.setter = "initWithValues"; - } - } - - @Override - public String toModelImport(String name) { - return name; - } - - @Override - public String apiDocFileFolder() { - return (outputFolder + "/" + apiDocPath).replace("/", File.separator); - } - - @Override - public String modelDocFileFolder() { - return (outputFolder + "/" + modelDocPath).replace("/", File.separator); - } - - @Override - public String toModelDocFilename(String name) { - return toModelName(name); - } - - @Override - public String toApiDocFilename(String name) { - return toApiName(name); - } - - @Override - public String apiFileFolder() { - return (outputFolder + "/"+ apiPackage() + "/" + apiFilesPath).replace("/", File.separator); - } - - @Override - public String modelFileFolder() { - return (outputFolder + "/"+ modelPackage() + "/" + modelFilesPath).replace("/", File.separator); - } - - public String coreFileFolder() { - return (apiPackage() + "/" + coreFilesPath).replace("/", File.separator); - } - - @Override - public String toApiName(String name) { - return classPrefix + camelize(name) + "Api"; - } - - @Override - public String toApiFilename(String name) { - return classPrefix + camelize(name) + "Api"; - } - - @Override - public String toVarName(String name) { - // sanitize name - name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - - // if it's all upper case, do noting - if (name.matches("^[A-Z_]$")) { - return name; - } - - // if name starting with special word, escape with '_' - for(int i =0; i < specialWords.length; i++) { - if (name.matches("(?i:^" + specialWords[i] + ".*)")) - name = escapeSpecialWord(name); - } - - // camelize (lower first character) the variable name - // e.g. `pet_id` to `petId` - name = camelize(name, true); - - // for reserved word or word starting with number, prepend `_` - if (isReservedWord(name) || name.matches("^\\d.*")) { - name = escapeReservedWord(name); - } - - - return name; - } - - @Override - public String toParamName(String name) { - // should be the same as variable name - return toVarName(name); - } - - @Override - public String escapeReservedWord(String name) { - return "_" + name; - } - - @SuppressWarnings("static-method") - public String escapeSpecialWord(String name) { - return "var_" + name; - } - - @Override - public String toOperationId(String operationId) { - // throw exception if method name is empty - if (StringUtils.isEmpty(operationId)) { - throw new RuntimeException("Empty method name (operationId) not allowed"); - } - - // method name cannot use reserved keyword, e.g. return - if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId), true)); - operationId = "call_" + operationId; - } - - return camelize(sanitizeName(operationId), true); - } - - public void setClassPrefix(String classPrefix) { - this.classPrefix = classPrefix; - } - - public void setPodName(String podName) { - this.podName = podName; - } - - public void setPodVersion(String podVersion) { - this.podVersion = podVersion; - } - - public void setAuthorEmail(String authorEmail) { - this.authorEmail = authorEmail; - } - - public void setAuthorName(String authorName) { - this.authorName = authorName; - } - - public void setGitRepoURL(String gitRepoURL) { - this.gitRepoURL = gitRepoURL; - } - - public void setLicense(String license) { - this.license = license; - } - - @Override - public Map postProcessOperations(Map objs) { - Map operations = (Map) objs.get("operations"); - if (operations != null) { - List ops = (List) operations.get("operation"); - for (CodegenOperation operation : ops) { - if (!operation.allParams.isEmpty()) { - String firstParamName = operation.allParams.get(0).paramName; - operation.vendorExtensions.put("firstParamAltName", camelize(firstParamName)); - } - } - } - return objs; - } - - @Override - public void postProcessModelProperty(CodegenModel model, CodegenProperty property){ - super.postProcessModelProperty(model,property); - property.vendorExtensions.put("x-uppercaseName", camelize(property.name)); - } - - /** - * 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; - } - - @Override - public void setParameterExampleValue(CodegenParameter p) { - String example; - - if (p.defaultValue == null) { - example = p.example; - } else { - example = p.defaultValue; - } - - String type = p.baseType; - if (type == null) { - type = p.dataType; - } - - if ("NSString*".equalsIgnoreCase(type)) { - if (example == null) { - example = p.paramName + "_example"; - } - example = "@\"" + escapeText(example) + "\""; - } else if ("NSNumber*".equals(type)) { - if (example == null) { - example = "56"; - } - example = "@" + example; - /* OBJC uses NSNumber to represent both int, long, double and float - } else if ("Float".equalsIgnoreCase(type) || "Double".equalsIgnoreCase(type)) { - if (example == null) { - example = "3.4"; - } */ - } else if ("BOOLEAN".equalsIgnoreCase(type) || "bool".equalsIgnoreCase(type)) { - if (example == null) { - example = "True"; - } - } else if ("NSURL*".equalsIgnoreCase(type)) { - if (example == null) { - example = "/path/to/file"; - } - //[NSURL fileURLWithPath:@"path/to/file"] - example = "[NSURL fileURLWithPath:@\"" + escapeText(example) + "\"]"; - /*} else if ("NSDate".equalsIgnoreCase(type)) { - if (example == null) { - example = "2013-10-20"; - } - example = "'" + escapeText(example) + "'";*/ - } else if ("NSDate*".equalsIgnoreCase(type)) { - if (example == null) { - example = "2013-10-20T19:20:30+01:00"; - } - example = "@\"" + escapeText(example) + "\""; - } else if (!languageSpecificPrimitives.contains(type)) { - // type is a model class, e.g. User - type = type.replace("*", ""); - // e.g. [[SWGPet alloc] init - example = "[[" + type + " alloc] init]"; - } else { - LOGGER.warn("Type " + type + " not handled properly in setParameterExampleValue"); - } - - if (example == null) { - example = "NULL"; - } else if (Boolean.TRUE.equals(p.isListContainer)) { - example = "@[" + example + "]"; - } else if (Boolean.TRUE.equals(p.isMapContainer)) { - example = "@{@\"key\" : " + example + "}"; - } - - p.example = example; - } - - @Override - public String escapeQuotationMark(String input) { - // remove " to avoid code injection - return input.replace("\"", ""); - } - - @Override - public String escapeUnsafeCharacters(String input) { - return input.replace("*/", "*_/").replace("/*", "/_*"); - } - -} diff --git a/output/objcSessionManager_old/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/output/objcSessionManager_old/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig deleted file mode 100644 index e3cfa53811b..00000000000 --- a/output/objcSessionManager_old/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig +++ /dev/null @@ -1 +0,0 @@ -io.swagger.codegen.languages.ObjcSessionManagerClientCodegen \ No newline at end of file diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache deleted file mode 100644 index 5e5ad41e2df..00000000000 --- a/output/objcSessionManager_old/src/main/resources/objcSessionManager/ApiSessionManager-body.mustache +++ /dev/null @@ -1,461 +0,0 @@ -#import - -#import "{{classPrefix}}ApiSessionManager.h" -#import "{{classPrefix}}JSONRequestSerializer.h" -#import "{{classPrefix}}JSONResponseSerializer.h" -#import "{{classPrefix}}QueryParamCollection.h" -#import "{{classPrefix}}Object.h" -#import "{{classPrefix}}DefaultConfiguration.h" - - -NSString * const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}ResponseObject"; - - -static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) { - NSDictionary * headers = {{classPrefix}}__headerFieldsForResponse(response); - if(!headers[@"Content-Disposition"]) { - return [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]]; - } - NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?"; - NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern - options:NSRegularExpressionCaseInsensitive - error:nil]; - NSString *contentDispositionHeader = headers[@"Content-Disposition"]; - NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader - options:0 - range:NSMakeRange(0, [contentDispositionHeader length])]; - return [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]]; -} - - -@interface {{classPrefix}}ApiSessionManager () - -@property (nonatomic, strong, readwrite) id<{{classPrefix}}Configuration> configuration; - -@end - -@implementation {{classPrefix}}ApiSessionManager - -- (instancetype)init { - - return [self initWithConfiguration:[{{classPrefix}}DefaultConfiguration sharedConfiguration]]; -} - -- (instancetype)initWithBaseURL:(NSURL *)url { - - return [self initWithBaseURL:url - configuration:[{{classPrefix}}DefaultConfiguration sharedConfiguration]]; - -} - -- (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration { - - return [self initWithBaseURL:[NSURL URLWithString:configuration.host] configuration:configuration]; -} - -- (instancetype)initWithBaseURL:(NSURL *)url - configuration:(id<{{classPrefix}}Configuration>)configuration { - - self = [super initWithBaseURL:url]; - if (self) { - _configuration = configuration; - } - - return self; -} - -#pragma mark - Setter Methods - -+ (void) setOfflineState:(BOOL) state { - offlineState = state; -} - -+ (void) setCacheEnabled:(BOOL)enabled { - cacheEnabled = enabled; -} - -+(void) setReachabilityStatus:(AFNetworkReachabilityStatus)status { - reachabilityStatus = status; -} - -- (void)setHeaderValue:(NSString*) value forKey:(NSString*) forKey { - [self.requestSerializer setValue:value forHTTPHeaderField:forKey]; -} - -- (void)setRequestSerializer:(AFHTTPRequestSerializer *)requestSerializer { - [super setRequestSerializer:requestSerializer]; - requestSerializer.timeoutInterval = self.timeoutInterval; -} - -#pragma mark - Cache Methods - -+(void)clearCache { - [[NSURLCache sharedURLCache] removeAllCachedResponses]; -} - -+(void)configureCacheWithMemoryAndDiskCapacity: (unsigned long) memorySize - diskSize: (unsigned long) diskSize { - NSAssert(memorySize > 0, @"invalid in-memory cache size"); - NSAssert(diskSize >= 0, @"invalid disk cache size"); - - NSURLCache *cache = - [[NSURLCache alloc] - initWithMemoryCapacity:memorySize - diskCapacity:diskSize - diskPath:@"swagger_url_cache"]; - - [NSURLCache setSharedURLCache:cache]; -} - -#pragma mark - Reachability Methods - -+(AFNetworkReachabilityStatus) getReachabilityStatus { - return reachabilityStatus; -} - -+(BOOL) getOfflineState { - return offlineState; -} - -+(void) setReachabilityChangeBlock:(void(^)(int))changeBlock { - reachabilityChangeBlock = changeBlock; -} - -- (void) configureCacheReachibility { - [self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { - reachabilityStatus = status; - {{classPrefix}}DebugLog(@"reachability changed to %@",AFStringFromNetworkReachabilityStatus(status)); - [{{classPrefix}}ApiClient setOfflineState:status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable]; - - // call the reachability block, if configured - if (reachabilityChangeBlock != nil) { - reachabilityChangeBlock(status); - } - }]; - - [self.reachabilityManager startMonitoring]; -} - -#pragma mark - Task Methods - -- (NSURLSessionDataTask*) taskWithCompletionBlock: (NSURLRequest *)request - completionBlock: (void (^)(id, NSError *))completionBlock { - - NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { - {{classPrefix}}DebugLogResponse(response, responseObject,request,error); - - if(!error) { - completionBlock(responseObject, nil); - return; - } - - NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; - if (responseObject) { - // Add in the (parsed) response body. - userInfo[{{classPrefix}}ResponseObjectErrorKey] = responseObject; - } - NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; - completionBlock(nil, augmentedError); - }]; - - return task; -} - -- (NSURLSessionDownloadTask*) downloadTaskWithCompletionBlock: (NSURLRequest *)request - completionBlock: (void (^)(id, NSError *))completionBlock { - - id<{{classPrefix}}Configuration> config = self.configuration; - - NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { - {{classPrefix}}DebugLogResponse(response, responseObject,request,error); - - if(error) { - NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; - if (responseObject) { - userInfo[{{classPrefix}}ResponseObjectErrorKey] = responseObject; - } - NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; - completionBlock(nil, augmentedError); - } - - NSString *directory = config.tempFolderPath ?: NSTemporaryDirectory(); - NSString *filename = {{classPrefix}}__fileNameForResponse(response); - - NSString *filepath = [directory stringByAppendingPathComponent:filename]; - NSURL *file = [NSURL fileURLWithPath:filepath]; - - [responseObject writeToURL:file atomically:YES]; - - completionBlock(file, nil); - }]; - - return task; -} - -#pragma mark - Perform Request Methods - -- (NSURLSessionTask*) requestWithPath: (NSString*) path - method: (NSString*) method - pathParams: (NSDictionary *) pathParams - queryParams: (NSDictionary*) queryParams - formParams: (NSDictionary *) formParams - files: (NSDictionary *) files - body: (id) body - headerParams: (NSDictionary*) headerParams - authSettings: (NSArray *) authSettings - requestContentType: (NSString*) requestContentType - responseContentType: (NSString*) responseContentType - responseType: (NSString *) responseType - completionBlock: (void (^)(id, NSError *))completionBlock { - - // setting request serializer - if ([requestContentType isEqualToString:@"application/json"]) { - self.requestSerializer = [{{classPrefix}}JSONRequestSerializer serializer]; - } - else if ([requestContentType isEqualToString:@"application/x-www-form-urlencoded"]) { - self.requestSerializer = [AFHTTPRequestSerializer serializer]; - } - else if ([requestContentType isEqualToString:@"multipart/form-data"]) { - self.requestSerializer = [AFHTTPRequestSerializer serializer]; - } - else { - self.requestSerializer = [AFHTTPRequestSerializer serializer]; - NSAssert(NO, @"Unsupported request type %@", requestContentType); - } - - // setting response serializer - if ([responseContentType isEqualToString:@"application/json"]) { - self.responseSerializer = [{{classPrefix}}JSONResponseSerializer serializer]; - } else { - self.responseSerializer = [AFHTTPResponseSerializer serializer]; - } - - // sanitize parameters - pathParams = [self.sanitizer sanitizeForSerialization:pathParams]; - queryParams = [self.sanitizer sanitizeForSerialization:queryParams]; - headerParams = [self.sanitizer sanitizeForSerialization:headerParams]; - formParams = [self.sanitizer sanitizeForSerialization:formParams]; - if(![body isKindOfClass:[NSData class]]) { - body = [self.sanitizer sanitizeForSerialization:body]; - } - - // auth setting - [self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings]; - - NSMutableString *resourcePath = [NSMutableString stringWithString:path]; - [pathParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - NSString * safeString = ([obj isKindOfClass:[NSString class]]) ? obj : [NSString stringWithFormat:@"%@", obj]; - safeString = {{classPrefix}}PercentEscapedStringFromString(safeString); - [resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"{%@}", key]] withString:safeString]; - }]; - - NSMutableURLRequest * request = nil; - - NSString* pathWithQueryParams = [self pathWithQueryParamsToString:resourcePath queryParams:queryParams]; - if ([pathWithQueryParams hasPrefix:@"/"]) { - pathWithQueryParams = [pathWithQueryParams substringFromIndex:1]; - } - - NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString]; - if (files.count > 0) { - __weak __typeof(self)weakSelf = self; - request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" - URLString:urlString - parameters:nil - constructingBodyWithBlock:^(id formData) { - [formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - NSString *objString = [weakSelf.sanitizer parameterToString:obj]; - NSData *data = [objString dataUsingEncoding:NSUTF8StringEncoding]; - [formData appendPartWithFormData:data name:key]; - }]; - [files enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - NSURL *filePath = (NSURL *)obj; - [formData appendPartWithFileURL:filePath name:key error:nil]; - }]; - } error:nil]; - } - else { - if (formParams) { - request = [self.requestSerializer requestWithMethod:method - URLString:urlString - parameters:formParams - error:nil]; - } - if (body) { - request = [self.requestSerializer requestWithMethod:method - URLString:urlString - parameters:body - error:nil]; - } - } - - // request cache - BOOL hasHeaderParams = [headerParams count] > 0; - if (offlineState) { - {{classPrefix}}DebugLog(@"%@ cache forced", resourcePath); - [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; - } - else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { - {{classPrefix}}DebugLog(@"%@ cache enabled", resourcePath); - [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; - } - else { - {{classPrefix}}DebugLog(@"%@ cache disabled", resourcePath); - [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; - } - - if (hasHeaderParams){ - for(NSString * key in [headerParams keyEnumerator]){ - [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; - } - } - [self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"]; - - [self postProcessRequest:request]; - - - NSURLSessionTask *task = nil - - if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) { - task = [self downloadTaskWithCompletionBlock:request completionBlock:^(id data, NSError *error) { - completionBlock(data, error); - }]; - } - else { - [self taskWithCompletionBlock:request completionBlock:^(id data, NSError *error) { - NSError * serializationError; - id response = [self.responseDeserializer deserialize:data class:responseType error:&serializationError]; - if(!response && !error){ - error = serializationError; - } - completionBlock(response, error); - }]; - } - - [task resume]; - - return task; -} - -// Added for easier override to modify request -- (void)postProcessRequest:(NSMutableURLRequest *)request { - // Always disable cookies! - [request setHTTPShouldHandleCookies:NO]; -} - -#pragma mark - - -- (NSString*)pathWithQueryParamsToString:(NSString*) path - queryParams:(NSDictionary*) queryParams { - if(queryParams.count == 0) { - return path; - } - NSString * separator = nil; - NSUInteger counter = 0; - - NSMutableString * requestUrl = [NSMutableString stringWithFormat:@"%@", path]; - - NSDictionary *separatorStyles = @{@"csv" : @",", - @"tsv" : @"\t", - @"pipes": @"|" - }; - for(NSString * key in [queryParams keyEnumerator]){ - if (counter == 0) { - separator = @"?"; - } else { - separator = @"&"; - } - id queryParam = [queryParams valueForKey:key]; - if(!queryParam) { - continue; - } - NSString *safeKey = {{classPrefix}}PercentEscapedStringFromString(key); - if ([queryParam isKindOfClass:[NSString class]]){ - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, {{classPrefix}}PercentEscapedStringFromString(queryParam)]]; - - } else if ([queryParam isKindOfClass:[{{classPrefix}}QueryParamCollection class]]){ - {{classPrefix}}QueryParamCollection * coll = ({{classPrefix}}QueryParamCollection*) queryParam; - NSArray* values = [coll values]; - NSString* format = [coll format]; - - if([format isEqualToString:@"multi"]) { - for(id obj in values) { - if (counter > 0) { - separator = @"&"; - } - NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([NSString stringWithFormat:@"%@",obj]); - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; - counter += 1; - } - continue; - } - NSString * separatorStyle = separatorStyles[format]; - NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([values componentsJoinedByString:separatorStyle]); - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; - } else { - NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([NSString stringWithFormat:@"%@",queryParam]); - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; - } - counter += 1; - } - return requestUrl; -} - -/** - * Update header and query params based on authentication settings - */ -- (void) updateHeaderParams:(NSDictionary *__autoreleasing *)headers - queryParams:(NSDictionary *__autoreleasing *)querys - WithAuthSettings:(NSArray *)authSettings { - - if (!authSettings || [authSettings count] == 0) { - return; - } - - NSMutableDictionary *headersWithAuth = [NSMutableDictionary dictionaryWithDictionary:*headers]; - NSMutableDictionary *querysWithAuth = [NSMutableDictionary dictionaryWithDictionary:*querys]; - - id<{{classPrefix}}Configuration> config = self.configuration; - for (NSString *auth in authSettings) { - NSDictionary *authSetting = config.authSettings[auth]; - - if(!authSetting) { // auth setting is set only if the key is non-empty - continue; - } - - NSString *type = authSetting[@"in"]; - NSString *key = authSetting[@"key"]; - NSString *value = authSetting[@"value"]; - if ([type isEqualToString:@"header"] && [key length] > 0 ) { - headersWithAuth[key] = value; - } else if ([type isEqualToString:@"query"] && [key length] != 0) { - querysWithAuth[key] = value; - } - } - - *headers = [NSDictionary dictionaryWithDictionary:headersWithAuth]; - *querys = [NSDictionary dictionaryWithDictionary:querysWithAuth]; -} - -- (AFSecurityPolicy *) customSecurityPolicy { - AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; - - id<{{classPrefix}}Configuration> config = self.configuration; - - if (config.sslCaCert) { - NSData *certData = [NSData dataWithContentsOfFile:config.sslCaCert]; - [securityPolicy setPinnedCertificates:@[certData]]; - } - - if (config.verifySSL) { - [securityPolicy setAllowInvalidCertificates:NO]; - } - else { - [securityPolicy setAllowInvalidCertificates:YES]; - [securityPolicy setValidatesDomainName:NO]; - } - - return securityPolicy; -} - -@end diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/ApiSessionManager-header.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/ApiSessionManager-header.mustache deleted file mode 100644 index 010966b14a5..00000000000 --- a/output/objcSessionManager_old/src/main/resources/objcSessionManager/ApiSessionManager-header.mustache +++ /dev/null @@ -1,147 +0,0 @@ -/** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ - -#import -#import "{{classPrefix}}Configuration.h" - -/** - * A key for `NSError` user info dictionaries. - * - * The corresponding value is the parsed response body for an HTTP error. - */ -extern NSString *const {{classPrefix}}ResponseObjectErrorKey; - - -@interface {{classPrefix}}ApiSessionManager : AFHTTPSessionManager - -@property (nonatomic, strong, readonly) id<{{classPrefix}}Configuration> configuration; - -@property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy; -@property(nonatomic, assign) NSTimeInterval timeoutInterval; -@property(nonatomic, readonly) NSOperationQueue* queue; - -@property(nonatomic, strong) id<{{classPrefix}}ResponseDeserializer> responseDeserializer; - -@property(nonatomic, strong) id<{{classPrefix}}Sanitizer> sanitizer; - -/** - * Clears Cache - */ -+(void)clearCache; - -/** - * Turns on cache - * - * @param enabled If the cached is enable, must be `YES` or `NO` - */ -+(void)setCacheEnabled:(BOOL) enabled; - -/** - * Sets the client unreachable - * - * @param state off line state, must be `YES` or `NO` - */ -+(void) setOfflineState:(BOOL) state; - -/** - * Gets if the client is unreachable - * - * @return The client offline state - */ -+(BOOL) getOfflineState; - -/** - * Sets the client reachability, this may be overridden by the reachability manager if reachability changes - * - * @param The client reachability. - */ -+(void) setReachabilityStatus:(AFNetworkReachabilityStatus) status; - -/** - * Gets the client reachability - * - * @return The client reachability. - */ -+(AFNetworkReachabilityStatus) getReachabilityStatus; - -/** - * Customizes the behavior when the reachability changed - * - * @param changeBlock The block will be executed when the reachability changed. - */ -+(void) setReachabilityChangeBlock:(void(^)(int))changeBlock; - -/** - * Sets the api client reachability strategy - */ -- (void)configureCacheReachibility; - -/** - * Sets header for request - * - * @param value The header value - * @param forKey The header key - */ --(void)setHeaderValue:(NSString*) value - forKey:(NSString*) forKey; - -/** - * Updates header parameters and query parameters for authentication - * - * @param headers The header parameter will be udpated, passed by pointer to pointer. - * @param querys The query parameters will be updated, passed by pointer to pointer. - * @param authSettings The authentication names NSArray. - */ -- (void) updateHeaderParams:(NSDictionary **)headers - queryParams:(NSDictionary **)querys - WithAuthSettings:(NSArray *)authSettings; - - -/** - * Initializes the session manager with a configuration. - * - * @param configuration The configuration implementation - */ -- (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration; - -/** - * Performs request - * - * @param path Request url. - * @param method Request method. - * @param pathParams Request path parameters. - * @param queryParams Request query parameters. - * @param body Request body. - * @param headerParams Request header parameters. - * @param authSettings Request authentication names. - * @param requestContentType Request content-type. - * @param responseContentType Response content-type. - * @param completionBlock The block will be executed when the request completed. - * - * @return The created session task. - */ -- (NSURLSessionTask *)requestWithCompletionBlock:(NSString*)path - method:(NSString*) method - pathParams:(NSDictionary *)pathParams - queryParams:(NSDictionary*)queryParams - formParams:(NSDictionary *)formParams - files:(NSDictionary *)files - body:(id)body - headerParams:(NSDictionary *)headerParams - authSettings: (NSArray *)authSettings - requestContentType:(NSString *)requestContentType - responseContentType:(NSString *)responseContentType - responseType:(NSString *)responseType - completionBlock:(void (^)(id, NSError *))completionBlock; - -/** - * Custom security policy - * - * @return AFSecurityPolicy - */ -- (AFSecurityPolicy *) customSecurityPolicy; - -@end diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/BasicAuthTokenProvider-body.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/BasicAuthTokenProvider-body.mustache deleted file mode 100644 index e2ba00badb7..00000000000 --- a/output/objcSessionManager_old/src/main/resources/objcSessionManager/BasicAuthTokenProvider-body.mustache +++ /dev/null @@ -1,14 +0,0 @@ -#import "{{classPrefix}}BasicAuthTokenProvider.h" - -@implementation {{classPrefix}}BasicAuthTokenProvider - -+ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password { - - NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password]; - NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; - basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; - - return basicAuthCredentials; -} - -@end diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/BasicAuthTokenProvider-header.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/BasicAuthTokenProvider-header.mustache deleted file mode 100644 index dfb287568a0..00000000000 --- a/output/objcSessionManager_old/src/main/resources/objcSessionManager/BasicAuthTokenProvider-header.mustache +++ /dev/null @@ -1,14 +0,0 @@ -/** The `{{classPrefix}}BasicAuthTokenProvider` class creates a basic auth token from username and password. - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ - -#import - -@interface {{classPrefix}}BasicAuthTokenProvider : NSObject - -+ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password; - -@end \ No newline at end of file diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/Configuration-protocol.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/Configuration-protocol.mustache deleted file mode 100644 index db429a38150..00000000000 --- a/output/objcSessionManager_old/src/main/resources/objcSessionManager/Configuration-protocol.mustache +++ /dev/null @@ -1,75 +0,0 @@ -#import -#import "{{classPrefix}}Logger.h" - -{{>licenceInfo}} - -@protocol {{classPrefix}}Configuration - -/** - * Api logger - */ -@property (readonly, nonatomic) {{classPrefix}}Logger *logger; - -/** - * Base url - */ -@property (readonly, nonatomic) NSString *host; - -/** - * Api key values for Api Key type Authentication - */ -@property (readonly, nonatomic) NSDictionary *apiKey; - -/** - * Api key prefix values to be prepend to the respective api key - */ -@property (readonly, nonatomic) NSDictionary *apiKeyPrefix; - -/** - * Username for HTTP Basic Authentication - */ -@property (readonly, nonatomic) NSString *username; - -/** - * Password for HTTP Basic Authentication - */ -@property (readonly, nonatomic) NSString *password; - -/** - * Access token for OAuth - */ -@property (readonly, nonatomic) NSString *accessToken; - -/** - * Temp folder for file download - */ -@property (readonly, nonatomic) NSString *tempFolderPath; - -/** - * Debug switch, default false - */ -@property (readonly, nonatomic) BOOL debug; - -/** - * SSL/TLS verification - * Set this to NO to skip verifying SSL certificate when calling API from https server - */ -@property (readonly, nonatomic) BOOL verifySSL; - -/** - * SSL/TLS verification - * Set this to customize the certificate file to verify the peer - */ -@property (readonly, nonatomic) NSString *sslCaCert; - -/** - * Authentication Settings - */ -@property (readonly, nonatomic) NSDictionary *authSettings; - -/** -* Default headers for all services -*/ -@property (readonly, nonatomic, strong) NSDictionary *defaultHeaders; - -@end \ No newline at end of file diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/DefaultConfiguration-body.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/DefaultConfiguration-body.mustache deleted file mode 100644 index a45eba7ba55..00000000000 --- a/output/objcSessionManager_old/src/main/resources/objcSessionManager/DefaultConfiguration-body.mustache +++ /dev/null @@ -1,157 +0,0 @@ -#import "{{classPrefix}}DefaultConfiguration.h" - -@implementation {{classPrefix}}DefaultConfiguration - -#pragma mark - Singleton Methods - -+ (instancetype)sharedConfiguration { - - static {{classPrefix}}DefaultConfiguration *shardConfig = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - shardConfig = [[self alloc] init]; - }); - return shardConfig; -} - -#pragma mark - Initialize Methods - -- (instancetype)init { - self = [super init]; - if (self) { - _host = @"{{basePath}}"; - _username = @""; - _password = @""; - _accessToken= @""; - _verifySSL = YES; - _mutableApiKey = [NSMutableDictionary dictionary]; - _mutableApiKeyPrefix = [NSMutableDictionary dictionary]; - _mutableDefaultHeaders = [NSMutableDictionary dictionary]; - _mutableDefaultHeaders[@"User-Agent"] = {{#httpUserAgent}}@"{{httpUserAgent}}"{{/httpUserAgent}}{{^httpUserAgent}}[NSString stringWithFormat:@"Swagger-Codegen/{{version}}/objc (%@; iOS %@; Scale/%0.2f)",[[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]]{{/httpUserAgent}}; - _logger = [{{classPrefix}}Logger sharedLogger]; - } - return self; -} - -#pragma mark - Instance Methods - -- (NSString *) getApiKeyWithPrefix:(NSString *)key { - NSString *prefix = self.apiKeyPrefix[key]; - NSString *apiKey = self.apiKey[key]; - if (prefix && apiKey != (id)[NSNull null] && apiKey.length > 0) { // both api key prefix and api key are set - return [NSString stringWithFormat:@"%@ %@", prefix, apiKey]; - } - else if (apiKey != (id)[NSNull null] && apiKey.length > 0) { // only api key, no api key prefix - return [NSString stringWithFormat:@"%@", self.apiKey[key]]; - } - else { // return empty string if nothing is set - return @""; - } -} - -- (NSString *) getBasicAuthToken { - // return empty string if username and password are empty - if (self.username.length == 0 && self.password.length == 0){ - return @""; - } - - NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.username, self.password]; - NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; - basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; - - return basicAuthCredentials; -} - -- (NSString *) getAccessToken { - if (self.accessToken.length == 0) { // token not set, return empty string - return @""; - } else { - return [NSString stringWithFormat:@"Bearer %@", self.accessToken]; - } -} - -#pragma mark - Setter Methods - -- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString *)identifier { - [self.mutableApiKey setValue:apiKey forKey:identifier]; -} - -- (void) removeApiKey:(NSString *)identifier { - [self.mutableApiKey removeObjectForKey:identifier]; -} - -- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier { - [self.mutableApiKeyPrefix setValue:prefix forKey:identifier]; -} - -- (void) removeApiKeyPrefix:(NSString *)identifier { - [self.mutableApiKeyPrefix removeObjectForKey:identifier]; -} - -#pragma mark - - -- (NSDictionary *) authSettings { - return @{ -{{#authMethods}} -{{#isApiKey}} - @"{{name}}": - @{ - @"type": @"api_key", - @"in": {{#isKeyInHeader}}@"header"{{/isKeyInHeader}}{{#isKeyInQuery}}@"query"{{/isKeyInQuery}}, - @"key": @"{{keyParamName}}", - @"value": [self getApiKeyWithPrefix:@"{{keyParamName}}"] - }, -{{/isApiKey}} -{{#isBasic}} - @"{{name}}": - @{ - @"type": @"basic", - @"in": @"header", - @"key": @"Authorization", - @"value": [self getBasicAuthToken] - }, -{{/isBasic}} -{{#isOAuth}} - @"{{name}}": - @{ - @"type": @"oauth", - @"in": @"header", - @"key": @"Authorization", - @"value": [self getAccessToken] - }, -{{/isOAuth}} -{{/authMethods}} - }; -} - --(BOOL)debug { - return self.logger.isEnabled; -} - --(void)setDebug:(BOOL)debug { - self.logger.enabled = debug; -} - - - -- (void)setDefaultHeaderValue:(NSString *)value forKey:(NSString *)key { - if(!value) { - [self.mutableDefaultHeaders removeObjectForKey:key]; - return; - } - self.mutableDefaultHeaders[key] = value; -} - --(void) removeDefaultHeaderForKey:(NSString*)key { - [self.mutableDefaultHeaders removeObjectForKey:key]; -} - -- (NSString *)defaultHeaderForKey:(NSString *)key { - return self.mutableDefaultHeaders[key]; -} - -- (NSDictionary *)defaultHeaders { - return [self.mutableDefaultHeaders copy]; -} - -@end diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/DefaultConfiguration-header.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/DefaultConfiguration-header.mustache deleted file mode 100644 index 46f3b32fc93..00000000000 --- a/output/objcSessionManager_old/src/main/resources/objcSessionManager/DefaultConfiguration-header.mustache +++ /dev/null @@ -1,134 +0,0 @@ -#import -#import "{{classPrefix}}Configuration.h" - -{{>licenceInfo}} - -@interface {{classPrefix}}DefaultConfiguration : NSObject <{{classPrefix}}Configuration> - -+ ({{classPrefix}}DefaultConfiguration *)sharedConfiguration; - -/** - * Default api logger - */ -@property (nonatomic, strong) {{classPrefix}}Logger * logger; - -/** - * Default api client - */ -@property (nonatomic) {{classPrefix}}ApiClient *apiClient; - -/** - * Default base url - */ -@property (nonatomic) NSString *host; - -/** - * Api key values for Api Key type Authentication - * - * To add or remove api key, use `setApiKey:forApiKeyIdentifier:`. - */ -@property (readonly, nonatomic, strong) NSDictionary *apiKey; - -/** - * Api key prefix values to be prepend to the respective api key - * - * To add or remove prefix, use `setApiKeyPrefix:forApiKeyPrefixIdentifier:`. - */ -@property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix; - -/** - * Username for HTTP Basic Authentication - */ - @property (nonatomic) NSString *username; - -/** - * Password for HTTP Basic Authentication - */ -@property (nonatomic) NSString *password; - -/** - * Access token for OAuth - */ -@property (nonatomic) NSString *accessToken; - -/** - * Temp folder for file download - */ -@property (nonatomic) NSString *tempFolderPath; - -/** - * Debug switch, default false - */ -@property (nonatomic) BOOL debug; - -/** - * SSL/TLS verification - * Set this to NO to skip verifying SSL certificate when calling API from https server - */ -@property (nonatomic) BOOL verifySSL; - -/** - * SSL/TLS verification - * Set this to customize the certificate file to verify the peer - */ -@property (nonatomic) NSString *sslCaCert; - -/** - * Sets API key - * - * To remove a apiKey for an identifier, just set the apiKey to nil. - * - * @param apiKey API key or token. - * @param identifier API key identifier (authentication schema). - * - */ -- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString*)identifier; - -/** - * Removes api key - * - * @param identifier API key identifier. - */ -- (void) removeApiKey:(NSString *)identifier; - -/** - * Sets the prefix for API key - * - * @param apiKeyPrefix API key prefix. - * @param identifier API key identifier. - */ -- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier; - -/** - * Removes api key prefix - * - * @param identifier API key identifier. - */ -- (void) removeApiKeyPrefix:(NSString *)identifier; - -/** -* Default headers for all services -*/ -@property (readonly, nonatomic, strong) NSDictionary *defaultHeaders; - -/** -* Removes header from defaultHeaders -* -* @param Header name. -*/ --(void) removeDefaultHeaderForKey:(NSString*)key; - -/** -* Sets the header for key -* -* @param value Value for header name -* @param key Header name -*/ --(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key; - -/** -* @param Header key name. -*/ --(NSString*) defaultHeaderForKey:(NSString*)key; - -@end \ No newline at end of file diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONRequestSerializer-body.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONRequestSerializer-body.mustache deleted file mode 100644 index 63513335d9a..00000000000 --- a/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONRequestSerializer-body.mustache +++ /dev/null @@ -1,37 +0,0 @@ -#import "{{classPrefix}}JSONRequestSerializer.h" - -@implementation {{classPrefix}}JSONRequestSerializer - -/// -/// When customize a request serializer, -/// the serializer must conform the protocol `AFURLRequestSerialization` -/// and implements the protocol method `requestBySerializingRequest:withParameters:error:` -/// -/// @param request The original request. -/// @param parameters The parameters to be encoded. -/// @param error The error that occurred while attempting to encode the request parameters. -/// -/// @return A serialized request. -/// -- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request - withParameters:(id)parameters - error:(NSError *__autoreleasing *)error -{ - if (!parameters) { - return request; - } - // If the body data which will be serialized isn't NSArray or NSDictionary - // then put the data in the http request body directly. - if ([parameters isKindOfClass:[NSArray class]] || [parameters isKindOfClass:[NSDictionary class]]) { - return [super requestBySerializingRequest:request withParameters:parameters error:error]; - } - NSMutableURLRequest *mutableRequest = [request mutableCopy]; - if([parameters isKindOfClass:[NSData class]]) { - [mutableRequest setHTTPBody:parameters]; - } else { - [mutableRequest setHTTPBody:[parameters dataUsingEncoding:self.stringEncoding]]; - } - return mutableRequest; -} - -@end diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONRequestSerializer-header.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONRequestSerializer-header.mustache deleted file mode 100644 index 1259c5d1530..00000000000 --- a/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONRequestSerializer-header.mustache +++ /dev/null @@ -1,7 +0,0 @@ -#import -#import - -{{>licenceInfo}} - -@interface {{classPrefix}}JSONRequestSerializer : AFJSONRequestSerializer -@end diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONResponseSerializer-body.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONResponseSerializer-body.mustache deleted file mode 100644 index 7fa5e7b19e0..00000000000 --- a/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONResponseSerializer-body.mustache +++ /dev/null @@ -1,39 +0,0 @@ -#import "{{classPrefix}}JSONResponseSerializer.h" - -@implementation {{classPrefix}}JSONResponseSerializer - -/// -/// When customize a response serializer, -/// the serializer must conform the protocol `AFURLResponseSerialization` -/// and implements the protocol method `responseObjectForResponse:error:` -/// -/// @param response The response to be processed. -/// @param data The response data to be decoded. -/// @param error The error that occurred while attempting to decode the response data. -/// -/// @return The object decoded from the specified response data. -/// -- (id) responseObjectForResponse:(NSURLResponse *)response - data:(NSData *)data - error:(NSError *__autoreleasing *)error { - NSDictionary *responseJson = [super responseObjectForResponse:response data:data error:error]; - - // if response data is not a valid json, return string of data. - if ([self isParseError:*error]) { - *error = nil; - NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; - return responseString; - } - - return responseJson; -} - --(BOOL)isParseError:(NSError *)error { - return [error.domain isEqualToString:NSCocoaErrorDomain] && error.code == 3840; -} - -+ (instancetype)serializer { - return [self serializerWithReadingOptions:NSJSONReadingAllowFragments]; -} - -@end diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONResponseSerializer-header.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONResponseSerializer-header.mustache deleted file mode 100644 index 360e4f9cdc5..00000000000 --- a/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONResponseSerializer-header.mustache +++ /dev/null @@ -1,8 +0,0 @@ -#import -#import - -{{>licenceInfo}} - -@interface {{classPrefix}}JSONResponseSerializer : AFJSONResponseSerializer - -@end diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.h b/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.h deleted file mode 100644 index f621e7184a9..00000000000 --- a/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.h +++ /dev/null @@ -1,8 +0,0 @@ -#import -#import - -{{>licenceInfo}} - -@interface JSONValueTransformer (ISO8601) - -@end diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.m b/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.m deleted file mode 100644 index b544a1dae58..00000000000 --- a/output/objcSessionManager_old/src/main/resources/objcSessionManager/JSONValueTransformer+ISO8601.m +++ /dev/null @@ -1,11 +0,0 @@ -#import -#import "JSONValueTransformer+ISO8601.h" - -@implementation JSONValueTransformer (ISO8601) - -- (NSDate *) NSDateFromNSString:(NSString *)string -{ - return [NSDate dateWithISO8601String:string]; -} - -@end diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/Object-body.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/Object-body.mustache deleted file mode 100644 index 88df6d6c9ae..00000000000 --- a/output/objcSessionManager_old/src/main/resources/objcSessionManager/Object-body.mustache +++ /dev/null @@ -1,42 +0,0 @@ -#import "{{classPrefix}}Object.h" - -@implementation {{classPrefix}}Object - -/** - * Workaround for JSONModel multithreading issues - * https://github.com/icanzilb/JSONModel/issues/441 - */ -- (instancetype)initWithDictionary:(NSDictionary *)dict error:(NSError **)err { - static NSMutableSet *classNames; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - classNames = [NSMutableSet new]; - }); - - BOOL initSync; - @synchronized([self class]) - { - NSString *className = NSStringFromClass([self class]); - initSync = ![classNames containsObject:className]; - if(initSync) - { - [classNames addObject:className]; - self = [super initWithDictionary:dict error:err]; - } - } - if(!initSync) - { - self = [super initWithDictionary:dict error:err]; - } - return self; -} - -/** - * Gets the string presentation of the object. - * This method will be called when logging model object using `NSLog`. - */ -- (NSString *)description { - return [[self toDictionary] description]; -} - -@end diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/Object-header.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/Object-header.mustache deleted file mode 100644 index 89da6a4d8b6..00000000000 --- a/output/objcSessionManager_old/src/main/resources/objcSessionManager/Object-header.mustache +++ /dev/null @@ -1,8 +0,0 @@ -#import -#import - -{{>licenceInfo}} - -@interface {{classPrefix}}Object : JSONModel - -@end diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/QueryParamCollection-body.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/QueryParamCollection-body.mustache deleted file mode 100644 index b1c901dbffa..00000000000 --- a/output/objcSessionManager_old/src/main/resources/objcSessionManager/QueryParamCollection-body.mustache +++ /dev/null @@ -1,20 +0,0 @@ -#import "{{classPrefix}}QueryParamCollection.h" - -@implementation {{classPrefix}}QueryParamCollection - -@synthesize values = _values; -@synthesize format = _format; - -- (id)initWithValuesAndFormat:(NSArray *)values - format:(NSString *)format { - - self = [super init]; - if (self) { - _values = values; - _format = format; - } - - return self; -} - -@end diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/QueryParamCollection-header.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/QueryParamCollection-header.mustache deleted file mode 100644 index 9729c182bd8..00000000000 --- a/output/objcSessionManager_old/src/main/resources/objcSessionManager/QueryParamCollection-header.mustache +++ /dev/null @@ -1,13 +0,0 @@ -#import - -{{>licenceInfo}} - -@interface {{classPrefix}}QueryParamCollection : NSObject - -@property(nonatomic, readonly) NSArray* values; -@property(nonatomic, readonly) NSString* format; - -- (id) initWithValuesAndFormat: (NSArray*) values - format: (NSString*) format; - -@end diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/README.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/README.mustache deleted file mode 100644 index 4355ecc1af5..00000000000 --- a/output/objcSessionManager_old/src/main/resources/objcSessionManager/README.mustache +++ /dev/null @@ -1,143 +0,0 @@ -# {{podName}} - -{{#appDescription}} -{{{appDescription}}} -{{/appDescription}} - -This ObjC package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: - -- API version: {{appVersion}} -- Package version: {{artifactVersion}} -- Build date: {{generatedDate}} -- Build package: {{generatorClass}} -{{#infoUrl}} -For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) -{{/infoUrl}} - -## Requirements - -The SDK requires [**ARC (Automatic Reference Counting)**](http://stackoverflow.com/questions/7778356/how-to-enable-disable-automatic-reference-counting) to be enabled in the Xcode project. - -## Installation & Usage -### Install from Github using [CocoaPods](https://cocoapods.org/) - -Add the following to the Podfile: - -```ruby -pod '{{podName}}', :git => 'https://github.com/{{gitUserId}}/{{gitRepoId}}.git' -``` - -To specify a particular branch, append `, :branch => 'branch-name-here'` - -To specify a particular commit, append `, :commit => '11aa22'` - -### Install from local path using [CocoaPods](https://cocoapods.org/) - -Put the SDK under your project folder (e.g. /path/to/objc_project/Vendor/{{podName}}) and then add the following to the Podfile: - -```ruby -pod '{{podName}}', :path => 'Vendor/{{podName}}' -``` - -### Usage - -Import the following: - -```objc -#import <{{podName}}/{{{classPrefix}}}ApiClient.h> -#import <{{podName}}/{{{classPrefix}}}Configuration.h> -// load models -{{#models}}{{#model}}#import <{{podName}}/{{{classname}}}.h> -{{/model}}{{/models}}// load API classes for accessing endpoints -{{#apiInfo}}{{#apis}}#import <{{podName}}/{{{classname}}}.h> -{{/apis}}{{/apiInfo}} -``` - -## Recommendation - -It's recommended to create an instance of ApiClient per thread in a multi-threaded environment to avoid any potential issue. - -## Getting Started - -Please follow the [installation procedure](#installation--usage) and then run the following: - -```objc -{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}} -{{#hasAuthMethods}} -{{classPrefix}}Configuration *apiConfig = [{{classPrefix}}Configuration sharedConfig]; -{{#authMethods}}{{#isBasic}}// Configure HTTP basic authorization (authentication scheme: {{{name}}}) -[apiConfig setUsername:@"YOUR_USERNAME"]; -[apiConfig setPassword:@"YOUR_PASSWORD"]; -{{/isBasic}}{{#isApiKey}} -// Configure API key authorization: (authentication scheme: {{{name}}}) -[apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"{{{keyParamName}}}"]; -// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed -//[apiConfig setApiKeyPrefix:@"Bearer" forApiKeyIdentifier:@"{{{keyParamName}}}"]; -{{/isApiKey}}{{#isOAuth}} -// Configure OAuth2 access token for authorization: (authentication scheme: {{{name}}}) -[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; -{{/isOAuth}}{{/authMethods}} -{{/hasAuthMethods}} - -{{#allParams}}{{{dataType}}} *{{paramName}} = {{{example}}}; // {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} -{{/allParams}} - -{{classname}} *apiInstance = [[{{classname}} alloc] init]; - -{{#summary}}// {{{.}}} -{{/summary}}[apiInstance {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} - {{paramName}}{{/secondaryParam}}:{{paramName}}{{/allParams}} - {{#hasParams}}completionHandler: {{/hasParams}}^({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error) { -{{#returnType}} - if (output) { - NSLog(@"%@", output); - } -{{/returnType}} - if (error) { - NSLog(@"Error: %@", error); - } - }]; -{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} -``` - -## Documentation for API Endpoints - -All URIs are relative to *{{basePath}}* - -Class | Method | HTTP request | Description ------------- | ------------- | ------------- | ------------- -{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} -{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} - -## Documentation For Models - -{{#models}}{{#model}} - [{{{classname}}}]({{modelDocPath}}{{{classname}}}.md) -{{/model}}{{/models}} - -## Documentation For Authorization - -{{^authMethods}} All endpoints do not require authorization. -{{/authMethods}}{{#authMethods}}{{#last}} Authentication schemes defined for the API:{{/last}}{{/authMethods}} -{{#authMethods}}## {{{name}}} - -{{#isApiKey}}- **Type**: API key -- **API key parameter name**: {{{keyParamName}}} -- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} -{{/isApiKey}} -{{#isBasic}}- **Type**: HTTP basic authentication -{{/isBasic}} -{{#isOAuth}}- **Type**: OAuth -- **Flow**: {{{flow}}} -- **Authorization URL**: {{{authorizationUrl}}} -- **Scopes**: {{^scopes}}N/A{{/scopes}} -{{#scopes}} - **{{{scope}}}**: {{{description}}} -{{/scopes}} -{{/isOAuth}} - -{{/authMethods}} - -## Author - -{{#apiInfo}}{{#apis}}{{^hasMore}}{{infoEmail}} -{{/hasMore}}{{/apis}}{{/apiInfo}} - diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/api-body.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/api-body.mustache deleted file mode 100644 index 050368f9899..00000000000 --- a/output/objcSessionManager_old/src/main/resources/objcSessionManager/api-body.mustache +++ /dev/null @@ -1,161 +0,0 @@ -{{#operations}} -#import "{{classname}}.h" -#import "{{classPrefix}}QueryParamCollection.h" -{{#imports}}#import "{{import}}.h" -{{/imports}} -{{newline}} - -@interface {{classname}} () - -@property (nonatomic, strong, readwrite) NSMutableDictionary *defaultHeaders; - -@end - -@implementation {{classname}} - -NSString* k{{classname}}ErrorDomain = @"{{classname}}ErrorDomain"; -NSInteger k{{classname}}MissingParamErrorCode = 234513; - -@synthesize sessionManager = _sessionManager; - -#pragma mark - Initialize methods - -- (id)initWithSessionManager:({{classPrefix}}ApiSessionManager *)sessionManager { - self = [super init]; - if (self) { - _sessionManager = sessionManager; - _defaultHeaders = [NSMutableDictionary dictionary]; - } - - return self; -} - -#pragma mark - - --(NSString*) defaultHeaderForKey:(NSString*)key { - return self.defaultHeaders[key]; -} - --(void) addHeader:(NSString*)value forKey:(NSString*)key { - [self setDefaultHeaderValue:value forKey:key]; -} - --(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key { - [self.defaultHeaders setValue:value forKey:key]; -} - -#pragma mark - Api Methods - -{{#operation}} -/// -/// {{{summary}}} -/// {{{notes}}} -/// {{#allParams}} @param {{paramName}} {{{description}}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} -/// -/// {{/allParams}} @returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} -/// --(NSURLSessionTask*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} - {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}} - {{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler { - {{#allParams}} - {{#required}} - // verify the required parameter '{{paramName}}' is set - if ({{paramName}} == nil) { - NSParameterAssert({{paramName}}); - if(handler) { - NSDictionary * userInfo = @{NSLocalizedDescriptionKey : [NSString stringWithFormat:NSLocalizedString(@"Missing required parameter '%@'", nil),@"{{paramName}}"] }; - NSError* error = [NSError errorWithDomain:k{{classname}}ErrorDomain code:k{{classname}}MissingParamErrorCode userInfo:userInfo]; - handler({{#returnType}}nil, {{/returnType}}error); - } - return nil; - } - - {{/required}} - {{/allParams}} - NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"{{path}}"]; - - // remove format in URL if needed - [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; - - NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; - {{#pathParams}} - if ({{paramName}} != nil) { - pathParams[@"{{baseName}}"] = {{paramName}}; - } - {{/pathParams}} - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - {{#queryParams}} - if ({{paramName}} != nil) { - {{#collectionFormat}} - queryParams[@"{{baseName}}"] = [[{{classPrefix}}QueryParamCollection alloc] initWithValuesAndFormat: {{paramName}} format: @"{{collectionFormat}}"]; - {{/collectionFormat}} - {{^collectionFormat}}queryParams[@"{{baseName}}"] = {{paramName}};{{/collectionFormat}} - } - {{/queryParams}} - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders]; - [headerParams addEntriesFromDictionary:self.defaultHeaders]; - {{#headerParams}} - if ({{paramName}} != nil) { - headerParams[@"{{baseName}}"] = {{paramName}}; - } - {{/headerParams}} - // HTTP header `Accept` - NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[{{#produces}}@"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}}]]; - if(acceptHeader.length > 0) { - headerParams[@"Accept"] = acceptHeader; - } - - // response content type - NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; - - // request content type - NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[{{#consumes}}@"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}]]; - - // Authentication setting - NSArray *authSettings = @[{{#authMethods}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; - - id bodyParam = nil; - NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; - {{#bodyParam}} - bodyParam = {{paramName}}; - {{/bodyParam}} - {{^bodyParam}} - {{#formParams}} - {{#notFile}} - if ({{paramName}}) { - formParams[@"{{baseName}}"] = {{paramName}}; - } - {{/notFile}} - {{#isFile}} - localVarFiles[@"{{paramName}}"] = {{paramName}}; - {{/isFile}} - {{/formParams}} - {{/bodyParam}} - - return [self.sessionManager requestWithPath: resourcePath - method: @"{{httpMethod}}" - pathParams: pathParams - queryParams: queryParams - formParams: formParams - files: localVarFiles - body: bodyParam - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - responseType: {{^returnType}}nil{{/returnType}}{{#returnType}}@"{{{ returnType }}}"{{/returnType}} - completionBlock: ^(id data, NSError *error) { - if(handler) { - handler({{#returnType}}({{{ returnType }}})data, {{/returnType}}error); - } - } - ]; -} - -{{/operation}} - -{{newline}} -{{/operations}} -@end diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/api-header.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/api-header.mustache deleted file mode 100644 index 1b28b47c882..00000000000 --- a/output/objcSessionManager_old/src/main/resources/objcSessionManager/api-header.mustache +++ /dev/null @@ -1,34 +0,0 @@ -#import -{{#imports}}#import "{{import}}.h" -{{/imports}} -#import "{{classPrefix}}ApiSessionManager.h" - -{{>licenceInfo}} - - -@interface {{classname}}: NSObject <{{classPrefix}}Api> - -extern NSString* k{{classname}}ErrorDomain; -extern NSInteger k{{classname}}MissingParamErrorCode; - -+(instancetype) sharedAPI; - -{{#operations}} -{{#operation}} -/// {{{summary}}} -/// {{#notes}}{{{notes}}}{{/notes}} -/// -/// {{#allParams}}@param {{paramName}} {{description}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} -/// {{/allParams}}{{#responses}} -/// code:{{{code}}} message:"{{{message}}}"{{#hasMore}},{{/hasMore}}{{/responses}} -/// -/// @return {{{returnType}}} --(NSURLSessionTask*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} - {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}} - {{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler; - -{{newline}} -{{/operation}} -{{/operations}} - -@end diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/model-body.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/model-body.mustache deleted file mode 100644 index 2a4a548458e..00000000000 --- a/output/objcSessionManager_old/src/main/resources/objcSessionManager/model-body.mustache +++ /dev/null @@ -1,59 +0,0 @@ -{{#models}} -{{#model}} -#import "{{classname}}.h" - -@implementation {{classname}} - -- (instancetype)init { - self = [super init]; - if (self) { - // initialize property's default value, if any - {{#vars}}{{#defaultValue}}self.{{name}} = {{{defaultValue}}}; - {{/defaultValue}}{{/vars}} - } - return self; -} -{{#vars}}{{^vendorExtensions.x-unique-id-key}}{{/vendorExtensions.x-unique-id-key}}{{#vendorExtensions.x-unique-id-key}} --(NSString*)indexPropertyName { - return @"{{name}}"; -} -{{/vendorExtensions.x-unique-id-key}}{{/vars}} -{{#discriminator}} -/** - * Maps "discriminator" value to the sub-class name, so that inheritance is supported. - */ -- (id)initWithDictionary:(NSDictionary *)dict error:(NSError *__autoreleasing *)err { - NSString * discriminatedClassName = [dict valueForKey:@"{{discriminator}}"]; - if(discriminatedClassName == nil ){ - return [super initWithDictionary:dict error:err]; - } - Class class = NSClassFromString([@"{{classPrefix}}" stringByAppendingString:discriminatedClassName]); - if([self class ] == class) { - return [super initWithDictionary:dict error:err]; - } - return [[class alloc] initWithDictionary:dict error: err]; -} -{{/discriminator}} - -/** - * Maps json key to property name. - * This method is used by `JSONModel`. - */ -+ (JSONKeyMapper *)keyMapper { - return [[JSONKeyMapper alloc] initWithDictionary:@{ {{#vars}}@"{{baseName}}": @"{{name}}"{{#hasMore}}, {{/hasMore}}{{/vars}} }]; -} - -/** - * Indicates whether the property with the given name is optional. - * If `propertyName` is optional, then return `YES`, otherwise return `NO`. - * This method is used by `JSONModel`. - */ -+ (BOOL)propertyIsOptional:(NSString *)propertyName { - - NSArray *optionalProperties = @[{{#vars}}{{^required}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/required}}{{/vars}}]; - return [optionalProperties containsObject:propertyName]; -} - -{{/model}} -@end -{{/models}} diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/model-header.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/model-header.mustache deleted file mode 100644 index 04570e71a2f..00000000000 --- a/output/objcSessionManager_old/src/main/resources/objcSessionManager/model-header.mustache +++ /dev/null @@ -1,25 +0,0 @@ -#import -#import "{{classPrefix}}Object.h" - -{{>licenceInfo}} - -{{#imports}}#import "{{import}}.h" -{{/imports}} -{{newline}} -{{#models}} -{{#model}} - -@protocol {{classname}} -@end - -@interface {{classname}} : {{#parent}}{{{parent}}}{{/parent}}{{^parent}}{{classPrefix}}Object{{/parent}} - -{{#vars}} -{{#description}}/* {{{description}}} {{^required}}[optional]{{/required}} - */{{/description}} -@property(nonatomic) {{{ datatype }}} {{name}}; -{{/vars}} - -@end -{{/model}} -{{/models}} diff --git a/output/objcSessionManager_old/src/main/resources/objcSessionManager/podspec.mustache b/output/objcSessionManager_old/src/main/resources/objcSessionManager/podspec.mustache deleted file mode 100644 index bd0bd9f328e..00000000000 --- a/output/objcSessionManager_old/src/main/resources/objcSessionManager/podspec.mustache +++ /dev/null @@ -1,37 +0,0 @@ -# -# Be sure to run `pod lib lint {{podName}}.podspec' to ensure this is a -# valid spec and remove all comments before submitting the spec. -# -# Any lines starting with a # are optional, but encouraged -# -# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html -# - -Pod::Spec.new do |s| - s.name = "{{podName}}" - s.version = "{{podVersion}}" -{{#apiInfo}}{{#apis}}{{^hasMore}} - s.summary = "{{appName}}" - s.description = <<-DESC - {{{appDescription}}} - DESC -{{/hasMore}}{{/apis}}{{/apiInfo}} - s.platform = :ios, '7.0' - s.requires_arc = true - - {{^useCoreData}}s.framework = 'SystemConfiguration'{{/useCoreData}}{{#useCoreData}}s.frameworks = 'SystemConfiguration', 'CoreData'{{/useCoreData}} - - s.homepage = "{{gitRepoURL}}" - s.license = "{{#license}}{{license}}{{/license}}{{^license}}Apache License, Version 2.0{{/license}}" - s.source = { :git => "{{gitRepoURL}}.git", :tag => "#{s.version}" } - s.author = { "{{authorName}}" => "{{authorEmail}}" } - - s.source_files = '{{podName}}/**/*.{m,h}' - s.public_header_files = '{{podName}}/**/*.h' -{{#useCoreData}} s.resources = '{{podName}}/**/*.{xcdatamodeld,xcdatamodel}'{{/useCoreData}} - - s.dependency 'AFNetworking', '~> 3' - s.dependency 'JSONModel', '~> 1.2' - s.dependency 'ISO8601', '~> 0.5' -end - From 421c462ba9eb275bf50dede89b7edf48514dafc4 Mon Sep 17 00:00:00 2001 From: cbornet Date: Mon, 18 Jul 2016 16:33:20 +0200 Subject: [PATCH 121/470] set supportInheritance to true for java based gens --- .../languages/AbstractJavaCodegen.java | 1 + .../languages/JavaCXFServerCodegen.java | 1 - .../languages/JavaJAXRSSpecServerCodegen.java | 1 - .../java/io/swagger/client/ApiClient.java | 6 +-- .../java/io/swagger/client/api/FakeApi.java | 2 +- .../java/io/swagger/client/api/PetApi.java | 2 +- .../java/io/swagger/client/model/Cat.java | 50 +------------------ .../java/io/swagger/client/model/Dog.java | 50 +------------------ .../client/petstore/java/jersey1/docs/Cat.md | 2 - .../client/petstore/java/jersey1/docs/Dog.md | 2 - .../java/io/swagger/client/ApiClient.java | 2 +- .../java/io/swagger/client/api/FakeApi.java | 2 +- .../java/io/swagger/client/api/PetApi.java | 2 +- .../java/io/swagger/client/model/Cat.java | 50 +------------------ .../java/io/swagger/client/model/Dog.java | 50 +------------------ .../petstore/java/jersey2-java8/docs/Cat.md | 2 - .../petstore/java/jersey2-java8/docs/Dog.md | 2 - .../petstore/java/jersey2-java8/pom.xml | 2 +- .../java/io/swagger/client/ApiClient.java | 2 +- .../java/io/swagger/client/api/FakeApi.java | 2 +- .../java/io/swagger/client/api/PetApi.java | 2 +- .../java/io/swagger/client/model/Cat.java | 50 +------------------ .../java/io/swagger/client/model/Dog.java | 50 +------------------ .../client/petstore/java/jersey2/docs/Cat.md | 2 - .../client/petstore/java/jersey2/docs/Dog.md | 2 - samples/client/petstore/java/jersey2/pom.xml | 2 +- .../java/io/swagger/client/ApiClient.java | 2 +- .../java/io/swagger/client/api/FakeApi.java | 2 +- .../java/io/swagger/client/api/PetApi.java | 2 +- .../java/io/swagger/client/model/Cat.java | 50 +------------------ .../java/io/swagger/client/model/Dog.java | 50 +------------------ .../petstore/java/okhttp-gson/docs/Cat.md | 2 - .../petstore/java/okhttp-gson/docs/Dog.md | 2 - .../java/io/swagger/client/ApiClient.java | 2 +- .../java/io/swagger/client/api/FakeApi.java | 2 +- .../java/io/swagger/client/api/PetApi.java | 2 +- .../java/io/swagger/client/model/Cat.java | 50 +------------------ .../java/io/swagger/client/model/Dog.java | 50 +------------------ samples/client/petstore/java/retrofit/pom.xml | 2 +- .../java/io/swagger/client/ApiClient.java | 6 +-- .../java/io/swagger/client/api/FakeApi.java | 2 +- .../java/io/swagger/client/api/PetApi.java | 2 +- .../java/io/swagger/client/model/Cat.java | 50 +------------------ .../java/io/swagger/client/model/Dog.java | 50 +------------------ .../petstore/java/retrofit2/docs/Cat.md | 2 - .../petstore/java/retrofit2/docs/Dog.md | 2 - .../java/io/swagger/client/ApiClient.java | 6 +-- .../java/io/swagger/client/api/FakeApi.java | 2 +- .../java/io/swagger/client/api/PetApi.java | 2 +- .../java/io/swagger/client/model/Cat.java | 50 +------------------ .../java/io/swagger/client/model/Dog.java | 50 +------------------ .../petstore/java/retrofit2rx/docs/Cat.md | 2 - .../petstore/java/retrofit2rx/docs/Dog.md | 2 - .../java/io/swagger/client/ApiClient.java | 6 +-- .../java/io/swagger/client/api/FakeApi.java | 2 +- .../java/io/swagger/client/api/PetApi.java | 2 +- .../java/io/swagger/client/model/Cat.java | 50 +------------------ .../java/io/swagger/client/model/Dog.java | 50 +------------------ 58 files changed, 68 insertions(+), 829 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java index 9c46c524f1d..84c07280815 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java @@ -43,6 +43,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code public AbstractJavaCodegen() { super(); + supportsInheritance = true; modelTemplateFiles.put("model.mustache", ".java"); apiTemplateFiles.put("api.mustache", ".java"); apiTestTemplateFiles.put("api_test.mustache", ".java"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java index c9d558d51ab..f11821ef2b0 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java @@ -15,7 +15,6 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen public JavaCXFServerCodegen() { super(); - supportsInheritance = true; sourceFolder = "gen" + File.separator + "java"; outputFolder = "generated-code/JavaJaxRS-CXF"; apiTestTemplateFiles.clear(); // TODO: add test template diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSSpecServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSSpecServerCodegen.java index e7d15868282..28e7e75a2a0 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSSpecServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSSpecServerCodegen.java @@ -25,7 +25,6 @@ public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen public JavaJAXRSSpecServerCodegen() { super(); - supportsInheritance = true; sourceFolder = "src/main/java"; invokerPackage = "io.swagger.api"; artifactId = "swagger-jaxrs-server"; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java index e21bded5212..75b3a96f2c7 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java @@ -41,10 +41,10 @@ public ApiClient(String[] authNames) { this(); for(String authName : authNames) { RequestInterceptor auth; - if (authName == "api_key") { - auth = new ApiKeyAuth("header", "api_key"); - } else if (authName == "petstore_auth") { + if (authName == "petstore_auth") { auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); + } else if (authName == "api_key") { + auth = new ApiKeyAuth("header", "api_key"); } else { throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java index 57fa0cdd95a..5825fbfed42 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java @@ -4,8 +4,8 @@ import io.swagger.client.model.Client; import org.joda.time.LocalDate; -import org.joda.time.DateTime; import java.math.BigDecimal; +import org.joda.time.DateTime; import java.util.ArrayList; import java.util.HashMap; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java index 4d4cc14f625..e486495c5a9 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java @@ -3,8 +3,8 @@ import io.swagger.client.ApiClient; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.ModelApiResponse; +import java.io.File; import java.util.ArrayList; import java.util.HashMap; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java index f39b159f0b4..753aac88213 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java @@ -37,51 +37,9 @@ */ public class Cat extends Animal { - @JsonProperty("className") - private String className = null; - - @JsonProperty("color") - private String color = "red"; - @JsonProperty("declawed") private Boolean declawed = null; - public Cat className(String className) { - this.className = className; - return this; - } - - /** - * Get className - * @return className - **/ - @ApiModelProperty(example = "null", required = true, value = "") - public String getClassName() { - return className; - } - - public void setClassName(String className) { - this.className = className; - } - - public Cat color(String color) { - this.color = color; - return this; - } - - /** - * Get color - * @return color - **/ - @ApiModelProperty(example = "null", value = "") - public String getColor() { - return color; - } - - public void setColor(String color) { - this.color = color; - } - public Cat declawed(Boolean declawed) { this.declawed = declawed; return this; @@ -110,15 +68,13 @@ public boolean equals(java.lang.Object o) { return false; } Cat cat = (Cat) o; - return Objects.equals(this.className, cat.className) && - Objects.equals(this.color, cat.color) && - Objects.equals(this.declawed, cat.declawed) && + return Objects.equals(this.declawed, cat.declawed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, color, declawed, super.hashCode()); + return Objects.hash(declawed, super.hashCode()); } @Override @@ -126,8 +82,6 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Cat {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java index dbcd1a7207b..178ec87c893 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java @@ -37,51 +37,9 @@ */ public class Dog extends Animal { - @JsonProperty("className") - private String className = null; - - @JsonProperty("color") - private String color = "red"; - @JsonProperty("breed") private String breed = null; - public Dog className(String className) { - this.className = className; - return this; - } - - /** - * Get className - * @return className - **/ - @ApiModelProperty(example = "null", required = true, value = "") - public String getClassName() { - return className; - } - - public void setClassName(String className) { - this.className = className; - } - - public Dog color(String color) { - this.color = color; - return this; - } - - /** - * Get color - * @return color - **/ - @ApiModelProperty(example = "null", value = "") - public String getColor() { - return color; - } - - public void setColor(String color) { - this.color = color; - } - public Dog breed(String breed) { this.breed = breed; return this; @@ -110,15 +68,13 @@ public boolean equals(java.lang.Object o) { return false; } Dog dog = (Dog) o; - return Objects.equals(this.className, dog.className) && - Objects.equals(this.color, dog.color) && - Objects.equals(this.breed, dog.breed) && + return Objects.equals(this.breed, dog.breed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, color, breed, super.hashCode()); + return Objects.hash(breed, super.hashCode()); } @Override @@ -126,8 +82,6 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Dog {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/jersey1/docs/Cat.md b/samples/client/petstore/java/jersey1/docs/Cat.md index be6e56fa8ce..6e9f71ce7dd 100644 --- a/samples/client/petstore/java/jersey1/docs/Cat.md +++ b/samples/client/petstore/java/jersey1/docs/Cat.md @@ -4,8 +4,6 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**className** | **String** | | -**color** | **String** | | [optional] **declawed** | **Boolean** | | [optional] diff --git a/samples/client/petstore/java/jersey1/docs/Dog.md b/samples/client/petstore/java/jersey1/docs/Dog.md index 71a7dbe809e..ac7cea323ff 100644 --- a/samples/client/petstore/java/jersey1/docs/Dog.md +++ b/samples/client/petstore/java/jersey1/docs/Dog.md @@ -4,8 +4,6 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**className** | **String** | | -**color** | **String** | | [optional] **breed** | **String** | | [optional] diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java index b16fdbbdfa9..bf4695d7854 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java @@ -99,8 +99,8 @@ public ApiClient() { // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap(); - authentications.put("api_key", new ApiKeyAuth("header", "api_key")); authentications.put("petstore_auth", new OAuth()); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java index f949514a7ff..190eb3d9422 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java @@ -34,8 +34,8 @@ import io.swagger.client.model.Client; import org.joda.time.LocalDate; -import org.joda.time.DateTime; import java.math.BigDecimal; +import org.joda.time.DateTime; import java.util.ArrayList; diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java index c126283d2aa..917849acd2d 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java @@ -33,8 +33,8 @@ import io.swagger.client.Pair; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.ModelApiResponse; +import java.io.File; import java.util.ArrayList; diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Cat.java index f39b159f0b4..753aac88213 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Cat.java @@ -37,51 +37,9 @@ */ public class Cat extends Animal { - @JsonProperty("className") - private String className = null; - - @JsonProperty("color") - private String color = "red"; - @JsonProperty("declawed") private Boolean declawed = null; - public Cat className(String className) { - this.className = className; - return this; - } - - /** - * Get className - * @return className - **/ - @ApiModelProperty(example = "null", required = true, value = "") - public String getClassName() { - return className; - } - - public void setClassName(String className) { - this.className = className; - } - - public Cat color(String color) { - this.color = color; - return this; - } - - /** - * Get color - * @return color - **/ - @ApiModelProperty(example = "null", value = "") - public String getColor() { - return color; - } - - public void setColor(String color) { - this.color = color; - } - public Cat declawed(Boolean declawed) { this.declawed = declawed; return this; @@ -110,15 +68,13 @@ public boolean equals(java.lang.Object o) { return false; } Cat cat = (Cat) o; - return Objects.equals(this.className, cat.className) && - Objects.equals(this.color, cat.color) && - Objects.equals(this.declawed, cat.declawed) && + return Objects.equals(this.declawed, cat.declawed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, color, declawed, super.hashCode()); + return Objects.hash(declawed, super.hashCode()); } @Override @@ -126,8 +82,6 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Cat {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Dog.java index dbcd1a7207b..178ec87c893 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Dog.java @@ -37,51 +37,9 @@ */ public class Dog extends Animal { - @JsonProperty("className") - private String className = null; - - @JsonProperty("color") - private String color = "red"; - @JsonProperty("breed") private String breed = null; - public Dog className(String className) { - this.className = className; - return this; - } - - /** - * Get className - * @return className - **/ - @ApiModelProperty(example = "null", required = true, value = "") - public String getClassName() { - return className; - } - - public void setClassName(String className) { - this.className = className; - } - - public Dog color(String color) { - this.color = color; - return this; - } - - /** - * Get color - * @return color - **/ - @ApiModelProperty(example = "null", value = "") - public String getColor() { - return color; - } - - public void setColor(String color) { - this.color = color; - } - public Dog breed(String breed) { this.breed = breed; return this; @@ -110,15 +68,13 @@ public boolean equals(java.lang.Object o) { return false; } Dog dog = (Dog) o; - return Objects.equals(this.className, dog.className) && - Objects.equals(this.color, dog.color) && - Objects.equals(this.breed, dog.breed) && + return Objects.equals(this.breed, dog.breed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, color, breed, super.hashCode()); + return Objects.hash(breed, super.hashCode()); } @Override @@ -126,8 +82,6 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Dog {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/jersey2-java8/docs/Cat.md b/samples/client/petstore/java/jersey2-java8/docs/Cat.md index be6e56fa8ce..6e9f71ce7dd 100644 --- a/samples/client/petstore/java/jersey2-java8/docs/Cat.md +++ b/samples/client/petstore/java/jersey2-java8/docs/Cat.md @@ -4,8 +4,6 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**className** | **String** | | -**color** | **String** | | [optional] **declawed** | **Boolean** | | [optional] diff --git a/samples/client/petstore/java/jersey2-java8/docs/Dog.md b/samples/client/petstore/java/jersey2-java8/docs/Dog.md index 71a7dbe809e..ac7cea323ff 100644 --- a/samples/client/petstore/java/jersey2-java8/docs/Dog.md +++ b/samples/client/petstore/java/jersey2-java8/docs/Dog.md @@ -4,8 +4,6 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**className** | **String** | | -**color** | **String** | | [optional] **breed** | **String** | | [optional] diff --git a/samples/client/petstore/java/jersey2-java8/pom.xml b/samples/client/petstore/java/jersey2-java8/pom.xml index d3327ef4b98..944ffdd829e 100644 --- a/samples/client/petstore/java/jersey2-java8/pom.xml +++ b/samples/client/petstore/java/jersey2-java8/pom.xml @@ -168,7 +168,7 @@ - 1.5.8 + 1.5.9 2.22.2 2.7.5 1.0.0 diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiClient.java index 047a47252f8..06f6d4d899a 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiClient.java @@ -84,8 +84,8 @@ public ApiClient() { // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap(); - authentications.put("api_key", new ApiKeyAuth("header", "api_key")); authentications.put("petstore_auth", new OAuth()); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/FakeApi.java index c010d34a655..feabca0a7cd 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/FakeApi.java @@ -8,8 +8,8 @@ import javax.ws.rs.core.GenericType; import io.swagger.client.model.Client; -import java.time.LocalDate; import java.time.OffsetDateTime; +import java.time.LocalDate; import java.math.BigDecimal; import java.util.ArrayList; diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/PetApi.java index ab85c4ac394..ad66598406d 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/PetApi.java @@ -8,8 +8,8 @@ import javax.ws.rs.core.GenericType; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.ModelApiResponse; +import java.io.File; import java.util.ArrayList; import java.util.HashMap; diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Cat.java index f39b159f0b4..753aac88213 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Cat.java @@ -37,51 +37,9 @@ */ public class Cat extends Animal { - @JsonProperty("className") - private String className = null; - - @JsonProperty("color") - private String color = "red"; - @JsonProperty("declawed") private Boolean declawed = null; - public Cat className(String className) { - this.className = className; - return this; - } - - /** - * Get className - * @return className - **/ - @ApiModelProperty(example = "null", required = true, value = "") - public String getClassName() { - return className; - } - - public void setClassName(String className) { - this.className = className; - } - - public Cat color(String color) { - this.color = color; - return this; - } - - /** - * Get color - * @return color - **/ - @ApiModelProperty(example = "null", value = "") - public String getColor() { - return color; - } - - public void setColor(String color) { - this.color = color; - } - public Cat declawed(Boolean declawed) { this.declawed = declawed; return this; @@ -110,15 +68,13 @@ public boolean equals(java.lang.Object o) { return false; } Cat cat = (Cat) o; - return Objects.equals(this.className, cat.className) && - Objects.equals(this.color, cat.color) && - Objects.equals(this.declawed, cat.declawed) && + return Objects.equals(this.declawed, cat.declawed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, color, declawed, super.hashCode()); + return Objects.hash(declawed, super.hashCode()); } @Override @@ -126,8 +82,6 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Cat {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Dog.java index dbcd1a7207b..178ec87c893 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Dog.java @@ -37,51 +37,9 @@ */ public class Dog extends Animal { - @JsonProperty("className") - private String className = null; - - @JsonProperty("color") - private String color = "red"; - @JsonProperty("breed") private String breed = null; - public Dog className(String className) { - this.className = className; - return this; - } - - /** - * Get className - * @return className - **/ - @ApiModelProperty(example = "null", required = true, value = "") - public String getClassName() { - return className; - } - - public void setClassName(String className) { - this.className = className; - } - - public Dog color(String color) { - this.color = color; - return this; - } - - /** - * Get color - * @return color - **/ - @ApiModelProperty(example = "null", value = "") - public String getColor() { - return color; - } - - public void setColor(String color) { - this.color = color; - } - public Dog breed(String breed) { this.breed = breed; return this; @@ -110,15 +68,13 @@ public boolean equals(java.lang.Object o) { return false; } Dog dog = (Dog) o; - return Objects.equals(this.className, dog.className) && - Objects.equals(this.color, dog.color) && - Objects.equals(this.breed, dog.breed) && + return Objects.equals(this.breed, dog.breed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, color, breed, super.hashCode()); + return Objects.hash(breed, super.hashCode()); } @Override @@ -126,8 +82,6 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Dog {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/jersey2/docs/Cat.md b/samples/client/petstore/java/jersey2/docs/Cat.md index be6e56fa8ce..6e9f71ce7dd 100644 --- a/samples/client/petstore/java/jersey2/docs/Cat.md +++ b/samples/client/petstore/java/jersey2/docs/Cat.md @@ -4,8 +4,6 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**className** | **String** | | -**color** | **String** | | [optional] **declawed** | **Boolean** | | [optional] diff --git a/samples/client/petstore/java/jersey2/docs/Dog.md b/samples/client/petstore/java/jersey2/docs/Dog.md index 71a7dbe809e..ac7cea323ff 100644 --- a/samples/client/petstore/java/jersey2/docs/Dog.md +++ b/samples/client/petstore/java/jersey2/docs/Dog.md @@ -4,8 +4,6 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**className** | **String** | | -**color** | **String** | | [optional] **breed** | **String** | | [optional] diff --git a/samples/client/petstore/java/jersey2/pom.xml b/samples/client/petstore/java/jersey2/pom.xml index 0026cda2c47..c6efd0fa77d 100644 --- a/samples/client/petstore/java/jersey2/pom.xml +++ b/samples/client/petstore/java/jersey2/pom.xml @@ -173,7 +173,7 @@ - 1.5.8 + 1.5.9 2.22.2 2.7.5 2.9.4 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 047a47252f8..06f6d4d899a 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 @@ -84,8 +84,8 @@ public ApiClient() { // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap(); - authentications.put("api_key", new ApiKeyAuth("header", "api_key")); authentications.put("petstore_auth", new OAuth()); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java index d4a083ffe88..62924ba9bf8 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java @@ -9,8 +9,8 @@ import io.swagger.client.model.Client; import org.joda.time.LocalDate; -import org.joda.time.DateTime; import java.math.BigDecimal; +import org.joda.time.DateTime; import java.util.ArrayList; import java.util.HashMap; 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 ab85c4ac394..ad66598406d 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java @@ -8,8 +8,8 @@ import javax.ws.rs.core.GenericType; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.ModelApiResponse; +import java.io.File; import java.util.ArrayList; import java.util.HashMap; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Cat.java index f39b159f0b4..753aac88213 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Cat.java @@ -37,51 +37,9 @@ */ public class Cat extends Animal { - @JsonProperty("className") - private String className = null; - - @JsonProperty("color") - private String color = "red"; - @JsonProperty("declawed") private Boolean declawed = null; - public Cat className(String className) { - this.className = className; - return this; - } - - /** - * Get className - * @return className - **/ - @ApiModelProperty(example = "null", required = true, value = "") - public String getClassName() { - return className; - } - - public void setClassName(String className) { - this.className = className; - } - - public Cat color(String color) { - this.color = color; - return this; - } - - /** - * Get color - * @return color - **/ - @ApiModelProperty(example = "null", value = "") - public String getColor() { - return color; - } - - public void setColor(String color) { - this.color = color; - } - public Cat declawed(Boolean declawed) { this.declawed = declawed; return this; @@ -110,15 +68,13 @@ public boolean equals(java.lang.Object o) { return false; } Cat cat = (Cat) o; - return Objects.equals(this.className, cat.className) && - Objects.equals(this.color, cat.color) && - Objects.equals(this.declawed, cat.declawed) && + return Objects.equals(this.declawed, cat.declawed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, color, declawed, super.hashCode()); + return Objects.hash(declawed, super.hashCode()); } @Override @@ -126,8 +82,6 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Cat {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Dog.java index dbcd1a7207b..178ec87c893 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Dog.java @@ -37,51 +37,9 @@ */ public class Dog extends Animal { - @JsonProperty("className") - private String className = null; - - @JsonProperty("color") - private String color = "red"; - @JsonProperty("breed") private String breed = null; - public Dog className(String className) { - this.className = className; - return this; - } - - /** - * Get className - * @return className - **/ - @ApiModelProperty(example = "null", required = true, value = "") - public String getClassName() { - return className; - } - - public void setClassName(String className) { - this.className = className; - } - - public Dog color(String color) { - this.color = color; - return this; - } - - /** - * Get color - * @return color - **/ - @ApiModelProperty(example = "null", value = "") - public String getColor() { - return color; - } - - public void setColor(String color) { - this.color = color; - } - public Dog breed(String breed) { this.breed = breed; return this; @@ -110,15 +68,13 @@ public boolean equals(java.lang.Object o) { return false; } Dog dog = (Dog) o; - return Objects.equals(this.className, dog.className) && - Objects.equals(this.color, dog.color) && - Objects.equals(this.breed, dog.breed) && + return Objects.equals(this.breed, dog.breed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, color, breed, super.hashCode()); + return Objects.hash(breed, super.hashCode()); } @Override @@ -126,8 +82,6 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Dog {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/okhttp-gson/docs/Cat.md b/samples/client/petstore/java/okhttp-gson/docs/Cat.md index be6e56fa8ce..6e9f71ce7dd 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/Cat.md +++ b/samples/client/petstore/java/okhttp-gson/docs/Cat.md @@ -4,8 +4,6 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**className** | **String** | | -**color** | **String** | | [optional] **declawed** | **Boolean** | | [optional] diff --git a/samples/client/petstore/java/okhttp-gson/docs/Dog.md b/samples/client/petstore/java/okhttp-gson/docs/Dog.md index 71a7dbe809e..ac7cea323ff 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/Dog.md +++ b/samples/client/petstore/java/okhttp-gson/docs/Dog.md @@ -4,8 +4,6 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**className** | **String** | | -**color** | **String** | | [optional] **breed** | **String** | | [optional] 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 b7b04e3e4c5..c0630ba7ebc 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 @@ -173,8 +173,8 @@ public ApiClient() { // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap(); - authentications.put("api_key", new ApiKeyAuth("header", "api_key")); authentications.put("petstore_auth", new OAuth()); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java index c6e71e5f1b6..39e9bf37621 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java @@ -40,8 +40,8 @@ import io.swagger.client.model.Client; import org.joda.time.LocalDate; -import org.joda.time.DateTime; import java.math.BigDecimal; +import org.joda.time.DateTime; import java.lang.reflect.Type; import java.util.ArrayList; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java index 2039a8842c1..890e1a216f2 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java @@ -39,8 +39,8 @@ import java.io.IOException; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.ModelApiResponse; +import java.io.File; import java.lang.reflect.Type; import java.util.ArrayList; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Cat.java index 21ed0f4c26b..985342803a8 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Cat.java @@ -37,51 +37,9 @@ */ public class Cat extends Animal { - @SerializedName("className") - private String className = null; - - @SerializedName("color") - private String color = "red"; - @SerializedName("declawed") private Boolean declawed = null; - public Cat className(String className) { - this.className = className; - return this; - } - - /** - * Get className - * @return className - **/ - @ApiModelProperty(example = "null", required = true, value = "") - public String getClassName() { - return className; - } - - public void setClassName(String className) { - this.className = className; - } - - public Cat color(String color) { - this.color = color; - return this; - } - - /** - * Get color - * @return color - **/ - @ApiModelProperty(example = "null", value = "") - public String getColor() { - return color; - } - - public void setColor(String color) { - this.color = color; - } - public Cat declawed(Boolean declawed) { this.declawed = declawed; return this; @@ -110,15 +68,13 @@ public boolean equals(java.lang.Object o) { return false; } Cat cat = (Cat) o; - return Objects.equals(this.className, cat.className) && - Objects.equals(this.color, cat.color) && - Objects.equals(this.declawed, cat.declawed) && + return Objects.equals(this.declawed, cat.declawed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, color, declawed, super.hashCode()); + return Objects.hash(declawed, super.hashCode()); } @Override @@ -126,8 +82,6 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Cat {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Dog.java index 4ba5804553f..c59b3783d18 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Dog.java @@ -37,51 +37,9 @@ */ public class Dog extends Animal { - @SerializedName("className") - private String className = null; - - @SerializedName("color") - private String color = "red"; - @SerializedName("breed") private String breed = null; - public Dog className(String className) { - this.className = className; - return this; - } - - /** - * Get className - * @return className - **/ - @ApiModelProperty(example = "null", required = true, value = "") - public String getClassName() { - return className; - } - - public void setClassName(String className) { - this.className = className; - } - - public Dog color(String color) { - this.color = color; - return this; - } - - /** - * Get color - * @return color - **/ - @ApiModelProperty(example = "null", value = "") - public String getColor() { - return color; - } - - public void setColor(String color) { - this.color = color; - } - public Dog breed(String breed) { this.breed = breed; return this; @@ -110,15 +68,13 @@ public boolean equals(java.lang.Object o) { return false; } Dog dog = (Dog) o; - return Objects.equals(this.className, dog.className) && - Objects.equals(this.color, dog.color) && - Objects.equals(this.breed, dog.breed) && + return Objects.equals(this.breed, dog.breed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, color, breed, super.hashCode()); + return Objects.hash(breed, super.hashCode()); } @Override @@ -126,8 +82,6 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Dog {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/retrofit/pom.xml b/samples/client/petstore/java/retrofit/pom.xml index ee6ce62988f..2b5fdef2dbd 100644 --- a/samples/client/petstore/java/retrofit/pom.xml +++ b/samples/client/petstore/java/retrofit/pom.xml @@ -142,7 +142,7 @@ - 1.5.8 + 1.5.9 1.9.0 2.7.5 2.9.3 diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java index 08cfb4b3751..2363bf4c84f 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java @@ -54,10 +54,10 @@ public ApiClient(String[] authNames) { this(); for(String authName : authNames) { Interceptor auth; - if (authName == "api_key") { - auth = new ApiKeyAuth("header", "api_key"); - } else if (authName == "petstore_auth") { + if (authName == "petstore_auth") { auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); + } else if (authName == "api_key") { + auth = new ApiKeyAuth("header", "api_key"); } else { throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java index 076b9fc2ab1..0f1ce0f98ae 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java @@ -8,8 +8,8 @@ import io.swagger.client.model.Client; import org.joda.time.LocalDate; -import org.joda.time.DateTime; import java.math.BigDecimal; +import org.joda.time.DateTime; import java.util.ArrayList; import java.util.HashMap; diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java index 66ed6aea981..a019a4bf886 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java @@ -7,8 +7,8 @@ import retrofit.mime.*; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.ModelApiResponse; +import java.io.File; import java.util.ArrayList; import java.util.HashMap; diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Cat.java index 21ed0f4c26b..985342803a8 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Cat.java @@ -37,51 +37,9 @@ */ public class Cat extends Animal { - @SerializedName("className") - private String className = null; - - @SerializedName("color") - private String color = "red"; - @SerializedName("declawed") private Boolean declawed = null; - public Cat className(String className) { - this.className = className; - return this; - } - - /** - * Get className - * @return className - **/ - @ApiModelProperty(example = "null", required = true, value = "") - public String getClassName() { - return className; - } - - public void setClassName(String className) { - this.className = className; - } - - public Cat color(String color) { - this.color = color; - return this; - } - - /** - * Get color - * @return color - **/ - @ApiModelProperty(example = "null", value = "") - public String getColor() { - return color; - } - - public void setColor(String color) { - this.color = color; - } - public Cat declawed(Boolean declawed) { this.declawed = declawed; return this; @@ -110,15 +68,13 @@ public boolean equals(java.lang.Object o) { return false; } Cat cat = (Cat) o; - return Objects.equals(this.className, cat.className) && - Objects.equals(this.color, cat.color) && - Objects.equals(this.declawed, cat.declawed) && + return Objects.equals(this.declawed, cat.declawed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, color, declawed, super.hashCode()); + return Objects.hash(declawed, super.hashCode()); } @Override @@ -126,8 +82,6 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Cat {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Dog.java index 4ba5804553f..c59b3783d18 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Dog.java @@ -37,51 +37,9 @@ */ public class Dog extends Animal { - @SerializedName("className") - private String className = null; - - @SerializedName("color") - private String color = "red"; - @SerializedName("breed") private String breed = null; - public Dog className(String className) { - this.className = className; - return this; - } - - /** - * Get className - * @return className - **/ - @ApiModelProperty(example = "null", required = true, value = "") - public String getClassName() { - return className; - } - - public void setClassName(String className) { - this.className = className; - } - - public Dog color(String color) { - this.color = color; - return this; - } - - /** - * Get color - * @return color - **/ - @ApiModelProperty(example = "null", value = "") - public String getColor() { - return color; - } - - public void setColor(String color) { - this.color = color; - } - public Dog breed(String breed) { this.breed = breed; return this; @@ -110,15 +68,13 @@ public boolean equals(java.lang.Object o) { return false; } Dog dog = (Dog) o; - return Objects.equals(this.className, dog.className) && - Objects.equals(this.color, dog.color) && - Objects.equals(this.breed, dog.breed) && + return Objects.equals(this.breed, dog.breed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, color, breed, super.hashCode()); + return Objects.hash(breed, super.hashCode()); } @Override @@ -126,8 +82,6 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Dog {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/retrofit2/docs/Cat.md b/samples/client/petstore/java/retrofit2/docs/Cat.md index be6e56fa8ce..6e9f71ce7dd 100644 --- a/samples/client/petstore/java/retrofit2/docs/Cat.md +++ b/samples/client/petstore/java/retrofit2/docs/Cat.md @@ -4,8 +4,6 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**className** | **String** | | -**color** | **String** | | [optional] **declawed** | **Boolean** | | [optional] diff --git a/samples/client/petstore/java/retrofit2/docs/Dog.md b/samples/client/petstore/java/retrofit2/docs/Dog.md index 71a7dbe809e..ac7cea323ff 100644 --- a/samples/client/petstore/java/retrofit2/docs/Dog.md +++ b/samples/client/petstore/java/retrofit2/docs/Dog.md @@ -4,8 +4,6 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**className** | **String** | | -**color** | **String** | | [optional] **breed** | **String** | | [optional] diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java index 604861f6072..18fa73633f0 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java @@ -53,10 +53,10 @@ public ApiClient(String[] authNames) { this(); for(String authName : authNames) { Interceptor auth; - if (authName == "api_key") { - auth = new ApiKeyAuth("header", "api_key"); - } else if (authName == "petstore_auth") { + if (authName == "petstore_auth") { auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); + } else if (authName == "api_key") { + auth = new ApiKeyAuth("header", "api_key"); } else { throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java index 9bd1f7b9882..7d1543fbe4b 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java @@ -10,8 +10,8 @@ import io.swagger.client.model.Client; import org.joda.time.LocalDate; -import org.joda.time.DateTime; import java.math.BigDecimal; +import org.joda.time.DateTime; import java.util.ArrayList; import java.util.HashMap; diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java index a55cb2ee17f..a1ea00e368a 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java @@ -9,8 +9,8 @@ import okhttp3.RequestBody; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.ModelApiResponse; +import java.io.File; import java.util.ArrayList; import java.util.HashMap; diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Cat.java index 21ed0f4c26b..985342803a8 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Cat.java @@ -37,51 +37,9 @@ */ public class Cat extends Animal { - @SerializedName("className") - private String className = null; - - @SerializedName("color") - private String color = "red"; - @SerializedName("declawed") private Boolean declawed = null; - public Cat className(String className) { - this.className = className; - return this; - } - - /** - * Get className - * @return className - **/ - @ApiModelProperty(example = "null", required = true, value = "") - public String getClassName() { - return className; - } - - public void setClassName(String className) { - this.className = className; - } - - public Cat color(String color) { - this.color = color; - return this; - } - - /** - * Get color - * @return color - **/ - @ApiModelProperty(example = "null", value = "") - public String getColor() { - return color; - } - - public void setColor(String color) { - this.color = color; - } - public Cat declawed(Boolean declawed) { this.declawed = declawed; return this; @@ -110,15 +68,13 @@ public boolean equals(java.lang.Object o) { return false; } Cat cat = (Cat) o; - return Objects.equals(this.className, cat.className) && - Objects.equals(this.color, cat.color) && - Objects.equals(this.declawed, cat.declawed) && + return Objects.equals(this.declawed, cat.declawed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, color, declawed, super.hashCode()); + return Objects.hash(declawed, super.hashCode()); } @Override @@ -126,8 +82,6 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Cat {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Dog.java index 4ba5804553f..c59b3783d18 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Dog.java @@ -37,51 +37,9 @@ */ public class Dog extends Animal { - @SerializedName("className") - private String className = null; - - @SerializedName("color") - private String color = "red"; - @SerializedName("breed") private String breed = null; - public Dog className(String className) { - this.className = className; - return this; - } - - /** - * Get className - * @return className - **/ - @ApiModelProperty(example = "null", required = true, value = "") - public String getClassName() { - return className; - } - - public void setClassName(String className) { - this.className = className; - } - - public Dog color(String color) { - this.color = color; - return this; - } - - /** - * Get color - * @return color - **/ - @ApiModelProperty(example = "null", value = "") - public String getColor() { - return color; - } - - public void setColor(String color) { - this.color = color; - } - public Dog breed(String breed) { this.breed = breed; return this; @@ -110,15 +68,13 @@ public boolean equals(java.lang.Object o) { return false; } Dog dog = (Dog) o; - return Objects.equals(this.className, dog.className) && - Objects.equals(this.color, dog.color) && - Objects.equals(this.breed, dog.breed) && + return Objects.equals(this.breed, dog.breed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, color, breed, super.hashCode()); + return Objects.hash(breed, super.hashCode()); } @Override @@ -126,8 +82,6 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Dog {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/retrofit2rx/docs/Cat.md b/samples/client/petstore/java/retrofit2rx/docs/Cat.md index be6e56fa8ce..6e9f71ce7dd 100644 --- a/samples/client/petstore/java/retrofit2rx/docs/Cat.md +++ b/samples/client/petstore/java/retrofit2rx/docs/Cat.md @@ -4,8 +4,6 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**className** | **String** | | -**color** | **String** | | [optional] **declawed** | **Boolean** | | [optional] diff --git a/samples/client/petstore/java/retrofit2rx/docs/Dog.md b/samples/client/petstore/java/retrofit2rx/docs/Dog.md index 71a7dbe809e..ac7cea323ff 100644 --- a/samples/client/petstore/java/retrofit2rx/docs/Dog.md +++ b/samples/client/petstore/java/retrofit2rx/docs/Dog.md @@ -4,8 +4,6 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**className** | **String** | | -**color** | **String** | | [optional] **breed** | **String** | | [optional] diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java index 43eaeba87f4..997bbe1401e 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java @@ -53,10 +53,10 @@ public ApiClient(String[] authNames) { this(); for(String authName : authNames) { Interceptor auth; - if (authName == "api_key") { - auth = new ApiKeyAuth("header", "api_key"); - } else if (authName == "petstore_auth") { + if (authName == "petstore_auth") { auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); + } else if (authName == "api_key") { + auth = new ApiKeyAuth("header", "api_key"); } else { throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java index aadcdfdee76..8dd4da0e72c 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java @@ -10,8 +10,8 @@ import io.swagger.client.model.Client; import org.joda.time.LocalDate; -import org.joda.time.DateTime; import java.math.BigDecimal; +import org.joda.time.DateTime; import java.util.ArrayList; import java.util.HashMap; diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java index 94e2161d5a4..836de6f11fa 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java @@ -9,8 +9,8 @@ import okhttp3.RequestBody; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.ModelApiResponse; +import java.io.File; import java.util.ArrayList; import java.util.HashMap; diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Cat.java index 21ed0f4c26b..985342803a8 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Cat.java @@ -37,51 +37,9 @@ */ public class Cat extends Animal { - @SerializedName("className") - private String className = null; - - @SerializedName("color") - private String color = "red"; - @SerializedName("declawed") private Boolean declawed = null; - public Cat className(String className) { - this.className = className; - return this; - } - - /** - * Get className - * @return className - **/ - @ApiModelProperty(example = "null", required = true, value = "") - public String getClassName() { - return className; - } - - public void setClassName(String className) { - this.className = className; - } - - public Cat color(String color) { - this.color = color; - return this; - } - - /** - * Get color - * @return color - **/ - @ApiModelProperty(example = "null", value = "") - public String getColor() { - return color; - } - - public void setColor(String color) { - this.color = color; - } - public Cat declawed(Boolean declawed) { this.declawed = declawed; return this; @@ -110,15 +68,13 @@ public boolean equals(java.lang.Object o) { return false; } Cat cat = (Cat) o; - return Objects.equals(this.className, cat.className) && - Objects.equals(this.color, cat.color) && - Objects.equals(this.declawed, cat.declawed) && + return Objects.equals(this.declawed, cat.declawed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, color, declawed, super.hashCode()); + return Objects.hash(declawed, super.hashCode()); } @Override @@ -126,8 +82,6 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Cat {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Dog.java index 4ba5804553f..c59b3783d18 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Dog.java @@ -37,51 +37,9 @@ */ public class Dog extends Animal { - @SerializedName("className") - private String className = null; - - @SerializedName("color") - private String color = "red"; - @SerializedName("breed") private String breed = null; - public Dog className(String className) { - this.className = className; - return this; - } - - /** - * Get className - * @return className - **/ - @ApiModelProperty(example = "null", required = true, value = "") - public String getClassName() { - return className; - } - - public void setClassName(String className) { - this.className = className; - } - - public Dog color(String color) { - this.color = color; - return this; - } - - /** - * Get color - * @return color - **/ - @ApiModelProperty(example = "null", value = "") - public String getColor() { - return color; - } - - public void setColor(String color) { - this.color = color; - } - public Dog breed(String breed) { this.breed = breed; return this; @@ -110,15 +68,13 @@ public boolean equals(java.lang.Object o) { return false; } Dog dog = (Dog) o; - return Objects.equals(this.className, dog.className) && - Objects.equals(this.color, dog.color) && - Objects.equals(this.breed, dog.breed) && + return Objects.equals(this.breed, dog.breed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, color, breed, super.hashCode()); + return Objects.hash(breed, super.hashCode()); } @Override @@ -126,8 +82,6 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Dog {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); sb.append("}"); return sb.toString(); From 5e4e84ffe7642c2b15c6c3ffdadb03b766d3998d Mon Sep 17 00:00:00 2001 From: clasnake Date: Mon, 18 Jul 2016 23:58:03 +0800 Subject: [PATCH 122/470] Fix the scalatra petstore sample compile error. --- .../languages/ScalatraServerCodegen.java | 2 +- .../src/main/resources/scalatra/api.mustache | 5 +- .../src/main/scala/ScalatraBootstrap.scala | 4 +- .../scalatra/src/main/scala/ServletApp.scala | 24 +-- .../scala/com/wordnik/client/api/PetApi.scala | 172 +++++++----------- .../com/wordnik/client/api/StoreApi.scala | 55 +++--- .../com/wordnik/client/api/UserApi.scala | 124 ++++++------- .../wordnik/client/model/ApiResponse.scala | 9 +- .../com/wordnik/client/model/Category.scala | 7 +- .../com/wordnik/client/model/Order.scala | 14 +- .../scala/com/wordnik/client/model/Pet.scala | 15 +- .../scala/com/wordnik/client/model/Tag.scala | 7 +- .../scala/com/wordnik/client/model/User.scala | 20 +- 13 files changed, 189 insertions(+), 269 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java index b148a4da08f..63f43dfd383 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java @@ -42,7 +42,7 @@ public ScalatraServerCodegen() { "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") + "native", "super", "while", "type") ); defaultIncludes = new HashSet( diff --git a/modules/swagger-codegen/src/main/resources/scalatra/api.mustache b/modules/swagger-codegen/src/main/resources/scalatra/api.mustache index bd3b40b8fac..d7b36246a82 100644 --- a/modules/swagger-codegen/src/main/resources/scalatra/api.mustache +++ b/modules/swagger-codegen/src/main/resources/scalatra/api.mustache @@ -35,8 +35,7 @@ class {{classname}} (implicit val swagger: Swagger) extends ScalatraServlet val {{nickname}}Operation = (apiOperation[{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Unit{{/returnType}}]("{{nickname}}") summary "{{{summary}}}" - parameters({{#allParams}}{{>queryParam}}{{>pathParam}}{{>bodyParam}}{{>formParam}}{{#hasMore}}, - {{/hasMore}}{{/allParams}}) + parameters({{#allParams}}{{>queryParam}}{{>pathParam}}{{>bodyParam}}{{>formParam}}{{>headerParam}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) ) {{httpMethod}}("{{path}}",operation({{nickname}}Operation)) { @@ -44,7 +43,7 @@ class {{classname}} (implicit val swagger: Swagger) extends ScalatraServlet {{#isFile}}val {{paramName}} = fileParams("{{paramName}}"){{/isFile}} {{^isFile}}{{#isPathParam}} val {{paramName}} = params.getOrElse("{{paramName}}", halt(400)){{/isPathParam}} - {{>queryParamOperation}}{{>headerParamOperation}}{{>formParamMustache}}{{>bodyParam}} + {{>queryParamOperation}}{{>headerParamOperation}}{{>formParamMustache}}{{>bodyParamOperation}} {{/isFile}} println("{{paramName}}: " + {{paramName}}) {{/allParams}} diff --git a/samples/server/petstore/scalatra/src/main/scala/ScalatraBootstrap.scala b/samples/server/petstore/scalatra/src/main/scala/ScalatraBootstrap.scala index c78a1132148..445cb7783ab 100644 --- a/samples/server/petstore/scalatra/src/main/scala/ScalatraBootstrap.scala +++ b/samples/server/petstore/scalatra/src/main/scala/ScalatraBootstrap.scala @@ -24,7 +24,7 @@ import com.wordnik.client.api._ import akka.actor.ActorSystem -import io.swagger.app.{ResourcesApp, SwaggerApp} +import io.swagger.app.{ ResourcesApp, SwaggerApp } import javax.servlet.ServletContext import org.scalatra.LifeCycle @@ -37,7 +37,7 @@ class ScalatraBootstrap extends LifeCycle { context mount (new PetApi, "/Pet/*") context mount (new StoreApi, "/Store/*") context mount (new UserApi, "/User/*") - + context mount (new ResourcesApp, "/api-docs/*") } catch { case e: Throwable => e.printStackTrace() diff --git a/samples/server/petstore/scalatra/src/main/scala/ServletApp.scala b/samples/server/petstore/scalatra/src/main/scala/ServletApp.scala index 35c8a3a84d0..83b8e784c47 100644 --- a/samples/server/petstore/scalatra/src/main/scala/ServletApp.scala +++ b/samples/server/petstore/scalatra/src/main/scala/ServletApp.scala @@ -27,26 +27,26 @@ package io.swagger.app import _root_.akka.actor.ActorSystem import org.scalatra.swagger.{ ApiInfo, SwaggerWithAuth, Swagger } -import org.scalatra.swagger.{JacksonSwaggerBase, Swagger} +import org.scalatra.swagger.{ JacksonSwaggerBase, Swagger } import org.scalatra.ScalatraServlet -import org.json4s.{DefaultFormats, Formats} +import org.json4s.{ DefaultFormats, Formats } class ResourcesApp(implicit protected val system: ActorSystem, val swagger: SwaggerApp) - extends ScalatraServlet with JacksonSwaggerBase { + extends ScalatraServlet with JacksonSwaggerBase { before() { response.headers += ("Access-Control-Allow-Origin" -> "*") } protected def buildFullUrl(path: String) = if (path.startsWith("http")) path else { - val port = request.getServerPort - val h = request.getServerName - val prot = if (port == 443) "https" else "http" - val (proto, host) = if (port != 80 && port != 443) ("http", h+":"+port.toString) else (prot, h) - "%s://%s%s%s".format( - proto, - host, - request.getContextPath, - path) + val port = request.getServerPort + val h = request.getServerName + val prot = if (port == 443) "https" else "http" + val (proto, host) = if (port != 80 && port != 443) ("http", h + ":" + port.toString) else (prot, h) + "%s://%s%s%s".format( + proto, + host, + request.getContextPath, + path) } } diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala index 56288e3518f..9a7d43dd686 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala @@ -35,11 +35,11 @@ import org.scalatra.swagger._ import org.json4s._ import org.json4s.JsonDSL._ import org.scalatra.json.{ JValueResult, JacksonJsonSupport } -import org.scalatra.servlet.{FileUploadSupport, MultipartConfig, SizeConstraintExceededException} +import org.scalatra.servlet.{ FileUploadSupport, MultipartConfig, SizeConstraintExceededException } import scala.collection.JavaConverters._ -class PetApi (implicit val swagger: Swagger) extends ScalatraServlet +class PetApi(implicit val swagger: Swagger) extends ScalatraServlet with FileUploadSupport with JacksonJsonSupport with SwaggerSupport { @@ -52,167 +52,133 @@ class PetApi (implicit val swagger: Swagger) extends ScalatraServlet contentType = formats("json") response.headers += ("Access-Control-Allow-Origin" -> "*") } - val addPetOperation = (apiOperation[Unit]("addPet") - summary "Add a new pet to the store" - parameters(bodyParam[Pet]("body").description("")) + summary "Add a new pet to the store" + parameters (bodyParam[Pet]("body").description("")) ) - post("/pet",operation(addPetOperation)) { - - - bodyParam[Pet]("body").description("") + post("/pet", operation(addPetOperation)) { + + val body = parsedBody.extract[Pet] + println("body: " + body) } - - val deletePetOperation = (apiOperation[Unit]("deletePet") - summary "Deletes a pet" - parameters(pathParam[Long]("petId").description(""), - ) + summary "Deletes a pet" + parameters (pathParam[Long]("petId").description(""), headerParam[String]("apiKey").description("").optional) ) - delete("/pet/{petId}",operation(deletePetOperation)) { - - - val petId = params.getOrElse("petId", halt(400)) - + delete("/pet/{petId}", operation(deletePetOperation)) { + + val petId = params.getOrElse("petId", halt(400)) + println("petId: " + petId) - - - val apiKey = request.getHeader("apiKey") + + val apiKey = request.getHeader("apiKey") println("apiKey: " + apiKey) } - - val findPetsByStatusOperation = (apiOperation[List[Pet]]("findPetsByStatus") - summary "Finds Pets by status" - parameters(queryParam[List[String]]("status").description("")) + summary "Finds Pets by status" + parameters (queryParam[List[String]]("status").description("")) ) - get("/pet/findByStatus",operation(findPetsByStatusOperation)) { - - - val statusString = params.getAs[String]("status") - val status = if("csv".equals("default")) { - statusString match { - case Some(str) => str.split(",") - case None => List() - } + get("/pet/findByStatus", operation(findPetsByStatusOperation)) { + + val statusString = params.getAs[String]("status") + val status = if ("csv".equals("default")) { + statusString match { + case Some(str) => str.split(",") + case None => List() } - else - List() - + } else + List() println("status: " + status) } - - val findPetsByTagsOperation = (apiOperation[List[Pet]]("findPetsByTags") - summary "Finds Pets by tags" - parameters(queryParam[List[String]]("tags").description("")) + summary "Finds Pets by tags" + parameters (queryParam[List[String]]("tags").description("")) ) - get("/pet/findByTags",operation(findPetsByTagsOperation)) { - - - val tagsString = params.getAs[String]("tags") - val tags = if("csv".equals("default")) { - tagsString match { - case Some(str) => str.split(",") - case None => List() - } + get("/pet/findByTags", operation(findPetsByTagsOperation)) { + + val tagsString = params.getAs[String]("tags") + val tags = if ("csv".equals("default")) { + tagsString match { + case Some(str) => str.split(",") + case None => List() } - else - List() - + } else + List() println("tags: " + tags) } - - val getPetByIdOperation = (apiOperation[Pet]("getPetById") - summary "Find pet by ID" - parameters(pathParam[Long]("petId").description("")) + summary "Find pet by ID" + parameters (pathParam[Long]("petId").description("")) ) - get("/pet/{petId}",operation(getPetByIdOperation)) { - - - val petId = params.getOrElse("petId", halt(400)) - + get("/pet/{petId}", operation(getPetByIdOperation)) { + + val petId = params.getOrElse("petId", halt(400)) + println("petId: " + petId) } - - val updatePetOperation = (apiOperation[Unit]("updatePet") - summary "Update an existing pet" - parameters(bodyParam[Pet]("body").description("")) + summary "Update an existing pet" + parameters (bodyParam[Pet]("body").description("")) ) - put("/pet",operation(updatePetOperation)) { - - - bodyParam[Pet]("body").description("") + put("/pet", operation(updatePetOperation)) { + + val body = parsedBody.extract[Pet] + println("body: " + body) } - - val updatePetWithFormOperation = (apiOperation[Unit]("updatePetWithForm") - summary "Updates a pet in the store with form data" - parameters(pathParam[Long]("petId").description(""), - formParam[String]("name").description("").optional, - formParam[String]("status").description("").optional) + summary "Updates a pet in the store with form data" + parameters (pathParam[Long]("petId").description(""), formParam[String]("name").description("").optional, formParam[String]("status").description("").optional) ) - post("/pet/{petId}",operation(updatePetWithFormOperation)) { - - - val petId = params.getOrElse("petId", halt(400)) - + post("/pet/{petId}", operation(updatePetWithFormOperation)) { + + val petId = params.getOrElse("petId", halt(400)) + println("petId: " + petId) - - - val name = params.getAs[String]("name") + + val name = params.getAs[String]("name") println("name: " + name) - - - val status = params.getAs[String]("status") + + val status = params.getAs[String]("status") println("status: " + status) } - - val uploadFileOperation = (apiOperation[ApiResponse]("uploadFile") - summary "uploads an image" - parameters(pathParam[Long]("petId").description(""), - formParam[String]("additionalMetadata").description("").optional, - formParam[File]("file").description("").optional) + summary "uploads an image" + parameters (pathParam[Long]("petId").description(""), formParam[String]("additionalMetadata").description("").optional, formParam[File]("file").description("").optional) ) - post("/pet/{petId}/uploadImage",operation(uploadFileOperation)) { - - - val petId = params.getOrElse("petId", halt(400)) - + post("/pet/{petId}/uploadImage", operation(uploadFileOperation)) { + + val petId = params.getOrElse("petId", halt(400)) + println("petId: " + petId) - - - val additionalMetadata = params.getAs[String]("additionalMetadata") + + val additionalMetadata = params.getAs[String]("additionalMetadata") println("additionalMetadata: " + additionalMetadata) val file = fileParams("file") - println("file: " + file) + println("file: " + file) } } \ No newline at end of file diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/StoreApi.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/StoreApi.scala index b2a8df92b39..5427c63f88e 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/StoreApi.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/StoreApi.scala @@ -33,11 +33,11 @@ import org.scalatra.swagger._ import org.json4s._ import org.json4s.JsonDSL._ import org.scalatra.json.{ JValueResult, JacksonJsonSupport } -import org.scalatra.servlet.{FileUploadSupport, MultipartConfig, SizeConstraintExceededException} +import org.scalatra.servlet.{ FileUploadSupport, MultipartConfig, SizeConstraintExceededException } import scala.collection.JavaConverters._ -class StoreApi (implicit val swagger: Swagger) extends ScalatraServlet +class StoreApi(implicit val swagger: Swagger) extends ScalatraServlet with FileUploadSupport with JacksonJsonSupport with SwaggerSupport { @@ -50,57 +50,48 @@ class StoreApi (implicit val swagger: Swagger) extends ScalatraServlet contentType = formats("json") response.headers += ("Access-Control-Allow-Origin" -> "*") } - val deleteOrderOperation = (apiOperation[Unit]("deleteOrder") - summary "Delete purchase order by ID" - parameters(pathParam[String]("orderId").description("")) + summary "Delete purchase order by ID" + parameters (pathParam[String]("orderId").description("")) ) - delete("/store/order/{orderId}",operation(deleteOrderOperation)) { - - - val orderId = params.getOrElse("orderId", halt(400)) - + delete("/store/order/{orderId}", operation(deleteOrderOperation)) { + + val orderId = params.getOrElse("orderId", halt(400)) + println("orderId: " + orderId) } - - val getInventoryOperation = (apiOperation[Map[String, Int]]("getInventory") - summary "Returns pet inventories by status" - parameters() + summary "Returns pet inventories by status" + parameters () ) - get("/store/inventory",operation(getInventoryOperation)) { + get("/store/inventory", operation(getInventoryOperation)) { } - - val getOrderByIdOperation = (apiOperation[Order]("getOrderById") - summary "Find purchase order by ID" - parameters(pathParam[Long]("orderId").description("")) + summary "Find purchase order by ID" + parameters (pathParam[Long]("orderId").description("")) ) - get("/store/order/{orderId}",operation(getOrderByIdOperation)) { - - - val orderId = params.getOrElse("orderId", halt(400)) - + get("/store/order/{orderId}", operation(getOrderByIdOperation)) { + + val orderId = params.getOrElse("orderId", halt(400)) + println("orderId: " + orderId) } - - val placeOrderOperation = (apiOperation[Order]("placeOrder") - summary "Place an order for a pet" - parameters(bodyParam[Order]("body").description("")) + summary "Place an order for a pet" + parameters (bodyParam[Order]("body").description("")) ) - post("/store/order",operation(placeOrderOperation)) { - - - bodyParam[Order]("body").description("") + post("/store/order", operation(placeOrderOperation)) { + + val body = parsedBody.extract[Order] + println("body: " + body) } diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/UserApi.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/UserApi.scala index 7103ade331e..cff4a915b68 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/UserApi.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/UserApi.scala @@ -33,11 +33,11 @@ import org.scalatra.swagger._ import org.json4s._ import org.json4s.JsonDSL._ import org.scalatra.json.{ JValueResult, JacksonJsonSupport } -import org.scalatra.servlet.{FileUploadSupport, MultipartConfig, SizeConstraintExceededException} +import org.scalatra.servlet.{ FileUploadSupport, MultipartConfig, SizeConstraintExceededException } import scala.collection.JavaConverters._ -class UserApi (implicit val swagger: Swagger) extends ScalatraServlet +class UserApi(implicit val swagger: Swagger) extends ScalatraServlet with FileUploadSupport with JacksonJsonSupport with SwaggerSupport { @@ -50,126 +50,104 @@ class UserApi (implicit val swagger: Swagger) extends ScalatraServlet contentType = formats("json") response.headers += ("Access-Control-Allow-Origin" -> "*") } - val createUserOperation = (apiOperation[Unit]("createUser") - summary "Create user" - parameters(bodyParam[User]("body").description("")) + summary "Create user" + parameters (bodyParam[User]("body").description("")) ) - post("/user",operation(createUserOperation)) { - - - bodyParam[User]("body").description("") + post("/user", operation(createUserOperation)) { + + val body = parsedBody.extract[User] + println("body: " + body) } - - val createUsersWithArrayInputOperation = (apiOperation[Unit]("createUsersWithArrayInput") - summary "Creates list of users with given input array" - parameters(bodyParam[List[User]]("body").description("")) + summary "Creates list of users with given input array" + parameters (bodyParam[List[User]]("body").description("")) ) - post("/user/createWithArray",operation(createUsersWithArrayInputOperation)) { - - - bodyParam[List[User]]("body").description("") + post("/user/createWithArray", operation(createUsersWithArrayInputOperation)) { + + val body = parsedBody.extract[List[User]] + println("body: " + body) } - - val createUsersWithListInputOperation = (apiOperation[Unit]("createUsersWithListInput") - summary "Creates list of users with given input array" - parameters(bodyParam[List[User]]("body").description("")) + summary "Creates list of users with given input array" + parameters (bodyParam[List[User]]("body").description("")) ) - post("/user/createWithList",operation(createUsersWithListInputOperation)) { - - - bodyParam[List[User]]("body").description("") + post("/user/createWithList", operation(createUsersWithListInputOperation)) { + + val body = parsedBody.extract[List[User]] + println("body: " + body) } - - val deleteUserOperation = (apiOperation[Unit]("deleteUser") - summary "Delete user" - parameters(pathParam[String]("username").description("")) + summary "Delete user" + parameters (pathParam[String]("username").description("")) ) - delete("/user/{username}",operation(deleteUserOperation)) { - - - val username = params.getOrElse("username", halt(400)) - + delete("/user/{username}", operation(deleteUserOperation)) { + + val username = params.getOrElse("username", halt(400)) + println("username: " + username) } - - val getUserByNameOperation = (apiOperation[User]("getUserByName") - summary "Get user by user name" - parameters(pathParam[String]("username").description("")) + summary "Get user by user name" + parameters (pathParam[String]("username").description("")) ) - get("/user/{username}",operation(getUserByNameOperation)) { - - - val username = params.getOrElse("username", halt(400)) - + get("/user/{username}", operation(getUserByNameOperation)) { + + val username = params.getOrElse("username", halt(400)) + println("username: " + username) } - - val loginUserOperation = (apiOperation[String]("loginUser") - summary "Logs user into the system" - parameters(queryParam[String]("username").description(""), - queryParam[String]("password").description("")) + summary "Logs user into the system" + parameters (queryParam[String]("username").description(""), queryParam[String]("password").description("")) ) - get("/user/login",operation(loginUserOperation)) { - - - val username = params.getAs[String]("username") + get("/user/login", operation(loginUserOperation)) { + + val username = params.getAs[String]("username") println("username: " + username) - - - val password = params.getAs[String]("password") + + val password = params.getAs[String]("password") println("password: " + password) } - - val logoutUserOperation = (apiOperation[Unit]("logoutUser") - summary "Logs out current logged in user session" - parameters() + summary "Logs out current logged in user session" + parameters () ) - get("/user/logout",operation(logoutUserOperation)) { + get("/user/logout", operation(logoutUserOperation)) { } - - val updateUserOperation = (apiOperation[Unit]("updateUser") - summary "Updated user" - parameters(pathParam[String]("username").description(""), - bodyParam[User]("body").description("")) + summary "Updated user" + parameters (pathParam[String]("username").description(""), bodyParam[User]("body").description("")) ) - put("/user/{username}",operation(updateUserOperation)) { - - - val username = params.getOrElse("username", halt(400)) - + put("/user/{username}", operation(updateUserOperation)) { + + val username = params.getOrElse("username", halt(400)) + println("username: " + username) - - - bodyParam[User]("body").description("") + + val body = parsedBody.extract[User] + println("body: " + body) } diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/ApiResponse.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/ApiResponse.scala index 90396f5de75..5388c99eca8 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/ApiResponse.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/ApiResponse.scala @@ -24,10 +24,7 @@ package com.wordnik.client.model - - -case class ApiResponse ( +case class ApiResponse( code: Option[Int], -type: Option[String], -message: Option[String] -) + _type: Option[String], + message: Option[String]) diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Category.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Category.scala index 4bdadfbbe5c..0173c137595 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Category.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Category.scala @@ -24,9 +24,6 @@ package com.wordnik.client.model - - -case class Category ( +case class Category( id: Option[Long], -name: Option[String] -) + name: Option[String]) diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Order.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Order.scala index 6f399b0d1c3..eda2b851860 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Order.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Order.scala @@ -26,12 +26,10 @@ package com.wordnik.client.model import java.util.Date - -case class Order ( +case class Order( id: Option[Long], -petId: Option[Long], -quantity: Option[Int], -shipDate: Option[Date], -status: Option[String], // Order Status -complete: Option[Boolean] -) + petId: Option[Long], + quantity: Option[Int], + shipDate: Option[Date], + status: Option[String], // Order Status + complete: Option[Boolean]) diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Pet.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Pet.scala index 01aa08e73ce..d9f123eafc3 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Pet.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Pet.scala @@ -27,12 +27,11 @@ package com.wordnik.client.model import com.wordnik.client.model.Category import com.wordnik.client.model.Tag - -case class Pet ( +case class Pet( id: Option[Long], -category: Option[Category], -name: String, -photoUrls: List[String], -tags: Option[List[Tag]], -status: Option[String] // pet status in the store -) + category: Option[Category], + name: String, + photoUrls: List[String], + tags: Option[List[Tag]], + status: Option[String] // pet status in the store + ) diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Tag.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Tag.scala index a3d34e8d557..1b6ccd3e2ca 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Tag.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Tag.scala @@ -24,9 +24,6 @@ package com.wordnik.client.model - - -case class Tag ( +case class Tag( id: Option[Long], -name: Option[String] -) + name: Option[String]) diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/User.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/User.scala index ff792d91371..5115e77c528 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/User.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/User.scala @@ -24,15 +24,13 @@ package com.wordnik.client.model - - -case class User ( +case class User( id: Option[Long], -username: Option[String], -firstName: Option[String], -lastName: Option[String], -email: Option[String], -password: Option[String], -phone: Option[String], -userStatus: Option[Int] // User Status -) + username: Option[String], + firstName: Option[String], + lastName: Option[String], + email: Option[String], + password: Option[String], + phone: Option[String], + userStatus: Option[Int] // User Status + ) From 34d3a5e8d04a164bb5a11be0596eaf88a436ebbd Mon Sep 17 00:00:00 2001 From: cbornet Date: Mon, 18 Jul 2016 23:21:12 +0200 Subject: [PATCH 123/470] make jersey tests wait that jetty is closed before terminating --- .../src/main/resources/JavaJaxRS/libraries/jersey1/pom.mustache | 1 + .../swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache | 1 + samples/server/petstore/jaxrs/jersey1/pom.xml | 1 + samples/server/petstore/jaxrs/jersey2/pom.xml | 1 + 4 files changed, 4 insertions(+) diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/pom.mustache index c66f8823c4d..d21444dda26 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/pom.mustache @@ -36,6 +36,7 @@ target/${project.artifactId}-${project.version} 8079 stopit + 10 {{serverPort}} 60000 diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache index 0de50ccd1f9..d764934cf77 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache @@ -36,6 +36,7 @@ target/${project.artifactId}-${project.version} 8079 stopit + 10 {{serverPort}} 60000 diff --git a/samples/server/petstore/jaxrs/jersey1/pom.xml b/samples/server/petstore/jaxrs/jersey1/pom.xml index 59fe2067e6a..c8dd08376a7 100644 --- a/samples/server/petstore/jaxrs/jersey1/pom.xml +++ b/samples/server/petstore/jaxrs/jersey1/pom.xml @@ -36,6 +36,7 @@ target/${project.artifactId}-${project.version} 8079 stopit + 10 8080 60000 diff --git a/samples/server/petstore/jaxrs/jersey2/pom.xml b/samples/server/petstore/jaxrs/jersey2/pom.xml index 9574bbfbb05..bc2bc84665d 100644 --- a/samples/server/petstore/jaxrs/jersey2/pom.xml +++ b/samples/server/petstore/jaxrs/jersey2/pom.xml @@ -36,6 +36,7 @@ target/${project.artifactId}-${project.version} 8079 stopit + 10 8080 60000 From be65a26db0341a657e3be6b3ae6b024d5338a9c1 Mon Sep 17 00:00:00 2001 From: Jason Gavris Date: Sun, 17 Jul 2016 09:36:44 -0400 Subject: [PATCH 124/470] [Python] Fix flaky test with id collisions --- .../petstore/python/tests/test_api_exception.py | 11 ++++------- .../client/petstore/python/tests/test_pet_api.py | 14 +++++--------- samples/client/petstore/python/tests/util.py | 5 +++++ 3 files changed, 14 insertions(+), 16 deletions(-) create mode 100644 samples/client/petstore/python/tests/util.py diff --git a/samples/client/petstore/python/tests/test_api_exception.py b/samples/client/petstore/python/tests/test_api_exception.py index 8df2b681f01..d1f9dbaa6f2 100644 --- a/samples/client/petstore/python/tests/test_api_exception.py +++ b/samples/client/petstore/python/tests/test_api_exception.py @@ -9,12 +9,12 @@ import os import sys -import time import unittest import petstore_api from petstore_api.rest import ApiException +from .util import id_gen class ApiExceptionTests(unittest.TestCase): @@ -25,22 +25,19 @@ def setUp(self): def setUpModels(self): self.category = petstore_api.Category() - self.category.id = int(time.time()) + self.category.id = id_gen() self.category.name = "dog" self.tag = petstore_api.Tag() - self.tag.id = int(time.time()) + self.tag.id = id_gen() self.tag.name = "blank" self.pet = petstore_api.Pet() - self.pet.id = int(time.time()) + self.pet.id = id_gen() self.pet.name = "hello kity" self.pet.photo_urls = ["http://foo.bar.com/1", "http://foo.bar.com/2"] self.pet.status = "sold" self.pet.category = self.category self.pet.tags = [self.tag] - def tearDown(self): - time.sleep(1) - def test_404_error(self): self.pet_api.add_pet(body=self.pet) self.pet_api.delete_pet(pet_id=self.pet.id) diff --git a/samples/client/petstore/python/tests/test_pet_api.py b/samples/client/petstore/python/tests/test_pet_api.py index e2ed0ec267c..2f48ce8d335 100644 --- a/samples/client/petstore/python/tests/test_pet_api.py +++ b/samples/client/petstore/python/tests/test_pet_api.py @@ -8,14 +8,14 @@ """ import os -import time import unittest import petstore_api from petstore_api.rest import ApiException -HOST = 'http://petstore.swagger.io/v2' +from .util import id_gen +HOST = 'http://petstore.swagger.io/v2' class PetApiTests(unittest.TestCase): @@ -25,19 +25,15 @@ def setUp(self): self.setUpModels() self.setUpFiles() - def tearDown(self): - # sleep 1 sec between two every 2 tests - time.sleep(1) - def setUpModels(self): self.category = petstore_api.Category() - self.category.id = int(time.time()) + self.category.id = id_gen() self.category.name = "dog" self.tag = petstore_api.Tag() - self.tag.id = int(time.time()) + self.tag.id = id_gen() self.tag.name = "swagger-codegen-python-pet-tag" self.pet = petstore_api.Pet() - self.pet.id = int(time.time()) + self.pet.id = id_gen() self.pet.name = "hello kity" self.pet.photo_urls = ["http://foo.bar.com/1", "http://foo.bar.com/2"] self.pet.status = "sold" diff --git a/samples/client/petstore/python/tests/util.py b/samples/client/petstore/python/tests/util.py new file mode 100644 index 00000000000..6aeea16f63e --- /dev/null +++ b/samples/client/petstore/python/tests/util.py @@ -0,0 +1,5 @@ +import random + +def id_gen(bits=32): + """ Returns a n-bit randomly generated int """ + return int(random.getrandbits(bits)) From 87b79e5946dc481441f779513490c496fc147714 Mon Sep 17 00:00:00 2001 From: Jason Gavris Date: Thu, 14 Jul 2016 16:49:56 -0400 Subject: [PATCH 125/470] [Swift] Expose NSProgress to RequestBuilder --- .../src/main/resources/swift/APIs.mustache | 3 +++ .../swift/AlamofireImplementations.mustache | 13 ++++++++++--- .../PetstoreClient/Classes/Swaggers/APIs.swift | 3 +++ .../Swaggers/AlamofireImplementations.swift | 13 ++++++++++--- .../SwaggerClientTests/StoreAPITests.swift | 16 ++++++++++++++++ 5 files changed, 42 insertions(+), 6 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/swift/APIs.mustache b/modules/swagger-codegen/src/main/resources/swift/APIs.mustache index 5a9f1f7a278..9ba749ab69e 100644 --- a/modules/swagger-codegen/src/main/resources/swift/APIs.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/APIs.mustache @@ -37,6 +37,9 @@ public class RequestBuilder { let method: String let URLString: String + /// Optional block to obtain a reference to the request's progress instance when available. + public var onProgressReady: ((NSProgress) -> ())? + required public init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool) { self.method = method self.URLString = URLString diff --git a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache index 2faa0a6f24d..0b153ad17d2 100644 --- a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache @@ -57,15 +57,22 @@ class AlamofireRequestBuilder: RequestBuilder { encodingMemoryThreshold: Manager.MultipartFormDataEncodingMemoryThreshold, encodingCompletion: { encodingResult in switch encodingResult { - case .Success(let upload, _, _): - self.processRequest(upload, managerId, completion) + case .Success(let uploadRequest, _, _): + if let onProgressReady = self.onProgressReady { + onProgressReady(uploadRequest.progress) + } + self.processRequest(uploadRequest, managerId, completion) case .Failure(let encodingError): completion(response: nil, error: encodingError) } } ) } else { - processRequest(manager.request(xMethod!, URLString, parameters: parameters, encoding: encoding), managerId, completion) + let request = manager.request(xMethod!, URLString, parameters: parameters, encoding: encoding) + if let onProgressReady = self.onProgressReady { + onProgressReady(request.progress) + } + processRequest(request, managerId, completion) } } diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs.swift index 96eead0d8dd..ab0ea147e4f 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs.swift @@ -37,6 +37,9 @@ public class RequestBuilder { let method: String let URLString: String + /// Optional block to obtain a reference to the request's progress instance when available. + public var onProgressReady: ((NSProgress) -> ())? + required public init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool) { self.method = method self.URLString = URLString diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index 2faa0a6f24d..0b153ad17d2 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -57,15 +57,22 @@ class AlamofireRequestBuilder: RequestBuilder { encodingMemoryThreshold: Manager.MultipartFormDataEncodingMemoryThreshold, encodingCompletion: { encodingResult in switch encodingResult { - case .Success(let upload, _, _): - self.processRequest(upload, managerId, completion) + case .Success(let uploadRequest, _, _): + if let onProgressReady = self.onProgressReady { + onProgressReady(uploadRequest.progress) + } + self.processRequest(uploadRequest, managerId, completion) case .Failure(let encodingError): completion(response: nil, error: encodingError) } } ) } else { - processRequest(manager.request(xMethod!, URLString, parameters: parameters, encoding: encoding), managerId, completion) + let request = manager.request(xMethod!, URLString, parameters: parameters, encoding: encoding) + if let onProgressReady = self.onProgressReady { + onProgressReady(request.progress) + } + processRequest(request, managerId, completion) } } diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift index 679285394d0..98ed9e07957 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift @@ -90,6 +90,22 @@ class StoreAPITests: XCTestCase { self.waitForExpectationsWithTimeout(testTimeout, handler: nil) } + func testDownloadProgress() { + let responseExpectation = self.expectationWithDescription("obtain response") + let progressExpectation = self.expectationWithDescription("obtain progress") + let requestBuilder = StoreAPI.getOrderByIdWithRequestBuilder(orderId: "1000") + + requestBuilder.onProgressReady = { (progress) in + progressExpectation.fulfill() + } + + requestBuilder.execute { (response, error) in + responseExpectation.fulfill() + } + + self.waitForExpectationsWithTimeout(testTimeout, handler: nil) + } + } private extension NSDate { From cd79ae1ab4a595eb391b5111d437948da7ffd152 Mon Sep 17 00:00:00 2001 From: Jason Gavris Date: Fri, 1 Jul 2016 10:25:36 -0400 Subject: [PATCH 126/470] [Swift] Add support for NSUUID --- .../swagger/codegen/languages/SwiftCodegen.java | 2 ++ .../src/main/resources/swift/Extensions.mustache | 6 ++++++ .../src/main/resources/swift/Models.mustache | 3 +++ .../io/swagger/codegen/swift/SwiftModelTest.java | 15 +++++++++++++-- .../Classes/Swaggers/Extensions.swift | 6 ++++++ .../PetstoreClient/Classes/Swaggers/Models.swift | 3 +++ 6 files changed, 33 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java index f23cf72d502..214eca994ef 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java @@ -88,6 +88,7 @@ public SwiftCodegen() { Arrays.asList( "NSDate", "NSURL", // for file + "NSUUID", "Array", "Dictionary", "Set", @@ -131,6 +132,7 @@ public SwiftCodegen() { // mapped to String as a workaround typeMapping.put("binary", "String"); typeMapping.put("ByteArray", "String"); + typeMapping.put("UUID", "NSUUID"); importMapping = new HashMap(); diff --git a/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache b/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache index fce415ddcbf..7fbfa50b28d 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache @@ -73,6 +73,12 @@ extension NSDate: JSONEncodable { } } +extension NSUUID: JSONEncodable { + func encodeToJSON() -> AnyObject { + return self.UUIDString + } +} + {{#usePromiseKit}}extension RequestBuilder { public func execute() -> Promise> { let deferred = Promise>.pendingPromise() diff --git a/modules/swagger-codegen/src/main/resources/swift/Models.mustache b/modules/swagger-codegen/src/main/resources/swift/Models.mustache index 17b9c2cd276..4e858493e20 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Models.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Models.mustache @@ -62,6 +62,9 @@ class Decoders { if T.self is Int64.Type && source is NSNumber { return source.longLongValue as! T; } + if T.self is NSUUID.Type && source is String { + return NSUUID(UUIDString: source as! String) as! T + } if source is T { return source as! T } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftModelTest.java index eb2c18a40db..c925535403a 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftModelTest.java @@ -18,6 +18,7 @@ public void simpleModelTest() { .property("id", new LongProperty()) .property("name", new StringProperty()) .property("createdAt", new DateTimeProperty()) + .property("uuid", new UUIDProperty()) .required("id") .required("name") .discriminator("test"); @@ -27,7 +28,7 @@ public void simpleModelTest() { Assert.assertEquals(cm.name, "sample"); Assert.assertEquals(cm.classname, "Sample"); Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 3); + Assert.assertEquals(cm.vars.size(), 4); Assert.assertEquals(cm.discriminator,"test"); final CodegenProperty property1 = cm.vars.get(0); @@ -58,9 +59,19 @@ public void simpleModelTest() { Assert.assertEquals(property3.name, "createdAt"); Assert.assertNull(property3.defaultValue); Assert.assertEquals(property3.baseType, "NSDate"); - Assert.assertNull(property3.hasMore); + Assert.assertTrue(property3.hasMore); Assert.assertNull(property3.required); Assert.assertTrue(property3.isNotContainer); + + final CodegenProperty property4 = cm.vars.get(3); + Assert.assertEquals(property4.baseName, "uuid"); + Assert.assertEquals(property4.datatype, "NSUUID"); + Assert.assertEquals(property4.name, "uuid"); + Assert.assertNull(property4.defaultValue); + Assert.assertEquals(property4.baseType, "NSUUID"); + Assert.assertNull(property4.hasMore); + Assert.assertNull(property4.required); + Assert.assertTrue(property4.isNotContainer); } } diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Extensions.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Extensions.swift index 786e3218c80..f93d41600f4 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Extensions.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Extensions.swift @@ -72,4 +72,10 @@ extension NSDate: JSONEncodable { } } +extension NSUUID: JSONEncodable { + func encodeToJSON() -> AnyObject { + return self.UUIDString + } +} + diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models.swift index cad60a236a7..15a835a974e 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models.swift @@ -62,6 +62,9 @@ class Decoders { if T.self is Int64.Type && source is NSNumber { return source.longLongValue as! T; } + if T.self is NSUUID.Type && source is String { + return NSUUID(UUIDString: source as! String) as! T + } if source is T { return source as! T } From d780e3a5f559f9a9b49625688b9158906f32e857 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 19 Jul 2016 15:16:07 +0800 Subject: [PATCH 127/470] fix #3400 (ruby minLenght, maxLength) --- .../swagger-codegen/src/main/resources/ruby/api.mustache | 8 ++++---- .../main/resources/ruby/partial_model_generic.mustache | 8 ++++---- samples/client/petstore/ruby/README.md | 2 +- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index 7b333428899..53e455649cd 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -56,18 +56,18 @@ module {{moduleName}} {{/isEnum}} {{/required}} {{#hasValidation}} - {{#minLength}} + {{#maxLength}} if {{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}}.to_s.length > {{{maxLength}}} fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, the character length must be smaller than or equal to {{{maxLength}}}.' end - {{/minLength}} - {{#maxLength}} + {{/maxLength}} + {{#minLength}} if {{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}}.to_s.length < {{{minLength}}} fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, the character length must be great than or equal to {{{minLength}}}.' end - {{/maxLength}} + {{/minLength}} {{#maximum}} if {{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}} > {{{maximum}}} fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, must be smaller than or equal to {{{maximum}}}.' diff --git a/modules/swagger-codegen/src/main/resources/ruby/partial_model_generic.mustache b/modules/swagger-codegen/src/main/resources/ruby/partial_model_generic.mustache index 95c818a5ac4..690b1534e96 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/partial_model_generic.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/partial_model_generic.mustache @@ -82,18 +82,18 @@ fail ArgumentError, "{{{name}}} cannot be nil" end - {{#minLength}} + {{#maxLength}} if @{{{name}}}.to_s.length > {{{maxLength}}} invalid_properties.push("invalid value for '{{{name}}}', the character length must be smaller than or equal to {{{maxLength}}}.") end - {{/minLength}} - {{#maxLength}} + {{/maxLength}} + {{#minLength}} if @{{{name}}}.to_s.length < {{{minLength}}} invalid_properties.push("invalid value for '{{{name}}}', the character length must be great than or equal to {{{minLength}}}.") end - {{/maxLength}} + {{/minLength}} {{#maximum}} if @{{{name}}} > {{{maximum}}} invalid_properties.push("invalid value for '{{{name}}}', must be smaller than or equal to {{{maximum}}}.") diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index 56418b4412b..28228a68b4c 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -8,7 +8,7 @@ This SDK is automatically generated by the [Swagger Codegen](https://github.com/ - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-07-14T16:12:28.313+08:00 +- Build date: 2016-07-19T15:06:57.795+08:00 - Build package: class io.swagger.codegen.languages.RubyClientCodegen ## Installation From 37404909bfb241d6c17782780941d9fb46413369 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 19 Jul 2016 16:55:39 +0800 Subject: [PATCH 128/470] to set a default description if none is provided --- .../io/swagger/codegen/DefaultGenerator.java | 12 +++++-- .../client/petstore/objc/core-data/README.md | 18 +++++----- .../core-data/SwaggerClient/Api/SWGPetApi.m | 2 +- .../SwaggerClient/Core/SWGConfiguration.m | 14 ++++---- .../SwaggerClient.xcodeproj/project.pbxproj | 36 +++++++++---------- .../client/petstore/objc/default/README.md | 2 +- .../SwaggerClient.xcodeproj/project.pbxproj | 36 +++++++++---------- 7 files changed, 63 insertions(+), 57 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index 20b6acca907..0851a2e6f40 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -17,7 +17,7 @@ import java.io.*; import java.util.*; -import static org.apache.commons.lang3.StringUtils.isNotEmpty; +import org.apache.commons.lang3.StringUtils; public class DefaultGenerator extends AbstractGenerator implements Generator { protected Logger LOGGER = LoggerFactory.getLogger(DefaultGenerator.class); @@ -149,10 +149,16 @@ public List generate() { if (info.getVersion() != null) { config.additionalProperties().put("appVersion", config.escapeText(info.getVersion())); } - if (info.getDescription() != null) { + + if (StringUtils.isEmpty(info.getDescription())) { + // set a default description if none if provided + config.additionalProperties().put("appDescription", + "No descripton provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)"); + } else { config.additionalProperties().put("appDescription", config.escapeText(info.getDescription())); } + if (info.getContact() != null) { Contact contact = info.getContact(); config.additionalProperties().put("infoUrl", config.escapeText(contact.getUrl())); @@ -522,7 +528,7 @@ public int compare(CodegenOperation one, CodegenOperation another) { for (SupportingFile support : config.supportingFiles()) { try { String outputFolder = config.outputFolder(); - if (isNotEmpty(support.folder)) { + if (StringUtils.isNotEmpty(support.folder)) { outputFolder += File.separator + support.folder; } File of = new File(outputFolder); diff --git a/samples/client/petstore/objc/core-data/README.md b/samples/client/petstore/objc/core-data/README.md index 151ffe96225..3fe81114d77 100644 --- a/samples/client/petstore/objc/core-data/README.md +++ b/samples/client/petstore/objc/core-data/README.md @@ -6,7 +6,7 @@ This ObjC package is automatically generated by the [Swagger Codegen](https://gi - API version: 1.0.0 - Package version: -- Build date: 2016-06-16T11:33:34.619+02:00 +- Build date: 2016-07-19T16:53:26.476+08:00 - Build package: class io.swagger.codegen.languages.ObjcClientCodegen ## Requirements @@ -74,9 +74,9 @@ SWGPet* *body = [[SWGPet alloc] init]; // Pet object that needs to be added to t SWGPetApi *apiInstance = [[SWGPetApi alloc] init]; - // Add a new pet to the store +// Add a new pet to the store [apiInstance addPetWithBody:body - completionHandler: ^(NSError* error)) { + completionHandler: ^(NSError* error) { if (error) { NSLog(@"Error: %@", error); } @@ -124,6 +124,12 @@ Class | Method | HTTP request | Description ## Documentation For Authorization +## api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + ## petstore_auth - **Type**: OAuth @@ -133,12 +139,6 @@ Class | Method | HTTP request | Description - **write:pets**: modify pets in your account - **read:pets**: read your pets -## api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - ## Author diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.m b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.m index 409f5b86655..e35421fc520 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.m +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.m @@ -376,7 +376,7 @@ -(NSNumber*) getPetByIdWithPetId: (NSNumber*) petId NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting - NSArray *authSettings = @[@"petstore_auth", @"api_key"]; + NSArray *authSettings = @[@"api_key", @"petstore_auth"]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGConfiguration.m b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGConfiguration.m index 24172638bba..b21290068a1 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGConfiguration.m +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGConfiguration.m @@ -110,13 +110,6 @@ - (NSDictionary *) apiKeyPrefix { - (NSDictionary *) authSettings { return @{ - @"petstore_auth": - @{ - @"type": @"oauth", - @"in": @"header", - @"key": @"Authorization", - @"value": [self getAccessToken] - }, @"api_key": @{ @"type": @"api_key", @@ -124,6 +117,13 @@ - (NSDictionary *) authSettings { @"key": @"api_key", @"value": [self getApiKeyWithPrefix:@"api_key"] }, + @"petstore_auth": + @{ + @"type": @"oauth", + @"in": @"header", + @"key": @"Authorization", + @"value": [self getAccessToken] + }, }; } diff --git a/samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index b69c907b161..68c3e696436 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -214,12 +214,12 @@ isa = PBXNativeTarget; buildConfigurationList = 6003F5BF195388D20070C39A /* Build configuration list for PBXNativeTarget "SwaggerClient_Example" */; buildPhases = ( - 799E7E29D924C30424DFBA28 /* Check Pods Manifest.lock */, + 799E7E29D924C30424DFBA28 /* 📦 Check Pods Manifest.lock */, 6003F586195388D20070C39A /* Sources */, 6003F587195388D20070C39A /* Frameworks */, 6003F588195388D20070C39A /* Resources */, - 429AF5C69E165ED75311B4B0 /* Copy Pods Resources */, - 183E54C09C54DAEB54B2546F /* Embed Pods Frameworks */, + 429AF5C69E165ED75311B4B0 /* 📦 Copy Pods Resources */, + 183E54C09C54DAEB54B2546F /* 📦 Embed Pods Frameworks */, ); buildRules = ( ); @@ -234,12 +234,12 @@ isa = PBXNativeTarget; buildConfigurationList = 6003F5C2195388D20070C39A /* Build configuration list for PBXNativeTarget "SwaggerClient_Tests" */; buildPhases = ( - 7B069562A9F91E498732474F /* Check Pods Manifest.lock */, + 7B069562A9F91E498732474F /* 📦 Check Pods Manifest.lock */, 6003F5AA195388D20070C39A /* Sources */, 6003F5AB195388D20070C39A /* Frameworks */, 6003F5AC195388D20070C39A /* Resources */, - E337D7E459CCFFDF27046FFC /* Copy Pods Resources */, - 111D7956304BD6E860AA8709 /* Embed Pods Frameworks */, + E337D7E459CCFFDF27046FFC /* 📦 Copy Pods Resources */, + 111D7956304BD6E860AA8709 /* 📦 Embed Pods Frameworks */, ); buildRules = ( ); @@ -303,14 +303,14 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ - 111D7956304BD6E860AA8709 /* Embed Pods Frameworks */ = { + 111D7956304BD6E860AA8709 /* 📦 Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Embed Pods Frameworks"; + name = "📦 Embed Pods Frameworks"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -318,14 +318,14 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Tests/Pods-SwaggerClient_Tests-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; - 183E54C09C54DAEB54B2546F /* Embed Pods Frameworks */ = { + 183E54C09C54DAEB54B2546F /* 📦 Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Embed Pods Frameworks"; + name = "📦 Embed Pods Frameworks"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -333,14 +333,14 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Example/Pods-SwaggerClient_Example-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; - 429AF5C69E165ED75311B4B0 /* Copy Pods Resources */ = { + 429AF5C69E165ED75311B4B0 /* 📦 Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Copy Pods Resources"; + name = "📦 Copy Pods Resources"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -348,14 +348,14 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Example/Pods-SwaggerClient_Example-resources.sh\"\n"; showEnvVarsInLog = 0; }; - 799E7E29D924C30424DFBA28 /* Check Pods Manifest.lock */ = { + 799E7E29D924C30424DFBA28 /* 📦 Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Check Pods Manifest.lock"; + name = "📦 Check Pods Manifest.lock"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -363,14 +363,14 @@ shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; showEnvVarsInLog = 0; }; - 7B069562A9F91E498732474F /* Check Pods Manifest.lock */ = { + 7B069562A9F91E498732474F /* 📦 Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Check Pods Manifest.lock"; + name = "📦 Check Pods Manifest.lock"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -378,14 +378,14 @@ shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; showEnvVarsInLog = 0; }; - E337D7E459CCFFDF27046FFC /* Copy Pods Resources */ = { + E337D7E459CCFFDF27046FFC /* 📦 Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Copy Pods Resources"; + name = "📦 Copy Pods Resources"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; diff --git a/samples/client/petstore/objc/default/README.md b/samples/client/petstore/objc/default/README.md index bef0aa17dab..808a950606e 100644 --- a/samples/client/petstore/objc/default/README.md +++ b/samples/client/petstore/objc/default/README.md @@ -6,7 +6,7 @@ This ObjC package is automatically generated by the [Swagger Codegen](https://gi - API version: 1.0.0 - Package version: -- Build date: 2016-07-03T21:49:00.509+08:00 +- Build date: 2016-07-19T16:53:24.981+08:00 - Build package: class io.swagger.codegen.languages.ObjcClientCodegen ## Requirements diff --git a/samples/client/petstore/objc/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/objc/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index cd20eb43998..25e7b5a2d2c 100644 --- a/samples/client/petstore/objc/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/objc/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -232,12 +232,12 @@ isa = PBXNativeTarget; buildConfigurationList = 6003F5BF195388D20070C39A /* Build configuration list for PBXNativeTarget "SwaggerClient_Example" */; buildPhases = ( - 799E7E29D924C30424DFBA28 /* Check Pods Manifest.lock */, + 799E7E29D924C30424DFBA28 /* 📦 Check Pods Manifest.lock */, 6003F586195388D20070C39A /* Sources */, 6003F587195388D20070C39A /* Frameworks */, 6003F588195388D20070C39A /* Resources */, - 429AF5C69E165ED75311B4B0 /* Copy Pods Resources */, - 183E54C09C54DAEB54B2546F /* Embed Pods Frameworks */, + 429AF5C69E165ED75311B4B0 /* 📦 Copy Pods Resources */, + 183E54C09C54DAEB54B2546F /* 📦 Embed Pods Frameworks */, ); buildRules = ( ); @@ -252,12 +252,12 @@ isa = PBXNativeTarget; buildConfigurationList = 6003F5C2195388D20070C39A /* Build configuration list for PBXNativeTarget "SwaggerClient_Tests" */; buildPhases = ( - 7B069562A9F91E498732474F /* Check Pods Manifest.lock */, + 7B069562A9F91E498732474F /* 📦 Check Pods Manifest.lock */, 6003F5AA195388D20070C39A /* Sources */, 6003F5AB195388D20070C39A /* Frameworks */, 6003F5AC195388D20070C39A /* Resources */, - E337D7E459CCFFDF27046FFC /* Copy Pods Resources */, - 111D7956304BD6E860AA8709 /* Embed Pods Frameworks */, + E337D7E459CCFFDF27046FFC /* 📦 Copy Pods Resources */, + 111D7956304BD6E860AA8709 /* 📦 Embed Pods Frameworks */, ); buildRules = ( ); @@ -321,14 +321,14 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ - 111D7956304BD6E860AA8709 /* Embed Pods Frameworks */ = { + 111D7956304BD6E860AA8709 /* 📦 Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Embed Pods Frameworks"; + name = "📦 Embed Pods Frameworks"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -336,14 +336,14 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Tests/Pods-SwaggerClient_Tests-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; - 183E54C09C54DAEB54B2546F /* Embed Pods Frameworks */ = { + 183E54C09C54DAEB54B2546F /* 📦 Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Embed Pods Frameworks"; + name = "📦 Embed Pods Frameworks"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -351,14 +351,14 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Example/Pods-SwaggerClient_Example-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; - 429AF5C69E165ED75311B4B0 /* Copy Pods Resources */ = { + 429AF5C69E165ED75311B4B0 /* 📦 Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Copy Pods Resources"; + name = "📦 Copy Pods Resources"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -366,14 +366,14 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Example/Pods-SwaggerClient_Example-resources.sh\"\n"; showEnvVarsInLog = 0; }; - 799E7E29D924C30424DFBA28 /* Check Pods Manifest.lock */ = { + 799E7E29D924C30424DFBA28 /* 📦 Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Check Pods Manifest.lock"; + name = "📦 Check Pods Manifest.lock"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -381,14 +381,14 @@ shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; showEnvVarsInLog = 0; }; - 7B069562A9F91E498732474F /* Check Pods Manifest.lock */ = { + 7B069562A9F91E498732474F /* 📦 Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Check Pods Manifest.lock"; + name = "📦 Check Pods Manifest.lock"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -396,14 +396,14 @@ shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; showEnvVarsInLog = 0; }; - E337D7E459CCFFDF27046FFC /* Copy Pods Resources */ = { + E337D7E459CCFFDF27046FFC /* 📦 Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Copy Pods Resources"; + name = "📦 Copy Pods Resources"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; From 41bab483e04607b339e9bfdf57410607ea8d42cd Mon Sep 17 00:00:00 2001 From: lunat Date: Tue, 19 Jul 2016 12:45:52 +0200 Subject: [PATCH 129/470] Issue #3295 [csharp] header problem due to static method for adding header --- .../main/resources/csharp/Configuration.mustache | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache index d2d7a9ad34b..2932c59eb10 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache @@ -164,11 +164,23 @@ namespace {{packageName}}.Client } /// - /// Add Api Key. + /// Add Api Key Header. /// /// Api Key name. /// Api Key value. /// + public void AddApiKey(string key, string value) + { + if (ApiKey.ContainsKey(key)) + ApiKey.Remove(key); + ApiKey.Add(key, value); + } + + /// + /// Sets the API key prefix. + /// + /// Api Key name. + /// Api Key value. public void AddApiKeyPrefix(string key, string value) { if (ApiKeyPrefix.ContainsKey(key)) @@ -176,6 +188,7 @@ namespace {{packageName}}.Client ApiKeyPrefix.Add(key, value); } + /// /// Gets or sets the HTTP user agent. /// From 92e8efde1a72d367c37716d3c1453d15d54a90ec Mon Sep 17 00:00:00 2001 From: lunat Date: Tue, 19 Jul 2016 14:37:03 +0200 Subject: [PATCH 130/470] Csharp api key header issue 3295 --- .../src/main/resources/csharp/Configuration.mustache | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache index 2932c59eb10..b8cd6c1b330 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache @@ -169,14 +169,14 @@ namespace {{packageName}}.Client /// Api Key name. /// Api Key value. /// - public void AddApiKey(string key, string value) + public void AddApiKey(string key, string value) { if (ApiKey.ContainsKey(key)) ApiKey.Remove(key); ApiKey.Add(key, value); } - /// + /// /// Sets the API key prefix. /// /// Api Key name. @@ -188,7 +188,6 @@ namespace {{packageName}}.Client ApiKeyPrefix.Add(key, value); } - /// /// Gets or sets the HTTP user agent. /// From 5001b54eca89682f463b69c00d6a3ac3d90e59a4 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 19 Jul 2016 20:50:22 +0800 Subject: [PATCH 131/470] update maintainer for spring-related generator --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d3d19f7c63a..78cf8cf7670 100644 --- a/README.md +++ b/README.md @@ -810,6 +810,7 @@ Swaagger Codegen core team members are contributors who have been making signfic | Groovy | | | Go | @guohuang (2016/05/01) @neilotoole (2016/05/01) | | Java | @cbornet (2016/05/01) @xhh (2016/05/01) @epaul (2016/06/04) | +| Java (Spring Cloud) | @cbornet (2016/07/19) | | NodeJS/Javascript | @xhh (2016/05/01) | | ObjC | @mateuszmackowiak (2016/05/09) | | Perl | @wing328 (2016/05/01) | @@ -828,8 +829,8 @@ Swaagger Codegen core team members are contributors who have been making signfic | C# ASP.NET5 | @jimschubert (2016/05/01) | | Go Server | @guohuang (2016/06/13) | | Haskell Servant | | -| Java Spring Boot | | -| Java SpringMVC | @kolyjjj (2016/05/01) | +| Java Spring Boot | @cbornet (2016/07/19) | +| Java Spring MVC | @kolyjjj (2016/05/01) @cbornet (2016/07/19) | | Java JAX-RS | | | NancyFX | | | NodeJS | @kolyjjj (2016/05/01) | From 72be69d2ed829908df09707e6adf131cf8a6ab84 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 19 Jul 2016 22:36:10 +0800 Subject: [PATCH 132/470] Run petstore.swagger.io locally (#3411) * update travis to run petstore server locally * fix docker command * update travis with addon * add comment to travis.yml --- .travis.yml | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/.travis.yml b/.travis.yml index 7b0ea4c6bf4..123e520bddc 100644 --- a/.travis.yml +++ b/.travis.yml @@ -11,11 +11,21 @@ cache: services: - docker +addons: + hosts: + - petstore.swagger.io + before_install: # required when sudo: required for the Ruby petstore tests - gem install bundler - npm install -g typescript - sudo pip install virtualenv + # to run petstore server locally via docker + - docker pull swaggerapi/petstore + - docker run -d -e SWAGGER_HOST=http://petstore.swagger.io -e SWAGGER_BASE_PATH=/v2 -p 80:8080 swaggerapi/petstore + - docker ps -a + # show host table to confirm petstore.swagger.io is mapped to localhost + - cat /etc/hosts install: From 9e6896c8f03ed58ac6ebe69aa8325b5ab43323f2 Mon Sep 17 00:00:00 2001 From: Jason Gavris Date: Mon, 18 Jul 2016 16:02:32 -0400 Subject: [PATCH 133/470] [Swift] Fix pod authors in podspec --- .../codegen/languages/SwiftCodegen.java | 5 ++++ .../src/main/resources/swift/Podspec.mustache | 2 +- .../codegen/languages/SwiftCodegenTest.java | 26 +++++++++++++++++++ .../swift/default/PetstoreClient.podspec | 2 +- .../PetstoreClient.podspec.json | 2 +- .../SwaggerClientTests/Pods/Manifest.lock | 2 +- 6 files changed, 35 insertions(+), 4 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java index 214eca994ef..b782e3626f4 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java @@ -38,6 +38,7 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { public static final String POD_SCREENSHOTS = "podScreenshots"; public static final String POD_DOCUMENTATION_URL = "podDocumentationURL"; public static final String SWIFT_USE_API_NAMESPACE = "swiftUseApiNamespace"; + public static final String DEFAULT_POD_AUTHORS = "Swagger Codegen"; protected static final String LIBRARY_PROMISE_KIT = "PromiseKit"; protected static final String[] RESPONSE_LIBRARIES = { LIBRARY_PROMISE_KIT }; protected String projectName = "SwaggerClient"; @@ -193,6 +194,10 @@ public void processOpts() { } additionalProperties.put(SWIFT_USE_API_NAMESPACE, swiftUseApiNamespace); + if (!additionalProperties.containsKey(POD_AUTHORS)) { + additionalProperties.put(POD_AUTHORS, DEFAULT_POD_AUTHORS); + } + supportingFiles.add(new SupportingFile("Podspec.mustache", "", projectName + ".podspec")); supportingFiles.add(new SupportingFile("Cartfile.mustache", "", "Cartfile")); supportingFiles.add(new SupportingFile("APIHelper.mustache", sourceFolder, "APIHelper.swift")); diff --git a/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache index 3af6910a094..2289e7f6f01 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache @@ -5,7 +5,7 @@ Pod::Spec.new do |s| s.osx.deployment_target = '10.9' s.version = '{{#podVersion}}{{podVersion}}{{/podVersion}}{{^podVersion}}0.0.1{{/podVersion}}' s.source = {{#podSource}}{{& podSource}}{{/podSource}}{{^podSource}}{ :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' }{{/podSource}}{{#podAuthors}} - s.authors = {{& podAuthors}}{{/podAuthors}}{{#podSocialMediaURL}} + s.authors = '{{podAuthors}}'{{/podAuthors}}{{#podSocialMediaURL}} s.social_media_url = '{{podSocialMediaURL}}'{{/podSocialMediaURL}}{{#podDocsetURL}} s.docset_url = '{{podDocsetURL}}'{{/podDocsetURL}} s.license = {{#podLicense}}{{& podLicense}}{{/podLicense}}{{^podLicense}}'Apache License, Version 2.0'{{/podLicense}}{{#podHomepage}} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/languages/SwiftCodegenTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/languages/SwiftCodegenTest.java index acede31f736..4f4508f78ef 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/languages/SwiftCodegenTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/languages/SwiftCodegenTest.java @@ -42,4 +42,30 @@ public void testLowercaseWithUnderscore() throws Exception { Assert.assertEquals(swiftCodegen.toSwiftyEnumName("entry_name"), "EntryName"); } + @Test + public void testDefaultPodAuthors() throws Exception { + // Given + + // When + swiftCodegen.processOpts(); + + // Then + final String podAuthors = (String) swiftCodegen.additionalProperties().get(SwiftCodegen.POD_AUTHORS); + Assert.assertEquals(podAuthors, SwiftCodegen.DEFAULT_POD_AUTHORS); + } + + @Test + public void testPodAuthors() throws Exception { + // Given + final String swaggerDevs = "Swagger Devs"; + swiftCodegen.additionalProperties().put(SwiftCodegen.POD_AUTHORS, swaggerDevs); + + // When + swiftCodegen.processOpts(); + + // Then + final String podAuthors = (String) swiftCodegen.additionalProperties().get(SwiftCodegen.POD_AUTHORS); + Assert.assertEquals(podAuthors, swaggerDevs); + } + } \ No newline at end of file diff --git a/samples/client/petstore/swift/default/PetstoreClient.podspec b/samples/client/petstore/swift/default/PetstoreClient.podspec index 86fa60dd1c6..d1c9460ba1a 100644 --- a/samples/client/petstore/swift/default/PetstoreClient.podspec +++ b/samples/client/petstore/swift/default/PetstoreClient.podspec @@ -4,7 +4,7 @@ Pod::Spec.new do |s| s.osx.deployment_target = '10.9' s.version = '0.0.1' s.source = { :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' } - s.authors = + s.authors = '' s.license = 'Apache License, Version 2.0' s.homepage = 'https://github.com/swagger-api/swagger-codegen' s.summary = 'PetstoreClient' diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json index 069b678d88c..addbe0f7543 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json @@ -9,8 +9,8 @@ "git": "git@github.com:swagger-api/swagger-mustache.git", "tag": "v1.0.0" }, + "authors": "", "license": "Apache License, Version 2.0", - "authors": "Apache License, Version 2.0", "homepage": "https://github.com/swagger-api/swagger-codegen", "summary": "PetstoreClient", "source_files": "PetstoreClient/Classes/Swaggers/**/*.swift", diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Manifest.lock b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Manifest.lock index ce1490e954e..ac8d6671916 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Manifest.lock +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Manifest.lock @@ -12,7 +12,7 @@ EXTERNAL SOURCES: SPEC CHECKSUMS: Alamofire: 5f730ba29fd113b7ddd71c1e65d0c630acf5d7b0 - PetstoreClient: 65dabd411c65d965d5b4c3d5decb909323d1363b + PetstoreClient: 575f4a5776e6a693e70f9d14bae0aabd8c467111 PODFILE CHECKSUM: 84472aca2a88b7f7ed9fcd63e9f5fdb5ad4aab94 From 4f0b7dfaed9ce0ffbc2284d4fa348c2cd45e794e Mon Sep 17 00:00:00 2001 From: Jason Gavris Date: Thu, 30 Jun 2016 14:31:31 -0400 Subject: [PATCH 134/470] [Swift] Handle binary data types --- .../codegen/languages/ObjcClientCodegen.java | 2 + .../codegen/languages/SwiftCodegen.java | 12 ++-- .../swift/AlamofireImplementations.mustache | 69 +++++++++++++------ .../main/resources/swift/Extensions.mustache | 5 ++ .../src/main/resources/swift/Models.mustache | 3 + .../SwiftCodegenTest.java | 25 ++++++- .../swagger/codegen/swift/SwiftModelTest.java | 34 +++++++-- .../Swaggers/AlamofireImplementations.swift | 69 +++++++++++++------ .../Classes/Swaggers/Extensions.swift | 5 ++ .../Classes/Swaggers/Models.swift | 3 + 10 files changed, 175 insertions(+), 52 deletions(-) rename modules/swagger-codegen/src/test/java/io/swagger/codegen/{languages => swift}/SwiftCodegenTest.java (66%) 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 e028083a74b..d8b20ae5dd0 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 @@ -703,6 +703,8 @@ public void setParameterExampleValue(CodegenParameter p) { example = "2013-10-20T19:20:30+01:00"; } example = "@\"" + escapeText(example) + "\""; + } else if ("NSData".equalsIgnoreCase(type)) { + example = "1234"; } else if (!languageSpecificPrimitives.contains(type)) { // type is a model class, e.g. User type = type.replace("*", ""); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java index b782e3626f4..3335be6bdcf 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java @@ -87,6 +87,7 @@ public SwiftCodegen() { ); defaultIncludes = new HashSet( Arrays.asList( + "NSData", "NSDate", "NSURL", // for file "NSUUID", @@ -129,10 +130,8 @@ public SwiftCodegen() { typeMapping.put("double", "Double"); typeMapping.put("object", "AnyObject"); typeMapping.put("file", "NSURL"); - //TODO binary should be mapped to byte array - // mapped to String as a workaround - typeMapping.put("binary", "String"); - typeMapping.put("ByteArray", "String"); + typeMapping.put("binary", "NSData"); + typeMapping.put("ByteArray", "NSData"); typeMapping.put("UUID", "NSUUID"); importMapping = new HashMap(); @@ -258,6 +257,11 @@ public String getSwaggerType(Property p) { return toModelName(type); } + @Override + public boolean isDataTypeBinary(final String dataType) { + return dataType != null && dataType.equals("NSData"); + } + /** * Output the proper model name (capitalized) * diff --git a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache index 0b153ad17d2..cabf67567b5 100644 --- a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache @@ -82,30 +82,59 @@ class AlamofireRequestBuilder: RequestBuilder { request.authenticate(usingCredential: credential) } - request.validate().responseJSON(options: .AllowFragments) { response in + let cleanupRequest = { managerStore.removeValueForKey(managerId) + } - if response.result.isFailure { - completion(response: nil, error: response.result.error) - return - } + let validatedRequest = request.validate() - if () is T { - completion(response: Response(response: response.response!, body: () as! T), error: nil) - return - } - if let json: AnyObject = response.result.value { - let body = Decoders.decode(clazz: T.self, source: json) - completion(response: Response(response: response.response!, body: body), error: nil) - return - } else if "" is T { - // swagger-parser currently doesn't support void, which will be fixed in future swagger-parser release - // https://github.com/swagger-api/swagger-parser/pull/34 - completion(response: Response(response: response.response!, body: "" as! T), error: nil) - return - } + switch T.self { + case is NSData.Type: + validatedRequest.responseData({ (dataResponse) in + cleanupRequest() + + if (dataResponse.result.isFailure) { + completion( + response: nil, + error: dataResponse.result.error + ) + return + } + + completion( + response: Response( + response: dataResponse.response!, + body: dataResponse.data as! T + ), + error: nil + ) + }) + default: + validatedRequest.responseJSON(options: .AllowFragments) { response in + cleanupRequest() - completion(response: nil, error: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) + if response.result.isFailure { + completion(response: nil, error: response.result.error) + return + } + + if () is T { + completion(response: Response(response: response.response!, body: () as! T), error: nil) + return + } + if let json: AnyObject = response.result.value { + let body = Decoders.decode(clazz: T.self, source: json) + completion(response: Response(response: response.response!, body: body), error: nil) + return + } else if "" is T { + // swagger-parser currently doesn't support void, which will be fixed in future swagger-parser release + // https://github.com/swagger-api/swagger-parser/pull/34 + completion(response: Response(response: response.response!, body: "" as! T), error: nil) + return + } + + completion(response: nil, error: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) + } } } diff --git a/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache b/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache index 7fbfa50b28d..27253b6d95f 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache @@ -59,6 +59,11 @@ extension Dictionary: JSONEncodable { } } +extension NSData: JSONEncodable { + func encodeToJSON() -> AnyObject { + return self.base64EncodedStringWithOptions(NSDataBase64EncodingOptions()) + } +} private let dateFormatter: NSDateFormatter = { let fmt = NSDateFormatter() diff --git a/modules/swagger-codegen/src/main/resources/swift/Models.mustache b/modules/swagger-codegen/src/main/resources/swift/Models.mustache index 4e858493e20..a79bbdea075 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Models.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Models.mustache @@ -68,6 +68,9 @@ class Decoders { if source is T { return source as! T } + if T.self is NSData.Type && source is String { + return NSData(base64EncodedString: source as! String, options: NSDataBase64DecodingOptions()) as! T + } let key = "\(T.self)" if let decoder = decoders[key] { diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/languages/SwiftCodegenTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftCodegenTest.java similarity index 66% rename from modules/swagger-codegen/src/test/java/io/swagger/codegen/languages/SwiftCodegenTest.java rename to modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftCodegenTest.java index 4f4508f78ef..0fbfcf5efea 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/languages/SwiftCodegenTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftCodegenTest.java @@ -1,5 +1,12 @@ -package io.swagger.codegen.languages; - +package io.swagger.codegen.swift; + +import io.swagger.codegen.CodegenOperation; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.InlineModelResolver; +import io.swagger.codegen.languages.SwiftCodegen; +import io.swagger.models.Operation; +import io.swagger.models.Swagger; +import io.swagger.parser.SwaggerParser; import org.testng.Assert; import org.testng.annotations.Test; @@ -42,6 +49,20 @@ public void testLowercaseWithUnderscore() throws Exception { Assert.assertEquals(swiftCodegen.toSwiftyEnumName("entry_name"), "EntryName"); } + @Test(description = "returns NSData when response format is binary") + public void binaryDataTest() { + final Swagger model = new SwaggerParser().read("src/test/resources/2_0/binaryDataTest.json"); + final DefaultCodegen codegen = new SwiftCodegen(); + final String path = "/tests/binaryResponse"; + final Operation p = model.getPaths().get(path).getPost(); + final CodegenOperation op = codegen.fromOperation(path, "post", p, model.getDefinitions()); + + Assert.assertEquals(op.returnType, "NSData"); + Assert.assertEquals(op.bodyParam.dataType, "NSData"); + Assert.assertTrue(op.bodyParam.isBinary); + Assert.assertTrue(op.responses.get(0).isBinary); + } + @Test public void testDefaultPodAuthors() throws Exception { // Given diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftModelTest.java index c925535403a..c3d2d829c9c 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftModelTest.java @@ -18,6 +18,8 @@ public void simpleModelTest() { .property("id", new LongProperty()) .property("name", new StringProperty()) .property("createdAt", new DateTimeProperty()) + .property("binary", new BinaryProperty()) + .property("byte", new ByteArrayProperty()) .property("uuid", new UUIDProperty()) .required("id") .required("name") @@ -28,7 +30,7 @@ public void simpleModelTest() { Assert.assertEquals(cm.name, "sample"); Assert.assertEquals(cm.classname, "Sample"); Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 4); + Assert.assertEquals(cm.vars.size(), 6); Assert.assertEquals(cm.discriminator,"test"); final CodegenProperty property1 = cm.vars.get(0); @@ -64,14 +66,34 @@ public void simpleModelTest() { Assert.assertTrue(property3.isNotContainer); final CodegenProperty property4 = cm.vars.get(3); - Assert.assertEquals(property4.baseName, "uuid"); - Assert.assertEquals(property4.datatype, "NSUUID"); - Assert.assertEquals(property4.name, "uuid"); + Assert.assertEquals(property4.baseName, "binary"); + Assert.assertEquals(property4.datatype, "NSData"); + Assert.assertEquals(property4.name, "binary"); Assert.assertNull(property4.defaultValue); - Assert.assertEquals(property4.baseType, "NSUUID"); - Assert.assertNull(property4.hasMore); + Assert.assertEquals(property4.baseType, "NSData"); + Assert.assertTrue(property4.hasMore); Assert.assertNull(property4.required); Assert.assertTrue(property4.isNotContainer); + + final CodegenProperty property5 = cm.vars.get(4); + Assert.assertEquals(property5.baseName, "byte"); + Assert.assertEquals(property5.datatype, "NSData"); + Assert.assertEquals(property5.name, "byte"); + Assert.assertNull(property5.defaultValue); + Assert.assertEquals(property5.baseType, "NSData"); + Assert.assertTrue(property5.hasMore); + Assert.assertNull(property5.required); + Assert.assertTrue(property5.isNotContainer); + + final CodegenProperty property6 = cm.vars.get(5); + Assert.assertEquals(property6.baseName, "uuid"); + Assert.assertEquals(property6.datatype, "NSUUID"); + Assert.assertEquals(property6.name, "uuid"); + Assert.assertNull(property6.defaultValue); + Assert.assertEquals(property6.baseType, "NSUUID"); + Assert.assertNull(property6.hasMore); + Assert.assertNull(property6.required); + Assert.assertTrue(property6.isNotContainer); } } diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index 0b153ad17d2..cabf67567b5 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -82,30 +82,59 @@ class AlamofireRequestBuilder: RequestBuilder { request.authenticate(usingCredential: credential) } - request.validate().responseJSON(options: .AllowFragments) { response in + let cleanupRequest = { managerStore.removeValueForKey(managerId) + } - if response.result.isFailure { - completion(response: nil, error: response.result.error) - return - } + let validatedRequest = request.validate() - if () is T { - completion(response: Response(response: response.response!, body: () as! T), error: nil) - return - } - if let json: AnyObject = response.result.value { - let body = Decoders.decode(clazz: T.self, source: json) - completion(response: Response(response: response.response!, body: body), error: nil) - return - } else if "" is T { - // swagger-parser currently doesn't support void, which will be fixed in future swagger-parser release - // https://github.com/swagger-api/swagger-parser/pull/34 - completion(response: Response(response: response.response!, body: "" as! T), error: nil) - return - } + switch T.self { + case is NSData.Type: + validatedRequest.responseData({ (dataResponse) in + cleanupRequest() + + if (dataResponse.result.isFailure) { + completion( + response: nil, + error: dataResponse.result.error + ) + return + } + + completion( + response: Response( + response: dataResponse.response!, + body: dataResponse.data as! T + ), + error: nil + ) + }) + default: + validatedRequest.responseJSON(options: .AllowFragments) { response in + cleanupRequest() - completion(response: nil, error: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) + if response.result.isFailure { + completion(response: nil, error: response.result.error) + return + } + + if () is T { + completion(response: Response(response: response.response!, body: () as! T), error: nil) + return + } + if let json: AnyObject = response.result.value { + let body = Decoders.decode(clazz: T.self, source: json) + completion(response: Response(response: response.response!, body: body), error: nil) + return + } else if "" is T { + // swagger-parser currently doesn't support void, which will be fixed in future swagger-parser release + // https://github.com/swagger-api/swagger-parser/pull/34 + completion(response: Response(response: response.response!, body: "" as! T), error: nil) + return + } + + completion(response: nil, error: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) + } } } diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Extensions.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Extensions.swift index f93d41600f4..c974cc40b36 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Extensions.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Extensions.swift @@ -58,6 +58,11 @@ extension Dictionary: JSONEncodable { } } +extension NSData: JSONEncodable { + func encodeToJSON() -> AnyObject { + return self.base64EncodedStringWithOptions(NSDataBase64EncodingOptions()) + } +} private let dateFormatter: NSDateFormatter = { let fmt = NSDateFormatter() diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models.swift index 15a835a974e..519aa5cc787 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models.swift @@ -68,6 +68,9 @@ class Decoders { if source is T { return source as! T } + if T.self is NSData.Type && source is String { + return NSData(base64EncodedString: source as! String, options: NSDataBase64DecodingOptions()) as! T + } let key = "\(T.self)" if let decoder = decoders[key] { From 9fcb8a310dd2eb8d30dcf899b12285ddcbd14e0d Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 20 Jul 2016 15:49:41 +0800 Subject: [PATCH 135/470] fix #3418 - slim missing contextpath --- bin/objc-petstore-all.sh | 8 ++++ .../src/main/resources/slim/index.mustache | 2 +- samples/server/petstore/slim/index.php | 40 +++++++++---------- 3 files changed, 29 insertions(+), 21 deletions(-) create mode 100755 bin/objc-petstore-all.sh diff --git a/bin/objc-petstore-all.sh b/bin/objc-petstore-all.sh new file mode 100755 index 00000000000..ba79aee09d5 --- /dev/null +++ b/bin/objc-petstore-all.sh @@ -0,0 +1,8 @@ +#!/bin/sh + +# default setting +./bin/objc-petstore.sh + +# coredata support +./bin/objc-petstore-coredata.sh + diff --git a/modules/swagger-codegen/src/main/resources/slim/index.mustache b/modules/swagger-codegen/src/main/resources/slim/index.mustache index 383094821dd..127786c4325 100644 --- a/modules/swagger-codegen/src/main/resources/slim/index.mustache +++ b/modules/swagger-codegen/src/main/resources/slim/index.mustache @@ -15,7 +15,7 @@ $app = new Slim\App(); * Notes: {{notes}} {{#hasProduces}} * Output-Formats: [{{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}]{{/hasProduces}} */ -$app->{{httpMethod}}('{{path}}', function($request, $response, $args) { +$app->{{httpMethod}}('{{basePathWithoutHost}}{{path}}', function($request, $response, $args) { {{#hasHeaderParams}}$headers = $request->getHeaders();{{/hasHeaderParams}} {{#hasQueryParams}}$queryParams = $request->getQueryParams(); {{#queryParams}}${{paramName}} = $queryParams['{{paramName}}'];{{newline}} {{/queryParams}}{{/hasQueryParams}} diff --git a/samples/server/petstore/slim/index.php b/samples/server/petstore/slim/index.php index 0138feb1d55..74d6648df9f 100644 --- a/samples/server/petstore/slim/index.php +++ b/samples/server/petstore/slim/index.php @@ -15,7 +15,7 @@ * Notes: * Output-Formats: [application/xml, application/json] */ -$app->POST('/pet', function($request, $response, $args) { +$app->POST('/v2/pet', function($request, $response, $args) { @@ -31,7 +31,7 @@ * Notes: * Output-Formats: [application/xml, application/json] */ -$app->DELETE('/pet/{petId}', function($request, $response, $args) { +$app->DELETE('/v2/pet/{petId}', function($request, $response, $args) { $headers = $request->getHeaders(); @@ -47,7 +47,7 @@ * Notes: Multiple status values can be provided with comma separated strings * Output-Formats: [application/xml, application/json] */ -$app->GET('/pet/findByStatus', function($request, $response, $args) { +$app->GET('/v2/pet/findByStatus', function($request, $response, $args) { $queryParams = $request->getQueryParams(); $status = $queryParams['status']; @@ -64,7 +64,7 @@ * Notes: Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Output-Formats: [application/xml, application/json] */ -$app->GET('/pet/findByTags', function($request, $response, $args) { +$app->GET('/v2/pet/findByTags', function($request, $response, $args) { $queryParams = $request->getQueryParams(); $tags = $queryParams['tags']; @@ -81,7 +81,7 @@ * Notes: Returns a single pet * Output-Formats: [application/xml, application/json] */ -$app->GET('/pet/{petId}', function($request, $response, $args) { +$app->GET('/v2/pet/{petId}', function($request, $response, $args) { @@ -97,7 +97,7 @@ * Notes: * Output-Formats: [application/xml, application/json] */ -$app->PUT('/pet', function($request, $response, $args) { +$app->PUT('/v2/pet', function($request, $response, $args) { @@ -113,7 +113,7 @@ * Notes: * Output-Formats: [application/xml, application/json] */ -$app->POST('/pet/{petId}', function($request, $response, $args) { +$app->POST('/v2/pet/{petId}', function($request, $response, $args) { $name = $args['name']; $status = $args['status']; @@ -129,7 +129,7 @@ * Notes: * Output-Formats: [application/json] */ -$app->POST('/pet/{petId}/uploadImage', function($request, $response, $args) { +$app->POST('/v2/pet/{petId}/uploadImage', function($request, $response, $args) { $additionalMetadata = $args['additionalMetadata']; $file = $args['file']; @@ -145,7 +145,7 @@ * Notes: For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * Output-Formats: [application/xml, application/json] */ -$app->DELETE('/store/order/{orderId}', function($request, $response, $args) { +$app->DELETE('/v2/store/order/{orderId}', function($request, $response, $args) { @@ -161,7 +161,7 @@ * Notes: Returns a map of status codes to quantities * Output-Formats: [application/json] */ -$app->GET('/store/inventory', function($request, $response, $args) { +$app->GET('/v2/store/inventory', function($request, $response, $args) { @@ -177,7 +177,7 @@ * Notes: For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * Output-Formats: [application/xml, application/json] */ -$app->GET('/store/order/{orderId}', function($request, $response, $args) { +$app->GET('/v2/store/order/{orderId}', function($request, $response, $args) { @@ -193,7 +193,7 @@ * Notes: * Output-Formats: [application/xml, application/json] */ -$app->POST('/store/order', function($request, $response, $args) { +$app->POST('/v2/store/order', function($request, $response, $args) { @@ -209,7 +209,7 @@ * Notes: This can only be done by the logged in user. * Output-Formats: [application/xml, application/json] */ -$app->POST('/user', function($request, $response, $args) { +$app->POST('/v2/user', function($request, $response, $args) { @@ -225,7 +225,7 @@ * Notes: * Output-Formats: [application/xml, application/json] */ -$app->POST('/user/createWithArray', function($request, $response, $args) { +$app->POST('/v2/user/createWithArray', function($request, $response, $args) { @@ -241,7 +241,7 @@ * Notes: * Output-Formats: [application/xml, application/json] */ -$app->POST('/user/createWithList', function($request, $response, $args) { +$app->POST('/v2/user/createWithList', function($request, $response, $args) { @@ -257,7 +257,7 @@ * Notes: This can only be done by the logged in user. * Output-Formats: [application/xml, application/json] */ -$app->DELETE('/user/{username}', function($request, $response, $args) { +$app->DELETE('/v2/user/{username}', function($request, $response, $args) { @@ -273,7 +273,7 @@ * Notes: * Output-Formats: [application/xml, application/json] */ -$app->GET('/user/{username}', function($request, $response, $args) { +$app->GET('/v2/user/{username}', function($request, $response, $args) { @@ -289,7 +289,7 @@ * Notes: * Output-Formats: [application/xml, application/json] */ -$app->GET('/user/login', function($request, $response, $args) { +$app->GET('/v2/user/login', function($request, $response, $args) { $queryParams = $request->getQueryParams(); $username = $queryParams['username']; $password = $queryParams['password']; @@ -306,7 +306,7 @@ * Notes: * Output-Formats: [application/xml, application/json] */ -$app->GET('/user/logout', function($request, $response, $args) { +$app->GET('/v2/user/logout', function($request, $response, $args) { @@ -322,7 +322,7 @@ * Notes: This can only be done by the logged in user. * Output-Formats: [application/xml, application/json] */ -$app->PUT('/user/{username}', function($request, $response, $args) { +$app->PUT('/v2/user/{username}', function($request, $response, $args) { From 889549a352bb20f4770a98a365e72b8cc9c4628d Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 20 Jul 2016 16:13:06 +0800 Subject: [PATCH 136/470] fix contextpath for php silex --- .../src/main/resources/silex/index.mustache | 2 +- .../petstore/silex/.swagger-codegen-ignore | 23 ++ samples/server/petstore/silex/LICENSE | 201 ++++++++++++++++++ .../petstore/silex/SwaggerServer/index.php | 40 ++-- 4 files changed, 245 insertions(+), 21 deletions(-) create mode 100644 samples/server/petstore/silex/.swagger-codegen-ignore create mode 100644 samples/server/petstore/silex/LICENSE diff --git a/modules/swagger-codegen/src/main/resources/silex/index.mustache b/modules/swagger-codegen/src/main/resources/silex/index.mustache index 9fbfca6049e..0ace4d41fda 100644 --- a/modules/swagger-codegen/src/main/resources/silex/index.mustache +++ b/modules/swagger-codegen/src/main/resources/silex/index.mustache @@ -12,7 +12,7 @@ $app = new Silex\Application(); {{#operations}} {{#operation}} -$app->{{httpMethod}}('{{path}}', function(Application $app, Request $request{{#pathParams}}, ${{paramName}}{{/pathParams}}) { +$app->{{httpMethod}}('{{basePathWithoutHost}}{{path}}', function(Application $app, Request $request{{#pathParams}}, ${{paramName}}{{/pathParams}}) { {{#queryParams}}${{paramName}} = $request->get('{{paramName}}');{{newline}} {{/queryParams}} {{#formParams}}${{paramName}} = $request->get('{{paramName}}');{{newline}} {{/formParams}} return new Response('How about implementing {{nickname}} as a {{httpMethod}} method ?'); diff --git a/samples/server/petstore/silex/.swagger-codegen-ignore b/samples/server/petstore/silex/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/silex/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/silex/LICENSE b/samples/server/petstore/silex/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/server/petstore/silex/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/server/petstore/silex/SwaggerServer/index.php b/samples/server/petstore/silex/SwaggerServer/index.php index aba755a883a..10b446e9974 100644 --- a/samples/server/petstore/silex/SwaggerServer/index.php +++ b/samples/server/petstore/silex/SwaggerServer/index.php @@ -8,140 +8,140 @@ $app = new Silex\Application(); -$app->POST('/pet', function(Application $app, Request $request) { +$app->POST('/v2/pet', function(Application $app, Request $request) { return new Response('How about implementing addPet as a POST method ?'); }); -$app->DELETE('/pet/{petId}', function(Application $app, Request $request, $pet_id) { +$app->DELETE('/v2/pet/{petId}', function(Application $app, Request $request, $pet_id) { return new Response('How about implementing deletePet as a DELETE method ?'); }); -$app->GET('/pet/findByStatus', function(Application $app, Request $request) { +$app->GET('/v2/pet/findByStatus', function(Application $app, Request $request) { $status = $request->get('status'); return new Response('How about implementing findPetsByStatus as a GET method ?'); }); -$app->GET('/pet/findByTags', function(Application $app, Request $request) { +$app->GET('/v2/pet/findByTags', function(Application $app, Request $request) { $tags = $request->get('tags'); return new Response('How about implementing findPetsByTags as a GET method ?'); }); -$app->GET('/pet/{petId}', function(Application $app, Request $request, $pet_id) { +$app->GET('/v2/pet/{petId}', function(Application $app, Request $request, $pet_id) { return new Response('How about implementing getPetById as a GET method ?'); }); -$app->PUT('/pet', function(Application $app, Request $request) { +$app->PUT('/v2/pet', function(Application $app, Request $request) { return new Response('How about implementing updatePet as a PUT method ?'); }); -$app->POST('/pet/{petId}', function(Application $app, Request $request, $pet_id) { +$app->POST('/v2/pet/{petId}', function(Application $app, Request $request, $pet_id) { $name = $request->get('name'); $status = $request->get('status'); return new Response('How about implementing updatePetWithForm as a POST method ?'); }); -$app->POST('/pet/{petId}/uploadImage', function(Application $app, Request $request, $pet_id) { +$app->POST('/v2/pet/{petId}/uploadImage', function(Application $app, Request $request, $pet_id) { $additional_metadata = $request->get('additional_metadata'); $file = $request->get('file'); return new Response('How about implementing uploadFile as a POST method ?'); }); -$app->DELETE('/store/order/{orderId}', function(Application $app, Request $request, $order_id) { +$app->DELETE('/v2/store/order/{orderId}', function(Application $app, Request $request, $order_id) { return new Response('How about implementing deleteOrder as a DELETE method ?'); }); -$app->GET('/store/inventory', function(Application $app, Request $request) { +$app->GET('/v2/store/inventory', function(Application $app, Request $request) { return new Response('How about implementing getInventory as a GET method ?'); }); -$app->GET('/store/order/{orderId}', function(Application $app, Request $request, $order_id) { +$app->GET('/v2/store/order/{orderId}', function(Application $app, Request $request, $order_id) { return new Response('How about implementing getOrderById as a GET method ?'); }); -$app->POST('/store/order', function(Application $app, Request $request) { +$app->POST('/v2/store/order', function(Application $app, Request $request) { return new Response('How about implementing placeOrder as a POST method ?'); }); -$app->POST('/user', function(Application $app, Request $request) { +$app->POST('/v2/user', function(Application $app, Request $request) { return new Response('How about implementing createUser as a POST method ?'); }); -$app->POST('/user/createWithArray', function(Application $app, Request $request) { +$app->POST('/v2/user/createWithArray', function(Application $app, Request $request) { return new Response('How about implementing createUsersWithArrayInput as a POST method ?'); }); -$app->POST('/user/createWithList', function(Application $app, Request $request) { +$app->POST('/v2/user/createWithList', function(Application $app, Request $request) { return new Response('How about implementing createUsersWithListInput as a POST method ?'); }); -$app->DELETE('/user/{username}', function(Application $app, Request $request, $username) { +$app->DELETE('/v2/user/{username}', function(Application $app, Request $request, $username) { return new Response('How about implementing deleteUser as a DELETE method ?'); }); -$app->GET('/user/{username}', function(Application $app, Request $request, $username) { +$app->GET('/v2/user/{username}', function(Application $app, Request $request, $username) { return new Response('How about implementing getUserByName as a GET method ?'); }); -$app->GET('/user/login', function(Application $app, Request $request) { +$app->GET('/v2/user/login', function(Application $app, Request $request) { $username = $request->get('username'); $password = $request->get('password'); return new Response('How about implementing loginUser as a GET method ?'); }); -$app->GET('/user/logout', function(Application $app, Request $request) { +$app->GET('/v2/user/logout', function(Application $app, Request $request) { return new Response('How about implementing logoutUser as a GET method ?'); }); -$app->PUT('/user/{username}', function(Application $app, Request $request, $username) { +$app->PUT('/v2/user/{username}', function(Application $app, Request $request, $username) { return new Response('How about implementing updateUser as a PUT method ?'); From dfe4944552b40daa0e50559e6a451f8567d3d0e9 Mon Sep 17 00:00:00 2001 From: Andy Date: Wed, 20 Jul 2016 01:52:07 -0700 Subject: [PATCH 137/470] Fix #3400 - incorrect MinLength and MaxLength on partial_model_generic.mustache template (#3415) * fix maxLength and Regexp issue * more fix * revert some changes --- .../ruby/partial_model_generic.mustache | 16 ++++++++-------- samples/client/petstore/ruby/README.md | 2 +- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/ruby/partial_model_generic.mustache b/modules/swagger-codegen/src/main/resources/ruby/partial_model_generic.mustache index 690b1534e96..e0eb84f8886 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/partial_model_generic.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/partial_model_generic.mustache @@ -130,12 +130,12 @@ {{/isContainer}} {{/isEnum}} {{#hasValidation}} - {{#minLength}} - return false if @{{{name}}}.to_s.length > {{{maxLength}}} - {{/minLength}} {{#maxLength}} - return false if @{{{name}}}.to_s.length < {{{minLength}}} + return false if @{{{name}}}.to_s.length > {{{maxLength}}} {{/maxLength}} + {{#minLength}} + return false if @{{{name}}}.to_s.length < {{{minLength}}} + {{/minLength}} {{#maximum}} return false if @{{{name}}} > {{{maximum}}} {{/maximum}} @@ -174,18 +174,18 @@ fail ArgumentError, "{{{name}}} cannot be nil" end - {{#minLength}} + {{#maxLength}} if {{{name}}}.to_s.length > {{{maxLength}}} fail ArgumentError, "invalid value for '{{{name}}}', the character length must be smaller than or equal to {{{maxLength}}}." end - {{/minLength}} - {{#maxLength}} + {{/maxLength}} + {{#minLength}} if {{{name}}}.to_s.length < {{{minLength}}} fail ArgumentError, "invalid value for '{{{name}}}', the character length must be great than or equal to {{{minLength}}}." end - {{/maxLength}} + {{/minLength}} {{#maximum}} if {{{name}}} > {{{maximum}}} fail ArgumentError, "invalid value for '{{{name}}}', must be smaller than or equal to {{{maximum}}}." diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index 28228a68b4c..5db4a41148b 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -8,7 +8,7 @@ This SDK is automatically generated by the [Swagger Codegen](https://github.com/ - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-07-19T15:06:57.795+08:00 +- Build date: 2016-07-19T11:36:39.517-07:00 - Build package: class io.swagger.codegen.languages.RubyClientCodegen ## Installation From 9c7710e6959c850eba36f2784ce6ead94af23f6d Mon Sep 17 00:00:00 2001 From: Chris Jang Date: Wed, 20 Jul 2016 06:00:52 -0400 Subject: [PATCH 138/470] Factory interface for typescript-fetch (#3398) * Added Factory interface for typescript-fetch * added tests * Removed 'this.' * Added Factory interface for typescript-fetch * added tests * Removed 'this.' --- .../resources/TypeScript-Fetch/api.mustache | 21 +- .../typescript-fetch/builds/default/api.ts | 195 +++++++++++++++++- .../typescript-fetch/builds/es6-target/api.ts | 195 +++++++++++++++++- .../builds/with-npm-version/api.ts | 195 +++++++++++++++++- .../tests/default/test/PetApiFactory.ts | 58 ++++++ .../tests/default/test/StoreApiFactory.ts | 12 ++ .../tests/default/test/index.ts | 4 +- 7 files changed, 669 insertions(+), 11 deletions(-) create mode 100644 samples/client/petstore/typescript-fetch/tests/default/test/PetApiFactory.ts create mode 100644 samples/client/petstore/typescript-fetch/tests/default/test/StoreApiFactory.ts diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache index df1b5e05ace..e8b9dd67fd6 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache @@ -161,7 +161,26 @@ export class {{classname}} extends BaseAPI { return {{classname}}Fp.{{nickname}}({{#hasParams}}params{{/hasParams}})(this.fetch, this.basePath); } {{/operation}} -} +}; + +/** + * {{classname}} - factory interface{{#description}} + * {{&description}}{{/description}} + */ +export const {{classname}}Factory = function (fetch?: FetchAPI, basePath?: string) { + return { +{{#operation}} + /** {{#summary}} + * {{summary}}{{/summary}}{{#notes}} + * {{notes}}{{/notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{/allParams}} + */ + {{nickname}}({{#hasParams}}params: { {{#allParams}} {{paramName}}{{^required}}?{{/required}}: {{{dataType}}};{{/allParams}} }{{/hasParams}}) { + return {{classname}}Fp.{{nickname}}({{#hasParams}}params{{/hasParams}})(fetch, basePath); + }, +{{/operation}} + } +}; {{/operations}} {{/apis}} diff --git a/samples/client/petstore/typescript-fetch/builds/default/api.ts b/samples/client/petstore/typescript-fetch/builds/default/api.ts index 92fdd806cc1..ee15be389c9 100644 --- a/samples/client/petstore/typescript-fetch/builds/default/api.ts +++ b/samples/client/petstore/typescript-fetch/builds/default/api.ts @@ -527,7 +527,84 @@ export class PetApi extends BaseAPI { uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }) { return PetApiFp.uploadFile(params)(this.fetch, this.basePath); } -} +}; + +/** + * PetApi - factory interface + */ +export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { + return { + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + addPet(params: { body?: Pet; }) { + return PetApiFp.addPet(params)(fetch, basePath); + }, + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + deletePet(params: { petId: number; apiKey?: string; }) { + return PetApiFp.deletePet(params)(fetch, basePath); + }, + /** + * 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 + */ + findPetsByStatus(params: { status?: Array; }) { + return PetApiFp.findPetsByStatus(params)(fetch, basePath); + }, + /** + * 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 + */ + findPetsByTags(params: { tags?: Array; }) { + return PetApiFp.findPetsByTags(params)(fetch, basePath); + }, + /** + * 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 + */ + getPetById(params: { petId: number; }) { + return PetApiFp.getPetById(params)(fetch, basePath); + }, + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + updatePet(params: { body?: Pet; }) { + return PetApiFp.updatePet(params)(fetch, basePath); + }, + /** + * 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 + */ + updatePetWithForm(params: { petId: string; name?: string; status?: string; }) { + return PetApiFp.updatePetWithForm(params)(fetch, basePath); + }, + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }) { + return PetApiFp.uploadFile(params)(fetch, basePath); + }, + } +}; /** @@ -733,7 +810,46 @@ export class StoreApi extends BaseAPI { placeOrder(params: { body?: Order; }) { return StoreApiFp.placeOrder(params)(this.fetch, this.basePath); } -} +}; + +/** + * StoreApi - factory interface + */ +export const StoreApiFactory = function (fetch?: FetchAPI, basePath?: string) { + return { + /** + * 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 + */ + deleteOrder(params: { orderId: string; }) { + return StoreApiFp.deleteOrder(params)(fetch, basePath); + }, + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + getInventory() { + return StoreApiFp.getInventory()(fetch, basePath); + }, + /** + * 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 + */ + getOrderById(params: { orderId: string; }) { + return StoreApiFp.getOrderById(params)(fetch, basePath); + }, + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + placeOrder(params: { body?: Order; }) { + return StoreApiFp.placeOrder(params)(fetch, basePath); + }, + } +}; /** @@ -1142,5 +1258,78 @@ export class UserApi extends BaseAPI { updateUser(params: { username: string; body?: User; }) { return UserApiFp.updateUser(params)(this.fetch, this.basePath); } -} +}; + +/** + * UserApi - factory interface + */ +export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { + return { + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + createUser(params: { body?: User; }) { + return UserApiFp.createUser(params)(fetch, basePath); + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithArrayInput(params: { body?: Array; }) { + return UserApiFp.createUsersWithArrayInput(params)(fetch, basePath); + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithListInput(params: { body?: Array; }) { + return UserApiFp.createUsersWithListInput(params)(fetch, basePath); + }, + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + deleteUser(params: { username: string; }) { + return UserApiFp.deleteUser(params)(fetch, basePath); + }, + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + getUserByName(params: { username: string; }) { + return UserApiFp.getUserByName(params)(fetch, basePath); + }, + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + loginUser(params: { username?: string; password?: string; }) { + return UserApiFp.loginUser(params)(fetch, basePath); + }, + /** + * Logs out current logged in user session + * + */ + logoutUser() { + return UserApiFp.logoutUser()(fetch, basePath); + }, + /** + * 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 + */ + updateUser(params: { username: string; body?: User; }) { + return UserApiFp.updateUser(params)(fetch, basePath); + }, + } +}; diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts b/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts index 0788ce4afe4..96b912c587f 100644 --- a/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts @@ -526,7 +526,84 @@ export class PetApi extends BaseAPI { uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }) { return PetApiFp.uploadFile(params)(this.fetch, this.basePath); } -} +}; + +/** + * PetApi - factory interface + */ +export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { + return { + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + addPet(params: { body?: Pet; }) { + return PetApiFp.addPet(params)(fetch, basePath); + }, + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + deletePet(params: { petId: number; apiKey?: string; }) { + return PetApiFp.deletePet(params)(fetch, basePath); + }, + /** + * 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 + */ + findPetsByStatus(params: { status?: Array; }) { + return PetApiFp.findPetsByStatus(params)(fetch, basePath); + }, + /** + * 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 + */ + findPetsByTags(params: { tags?: Array; }) { + return PetApiFp.findPetsByTags(params)(fetch, basePath); + }, + /** + * 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 + */ + getPetById(params: { petId: number; }) { + return PetApiFp.getPetById(params)(fetch, basePath); + }, + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + updatePet(params: { body?: Pet; }) { + return PetApiFp.updatePet(params)(fetch, basePath); + }, + /** + * 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 + */ + updatePetWithForm(params: { petId: string; name?: string; status?: string; }) { + return PetApiFp.updatePetWithForm(params)(fetch, basePath); + }, + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }) { + return PetApiFp.uploadFile(params)(fetch, basePath); + }, + } +}; /** @@ -732,7 +809,46 @@ export class StoreApi extends BaseAPI { placeOrder(params: { body?: Order; }) { return StoreApiFp.placeOrder(params)(this.fetch, this.basePath); } -} +}; + +/** + * StoreApi - factory interface + */ +export const StoreApiFactory = function (fetch?: FetchAPI, basePath?: string) { + return { + /** + * 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 + */ + deleteOrder(params: { orderId: string; }) { + return StoreApiFp.deleteOrder(params)(fetch, basePath); + }, + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + getInventory() { + return StoreApiFp.getInventory()(fetch, basePath); + }, + /** + * 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 + */ + getOrderById(params: { orderId: string; }) { + return StoreApiFp.getOrderById(params)(fetch, basePath); + }, + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + placeOrder(params: { body?: Order; }) { + return StoreApiFp.placeOrder(params)(fetch, basePath); + }, + } +}; /** @@ -1141,5 +1257,78 @@ export class UserApi extends BaseAPI { updateUser(params: { username: string; body?: User; }) { return UserApiFp.updateUser(params)(this.fetch, this.basePath); } -} +}; + +/** + * UserApi - factory interface + */ +export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { + return { + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + createUser(params: { body?: User; }) { + return UserApiFp.createUser(params)(fetch, basePath); + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithArrayInput(params: { body?: Array; }) { + return UserApiFp.createUsersWithArrayInput(params)(fetch, basePath); + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithListInput(params: { body?: Array; }) { + return UserApiFp.createUsersWithListInput(params)(fetch, basePath); + }, + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + deleteUser(params: { username: string; }) { + return UserApiFp.deleteUser(params)(fetch, basePath); + }, + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + getUserByName(params: { username: string; }) { + return UserApiFp.getUserByName(params)(fetch, basePath); + }, + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + loginUser(params: { username?: string; password?: string; }) { + return UserApiFp.loginUser(params)(fetch, basePath); + }, + /** + * Logs out current logged in user session + * + */ + logoutUser() { + return UserApiFp.logoutUser()(fetch, basePath); + }, + /** + * 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 + */ + updateUser(params: { username: string; body?: User; }) { + return UserApiFp.updateUser(params)(fetch, basePath); + }, + } +}; diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts b/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts index 92fdd806cc1..ee15be389c9 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts @@ -527,7 +527,84 @@ export class PetApi extends BaseAPI { uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }) { return PetApiFp.uploadFile(params)(this.fetch, this.basePath); } -} +}; + +/** + * PetApi - factory interface + */ +export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { + return { + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + addPet(params: { body?: Pet; }) { + return PetApiFp.addPet(params)(fetch, basePath); + }, + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + deletePet(params: { petId: number; apiKey?: string; }) { + return PetApiFp.deletePet(params)(fetch, basePath); + }, + /** + * 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 + */ + findPetsByStatus(params: { status?: Array; }) { + return PetApiFp.findPetsByStatus(params)(fetch, basePath); + }, + /** + * 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 + */ + findPetsByTags(params: { tags?: Array; }) { + return PetApiFp.findPetsByTags(params)(fetch, basePath); + }, + /** + * 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 + */ + getPetById(params: { petId: number; }) { + return PetApiFp.getPetById(params)(fetch, basePath); + }, + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + updatePet(params: { body?: Pet; }) { + return PetApiFp.updatePet(params)(fetch, basePath); + }, + /** + * 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 + */ + updatePetWithForm(params: { petId: string; name?: string; status?: string; }) { + return PetApiFp.updatePetWithForm(params)(fetch, basePath); + }, + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }) { + return PetApiFp.uploadFile(params)(fetch, basePath); + }, + } +}; /** @@ -733,7 +810,46 @@ export class StoreApi extends BaseAPI { placeOrder(params: { body?: Order; }) { return StoreApiFp.placeOrder(params)(this.fetch, this.basePath); } -} +}; + +/** + * StoreApi - factory interface + */ +export const StoreApiFactory = function (fetch?: FetchAPI, basePath?: string) { + return { + /** + * 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 + */ + deleteOrder(params: { orderId: string; }) { + return StoreApiFp.deleteOrder(params)(fetch, basePath); + }, + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + getInventory() { + return StoreApiFp.getInventory()(fetch, basePath); + }, + /** + * 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 + */ + getOrderById(params: { orderId: string; }) { + return StoreApiFp.getOrderById(params)(fetch, basePath); + }, + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + placeOrder(params: { body?: Order; }) { + return StoreApiFp.placeOrder(params)(fetch, basePath); + }, + } +}; /** @@ -1142,5 +1258,78 @@ export class UserApi extends BaseAPI { updateUser(params: { username: string; body?: User; }) { return UserApiFp.updateUser(params)(this.fetch, this.basePath); } -} +}; + +/** + * UserApi - factory interface + */ +export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { + return { + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + createUser(params: { body?: User; }) { + return UserApiFp.createUser(params)(fetch, basePath); + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithArrayInput(params: { body?: Array; }) { + return UserApiFp.createUsersWithArrayInput(params)(fetch, basePath); + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithListInput(params: { body?: Array; }) { + return UserApiFp.createUsersWithListInput(params)(fetch, basePath); + }, + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + deleteUser(params: { username: string; }) { + return UserApiFp.deleteUser(params)(fetch, basePath); + }, + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + getUserByName(params: { username: string; }) { + return UserApiFp.getUserByName(params)(fetch, basePath); + }, + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + loginUser(params: { username?: string; password?: string; }) { + return UserApiFp.loginUser(params)(fetch, basePath); + }, + /** + * Logs out current logged in user session + * + */ + logoutUser() { + return UserApiFp.logoutUser()(fetch, basePath); + }, + /** + * 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 + */ + updateUser(params: { username: string; body?: User; }) { + return UserApiFp.updateUser(params)(fetch, basePath); + }, + } +}; diff --git a/samples/client/petstore/typescript-fetch/tests/default/test/PetApiFactory.ts b/samples/client/petstore/typescript-fetch/tests/default/test/PetApiFactory.ts new file mode 100644 index 00000000000..38acc214e21 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/test/PetApiFactory.ts @@ -0,0 +1,58 @@ +import {expect} from 'chai'; +import {PetApiFactory, Pet, Category} from 'typescript-fetch-api'; + +describe('PetApiFactory', () => { + let fixture: Pet = createTestFixture(); + + it('should add and delete Pet', () => { + return PetApiFactory().addPet({ body: fixture }).then(() => { + }); + }); + + it('should get Pet by ID', () => { + return PetApiFactory().getPetById({ petId: fixture.id }).then((result) => { + return expect(result).to.deep.equal(fixture); + }); + }); + + it('should update Pet by ID', () => { + return PetApiFactory().getPetById({ petId: fixture.id }).then( (result) => { + result.name = 'newname'; + return PetApiFactory().updatePet({ body: result }).then(() => { + return PetApiFactory().getPetById({ petId: fixture.id }).then( (result) => { + return expect(result.name).to.deep.equal('newname'); + }); + }); + }); + }); + + it('should delete Pet', () => { + return PetApiFactory().deletePet({ petId: fixture.id }); + }); + + it('should not contain deleted Pet', () => { + return PetApiFactory().getPetById({ petId: fixture.id }).then((result) => { + return expect(result).to.not.exist; + }, (err) => { + return expect(err).to.exist; + }); + }); +}); + +function createTestFixture(ts = Date.now()) { + const category: Category = { + 'id': ts, + 'name': `category${ts}`, + }; + + const pet: Pet = { + 'id': ts, + 'name': `pet${ts}`, + 'category': category, + 'photoUrls': ['http://foo.bar.com/1', 'http://foo.bar.com/2'], + 'status': 'available', + 'tags': [] + }; + + return pet; +}; diff --git a/samples/client/petstore/typescript-fetch/tests/default/test/StoreApiFactory.ts b/samples/client/petstore/typescript-fetch/tests/default/test/StoreApiFactory.ts new file mode 100644 index 00000000000..c1d5560e2af --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/test/StoreApiFactory.ts @@ -0,0 +1,12 @@ +import {expect} from 'chai'; +import {StoreApiFactory} from 'typescript-fetch-api'; + +describe('StoreApiFactory', function() { + it('should get inventory', function() { + return StoreApiFactory().getInventory().then((result) => { + expect(Object.keys(result)).to.not.be.empty; + }); + }); + +}); + diff --git a/samples/client/petstore/typescript-fetch/tests/default/test/index.ts b/samples/client/petstore/typescript-fetch/tests/default/test/index.ts index 29369a2d0e2..e3b9cbf4a50 100644 --- a/samples/client/petstore/typescript-fetch/tests/default/test/index.ts +++ b/samples/client/petstore/typescript-fetch/tests/default/test/index.ts @@ -1,2 +1,4 @@ import './PetApi'; -import './StoreApi'; \ No newline at end of file +import './StoreApi'; +import './PetApiFactory'; +import './StoreApiFactory'; \ No newline at end of file From bee6803bcb039aa2060de2080a0008477b22cfe7 Mon Sep 17 00:00:00 2001 From: abcsun Date: Wed, 20 Jul 2016 19:06:14 +0800 Subject: [PATCH 139/470] add context path (#3425) --- .../src/main/resources/lumen/routes.mustache | 2 +- .../lumen/app/Http/controllers/FakeApi.php | 24 +++++++++ .../server/petstore/lumen/app/Http/routes.php | 51 +++++++++++-------- 3 files changed, 54 insertions(+), 23 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/lumen/routes.mustache b/modules/swagger-codegen/src/main/resources/lumen/routes.mustache index c5f3bdf858a..4b9631fd9a5 100644 --- a/modules/swagger-codegen/src/main/resources/lumen/routes.mustache +++ b/modules/swagger-codegen/src/main/resources/lumen/routes.mustache @@ -19,7 +19,7 @@ $app->get('/', function () use ($app) { * Notes: {{notes}} {{#hasProduces}} * Output-Formats: [{{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}]{{/hasProduces}} */ -$app->{{httpMethod}}('{{path}}', '{{classname}}@{{operationId}}'); +$app->{{httpMethod}}('{{basePathWithoutHost}}{{path}}', '{{classname}}@{{operationId}}'); {{/operation}} {{/operations}} {{/apis}} diff --git a/samples/server/petstore/lumen/app/Http/controllers/FakeApi.php b/samples/server/petstore/lumen/app/Http/controllers/FakeApi.php index 11c9e2dc4c4..a55492b90f1 100644 --- a/samples/server/petstore/lumen/app/Http/controllers/FakeApi.php +++ b/samples/server/petstore/lumen/app/Http/controllers/FakeApi.php @@ -38,6 +38,30 @@ public function __construct() { } + /** + * Operation testClientModel + * + * To test \"client\" model. + * + * + * @return Http response + */ + public function testClientModel() + { + $input = Request::all(); + + //path params validation + + + //not path params validation + if (!isset($input['body'])) { + throw new \InvalidArgumentException('Missing the required parameter $body when calling testClientModel'); + } + $body = $input['body']; + + + return response('How about implementing testClientModel as a PATCH method ?'); + } /** * Operation testEndpointParameters * diff --git a/samples/server/petstore/lumen/app/Http/routes.php b/samples/server/petstore/lumen/app/Http/routes.php index c61d6d3c4d3..ea9b463bffa 100644 --- a/samples/server/petstore/lumen/app/Http/routes.php +++ b/samples/server/petstore/lumen/app/Http/routes.php @@ -33,158 +33,165 @@ return $app->version(); }); +/** + * PATCH testClientModel + * Summary: To test \"client\" model + * Notes: + * Output-Formats: [application/json] + */ +$app->PATCH('/v2/fake', 'FakeApi@testClientModel'); /** * POST testEndpointParameters * Summary: Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * Notes: Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * Output-Formats: [application/xml; charset=utf-8, application/json; charset=utf-8] */ -$app->POST('/fake', 'FakeApi@testEndpointParameters'); +$app->POST('/v2/fake', 'FakeApi@testEndpointParameters'); /** * GET testEnumQueryParameters * Summary: To test enum query parameters * Notes: * Output-Formats: [application/json] */ -$app->GET('/fake', 'FakeApi@testEnumQueryParameters'); +$app->GET('/v2/fake', 'FakeApi@testEnumQueryParameters'); /** * POST addPet * Summary: Add a new pet to the store * Notes: * Output-Formats: [application/xml, application/json] */ -$app->POST('/pet', 'PetApi@addPet'); +$app->POST('/v2/pet', 'PetApi@addPet'); /** * PUT updatePet * Summary: Update an existing pet * Notes: * Output-Formats: [application/xml, application/json] */ -$app->PUT('/pet', 'PetApi@updatePet'); +$app->PUT('/v2/pet', 'PetApi@updatePet'); /** * GET findPetsByStatus * Summary: Finds Pets by status * Notes: Multiple status values can be provided with comma separated strings * Output-Formats: [application/xml, application/json] */ -$app->GET('/pet/findByStatus', 'PetApi@findPetsByStatus'); +$app->GET('/v2/pet/findByStatus', 'PetApi@findPetsByStatus'); /** * GET findPetsByTags * Summary: Finds Pets by tags * Notes: Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Output-Formats: [application/xml, application/json] */ -$app->GET('/pet/findByTags', 'PetApi@findPetsByTags'); +$app->GET('/v2/pet/findByTags', 'PetApi@findPetsByTags'); /** * DELETE deletePet * Summary: Deletes a pet * Notes: * Output-Formats: [application/xml, application/json] */ -$app->DELETE('/pet/{petId}', 'PetApi@deletePet'); +$app->DELETE('/v2/pet/{petId}', 'PetApi@deletePet'); /** * GET getPetById * Summary: Find pet by ID * Notes: Returns a single pet * Output-Formats: [application/xml, application/json] */ -$app->GET('/pet/{petId}', 'PetApi@getPetById'); +$app->GET('/v2/pet/{petId}', 'PetApi@getPetById'); /** * POST updatePetWithForm * Summary: Updates a pet in the store with form data * Notes: * Output-Formats: [application/xml, application/json] */ -$app->POST('/pet/{petId}', 'PetApi@updatePetWithForm'); +$app->POST('/v2/pet/{petId}', 'PetApi@updatePetWithForm'); /** * POST uploadFile * Summary: uploads an image * Notes: * Output-Formats: [application/json] */ -$app->POST('/pet/{petId}/uploadImage', 'PetApi@uploadFile'); +$app->POST('/v2/pet/{petId}/uploadImage', 'PetApi@uploadFile'); /** * GET getInventory * Summary: Returns pet inventories by status * Notes: Returns a map of status codes to quantities * Output-Formats: [application/json] */ -$app->GET('/store/inventory', 'StoreApi@getInventory'); +$app->GET('/v2/store/inventory', 'StoreApi@getInventory'); /** * POST placeOrder * Summary: Place an order for a pet * Notes: * Output-Formats: [application/xml, application/json] */ -$app->POST('/store/order', 'StoreApi@placeOrder'); +$app->POST('/v2/store/order', 'StoreApi@placeOrder'); /** * DELETE deleteOrder * Summary: Delete purchase order by ID * Notes: For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * Output-Formats: [application/xml, application/json] */ -$app->DELETE('/store/order/{orderId}', 'StoreApi@deleteOrder'); +$app->DELETE('/v2/store/order/{orderId}', 'StoreApi@deleteOrder'); /** * GET getOrderById * Summary: Find purchase order by ID * Notes: For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * Output-Formats: [application/xml, application/json] */ -$app->GET('/store/order/{orderId}', 'StoreApi@getOrderById'); +$app->GET('/v2/store/order/{orderId}', 'StoreApi@getOrderById'); /** * POST createUser * Summary: Create user * Notes: This can only be done by the logged in user. * Output-Formats: [application/xml, application/json] */ -$app->POST('/user', 'UserApi@createUser'); +$app->POST('/v2/user', 'UserApi@createUser'); /** * POST createUsersWithArrayInput * Summary: Creates list of users with given input array * Notes: * Output-Formats: [application/xml, application/json] */ -$app->POST('/user/createWithArray', 'UserApi@createUsersWithArrayInput'); +$app->POST('/v2/user/createWithArray', 'UserApi@createUsersWithArrayInput'); /** * POST createUsersWithListInput * Summary: Creates list of users with given input array * Notes: * Output-Formats: [application/xml, application/json] */ -$app->POST('/user/createWithList', 'UserApi@createUsersWithListInput'); +$app->POST('/v2/user/createWithList', 'UserApi@createUsersWithListInput'); /** * GET loginUser * Summary: Logs user into the system * Notes: * Output-Formats: [application/xml, application/json] */ -$app->GET('/user/login', 'UserApi@loginUser'); +$app->GET('/v2/user/login', 'UserApi@loginUser'); /** * GET logoutUser * Summary: Logs out current logged in user session * Notes: * Output-Formats: [application/xml, application/json] */ -$app->GET('/user/logout', 'UserApi@logoutUser'); +$app->GET('/v2/user/logout', 'UserApi@logoutUser'); /** * DELETE deleteUser * Summary: Delete user * Notes: This can only be done by the logged in user. * Output-Formats: [application/xml, application/json] */ -$app->DELETE('/user/{username}', 'UserApi@deleteUser'); +$app->DELETE('/v2/user/{username}', 'UserApi@deleteUser'); /** * GET getUserByName * Summary: Get user by user name * Notes: * Output-Formats: [application/xml, application/json] */ -$app->GET('/user/{username}', 'UserApi@getUserByName'); +$app->GET('/v2/user/{username}', 'UserApi@getUserByName'); /** * PUT updateUser * Summary: Updated user * Notes: This can only be done by the logged in user. * Output-Formats: [application/xml, application/json] */ -$app->PUT('/user/{username}', 'UserApi@updateUser'); +$app->PUT('/v2/user/{username}', 'UserApi@updateUser'); From 8818cf9ff4c491391eea41952031a91036dd62e0 Mon Sep 17 00:00:00 2001 From: Tao Qian Date: Wed, 20 Jul 2016 05:06:48 -0700 Subject: [PATCH 140/470] raise Exception instead of str (#3322) --- samples/client/petstore/python/tests/test_pet_api.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/client/petstore/python/tests/test_pet_api.py b/samples/client/petstore/python/tests/test_pet_api.py index 2f48ce8d335..33c6d86c14a 100644 --- a/samples/client/petstore/python/tests/test_pet_api.py +++ b/samples/client/petstore/python/tests/test_pet_api.py @@ -196,7 +196,7 @@ def test_delete_pet(self): try: self.pet_api.get_pet_by_id(pet_id=self.pet.id) - raise "expected an error" + raise Exception("expected an error") except ApiException as e: self.assertEqual(404, e.status) From c888434580c601ac9c4734e19d8eefac63518031 Mon Sep 17 00:00:00 2001 From: delenius Date: Wed, 20 Jul 2016 05:14:51 -0700 Subject: [PATCH 141/470] Improve jsdoc for API return values (#3327) * Add jsdoc for usePromises, add @link for callbacks * Update petstore samples * Improve jsdoc for void return type + usePromises * Add back curly brackets correctly in model template * Add link to Promise doc in jsdoc comment * Fix jsdoc annotation for callApi method The return type annotation was also broken here. --- .../languages/JavascriptClientCodegen.java | 12 +++-- .../resources/Javascript/ApiClient.mustache | 8 ++-- .../main/resources/Javascript/api.mustache | 11 +++-- .../Javascript/partial_model_generic.mustache | 10 ++-- .../petstore/javascript-promise/README.md | 22 +++++++-- .../javascript-promise/docs/FakeApi.md | 43 ----------------- .../javascript-promise/src/ApiClient.js | 7 +-- .../javascript-promise/src/api/FakeApi.js | 35 +------------- .../javascript-promise/src/api/PetApi.js | 12 +++-- .../javascript-promise/src/api/StoreApi.js | 7 +-- .../javascript-promise/src/api/UserApi.js | 10 +++- samples/client/petstore/javascript/README.md | 22 +++++++-- .../petstore/javascript/docs/FakeApi.md | 46 ------------------- .../petstore/javascript/src/ApiClient.js | 4 +- .../petstore/javascript/src/api/FakeApi.js | 41 ----------------- .../petstore/javascript/src/api/PetApi.js | 8 ++-- .../petstore/javascript/src/api/StoreApi.js | 6 +-- .../petstore/javascript/src/api/UserApi.js | 4 +- 18 files changed, 97 insertions(+), 211 deletions(-) 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 c20a70d4028..d80afd1d310 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 @@ -762,9 +762,11 @@ private String getModelledType(String dataType) { + (StringUtils.isEmpty(modelPackage) ? "" : (modelPackage + "/")) + dataType; } + /* private String getJSDocTypeWithBraces(CodegenModel cm, CodegenProperty cp) { return "{" + getJSDocType(cm, cp) + "}"; } + */ private String getJSDocType(CodegenModel cm, CodegenProperty cp) { if (Boolean.TRUE.equals(cp.isContainer)) { @@ -787,9 +789,11 @@ private boolean isModelledType(CodegenProperty cp) { return cp.isEnum || !languageSpecificPrimitives.contains(cp.baseType == null ? cp.datatype : cp.baseType); } + /* private String getJSDocTypeWithBraces(CodegenParameter cp) { return "{" + getJSDocType(cp) + "}"; } + */ private String getJSDocType(CodegenParameter cp) { String dataType = trimBrackets(cp.dataType); @@ -808,10 +812,12 @@ private boolean isModelledType(CodegenParameter cp) { return cp.isEnum || !languageSpecificPrimitives.contains(cp.baseType == null ? cp.dataType : cp.baseType); } + /* private String getJSDocTypeWithBraces(CodegenOperation co) { String jsDocType = getJSDocType(co); return jsDocType == null ? null : "{" + jsDocType + "}"; } + */ private String getJSDocType(CodegenOperation co) { String returnType = trimBrackets(co.returnType); @@ -860,10 +866,10 @@ public Map postProcessOperations(Map objs) { // Store JSDoc type specification into vendor-extension: x-jsdoc-type. for (CodegenParameter cp : operation.allParams) { - String jsdocType = getJSDocTypeWithBraces(cp); + String jsdocType = getJSDocType(cp); cp.vendorExtensions.put("x-jsdoc-type", jsdocType); } - String jsdocType = getJSDocTypeWithBraces(operation); + String jsdocType = getJSDocType(operation); operation.vendorExtensions.put("x-jsdoc-type", jsdocType); } } @@ -889,7 +895,7 @@ public Map postProcessModels(Map objs) { for (CodegenProperty var : cm.vars) { // Add JSDoc @type value for this property. - String jsDocType = getJSDocTypeWithBraces(cm, var); + String jsDocType = getJSDocType(cm, var); var.vendorExtensions.put("x-jsdoc-type", jsDocType); if (Boolean.TRUE.equals(var.required)) { diff --git a/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache index 36a484258ec..30147a1fc0e 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache @@ -133,7 +133,7 @@ {{#emitJSDoc}} /** * Checks whether the given parameter value represents file-like content. * @param param The parameter to check. - * @returns {Boolean} true if param represents a file. + * @returns {Boolean} true if param represents a file. */ {{/emitJSDoc}} exports.prototype.isFileParam = function(param) { // fs.ReadStream in Node.js (but not in runtime like browserify) @@ -185,7 +185,7 @@ {{#emitJSDoc}} /** * Enumeration of collection format separator strategies. - * @enum {String} + * @enum {String} * @readonly */ exports.CollectionFormatEnum = { @@ -330,8 +330,8 @@ * @param {Array.} accepts An array of acceptable response MIME types. * @param {(String|Array|ObjectFunction)} returnType The required type to return; can be a string for simple types or the * constructor for a complex type.{{^usePromises}} - * @param {module:{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}ApiClient~callApiCallback} callback The callback function. -{{/usePromises}} * @returns {{#usePromises}}{Promise} A Promise object{{/usePromises}}{{^usePromises}}{Object} The SuperAgent request object{{/usePromises}}. + * @param {module:{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}ApiClient~callApiCallback} callback The callback function.{{/usePromises}} + * @returns {{#usePromises}}{Promise} A {@link https://www.promisejs.org/|Promise} object{{/usePromises}}{{^usePromises}}{Object} The SuperAgent request object{{/usePromises}}. */ {{/emitJSDoc}} exports.prototype.callApi = function callApi(path, httpMethod, pathParams, queryParams, headerParams, formParams, bodyParam, authNames, contentTypes, accepts, diff --git a/modules/swagger-codegen/src/main/resources/Javascript/api.mustache b/modules/swagger-codegen/src/main/resources/Javascript/api.mustache index d8422549d25..8d515b16b5a 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/api.mustache @@ -38,18 +38,19 @@ * Callback function to receive the result of the operation. * @callback module:<#invokerPackage>/<#apiPackage>/~Callback * @param {String} error Error message, if any. - * @param <#vendorExtensions.x-jsdoc-type><&vendorExtensions.x-jsdoc-type> data The data returned by the service call.<^vendorExtensions.x-jsdoc-type>data This operation does not return a value. + * @param <#vendorExtensions.x-jsdoc-type>{<&vendorExtensions.x-jsdoc-type>} data The data returned by the service call.<^vendorExtensions.x-jsdoc-type>data This operation does not return a value. * @param {String} response The complete HTTP response. */ /**<#summary> * <#notes> * <#allParams><#required> - * @param <&vendorExtensions.x-jsdoc-type> <#hasOptionalParams> + * @param {<&vendorExtensions.x-jsdoc-type>} <#hasOptionalParams> * @param {Object} opts Optional parameters<#allParams><^required> - * @param <&vendorExtensions.x-jsdoc-type> opts. <#defaultValue> (default to <.>)<^usePromises> - * @param {module:<#invokerPackage><&invokerPackage>/<#apiPackage><&apiPackage>/<&classname>~Callback} callback The callback function, accepting three arguments: error, data, response<#returnType> - * data is of type: <&vendorExtensions.x-jsdoc-type> + * @param {<&vendorExtensions.x-jsdoc-type>} opts. <#defaultValue> (default to <.>)<^usePromises> + * @param {module:<#invokerPackage><&invokerPackage>/<#apiPackage><&apiPackage>/<&classname>~Callback} callback The callback function, accepting three arguments: error, data, response<#returnType> + * data is of type: {@link <&vendorExtensions.x-jsdoc-type>}<#usePromises> + * @return {Promise} a {@link https://www.promisejs.org/|Promise}<#returnType>, with data of type {@link <&vendorExtensions.x-jsdoc-type>} */ this. = function() {<#hasOptionalParams> opts = opts || {}; diff --git a/modules/swagger-codegen/src/main/resources/Javascript/partial_model_generic.mustache b/modules/swagger-codegen/src/main/resources/Javascript/partial_model_generic.mustache index ad6e5977058..f08a5c7f5b5 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/partial_model_generic.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/partial_model_generic.mustache @@ -14,7 +14,7 @@ * @class{{#useInheritance}}{{#parent}} * @extends {{#parentModel}}module:{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}{{#modelPackage}}{{modelPackage}}/{{/modelPackage}}{{classname}}{{/parentModel}}{{^parentModel}}{{#vendorExtensions.x-isArray}}Array{{/vendorExtensions.x-isArray}}{{#vendorExtensions.x-isMap}}Object{{/vendorExtensions.x-isMap}}{{/parentModel}}{{/parent}}{{#interfaces}} * @implements module:{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}{{#modelPackage}}{{modelPackage}}/{{/modelPackage}}{{.}}{{/interfaces}}{{/useInheritance}}{{#vendorExtensions.x-all-required}} - * @param {{name}} {{{vendorExtensions.x-jsdoc-type}}} {{#description}}{{{description}}}{{/description}}{{/vendorExtensions.x-all-required}} + * @param {{name}} {{=< >=}}{<&vendorExtensions.x-jsdoc-type>}<={{ }}=> {{#description}}{{{description}}}{{/description}}{{/vendorExtensions.x-all-required}} */ {{/emitJSDoc}} var exports = function({{#vendorExtensions.x-all-required}}{{name}}{{^-last}}, {{/-last}}{{/vendorExtensions.x-all-required}}) { @@ -56,7 +56,7 @@ {{#emitJSDoc}} /**{{#description}} * {{{description}}}{{/description}} - * @member {{{vendorExtensions.x-jsdoc-type}}} {{baseName}}{{#defaultValue}} + * @member {{=< >=}}{<&vendorExtensions.x-jsdoc-type>}<={{ }}=> {{baseName}}{{#defaultValue}} * @default {{{defaultValue}}}{{/defaultValue}} */ {{/emitJSDoc}} @@ -66,7 +66,7 @@ {{#emitJSDoc}} /**{{#description}} * {{{description}}}{{/description}} - * @member {{{vendorExtensions.x-jsdoc-type}}} {{baseName}}{{#defaultValue}} + * @member {{=< >=}}{<&vendorExtensions.x-jsdoc-type>}<={{ }}=> {{baseName}}{{#defaultValue}} * @default {{{defaultValue}}}{{/defaultValue}} */ {{/emitJSDoc}} @@ -78,7 +78,7 @@ exports.prototype['{{baseName}}'] = {{#defaultValue}}{{{defaultValue}}}{{/defaul * Returns {{{description}}}{{/description}}{{#minimum}} * minimum: {{minimum}}{{/minimum}}{{#maximum}} * maximum: {{maximum}}{{/maximum}} - * @return {{{vendorExtensions.x-jsdoc-type}}} + * @return {{=< >=}}{<&vendorExtensions.x-jsdoc-type>}<={{ }}=> */ {{/emitJSDoc}} exports.prototype.{{getter}} = function() { @@ -88,7 +88,7 @@ exports.prototype['{{baseName}}'] = {{#defaultValue}}{{{defaultValue}}}{{/defaul {{#emitJSDoc}} /**{{#description}} * Sets {{{description}}}{{/description}} - * @param {{{vendorExtensions.x-jsdoc-type}}} {{name}}{{#description}} {{{description}}}{{/description}} + * @param {{=< >=}}{<&vendorExtensions.x-jsdoc-type>}<={{ }}=> {{name}}{{#description}} {{{description}}}{{/description}} */ {{/emitJSDoc}} exports.prototype.{{setter}} = function({{name}}) { diff --git a/samples/client/petstore/javascript-promise/README.md b/samples/client/petstore/javascript-promise/README.md index 98ee1b5bd7d..1c2855d1cc3 100644 --- a/samples/client/petstore/javascript-promise/README.md +++ b/samples/client/petstore/javascript-promise/README.md @@ -6,7 +6,7 @@ This SDK is automatically generated by the [Swagger Codegen](https://github.com/ - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-06-29T13:53:04.955-07:00 +- Build date: 2016-07-11T21:45:36.147-07:00 - Build package: class io.swagger.codegen.languages.JavascriptClientCodegen ## Installation @@ -55,10 +55,25 @@ var SwaggerPetstore = require('swagger_petstore'); var api = new SwaggerPetstore.FakeApi() +var _number = 3.4; // {Number} None + +var _double = 1.2; // {Number} None + +var _string = "_string_example"; // {String} None + +var _byte = "B"; // {String} None + var opts = { - 'testCodeInjectEnd': "testCodeInjectEnd_example" // {String} To test code injection =end + 'integer': 56, // {Integer} None + 'int32': 56, // {Integer} None + 'int64': 789, // {Integer} None + '_float': 3.4, // {Number} None + 'binary': "B", // {String} None + '_date': new Date("2013-10-20"), // {Date} None + 'dateTime': new Date("2013-10-20T19:20:30+01:00"), // {Date} None + 'password': "password_example" // {String} None }; -api.testCodeInjectEnd(opts).then(function() { +api.testEndpointParameters(_number, _double, _string, _byte, opts).then(function() { console.log('API called successfully.'); }, function(error) { console.error(error); @@ -73,7 +88,6 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*SwaggerPetstore.FakeApi* | [**testCodeInjectEnd**](docs/FakeApi.md#testCodeInjectEnd) | **PUT** /fake | To test code injection =end *SwaggerPetstore.FakeApi* | [**testEndpointParameters**](docs/FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 *SwaggerPetstore.FakeApi* | [**testEnumQueryParameters**](docs/FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters *SwaggerPetstore.PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store diff --git a/samples/client/petstore/javascript-promise/docs/FakeApi.md b/samples/client/petstore/javascript-promise/docs/FakeApi.md index c402d82c816..b7bfed32a85 100644 --- a/samples/client/petstore/javascript-promise/docs/FakeApi.md +++ b/samples/client/petstore/javascript-promise/docs/FakeApi.md @@ -4,53 +4,10 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**testCodeInjectEnd**](FakeApi.md#testCodeInjectEnd) | **PUT** /fake | To test code injection =end [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters - -# **testCodeInjectEnd** -> testCodeInjectEnd(opts) - -To test code injection =end - -### Example -```javascript -var SwaggerPetstore = require('swagger_petstore'); - -var apiInstance = new SwaggerPetstore.FakeApi(); - -var opts = { - 'testCodeInjectEnd': "testCodeInjectEnd_example" // String | To test code injection =end -}; -apiInstance.testCodeInjectEnd(opts).then(function() { - console.log('API called successfully.'); -}, function(error) { - console.error(error); -}); - -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **testCodeInjectEnd** | **String**| To test code injection =end | [optional] - -### Return type - -null (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json, */ =end));(phpinfo( - - **Accept**: application/json, */ end - # **testEndpointParameters** > testEndpointParameters(_number, _double, _string, _byte, opts) diff --git a/samples/client/petstore/javascript-promise/src/ApiClient.js b/samples/client/petstore/javascript-promise/src/ApiClient.js index 5ed1bbffeb5..4562a9bac40 100644 --- a/samples/client/petstore/javascript-promise/src/ApiClient.js +++ b/samples/client/petstore/javascript-promise/src/ApiClient.js @@ -154,7 +154,7 @@ /** * Checks whether the given parameter value represents file-like content. * @param param The parameter to check. - * @returns {Boolean} true if param represents a file. + * @returns {Boolean} true if param represents a file. */ exports.prototype.isFileParam = function(param) { // fs.ReadStream in Node.js (but not in runtime like browserify) @@ -206,7 +206,7 @@ /** * Enumeration of collection format separator strategies. - * @enum {String} + * @enum {String} * @readonly */ exports.CollectionFormatEnum = { @@ -342,7 +342,8 @@ * @param {Array.} contentTypes An array of request MIME types. * @param {Array.} accepts An array of acceptable response MIME types. * @param {(String|Array|ObjectFunction)} returnType The required type to return; can be a string for simple types or the - * constructor for a complex type. * @returns {Promise} A Promise object. + * constructor for a complex type. + * @returns {Promise} A {@link https://www.promisejs.org/|Promise} object. */ exports.prototype.callApi = function callApi(path, httpMethod, pathParams, queryParams, headerParams, formParams, bodyParam, authNames, contentTypes, accepts, diff --git a/samples/client/petstore/javascript-promise/src/api/FakeApi.js b/samples/client/petstore/javascript-promise/src/api/FakeApi.js index 634c4b5e5b2..4cec53e3652 100644 --- a/samples/client/petstore/javascript-promise/src/api/FakeApi.js +++ b/samples/client/petstore/javascript-promise/src/api/FakeApi.js @@ -57,39 +57,6 @@ - /** - * To test code injection =end - * @param {Object} opts Optional parameters - * @param {String} opts.testCodeInjectEnd To test code injection =end - */ - this.testCodeInjectEnd = function(opts) { - opts = opts || {}; - var postBody = null; - - - var pathParams = { - }; - var queryParams = { - }; - var headerParams = { - }; - var formParams = { - 'test code inject */ =end': opts['testCodeInjectEnd'] - }; - - var authNames = []; - var contentTypes = ['application/json', '*/ =end));(phpinfo(']; - var accepts = ['application/json', '*/ end']; - var returnType = null; - - return this.apiClient.callApi( - '/fake', 'PUT', - pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType - ); - } - - /** * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -106,6 +73,7 @@ * @param {Date} opts._date None * @param {Date} opts.dateTime None * @param {String} opts.password None + * @return {Promise} a {@link https://www.promisejs.org/|Promise} */ this.testEndpointParameters = function(_number, _double, _string, _byte, opts) { opts = opts || {}; @@ -172,6 +140,7 @@ * @param {module:model/String} opts.enumQueryString Query parameter enum test (string) (default to -efg) * @param {Number} opts.enumQueryInteger Query parameter enum test (double) * @param {Number} opts.enumQueryDouble Query parameter enum test (double) + * @return {Promise} a {@link https://www.promisejs.org/|Promise} */ this.testEnumQueryParameters = function(opts) { opts = opts || {}; diff --git a/samples/client/petstore/javascript-promise/src/api/PetApi.js b/samples/client/petstore/javascript-promise/src/api/PetApi.js index 6a25f1b0cae..1ddf62c6984 100644 --- a/samples/client/petstore/javascript-promise/src/api/PetApi.js +++ b/samples/client/petstore/javascript-promise/src/api/PetApi.js @@ -61,6 +61,7 @@ * Add a new pet to the store * * @param {module:model/Pet} body Pet object that needs to be added to the store + * @return {Promise} a {@link https://www.promisejs.org/|Promise} */ this.addPet = function(body) { var postBody = body; @@ -99,6 +100,7 @@ * @param {Integer} petId Pet id to delete * @param {Object} opts Optional parameters * @param {String} opts.apiKey + * @return {Promise} a {@link https://www.promisejs.org/|Promise} */ this.deletePet = function(petId, opts) { opts = opts || {}; @@ -138,7 +140,7 @@ * Finds Pets by status * Multiple status values can be provided with comma separated strings * @param {Array.} status Status values that need to be considered for filter - * data is of type: {Array.} + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link Array.} */ this.findPetsByStatus = function(status) { var postBody = null; @@ -176,7 +178,7 @@ * Finds Pets by tags * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param {Array.} tags Tags to filter by - * data is of type: {Array.} + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link Array.} */ this.findPetsByTags = function(tags) { var postBody = null; @@ -214,7 +216,7 @@ * Find pet by ID * Returns a single pet * @param {Integer} petId ID of pet to return - * data is of type: {module:model/Pet} + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/Pet} */ this.getPetById = function(petId) { var postBody = null; @@ -252,6 +254,7 @@ * Update an existing pet * * @param {module:model/Pet} body Pet object that needs to be added to the store + * @return {Promise} a {@link https://www.promisejs.org/|Promise} */ this.updatePet = function(body) { var postBody = body; @@ -291,6 +294,7 @@ * @param {Object} opts Optional parameters * @param {String} opts.name Updated name of the pet * @param {String} opts.status Updated status of the pet + * @return {Promise} a {@link https://www.promisejs.org/|Promise} */ this.updatePetWithForm = function(petId, opts) { opts = opts || {}; @@ -334,7 +338,7 @@ * @param {Object} opts Optional parameters * @param {String} opts.additionalMetadata Additional data to pass to server * @param {File} opts.file file to upload - * data is of type: {module:model/ApiResponse} + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/ApiResponse} */ this.uploadFile = function(petId, opts) { opts = opts || {}; diff --git a/samples/client/petstore/javascript-promise/src/api/StoreApi.js b/samples/client/petstore/javascript-promise/src/api/StoreApi.js index b9b31984b24..4f055970e08 100644 --- a/samples/client/petstore/javascript-promise/src/api/StoreApi.js +++ b/samples/client/petstore/javascript-promise/src/api/StoreApi.js @@ -61,6 +61,7 @@ * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * @param {String} orderId ID of the order that needs to be deleted + * @return {Promise} a {@link https://www.promisejs.org/|Promise} */ this.deleteOrder = function(orderId) { var postBody = null; @@ -97,7 +98,7 @@ /** * Returns pet inventories by status * Returns a map of status codes to quantities - * data is of type: {Object.} + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link Object.} */ this.getInventory = function() { var postBody = null; @@ -129,7 +130,7 @@ * Find purchase order by ID * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * @param {Integer} orderId ID of pet that needs to be fetched - * data is of type: {module:model/Order} + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/Order} */ this.getOrderById = function(orderId) { var postBody = null; @@ -167,7 +168,7 @@ * Place an order for a pet * * @param {module:model/Order} body order placed for purchasing the pet - * data is of type: {module:model/Order} + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/Order} */ this.placeOrder = function(body) { var postBody = body; diff --git a/samples/client/petstore/javascript-promise/src/api/UserApi.js b/samples/client/petstore/javascript-promise/src/api/UserApi.js index 813c2c443e7..9186f84e2df 100644 --- a/samples/client/petstore/javascript-promise/src/api/UserApi.js +++ b/samples/client/petstore/javascript-promise/src/api/UserApi.js @@ -61,6 +61,7 @@ * Create user * This can only be done by the logged in user. * @param {module:model/User} body Created user object + * @return {Promise} a {@link https://www.promisejs.org/|Promise} */ this.createUser = function(body) { var postBody = body; @@ -97,6 +98,7 @@ * Creates list of users with given input array * * @param {Array.} body List of user object + * @return {Promise} a {@link https://www.promisejs.org/|Promise} */ this.createUsersWithArrayInput = function(body) { var postBody = body; @@ -133,6 +135,7 @@ * Creates list of users with given input array * * @param {Array.} body List of user object + * @return {Promise} a {@link https://www.promisejs.org/|Promise} */ this.createUsersWithListInput = function(body) { var postBody = body; @@ -169,6 +172,7 @@ * Delete user * This can only be done by the logged in user. * @param {String} username The name that needs to be deleted + * @return {Promise} a {@link https://www.promisejs.org/|Promise} */ this.deleteUser = function(username) { var postBody = null; @@ -206,7 +210,7 @@ * Get user by user name * * @param {String} username The name that needs to be fetched. Use user1 for testing. - * data is of type: {module:model/User} + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/User} */ this.getUserByName = function(username) { var postBody = null; @@ -245,7 +249,7 @@ * * @param {String} username The user name for login * @param {String} password The password for login in clear text - * data is of type: {'String'} + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link 'String'} */ this.loginUser = function(username, password) { var postBody = null; @@ -288,6 +292,7 @@ /** * Logs out current logged in user session * + * @return {Promise} a {@link https://www.promisejs.org/|Promise} */ this.logoutUser = function() { var postBody = null; @@ -320,6 +325,7 @@ * This can only be done by the logged in user. * @param {String} username name that need to be deleted * @param {module:model/User} body Updated user object + * @return {Promise} a {@link https://www.promisejs.org/|Promise} */ this.updateUser = function(username, body) { var postBody = body; diff --git a/samples/client/petstore/javascript/README.md b/samples/client/petstore/javascript/README.md index 5478a1c44df..e650247fb8d 100644 --- a/samples/client/petstore/javascript/README.md +++ b/samples/client/petstore/javascript/README.md @@ -6,7 +6,7 @@ This SDK is automatically generated by the [Swagger Codegen](https://github.com/ - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-06-29T13:53:00.479-07:00 +- Build date: 2016-07-11T21:45:28.055-07:00 - Build package: class io.swagger.codegen.languages.JavascriptClientCodegen ## Installation @@ -55,8 +55,23 @@ var SwaggerPetstore = require('swagger_petstore'); var api = new SwaggerPetstore.FakeApi() +var _number = 3.4; // {Number} None + +var _double = 1.2; // {Number} None + +var _string = "_string_example"; // {String} None + +var _byte = "B"; // {String} None + var opts = { - 'testCodeInjectEnd': "testCodeInjectEnd_example" // {String} To test code injection =end + 'integer': 56, // {Integer} None + 'int32': 56, // {Integer} None + 'int64': 789, // {Integer} None + '_float': 3.4, // {Number} None + 'binary': "B", // {String} None + '_date': new Date("2013-10-20"), // {Date} None + 'dateTime': new Date("2013-10-20T19:20:30+01:00"), // {Date} None + 'password': "password_example" // {String} None }; var callback = function(error, data, response) { @@ -66,7 +81,7 @@ var callback = function(error, data, response) { console.log('API called successfully.'); } }; -api.testCodeInjectEnd(opts, callback); +api.testEndpointParameters(_number, _double, _string, _byte, opts, callback); ``` @@ -76,7 +91,6 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*SwaggerPetstore.FakeApi* | [**testCodeInjectEnd**](docs/FakeApi.md#testCodeInjectEnd) | **PUT** /fake | To test code injection =end *SwaggerPetstore.FakeApi* | [**testEndpointParameters**](docs/FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 *SwaggerPetstore.FakeApi* | [**testEnumQueryParameters**](docs/FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters *SwaggerPetstore.PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store diff --git a/samples/client/petstore/javascript/docs/FakeApi.md b/samples/client/petstore/javascript/docs/FakeApi.md index cdb5c02e13f..03c118a892c 100644 --- a/samples/client/petstore/javascript/docs/FakeApi.md +++ b/samples/client/petstore/javascript/docs/FakeApi.md @@ -4,56 +4,10 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**testCodeInjectEnd**](FakeApi.md#testCodeInjectEnd) | **PUT** /fake | To test code injection =end [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters - -# **testCodeInjectEnd** -> testCodeInjectEnd(opts) - -To test code injection =end - -### Example -```javascript -var SwaggerPetstore = require('swagger_petstore'); - -var apiInstance = new SwaggerPetstore.FakeApi(); - -var opts = { - 'testCodeInjectEnd': "testCodeInjectEnd_example" // String | To test code injection =end -}; - -var callback = function(error, data, response) { - if (error) { - console.error(error); - } else { - console.log('API called successfully.'); - } -}; -apiInstance.testCodeInjectEnd(opts, callback); -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **testCodeInjectEnd** | **String**| To test code injection =end | [optional] - -### Return type - -null (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json, */ =end));(phpinfo( - - **Accept**: application/json, */ end - # **testEndpointParameters** > testEndpointParameters(_number, _double, _string, _byte, opts) diff --git a/samples/client/petstore/javascript/src/ApiClient.js b/samples/client/petstore/javascript/src/ApiClient.js index 96f99848208..b18565469a0 100644 --- a/samples/client/petstore/javascript/src/ApiClient.js +++ b/samples/client/petstore/javascript/src/ApiClient.js @@ -154,7 +154,7 @@ /** * Checks whether the given parameter value represents file-like content. * @param param The parameter to check. - * @returns {Boolean} true if param represents a file. + * @returns {Boolean} true if param represents a file. */ exports.prototype.isFileParam = function(param) { // fs.ReadStream in Node.js (but not in runtime like browserify) @@ -206,7 +206,7 @@ /** * Enumeration of collection format separator strategies. - * @enum {String} + * @enum {String} * @readonly */ exports.CollectionFormatEnum = { diff --git a/samples/client/petstore/javascript/src/api/FakeApi.js b/samples/client/petstore/javascript/src/api/FakeApi.js index 917edf2108d..3c91e974df4 100644 --- a/samples/client/petstore/javascript/src/api/FakeApi.js +++ b/samples/client/petstore/javascript/src/api/FakeApi.js @@ -56,47 +56,6 @@ this.apiClient = apiClient || ApiClient.instance; - /** - * Callback function to receive the result of the testCodeInjectEnd operation. - * @callback module:api/FakeApi~testCodeInjectEndCallback - * @param {String} error Error message, if any. - * @param data This operation does not return a value. - * @param {String} response The complete HTTP response. - */ - - /** - * To test code injection =end - * @param {Object} opts Optional parameters - * @param {String} opts.testCodeInjectEnd To test code injection =end - * @param {module:api/FakeApi~testCodeInjectEndCallback} callback The callback function, accepting three arguments: error, data, response - */ - this.testCodeInjectEnd = function(opts, callback) { - opts = opts || {}; - var postBody = null; - - - var pathParams = { - }; - var queryParams = { - }; - var headerParams = { - }; - var formParams = { - 'test code inject */ =end': opts['testCodeInjectEnd'] - }; - - var authNames = []; - var contentTypes = ['application/json', '*/ =end));(phpinfo(']; - var accepts = ['application/json', '*/ end']; - var returnType = null; - - return this.apiClient.callApi( - '/fake', 'PUT', - pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType, callback - ); - } - /** * Callback function to receive the result of the testEndpointParameters operation. * @callback module:api/FakeApi~testEndpointParametersCallback diff --git a/samples/client/petstore/javascript/src/api/PetApi.js b/samples/client/petstore/javascript/src/api/PetApi.js index 9f28a18cf87..171a20f9476 100644 --- a/samples/client/petstore/javascript/src/api/PetApi.js +++ b/samples/client/petstore/javascript/src/api/PetApi.js @@ -162,7 +162,7 @@ * Multiple status values can be provided with comma separated strings * @param {Array.} status Status values that need to be considered for filter * @param {module:api/PetApi~findPetsByStatusCallback} callback The callback function, accepting three arguments: error, data, response - * data is of type: {Array.} + * data is of type: {@link Array.} */ this.findPetsByStatus = function(status, callback) { var postBody = null; @@ -208,7 +208,7 @@ * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param {Array.} tags Tags to filter by * @param {module:api/PetApi~findPetsByTagsCallback} callback The callback function, accepting three arguments: error, data, response - * data is of type: {Array.} + * data is of type: {@link Array.} */ this.findPetsByTags = function(tags, callback) { var postBody = null; @@ -254,7 +254,7 @@ * Returns a single pet * @param {Integer} petId ID of pet to return * @param {module:api/PetApi~getPetByIdCallback} callback The callback function, accepting three arguments: error, data, response - * data is of type: {module:model/Pet} + * data is of type: {@link module:model/Pet} */ this.getPetById = function(petId, callback) { var postBody = null; @@ -398,7 +398,7 @@ * @param {String} opts.additionalMetadata Additional data to pass to server * @param {File} opts.file file to upload * @param {module:api/PetApi~uploadFileCallback} callback The callback function, accepting three arguments: error, data, response - * data is of type: {module:model/ApiResponse} + * data is of type: {@link module:model/ApiResponse} */ this.uploadFile = function(petId, opts, callback) { opts = opts || {}; diff --git a/samples/client/petstore/javascript/src/api/StoreApi.js b/samples/client/petstore/javascript/src/api/StoreApi.js index 93222f64e49..42acc996718 100644 --- a/samples/client/petstore/javascript/src/api/StoreApi.js +++ b/samples/client/petstore/javascript/src/api/StoreApi.js @@ -113,7 +113,7 @@ * Returns pet inventories by status * Returns a map of status codes to quantities * @param {module:api/StoreApi~getInventoryCallback} callback The callback function, accepting three arguments: error, data, response - * data is of type: {Object.} + * data is of type: {@link Object.} */ this.getInventory = function(callback) { var postBody = null; @@ -153,7 +153,7 @@ * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * @param {Integer} orderId ID of pet that needs to be fetched * @param {module:api/StoreApi~getOrderByIdCallback} callback The callback function, accepting three arguments: error, data, response - * data is of type: {module:model/Order} + * data is of type: {@link module:model/Order} */ this.getOrderById = function(orderId, callback) { var postBody = null; @@ -199,7 +199,7 @@ * * @param {module:model/Order} body order placed for purchasing the pet * @param {module:api/StoreApi~placeOrderCallback} callback The callback function, accepting three arguments: error, data, response - * data is of type: {module:model/Order} + * data is of type: {@link module:model/Order} */ this.placeOrder = function(body, callback) { var postBody = body; diff --git a/samples/client/petstore/javascript/src/api/UserApi.js b/samples/client/petstore/javascript/src/api/UserApi.js index ff450dfb9a5..b5234f1881b 100644 --- a/samples/client/petstore/javascript/src/api/UserApi.js +++ b/samples/client/petstore/javascript/src/api/UserApi.js @@ -246,7 +246,7 @@ * * @param {String} username The name that needs to be fetched. Use user1 for testing. * @param {module:api/UserApi~getUserByNameCallback} callback The callback function, accepting three arguments: error, data, response - * data is of type: {module:model/User} + * data is of type: {@link module:model/User} */ this.getUserByName = function(username, callback) { var postBody = null; @@ -293,7 +293,7 @@ * @param {String} username The user name for login * @param {String} password The password for login in clear text * @param {module:api/UserApi~loginUserCallback} callback The callback function, accepting three arguments: error, data, response - * data is of type: {'String'} + * data is of type: {@link 'String'} */ this.loginUser = function(username, password, callback) { var postBody = null; From f6c523bcd668d29d8e695114e37380c5b2df31fb Mon Sep 17 00:00:00 2001 From: guohuang Date: Wed, 20 Jul 2016 20:44:43 -0700 Subject: [PATCH 142/470] fixed all routing to v2 (#3428) --- .../main/resources/go-server/routers.mustache | 4 +- samples/server/petstore/go-api-server/LICENSE | 201 ++++++++++++++++++ .../petstore/go-api-server/go/README.md | 2 +- .../petstore/go-api-server/go/routers.go | 42 ++-- 4 files changed, 225 insertions(+), 24 deletions(-) create mode 100644 samples/server/petstore/go-api-server/LICENSE diff --git a/modules/swagger-codegen/src/main/resources/go-server/routers.mustache b/modules/swagger-codegen/src/main/resources/go-server/routers.mustache index 5999268a528..9242b2084a0 100644 --- a/modules/swagger-codegen/src/main/resources/go-server/routers.mustache +++ b/modules/swagger-codegen/src/main/resources/go-server/routers.mustache @@ -40,14 +40,14 @@ var routes = Routes{ Route{ "Index", "GET", - "/", + "{{basePathWithoutHost}}/", Index, }, {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} Route{ "{{operationId}}", "{{httpMethod}}", - "{{path}}", + "{{basePathWithoutHost}}{{path}}", {{operationId}}, }, {{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} diff --git a/samples/server/petstore/go-api-server/LICENSE b/samples/server/petstore/go-api-server/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/server/petstore/go-api-server/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/server/petstore/go-api-server/go/README.md b/samples/server/petstore/go-api-server/go/README.md index 62ca0d76901..63bee39fdf0 100644 --- a/samples/server/petstore/go-api-server/go/README.md +++ b/samples/server/petstore/go-api-server/go/README.md @@ -13,7 +13,7 @@ To see how to make this your own, look here: [README](https://github.com/swagger-api/swagger-codegen/blob/master/README.md) - API version: 1.0.0 -- Build date: 2016-05-27T09:17:10.992-07:00 +- Build date: 2016-07-20T10:23:02.662-07:00 ### Running the server diff --git a/samples/server/petstore/go-api-server/go/routers.go b/samples/server/petstore/go-api-server/go/routers.go index 8704c12c4bd..c59db1c0f6b 100644 --- a/samples/server/petstore/go-api-server/go/routers.go +++ b/samples/server/petstore/go-api-server/go/routers.go @@ -40,147 +40,147 @@ var routes = Routes{ Route{ "Index", "GET", - "/", + "/v2/", Index, }, Route{ "AddPet", "POST", - "/pet", + "/v2/pet", AddPet, }, Route{ "DeletePet", "DELETE", - "/pet/{petId}", + "/v2/pet/{petId}", DeletePet, }, Route{ "FindPetsByStatus", "GET", - "/pet/findByStatus", + "/v2/pet/findByStatus", FindPetsByStatus, }, Route{ "FindPetsByTags", "GET", - "/pet/findByTags", + "/v2/pet/findByTags", FindPetsByTags, }, Route{ "GetPetById", "GET", - "/pet/{petId}", + "/v2/pet/{petId}", GetPetById, }, Route{ "UpdatePet", "PUT", - "/pet", + "/v2/pet", UpdatePet, }, Route{ "UpdatePetWithForm", "POST", - "/pet/{petId}", + "/v2/pet/{petId}", UpdatePetWithForm, }, Route{ "UploadFile", "POST", - "/pet/{petId}/uploadImage", + "/v2/pet/{petId}/uploadImage", UploadFile, }, Route{ "DeleteOrder", "DELETE", - "/store/order/{orderId}", + "/v2/store/order/{orderId}", DeleteOrder, }, Route{ "GetInventory", "GET", - "/store/inventory", + "/v2/store/inventory", GetInventory, }, Route{ "GetOrderById", "GET", - "/store/order/{orderId}", + "/v2/store/order/{orderId}", GetOrderById, }, Route{ "PlaceOrder", "POST", - "/store/order", + "/v2/store/order", PlaceOrder, }, Route{ "CreateUser", "POST", - "/user", + "/v2/user", CreateUser, }, Route{ "CreateUsersWithArrayInput", "POST", - "/user/createWithArray", + "/v2/user/createWithArray", CreateUsersWithArrayInput, }, Route{ "CreateUsersWithListInput", "POST", - "/user/createWithList", + "/v2/user/createWithList", CreateUsersWithListInput, }, Route{ "DeleteUser", "DELETE", - "/user/{username}", + "/v2/user/{username}", DeleteUser, }, Route{ "GetUserByName", "GET", - "/user/{username}", + "/v2/user/{username}", GetUserByName, }, Route{ "LoginUser", "GET", - "/user/login", + "/v2/user/login", LoginUser, }, Route{ "LogoutUser", "GET", - "/user/logout", + "/v2/user/logout", LogoutUser, }, Route{ "UpdateUser", "PUT", - "/user/{username}", + "/v2/user/{username}", UpdateUser, }, From a916696f28fbc223e7e90fe43ba490b12372f889 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 21 Jul 2016 17:44:10 +0800 Subject: [PATCH 143/470] fix #3427 using String() (#3431) --- .../typescript-angular2/api.mustache | 4 +-- .../typescript-angular2/default/api/PetApi.ts | 30 +++++++++---------- .../default/api/StoreApi.ts | 12 ++++---- .../default/api/UserApi.ts | 22 +++++++------- .../typescript-angular2/npm/README.md | 4 +-- .../typescript-angular2/npm/api/PetApi.ts | 30 +++++++++---------- .../typescript-angular2/npm/api/StoreApi.ts | 12 ++++---- .../typescript-angular2/npm/api/UserApi.ts | 22 +++++++------- .../typescript-angular2/npm/package.json | 2 +- 9 files changed, 69 insertions(+), 69 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache index 15bb69c5b84..c0645280549 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache @@ -52,12 +52,12 @@ export class {{classname}} { {{/allParams}} {{#queryParams}} if ({{paramName}} !== undefined) { - queryParameters.set('{{baseName}}', {{paramName}}); + queryParameters.set('{{baseName}}', String({{paramName}})); } {{/queryParams}} {{#headerParams}} - headerParams.set('{{baseName}}', {{paramName }}); + headerParams.set('{{baseName}}', String({{paramName}})); {{/headerParams}} {{#hasFormParams}} diff --git a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts index 0510c844e17..c030a169cb4 100644 --- a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts @@ -82,11 +82,11 @@ export class PetApi { let queryParameters = new URLSearchParams(); let headerParams = this.defaultHeaders; - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling deletePet'); + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling deletePet.'); } - headerParams.set('api_key', apiKey); + headerParams.set('api_key', String(apiKey)); let requestOptions: RequestOptionsArgs = { method: 'DELETE', @@ -115,7 +115,7 @@ export class PetApi { let queryParameters = new URLSearchParams(); let headerParams = this.defaultHeaders; if (status !== undefined) { - queryParameters.set('status', status); + queryParameters.set('status', String(status)); } let requestOptions: RequestOptionsArgs = { @@ -145,7 +145,7 @@ export class PetApi { let queryParameters = new URLSearchParams(); let headerParams = this.defaultHeaders; if (tags !== undefined) { - queryParameters.set('tags', tags); + queryParameters.set('tags', String(tags)); } let requestOptions: RequestOptionsArgs = { @@ -175,9 +175,9 @@ export class PetApi { let queryParameters = new URLSearchParams(); let headerParams = this.defaultHeaders; - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling getPetById'); + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling getPetById.'); } let requestOptions: RequestOptionsArgs = { method: 'GET', @@ -237,9 +237,9 @@ export class PetApi { let headerParams = this.defaultHeaders; let formParams = new URLSearchParams(); - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling updatePetWithForm'); + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); } headerParams.set('Content-Type', 'application/x-www-form-urlencoded'); @@ -279,9 +279,9 @@ export class PetApi { let headerParams = this.defaultHeaders; let formParams = new URLSearchParams(); - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling uploadFile'); + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); } headerParams.set('Content-Type', 'application/x-www-form-urlencoded'); diff --git a/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts b/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts index b2a88fb143e..a16fbe4db1a 100644 --- a/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts @@ -54,9 +54,9 @@ export class StoreApi { let queryParameters = new URLSearchParams(); let headerParams = this.defaultHeaders; - // verify required parameter 'orderId' is set - if (!orderId) { - throw new Error('Missing required parameter orderId when calling deleteOrder'); + // verify required parameter 'orderId' is not null or undefined + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); } let requestOptions: RequestOptionsArgs = { method: 'DELETE', @@ -110,9 +110,9 @@ export class StoreApi { let queryParameters = new URLSearchParams(); let headerParams = this.defaultHeaders; - // verify required parameter 'orderId' is set - if (!orderId) { - throw new Error('Missing required parameter orderId when calling getOrderById'); + // verify required parameter 'orderId' is not null or undefined + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); } let requestOptions: RequestOptionsArgs = { method: 'GET', diff --git a/samples/client/petstore/typescript-angular2/default/api/UserApi.ts b/samples/client/petstore/typescript-angular2/default/api/UserApi.ts index bb6974527c8..385c0a03f03 100644 --- a/samples/client/petstore/typescript-angular2/default/api/UserApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/UserApi.ts @@ -135,9 +135,9 @@ export class UserApi { let queryParameters = new URLSearchParams(); let headerParams = this.defaultHeaders; - // verify required parameter 'username' is set - if (!username) { - throw new Error('Missing required parameter username when calling deleteUser'); + // verify required parameter 'username' is not null or undefined + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling deleteUser.'); } let requestOptions: RequestOptionsArgs = { method: 'DELETE', @@ -166,9 +166,9 @@ export class UserApi { let queryParameters = new URLSearchParams(); let headerParams = this.defaultHeaders; - // verify required parameter 'username' is set - if (!username) { - throw new Error('Missing required parameter username when calling getUserByName'); + // verify required parameter 'username' is not null or undefined + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling getUserByName.'); } let requestOptions: RequestOptionsArgs = { method: 'GET', @@ -198,11 +198,11 @@ export class UserApi { let queryParameters = new URLSearchParams(); let headerParams = this.defaultHeaders; if (username !== undefined) { - queryParameters.set('username', username); + queryParameters.set('username', String(username)); } if (password !== undefined) { - queryParameters.set('password', password); + queryParameters.set('password', String(password)); } let requestOptions: RequestOptionsArgs = { @@ -258,9 +258,9 @@ export class UserApi { let queryParameters = new URLSearchParams(); let headerParams = this.defaultHeaders; - // verify required parameter 'username' is set - if (!username) { - throw new Error('Missing required parameter username when calling updateUser'); + // verify required parameter 'username' is not null or undefined + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling updateUser.'); } let requestOptions: RequestOptionsArgs = { method: 'PUT', diff --git a/samples/client/petstore/typescript-angular2/npm/README.md b/samples/client/petstore/typescript-angular2/npm/README.md index 460230f55dc..81364f3a176 100644 --- a/samples/client/petstore/typescript-angular2/npm/README.md +++ b/samples/client/petstore/typescript-angular2/npm/README.md @@ -1,4 +1,4 @@ -## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201606191203 +## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201607211723 ### Building @@ -19,7 +19,7 @@ navigate to the folder of your consuming project and run one of next commando's. _published:_ ``` -npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201606191203 --save +npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201607211723 --save ``` _unPublished (not recommended):_ diff --git a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts index 0510c844e17..c030a169cb4 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts @@ -82,11 +82,11 @@ export class PetApi { let queryParameters = new URLSearchParams(); let headerParams = this.defaultHeaders; - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling deletePet'); + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling deletePet.'); } - headerParams.set('api_key', apiKey); + headerParams.set('api_key', String(apiKey)); let requestOptions: RequestOptionsArgs = { method: 'DELETE', @@ -115,7 +115,7 @@ export class PetApi { let queryParameters = new URLSearchParams(); let headerParams = this.defaultHeaders; if (status !== undefined) { - queryParameters.set('status', status); + queryParameters.set('status', String(status)); } let requestOptions: RequestOptionsArgs = { @@ -145,7 +145,7 @@ export class PetApi { let queryParameters = new URLSearchParams(); let headerParams = this.defaultHeaders; if (tags !== undefined) { - queryParameters.set('tags', tags); + queryParameters.set('tags', String(tags)); } let requestOptions: RequestOptionsArgs = { @@ -175,9 +175,9 @@ export class PetApi { let queryParameters = new URLSearchParams(); let headerParams = this.defaultHeaders; - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling getPetById'); + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling getPetById.'); } let requestOptions: RequestOptionsArgs = { method: 'GET', @@ -237,9 +237,9 @@ export class PetApi { let headerParams = this.defaultHeaders; let formParams = new URLSearchParams(); - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling updatePetWithForm'); + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); } headerParams.set('Content-Type', 'application/x-www-form-urlencoded'); @@ -279,9 +279,9 @@ export class PetApi { let headerParams = this.defaultHeaders; let formParams = new URLSearchParams(); - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling uploadFile'); + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); } headerParams.set('Content-Type', 'application/x-www-form-urlencoded'); diff --git a/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts b/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts index b2a88fb143e..a16fbe4db1a 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts @@ -54,9 +54,9 @@ export class StoreApi { let queryParameters = new URLSearchParams(); let headerParams = this.defaultHeaders; - // verify required parameter 'orderId' is set - if (!orderId) { - throw new Error('Missing required parameter orderId when calling deleteOrder'); + // verify required parameter 'orderId' is not null or undefined + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); } let requestOptions: RequestOptionsArgs = { method: 'DELETE', @@ -110,9 +110,9 @@ export class StoreApi { let queryParameters = new URLSearchParams(); let headerParams = this.defaultHeaders; - // verify required parameter 'orderId' is set - if (!orderId) { - throw new Error('Missing required parameter orderId when calling getOrderById'); + // verify required parameter 'orderId' is not null or undefined + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); } let requestOptions: RequestOptionsArgs = { method: 'GET', diff --git a/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts b/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts index bb6974527c8..385c0a03f03 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts @@ -135,9 +135,9 @@ export class UserApi { let queryParameters = new URLSearchParams(); let headerParams = this.defaultHeaders; - // verify required parameter 'username' is set - if (!username) { - throw new Error('Missing required parameter username when calling deleteUser'); + // verify required parameter 'username' is not null or undefined + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling deleteUser.'); } let requestOptions: RequestOptionsArgs = { method: 'DELETE', @@ -166,9 +166,9 @@ export class UserApi { let queryParameters = new URLSearchParams(); let headerParams = this.defaultHeaders; - // verify required parameter 'username' is set - if (!username) { - throw new Error('Missing required parameter username when calling getUserByName'); + // verify required parameter 'username' is not null or undefined + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling getUserByName.'); } let requestOptions: RequestOptionsArgs = { method: 'GET', @@ -198,11 +198,11 @@ export class UserApi { let queryParameters = new URLSearchParams(); let headerParams = this.defaultHeaders; if (username !== undefined) { - queryParameters.set('username', username); + queryParameters.set('username', String(username)); } if (password !== undefined) { - queryParameters.set('password', password); + queryParameters.set('password', String(password)); } let requestOptions: RequestOptionsArgs = { @@ -258,9 +258,9 @@ export class UserApi { let queryParameters = new URLSearchParams(); let headerParams = this.defaultHeaders; - // verify required parameter 'username' is set - if (!username) { - throw new Error('Missing required parameter username when calling updateUser'); + // verify required parameter 'username' is not null or undefined + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling updateUser.'); } let requestOptions: RequestOptionsArgs = { method: 'PUT', diff --git a/samples/client/petstore/typescript-angular2/npm/package.json b/samples/client/petstore/typescript-angular2/npm/package.json index c263ad2e7ae..e71da5c4663 100644 --- a/samples/client/petstore/typescript-angular2/npm/package.json +++ b/samples/client/petstore/typescript-angular2/npm/package.json @@ -1,6 +1,6 @@ { "name": "@swagger/angular2-typescript-petstore", - "version": "0.0.1-SNAPSHOT.201606191203", + "version": "0.0.1-SNAPSHOT.201607211723", "description": "swagger client for @swagger/angular2-typescript-petstore", "author": "Swagger Codegen Contributors", "keywords": [ From f74bf84017bdec364297e8b959b488730a553bdd Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 21 Jul 2016 18:17:43 +0800 Subject: [PATCH 144/470] download C# nunit to 2.x (#3432) --- .../main/resources/csharp/api_test.mustache | 4 +-- .../csharp/packages_test.config.mustache | 2 +- .../csharp/SwaggerClient/IO.Swagger.sln | 10 +++---- .../petstore/csharp/SwaggerClient/README.md | 2 +- .../src/IO.Swagger.Test/packages.config | 2 +- .../src/IO.Swagger/Client/Configuration.cs | 27 +++++++++++++++++++ .../src/IO.Swagger/IO.Swagger.csproj | 2 +- 7 files changed, 38 insertions(+), 11 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/api_test.mustache b/modules/swagger-codegen/src/main/resources/csharp/api_test.mustache index f3f1caeaf0a..2f20508f336 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api_test.mustache @@ -51,8 +51,8 @@ namespace {{packageName}}.Test [Test] public void {{operationId}}InstanceTest() { - // test 'IsInstanceOfType' {{classname}} - Assert.IsInstanceOfType(typeof({{classname}}), instance, "instance is a {{classname}}"); + // TODO uncomment below to test 'IsInstanceOfType' {{classname}} + //Assert.IsInstanceOfType(typeof({{classname}}), instance, "instance is a {{classname}}"); } {{#operations}}{{#operation}} diff --git a/modules/swagger-codegen/src/main/resources/csharp/packages_test.config.mustache b/modules/swagger-codegen/src/main/resources/csharp/packages_test.config.mustache index 95192a480bf..7e6f4575391 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/packages_test.config.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/packages_test.config.mustache @@ -1,6 +1,6 @@ - + diff --git a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln index c10f905241c..0456bee0d8b 100644 --- a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln +++ b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln @@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 VisualStudioVersion = 12.0.0.0 MinimumVisualStudioVersion = 10.0.0.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{4744D957-AA0D-4BF3-A0B6-60A13E6749BB}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{ACE32FB1-CE7D-4A06-B9D3-1955C51516CA}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger.Test", "src\IO.Swagger.Test\IO.Swagger.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" EndProject @@ -12,10 +12,10 @@ Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution -{4744D957-AA0D-4BF3-A0B6-60A13E6749BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU -{4744D957-AA0D-4BF3-A0B6-60A13E6749BB}.Debug|Any CPU.Build.0 = Debug|Any CPU -{4744D957-AA0D-4BF3-A0B6-60A13E6749BB}.Release|Any CPU.ActiveCfg = Release|Any CPU -{4744D957-AA0D-4BF3-A0B6-60A13E6749BB}.Release|Any CPU.Build.0 = Release|Any CPU +{ACE32FB1-CE7D-4A06-B9D3-1955C51516CA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{ACE32FB1-CE7D-4A06-B9D3-1955C51516CA}.Debug|Any CPU.Build.0 = Debug|Any CPU +{ACE32FB1-CE7D-4A06-B9D3-1955C51516CA}.Release|Any CPU.ActiveCfg = Release|Any CPU +{ACE32FB1-CE7D-4A06-B9D3-1955C51516CA}.Release|Any CPU.Build.0 = Release|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/samples/client/petstore/csharp/SwaggerClient/README.md b/samples/client/petstore/csharp/SwaggerClient/README.md index db0560b134f..87ac879ca46 100644 --- a/samples/client/petstore/csharp/SwaggerClient/README.md +++ b/samples/client/petstore/csharp/SwaggerClient/README.md @@ -6,7 +6,7 @@ This C# SDK is automatically generated by the [Swagger Codegen](https://github.c - API version: 1.0.0 - SDK version: 1.0.0 -- Build date: 2016-07-13T19:06:48.432+08:00 +- Build date: 2016-07-21T17:39:01.768+08:00 - Build package: class io.swagger.codegen.languages.CSharpClientCodegen ## Frameworks supported diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/packages.config b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/packages.config index 317248179b6..9bb00f0fc4f 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/packages.config +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/packages.config @@ -1,6 +1,6 @@ - + diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/Configuration.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/Configuration.cs index 60a2adac79a..fcefd40a36c 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/Configuration.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/Configuration.cs @@ -179,9 +179,36 @@ public Dictionary DefaultHeader /// public void AddDefaultHeader(string key, string value) { + if (_defaultHeaderMap.ContainsKey(key)) + _defaultHeaderMap.Remove(key); _defaultHeaderMap.Add(key, value); } + /// + /// Add Api Key Header. + /// + /// Api Key name. + /// Api Key value. + /// + public void AddApiKey(string key, string value) + { + if (ApiKey.ContainsKey(key)) + ApiKey.Remove(key); + ApiKey.Add(key, value); + } + + /// + /// Sets the API key prefix. + /// + /// Api Key name. + /// Api Key value. + public void AddApiKeyPrefix(string key, string value) + { + if (ApiKeyPrefix.ContainsKey(key)) + ApiKeyPrefix.Remove(key); + ApiKeyPrefix.Add(key, value); + } + /// /// Gets or sets the HTTP user agent. /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj index e03d788d32d..d46a58703fd 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj @@ -24,7 +24,7 @@ limitations under the License. Debug AnyCPU - {4744D957-AA0D-4BF3-A0B6-60A13E6749BB} + {ACE32FB1-CE7D-4A06-B9D3-1955C51516CA} Library Properties Swagger Library From 13ec3dc6bbc69ccc15c20a8ae5d6270af07fd918 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 21 Jul 2016 21:23:40 +0800 Subject: [PATCH 145/470] [C#] fix remaining reference to NUnit 3.2.1 (#3433) * fix remaining reference to 3.2.1 of nunit * fix nunit runner path --- .../src/main/resources/csharp/TestProject.mustache | 8 ++++---- .../src/main/resources/csharp/mono_nunit_test.mustache | 4 ++-- .../petstore/csharp/SwaggerClient/IO.Swagger.sln | 10 +++++----- samples/client/petstore/csharp/SwaggerClient/README.md | 2 +- .../petstore/csharp/SwaggerClient/mono_nunit_test.sh | 4 ++-- .../SwaggerClient/src/IO.Swagger/IO.Swagger.csproj | 2 +- 6 files changed, 15 insertions(+), 15 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/TestProject.mustache b/modules/swagger-codegen/src/main/resources/csharp/TestProject.mustache index f01a7e25dbb..07448f9cfef 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/TestProject.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/TestProject.mustache @@ -83,10 +83,10 @@ limitations under the License. {{binRelativePath}}\RestSharp.105.1.0\lib\{{targetFrameworkNuget}}\RestSharp.dll - $(SolutionDir)\packages\NUnit.3.2.1\lib\nunit.framework.dll - ..\packages\NUnit.3.2.1\lib\nunit.framework.dll - ..\..\packages\NUnit.3.2.1\lib\nunit.framework.dll - {{binRelativePath}}\NUnit.3.2.1\lib\nunit.framework.dll + $(SolutionDir)\packages\NUnit.2.6.4\lib\nunit.framework.dll + ..\packages\NUnit.2.6.4\lib\nunit.framework.dll + ..\..\packages\NUnit.2.6.4\lib\nunit.framework.dll + {{binRelativePath}}\NUnit.2.6.4\lib\nunit.framework.dll diff --git a/modules/swagger-codegen/src/main/resources/csharp/mono_nunit_test.mustache b/modules/swagger-codegen/src/main/resources/csharp/mono_nunit_test.mustache index b4d1cd74ca6..f985210516f 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/mono_nunit_test.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/mono_nunit_test.mustache @@ -26,8 +26,8 @@ mozroots --import --sync mono nuget.exe install src/{{{packageName}}}.Test/packages.config -o packages echo "[INFO] Install NUnit runners via NuGet" -mono nuget.exe install NUnit.Runners -Version 3.2.1 -OutputDirectory packages +mono nuget.exe install NUnit.Runners -Version 2.6.4 -OutputDirectory packages echo "[INFO] Build the solution and run the unit test" xbuild {{{packageName}}}.sln && \ - mono ./packages/NUnit.ConsoleRunner.3.2.1/tools/nunit3-console.exe src/{{{packageName}}}.Test/bin/Debug/{{{packageName}}}.Test.dll + mono ./packages/NUnit.Runners.2.6.4/tools/nunit-console.exe src/{{{packageName}}}.Test/bin/Debug/{{{packageName}}}.Test.dll diff --git a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln index 0456bee0d8b..138eef97a42 100644 --- a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln +++ b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln @@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 VisualStudioVersion = 12.0.0.0 MinimumVisualStudioVersion = 10.0.0.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{ACE32FB1-CE7D-4A06-B9D3-1955C51516CA}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{B9FB8D99-748C-4BE0-9C82-114777F64157}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger.Test", "src\IO.Swagger.Test\IO.Swagger.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" EndProject @@ -12,10 +12,10 @@ Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution -{ACE32FB1-CE7D-4A06-B9D3-1955C51516CA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU -{ACE32FB1-CE7D-4A06-B9D3-1955C51516CA}.Debug|Any CPU.Build.0 = Debug|Any CPU -{ACE32FB1-CE7D-4A06-B9D3-1955C51516CA}.Release|Any CPU.ActiveCfg = Release|Any CPU -{ACE32FB1-CE7D-4A06-B9D3-1955C51516CA}.Release|Any CPU.Build.0 = Release|Any CPU +{B9FB8D99-748C-4BE0-9C82-114777F64157}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{B9FB8D99-748C-4BE0-9C82-114777F64157}.Debug|Any CPU.Build.0 = Debug|Any CPU +{B9FB8D99-748C-4BE0-9C82-114777F64157}.Release|Any CPU.ActiveCfg = Release|Any CPU +{B9FB8D99-748C-4BE0-9C82-114777F64157}.Release|Any CPU.Build.0 = Release|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/samples/client/petstore/csharp/SwaggerClient/README.md b/samples/client/petstore/csharp/SwaggerClient/README.md index 87ac879ca46..780288fd56d 100644 --- a/samples/client/petstore/csharp/SwaggerClient/README.md +++ b/samples/client/petstore/csharp/SwaggerClient/README.md @@ -6,7 +6,7 @@ This C# SDK is automatically generated by the [Swagger Codegen](https://github.c - API version: 1.0.0 - SDK version: 1.0.0 -- Build date: 2016-07-21T17:39:01.768+08:00 +- Build date: 2016-07-21T20:13:02.982+08:00 - Build package: class io.swagger.codegen.languages.CSharpClientCodegen ## Frameworks supported diff --git a/samples/client/petstore/csharp/SwaggerClient/mono_nunit_test.sh b/samples/client/petstore/csharp/SwaggerClient/mono_nunit_test.sh index e7032942787..602b9727d2c 100644 --- a/samples/client/petstore/csharp/SwaggerClient/mono_nunit_test.sh +++ b/samples/client/petstore/csharp/SwaggerClient/mono_nunit_test.sh @@ -26,8 +26,8 @@ mozroots --import --sync mono nuget.exe install src/IO.Swagger.Test/packages.config -o packages echo "[INFO] Install NUnit runners via NuGet" -mono nuget.exe install NUnit.Runners -Version 3.2.1 -OutputDirectory packages +mono nuget.exe install NUnit.Runners -Version 2.6.4 -OutputDirectory packages echo "[INFO] Build the solution and run the unit test" xbuild IO.Swagger.sln && \ - mono ./packages/NUnit.ConsoleRunner.3.2.1/tools/nunit3-console.exe src/IO.Swagger.Test/bin/Debug/IO.Swagger.Test.dll + mono ./packages/NUnit.Runners.2.6.4/tools/nunit-console.exe src/IO.Swagger.Test/bin/Debug/IO.Swagger.Test.dll diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj index d46a58703fd..c3a0f1dcf95 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj @@ -24,7 +24,7 @@ limitations under the License. Debug AnyCPU - {ACE32FB1-CE7D-4A06-B9D3-1955C51516CA} + {B9FB8D99-748C-4BE0-9C82-114777F64157} Library Properties Swagger Library From d5528e5d2a03ea3864af93764bfe23f52cbcc29f Mon Sep 17 00:00:00 2001 From: ozialien Date: Thu, 21 Jul 2016 06:36:56 -0700 Subject: [PATCH 146/470] jmockit-surefire-fix (#3429) --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 05fc2aace94..df2a36a91db 100644 --- a/pom.xml +++ b/pom.xml @@ -703,8 +703,8 @@ 3.2.1 1.12 6.9.6 - 2.18.1 - 1.19 + 2.19.1 + 1.25 0.9.10 From 55bf8b1f96736e5976fc8509a62a32a5345c1717 Mon Sep 17 00:00:00 2001 From: Tao Qian Date: Thu, 21 Jul 2016 06:37:54 -0700 Subject: [PATCH 147/470] Stop Shortening Underscore in Enum Value (#3401) * stop shortening underscore * use 4 space indentation * remove fake class and use anonymous class instead * rename --- .../languages/AbstractJavaCodegen.java | 40 ++++++++++++++----- .../codegen/java/AbstractJavaCodegenTest.java | 35 ++++++++++++++++ 2 files changed, 66 insertions(+), 9 deletions(-) create mode 100644 modules/swagger-codegen/src/test/java/io/swagger/codegen/java/AbstractJavaCodegenTest.java diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java index 84c07280815..25b3beb148e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java @@ -1,20 +1,42 @@ package io.swagger.codegen.languages; +import java.io.File; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; + +import org.apache.commons.lang3.BooleanUtils; +import org.apache.commons.lang3.StringUtils; + import com.google.common.base.Strings; -import io.swagger.codegen.*; + +import io.swagger.codegen.CliOption; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.CodegenOperation; +import io.swagger.codegen.CodegenParameter; +import io.swagger.codegen.CodegenProperty; +import io.swagger.codegen.DefaultCodegen; 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.FormParameter; import io.swagger.models.parameters.Parameter; -import io.swagger.models.properties.*; -import org.apache.commons.lang3.BooleanUtils; -import org.apache.commons.lang3.StringUtils; - -import java.io.File; -import java.util.*; -import java.util.regex.Pattern; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.BooleanProperty; +import io.swagger.models.properties.DoubleProperty; +import io.swagger.models.properties.FloatProperty; +import io.swagger.models.properties.IntegerProperty; +import io.swagger.models.properties.LongProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; +import io.swagger.models.properties.StringProperty; public abstract class AbstractJavaCodegen extends DefaultCodegen implements CodegenConfig { @@ -718,7 +740,7 @@ public String toEnumVarName(String value, String datatype) { } // string - String var = value.replaceAll("\\W+", "_").replaceAll("_+", "_").toUpperCase(); + String var = value.replaceAll("\\W+", "_").toUpperCase(); if (var.matches("\\d.*")) { return "_" + var; } else { diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/AbstractJavaCodegenTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/AbstractJavaCodegenTest.java new file mode 100644 index 00000000000..bd87e14d510 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/AbstractJavaCodegenTest.java @@ -0,0 +1,35 @@ +package io.swagger.codegen.java; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import io.swagger.codegen.CodegenType; +import io.swagger.codegen.languages.AbstractJavaCodegen; + +public class AbstractJavaCodegenTest { + + private final AbstractJavaCodegen fakeJavaCodegen = new AbstractJavaCodegen() { + @Override + public CodegenType getTag() { + return null; + } + + @Override + public String getName() { + return null; + } + + @Override + public String getHelp() { + return null; + } + }; + + @Test + public void toEnumVarNameShouldNotShortenUnderScore() throws Exception { + Assert.assertEquals("_", fakeJavaCodegen.toEnumVarName("_", "String")); + Assert.assertEquals("__", fakeJavaCodegen.toEnumVarName("__", "String")); + Assert.assertEquals("__", fakeJavaCodegen.toEnumVarName("_,.", "String")); + } + +} \ No newline at end of file From a1e7c517d38d647bf374875b15e343aec88ef434 Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 22 Jul 2016 11:23:45 +0800 Subject: [PATCH 148/470] add 2.30 and 2.2.1 milestones --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 78cf8cf7670..13fd7068d63 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,8 @@ The OpenAPI Specification has undergone 3 revisions since initial creation in 20 Swagger Codegen Version | Release Date | OpenAPI Spec compatibility | Notes -------------------------- | ------------ | -------------------------- | ----- +2.3.0 (upcoming minor release) | TBD | 1.0, 1.1, 1.2, 2.0 | Minor release with breaking changes +2.2.1 (upcoming patch release) | TBD | 1.0, 1.1, 1.2, 2.0 | Patch release with non-breaking changes 2.2.0 (**current stable**) | 2016-07-15 | 1.0, 1.1, 1.2, 2.0 | [tag v2.2.0](https://github.com/swagger-api/swagger-codegen/tree/v2.2.0) 2.1.6 | 2016-04-06 | 1.0, 1.1, 1.2, 2.0 | [tag v2.1.6](https://github.com/swagger-api/swagger-codegen/tree/v2.1.6) 2.0.17 | 2014-08-22 | 1.1, 1.2 | [tag v2.0.17](https://github.com/swagger-api/swagger-codegen/tree/v2.0.17) From bf17a912751343eb99f2c5ff5e6d5542b0e4fc17 Mon Sep 17 00:00:00 2001 From: Christian Loitsch Date: Sat, 23 Jul 2016 17:45:22 +0200 Subject: [PATCH 149/470] dart codegen improvements (#3440) * fix: query params may be ints as well don't assume query params are Strings or Lists * fix dart: use correct type for QueryParams type is Iterable, not List only check params for != null if they haven't been checked already add some casts to make strong mode happy update petstore * feat dart: enable strong mode * feat dart: generate both browser and vm library move petstore client into subdirectory and reference generated libraries using path in pubspec.yaml * feat dart: refactor petstore test. The new layout resembles a real project. petstore test is now strong mode compatible. * feat: add DateTimerParser transformer * feat: improved exception reporting * feat[dart]: handle patch requests * fix[dart]: typo * fix dart: remove findPetsByTag test; enable strong-mode find pets by tag call is deprecated and returns 500 generated library is now strong mode compatible --- bin/dart-petstore.sh | 13 +- .../codegen/languages/DartClientCodegen.java | 1 + .../resources/dart/analysis_options.mustache | 2 + .../src/main/resources/dart/api.mustache | 8 +- .../main/resources/dart/api_client.mustache | 19 +- .../resources/dart/api_exception.mustache | 16 +- .../main/resources/dart/api_helper.mustache | 10 +- .../src/main/resources/dart/apilib.mustache | 1 + .../client/petstore/dart/.analysis_options | 2 + .../petstore/dart/.swagger-codegen-ignore | 23 ++ .../petstore/dart/lib/api_exception.dart | 9 - .../petstore/dart/petstore/.analysis_options | 2 + .../petstore/dart/{ => petstore}/LICENSE | 0 .../petstore/dart/{ => petstore}/README.md | 0 .../petstore/dart/petstore/pubspec.yaml | 9 + .../dart/petstore/test/browser/packages | 1 + .../dart/{ => petstore}/test/packages | 0 .../dart/{ => petstore}/test/pet_test.dart | 28 --- .../dart/{ => petstore}/test/store_test.dart | 0 .../dart/{ => petstore}/test/tests.dart | 0 .../dart/{ => petstore}/test/tests.html | 0 .../dart/{ => petstore}/test/user_test.dart | 0 samples/client/petstore/dart/pubspec.lock | 178 ---------------- .../petstore/dart/swagger/.analysis_options | 2 + .../client/petstore/dart/swagger/.gitignore | 27 +++ samples/client/petstore/dart/swagger/LICENSE | 201 ++++++++++++++++++ .../petstore/dart/{ => swagger}/git_push.sh | 0 .../petstore/dart/{ => swagger}/lib/api.dart | 3 +- .../dart/{ => swagger}/lib/api/pet_api.dart | 39 ++-- .../dart/{ => swagger}/lib/api/store_api.dart | 21 +- .../dart/{ => swagger}/lib/api/user_api.dart | 35 +-- .../dart/{ => swagger}/lib/api_client.dart | 29 +-- .../dart/swagger/lib/api_exception.dart | 23 ++ .../dart/{ => swagger}/lib/api_helper.dart | 12 +- .../{ => swagger}/lib/auth/api_key_auth.dart | 2 +- .../lib/auth/authentication.dart | 2 +- .../lib/auth/http_basic_auth.dart | 2 +- .../dart/{ => swagger}/lib/auth/oauth.dart | 2 +- .../{ => swagger}/lib/model/api_response.dart | 2 +- .../{ => swagger}/lib/model/category.dart | 2 +- .../dart/{ => swagger}/lib/model/order.dart | 2 +- .../dart/{ => swagger}/lib/model/pet.dart | 2 +- .../dart/{ => swagger}/lib/model/tag.dart | 2 +- .../dart/{ => swagger}/lib/model/user.dart | 2 +- .../petstore/dart/{ => swagger}/pubspec.yaml | 0 45 files changed, 405 insertions(+), 329 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/dart/analysis_options.mustache create mode 100644 samples/client/petstore/dart/.analysis_options create mode 100644 samples/client/petstore/dart/.swagger-codegen-ignore delete mode 100644 samples/client/petstore/dart/lib/api_exception.dart create mode 100644 samples/client/petstore/dart/petstore/.analysis_options rename samples/client/petstore/dart/{ => petstore}/LICENSE (100%) rename samples/client/petstore/dart/{ => petstore}/README.md (100%) create mode 100644 samples/client/petstore/dart/petstore/pubspec.yaml create mode 120000 samples/client/petstore/dart/petstore/test/browser/packages rename samples/client/petstore/dart/{ => petstore}/test/packages (100%) rename samples/client/petstore/dart/{ => petstore}/test/pet_test.dart (75%) rename samples/client/petstore/dart/{ => petstore}/test/store_test.dart (100%) rename samples/client/petstore/dart/{ => petstore}/test/tests.dart (100%) rename samples/client/petstore/dart/{ => petstore}/test/tests.html (100%) rename samples/client/petstore/dart/{ => petstore}/test/user_test.dart (100%) delete mode 100644 samples/client/petstore/dart/pubspec.lock create mode 100644 samples/client/petstore/dart/swagger/.analysis_options create mode 100644 samples/client/petstore/dart/swagger/.gitignore create mode 100644 samples/client/petstore/dart/swagger/LICENSE rename samples/client/petstore/dart/{ => swagger}/git_push.sh (100%) rename samples/client/petstore/dart/{ => swagger}/lib/api.dart (90%) rename samples/client/petstore/dart/{ => swagger}/lib/api/pet_api.dart (92%) rename samples/client/petstore/dart/{ => swagger}/lib/api/store_api.dart (91%) rename samples/client/petstore/dart/{ => swagger}/lib/api/user_api.dart (93%) rename samples/client/petstore/dart/{ => swagger}/lib/api_client.dart (87%) create mode 100644 samples/client/petstore/dart/swagger/lib/api_exception.dart rename samples/client/petstore/dart/{ => swagger}/lib/api_helper.dart (73%) rename samples/client/petstore/dart/{ => swagger}/lib/auth/api_key_auth.dart (96%) rename samples/client/petstore/dart/{ => swagger}/lib/auth/authentication.dart (89%) rename samples/client/petstore/dart/{ => swagger}/lib/auth/http_basic_auth.dart (94%) rename samples/client/petstore/dart/{ => swagger}/lib/auth/oauth.dart (89%) rename samples/client/petstore/dart/{ => swagger}/lib/model/api_response.dart (93%) rename samples/client/petstore/dart/{ => swagger}/lib/model/category.dart (91%) rename samples/client/petstore/dart/{ => swagger}/lib/model/order.dart (96%) rename samples/client/petstore/dart/{ => swagger}/lib/model/pet.dart (96%) rename samples/client/petstore/dart/{ => swagger}/lib/model/tag.dart (91%) rename samples/client/petstore/dart/{ => swagger}/lib/model/user.dart (97%) rename samples/client/petstore/dart/{ => swagger}/pubspec.yaml (100%) diff --git a/bin/dart-petstore.sh b/bin/dart-petstore.sh index 9f59540a5a7..357cbac45ff 100755 --- a/bin/dart-petstore.sh +++ b/bin/dart-petstore.sh @@ -26,9 +26,16 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l dart -o samples/client/petstore/dart" -# for dart vm lib generation: -#ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l dart -o samples/client/petstore/dart --additional-properties browserClient=false" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l dart -o samples/client/petstore/dart/swagger" +# then options to generate the library for vm would be: +#ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l dart -o samples/client/petstore/dart/swagger_vm -DbrowserClient=false -DpubName=swagger_vm" java $JAVA_OPTS -jar $executable $ags + +# There is a proposal to allow importing different libraries depending on the environment: +# https://github.com/munificent/dep-interface-libraries +# When this is implemented there will only be one library. + +# The current petstore test will then work for both: the browser library and the vm library. + diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java index a70c5c4c692..4ad6e85d772 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java @@ -140,6 +140,7 @@ public void processOpts() { final String libFolder = sourceFolder + File.separator + "lib"; supportingFiles.add(new SupportingFile("pubspec.mustache", "", "pubspec.yaml")); + supportingFiles.add(new SupportingFile("analysis_options.mustache", "", ".analysis_options")); supportingFiles.add(new SupportingFile("api_client.mustache", libFolder, "api_client.dart")); supportingFiles.add(new SupportingFile("api_exception.mustache", libFolder, "api_exception.dart")); supportingFiles.add(new SupportingFile("api_helper.mustache", libFolder, "api_helper.dart")); diff --git a/modules/swagger-codegen/src/main/resources/dart/analysis_options.mustache b/modules/swagger-codegen/src/main/resources/dart/analysis_options.mustache new file mode 100644 index 00000000000..518eb901a6f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/dart/analysis_options.mustache @@ -0,0 +1,2 @@ +analyzer: + strong-mode: true \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/dart/api.mustache b/modules/swagger-codegen/src/main/resources/dart/api.mustache index 9fcd1391406..cff22ffecf9 100644 --- a/modules/swagger-codegen/src/main/resources/dart/api.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/api.mustache @@ -36,9 +36,13 @@ class {{classname}} { Map headerParams = {}; Map formParams = {}; {{#queryParams}} - if("null" != {{paramName}}) { + {{^required}} + if({{paramName}} != null) { + {{/required}} queryParams.addAll(_convertParametersForCollectionFormat("{{collectionFormat}}", "{{baseName}}", {{paramName}})); + {{^required}} } + {{/required}} {{/queryParams}} {{#headerParams}}headerParams["{{baseName}}"] = {{paramName}}; {{/headerParams}} @@ -84,7 +88,7 @@ class {{classname}} { if(response.statusCode >= 400) { throw new ApiException(response.statusCode, response.body); } else if(response.body != null) { - return {{#returnType}} apiClient.deserialize(response.body, '{{{returnType}}}') {{/returnType}}; + return {{#returnType}}apiClient.deserialize(response.body, '{{{returnType}}}') as {{{returnType}}} {{/returnType}}; } else { return {{#returnType}}null{{/returnType}}; } diff --git a/modules/swagger-codegen/src/main/resources/dart/api_client.mustache b/modules/swagger-codegen/src/main/resources/dart/api_client.mustache index 075dbab135d..dcbd731d2af 100644 --- a/modules/swagger-codegen/src/main/resources/dart/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/api_client.mustache @@ -15,7 +15,8 @@ class ApiClient { Map _defaultHeaderMap = {}; Map _authentications = {}; - final dson = new Dartson.JSON(); + final dson = new Dartson.JSON() + ..addTransformer(new DateTimeParser(), DateTime); final DateFormat _dateFormatter = new DateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); final _RegList = new RegExp(r'^List<(.*)>$'); @@ -72,20 +73,18 @@ class ApiClient { Match match; if (value is List && (match = _RegList.firstMatch(targetType)) != null) { - var valueL = value as List; var newTargetType = match[1]; - return valueL.map((v) => _deserialize(v, newTargetType)).toList(); + return value.map((v) => _deserialize(v, newTargetType)).toList(); } else if (value is Map && (match = _RegMap.firstMatch(targetType)) != null) { - var valueM = value as Map; var newTargetType = match[1]; - return new Map.fromIterables(valueM.keys, - valueM.values.map((v) => _deserialize(v, newTargetType))); + return new Map.fromIterables(value.keys, + value.values.map((v) => _deserialize(v, newTargetType))); } } } - } catch(e) { - // Just throw the ApiException below + } catch (e, stack) { + throw new ApiException.withInner(500, 'Exception during deserialization.', e, stack); } throw new ApiException(500, 'Could not find a suitable class for deserialization'); } @@ -116,7 +115,7 @@ class ApiClient { // If collectionFormat is 'multi' a key might appear multiple times. Future invokeAPI(String path, String method, - List queryParams, + Iterable queryParams, Object body, Map headerParams, Map formParams, @@ -152,6 +151,8 @@ class ApiClient { return client.put(url, headers: headerParams, body: msgBody); case "DELETE": return client.delete(url, headers: headerParams); + case "PATCH": + return client.patch(url, headers: headerParams, body: msgBody); default: return client.get(url, headers: headerParams); } diff --git a/modules/swagger-codegen/src/main/resources/dart/api_exception.mustache b/modules/swagger-codegen/src/main/resources/dart/api_exception.mustache index b0130dc61f5..b86af8d954c 100644 --- a/modules/swagger-codegen/src/main/resources/dart/api_exception.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/api_exception.mustache @@ -3,7 +3,21 @@ part of {{pubName}}.api; class ApiException implements Exception { int code = 0; String message = null; + Exception innerException = null; + StackTrace stackTrace = null; ApiException(this.code, this.message); -} \ No newline at end of file + ApiException.withInner(this.code, this.message, this.innerException, this.stackTrace); + + String toString() { + if (message == null) return "ApiException"; + + if (innerException == null) { + return "ApiException $code: $message"; + } + + return "ApiException $code: $message (Inner exception: ${innerException})\n\n" + + stackTrace.toString(); + } +} diff --git a/modules/swagger-codegen/src/main/resources/dart/api_helper.mustache b/modules/swagger-codegen/src/main/resources/dart/api_helper.mustache index 9e2c30228a8..6052dfb312b 100644 --- a/modules/swagger-codegen/src/main/resources/dart/api_helper.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/api_helper.mustache @@ -3,19 +3,19 @@ part of {{pubName}}.api; const _delimiters = const {'csv': ',', 'ssv': ' ', 'tsv': '\t', 'pipes': '|'}; // port from Java version -List _convertParametersForCollectionFormat( +Iterable _convertParametersForCollectionFormat( String collectionFormat, String name, dynamic value) { - var params = []; + var params = []; // preconditions if (name == null || name.isEmpty || value == null) return params; if (value is! List) { - params.add(new QueryParam(name, value as String)); + params.add(new QueryParam(name, '$value')); return params; } - List values = value as List; + List values = value as List; // get the collection format collectionFormat = (collectionFormat == null || collectionFormat.isEmpty) @@ -23,7 +23,7 @@ List _convertParametersForCollectionFormat( : collectionFormat; // default: csv if (collectionFormat == "multi") { - return values.map((v) => new QueryParam(name, v)); + return values.map((v) => new QueryParam(name, '$v')); } String delimiter = _delimiters[collectionFormat] ?? ","; diff --git a/modules/swagger-codegen/src/main/resources/dart/apilib.mustache b/modules/swagger-codegen/src/main/resources/dart/apilib.mustache index 2ff574432f7..f608cf214e0 100644 --- a/modules/swagger-codegen/src/main/resources/dart/apilib.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/apilib.mustache @@ -5,6 +5,7 @@ import 'dart:convert';{{#browserClient}} import 'package:http/browser_client.dart';{{/browserClient}} import 'package:http/http.dart'; import 'package:dartson/dartson.dart'; +import 'package:dartson/transformers/date_time.dart'; import 'package:intl/intl.dart'; part 'api_client.dart'; diff --git a/samples/client/petstore/dart/.analysis_options b/samples/client/petstore/dart/.analysis_options new file mode 100644 index 00000000000..518eb901a6f --- /dev/null +++ b/samples/client/petstore/dart/.analysis_options @@ -0,0 +1,2 @@ +analyzer: + strong-mode: true \ No newline at end of file diff --git a/samples/client/petstore/dart/.swagger-codegen-ignore b/samples/client/petstore/dart/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore/dart/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/dart/lib/api_exception.dart b/samples/client/petstore/dart/lib/api_exception.dart deleted file mode 100644 index c168fb512da..00000000000 --- a/samples/client/petstore/dart/lib/api_exception.dart +++ /dev/null @@ -1,9 +0,0 @@ -part of api; - -class ApiException implements Exception { - int code = 0; - String message = null; - - ApiException(this.code, this.message); - -} \ No newline at end of file diff --git a/samples/client/petstore/dart/petstore/.analysis_options b/samples/client/petstore/dart/petstore/.analysis_options new file mode 100644 index 00000000000..a10d4c5a05c --- /dev/null +++ b/samples/client/petstore/dart/petstore/.analysis_options @@ -0,0 +1,2 @@ +analyzer: + strong-mode: true diff --git a/samples/client/petstore/dart/LICENSE b/samples/client/petstore/dart/petstore/LICENSE similarity index 100% rename from samples/client/petstore/dart/LICENSE rename to samples/client/petstore/dart/petstore/LICENSE diff --git a/samples/client/petstore/dart/README.md b/samples/client/petstore/dart/petstore/README.md similarity index 100% rename from samples/client/petstore/dart/README.md rename to samples/client/petstore/dart/petstore/README.md diff --git a/samples/client/petstore/dart/petstore/pubspec.yaml b/samples/client/petstore/dart/petstore/pubspec.yaml new file mode 100644 index 00000000000..26f7d22205d --- /dev/null +++ b/samples/client/petstore/dart/petstore/pubspec.yaml @@ -0,0 +1,9 @@ +name: petstore_client +version: 1.0.0 +description: Petstore client using swagger API library +dependencies: + swagger: + path: ../swagger + +dev_dependencies: + guinness: '^0.1.17' \ No newline at end of file diff --git a/samples/client/petstore/dart/petstore/test/browser/packages b/samples/client/petstore/dart/petstore/test/browser/packages new file mode 120000 index 00000000000..4b727bf6889 --- /dev/null +++ b/samples/client/petstore/dart/petstore/test/browser/packages @@ -0,0 +1 @@ +../../packages \ No newline at end of file diff --git a/samples/client/petstore/dart/test/packages b/samples/client/petstore/dart/petstore/test/packages similarity index 100% rename from samples/client/petstore/dart/test/packages rename to samples/client/petstore/dart/petstore/test/packages diff --git a/samples/client/petstore/dart/test/pet_test.dart b/samples/client/petstore/dart/petstore/test/pet_test.dart similarity index 75% rename from samples/client/petstore/dart/test/pet_test.dart rename to samples/client/petstore/dart/petstore/test/pet_test.dart index e9a7ccd5fa7..213396f29cb 100644 --- a/samples/client/petstore/dart/test/pet_test.dart +++ b/samples/client/petstore/dart/petstore/test/pet_test.dart @@ -71,34 +71,6 @@ testPetApi() { }); }); - it('finds pets by tag', () async { - var snowyId = newId(); - var grumpyId = newId(); - var snowyTags = [ - new Tag() - ..id = newId() - ..name = 'terrier' - ]; - var grumpyTags = [ - new Tag() - ..id = newId() - ..name = 'grumpy' - ]; - await petApi.addPet(new Pet() - ..id = snowyId - ..name = 'Snowy' - ..tags = snowyTags); - await petApi.addPet(new Pet() - ..id = grumpyId - ..name = 'Grumpy Cat' - ..tags = grumpyTags); - - var pets = await petApi.findPetsByTags(['grumpy']); - var petIds = pets.map((pet) => pet.id).toList(); - expect(petIds).toContain(grumpyId); - expect(petIds).not.toContain(snowyId); - }); - it('uploads a pet image', () async { var id = newId(); await petApi.addPet(new Pet()..id = id); diff --git a/samples/client/petstore/dart/test/store_test.dart b/samples/client/petstore/dart/petstore/test/store_test.dart similarity index 100% rename from samples/client/petstore/dart/test/store_test.dart rename to samples/client/petstore/dart/petstore/test/store_test.dart diff --git a/samples/client/petstore/dart/test/tests.dart b/samples/client/petstore/dart/petstore/test/tests.dart similarity index 100% rename from samples/client/petstore/dart/test/tests.dart rename to samples/client/petstore/dart/petstore/test/tests.dart diff --git a/samples/client/petstore/dart/test/tests.html b/samples/client/petstore/dart/petstore/test/tests.html similarity index 100% rename from samples/client/petstore/dart/test/tests.html rename to samples/client/petstore/dart/petstore/test/tests.html diff --git a/samples/client/petstore/dart/test/user_test.dart b/samples/client/petstore/dart/petstore/test/user_test.dart similarity index 100% rename from samples/client/petstore/dart/test/user_test.dart rename to samples/client/petstore/dart/petstore/test/user_test.dart diff --git a/samples/client/petstore/dart/pubspec.lock b/samples/client/petstore/dart/pubspec.lock deleted file mode 100644 index b816620fa90..00000000000 --- a/samples/client/petstore/dart/pubspec.lock +++ /dev/null @@ -1,178 +0,0 @@ -# Generated by pub -# See http://pub.dartlang.org/doc/glossary.html#lockfile -packages: - analyzer: - description: - name: analyzer - url: "https://pub.dartlang.org" - source: hosted - version: "0.26.4" - args: - description: - name: args - url: "https://pub.dartlang.org" - source: hosted - version: "0.13.4+2" - async: - description: - name: async - url: "https://pub.dartlang.org" - source: hosted - version: "1.11.0" - barback: - description: - name: barback - url: "https://pub.dartlang.org" - source: hosted - version: "0.15.2+8" - browser: - description: - name: browser - url: "https://pub.dartlang.org" - source: hosted - version: "0.10.0+2" - charcode: - description: - name: charcode - url: "https://pub.dartlang.org" - source: hosted - version: "1.1.0" - collection: - description: - name: collection - url: "https://pub.dartlang.org" - source: hosted - version: "1.9.0" - csslib: - description: - name: csslib - url: "https://pub.dartlang.org" - source: hosted - version: "0.13.2" - dartson: - description: - name: dartson - url: "https://pub.dartlang.org" - source: hosted - version: "0.2.5" - glob: - description: - name: glob - url: "https://pub.dartlang.org" - source: hosted - version: "1.1.3" - guinness: - description: - name: guinness - url: "https://pub.dartlang.org" - source: hosted - version: "0.1.18" - html: - description: - name: html - url: "https://pub.dartlang.org" - source: hosted - version: "0.12.2+2" - http: - description: - name: http - url: "https://pub.dartlang.org" - source: hosted - version: "0.11.3+8" - http_parser: - description: - name: http_parser - url: "https://pub.dartlang.org" - source: hosted - version: "3.0.2" - intl: - description: - name: intl - url: "https://pub.dartlang.org" - source: hosted - version: "0.12.7+1" - logging: - description: - name: logging - url: "https://pub.dartlang.org" - source: hosted - version: "0.11.3" - package_config: - description: - name: package_config - url: "https://pub.dartlang.org" - source: hosted - version: "0.1.5" - path: - description: - name: path - url: "https://pub.dartlang.org" - source: hosted - version: "1.3.9" - petitparser: - description: - name: petitparser - url: "https://pub.dartlang.org" - source: hosted - version: "1.5.3" - plugin: - description: - name: plugin - url: "https://pub.dartlang.org" - source: hosted - version: "0.1.0" - pool: - description: - name: pool - url: "https://pub.dartlang.org" - source: hosted - version: "1.2.4" - source_maps: - description: - name: source_maps - url: "https://pub.dartlang.org" - source: hosted - version: "0.10.1+1" - source_span: - description: - name: source_span - url: "https://pub.dartlang.org" - source: hosted - version: "1.2.3" - stack_trace: - description: - name: stack_trace - url: "https://pub.dartlang.org" - source: hosted - version: "1.6.6" - string_scanner: - description: - name: string_scanner - url: "https://pub.dartlang.org" - source: hosted - version: "1.0.0" - unittest: - description: - name: unittest - url: "https://pub.dartlang.org" - source: hosted - version: "0.11.6+4" - utf: - description: - name: utf - url: "https://pub.dartlang.org" - source: hosted - version: "0.9.0+3" - watcher: - description: - name: watcher - url: "https://pub.dartlang.org" - source: hosted - version: "0.9.7+2" - yaml: - description: - name: yaml - url: "https://pub.dartlang.org" - source: hosted - version: "2.1.10" -sdk: ">=1.14.0 <2.0.0" diff --git a/samples/client/petstore/dart/swagger/.analysis_options b/samples/client/petstore/dart/swagger/.analysis_options new file mode 100644 index 00000000000..518eb901a6f --- /dev/null +++ b/samples/client/petstore/dart/swagger/.analysis_options @@ -0,0 +1,2 @@ +analyzer: + strong-mode: true \ No newline at end of file diff --git a/samples/client/petstore/dart/swagger/.gitignore b/samples/client/petstore/dart/swagger/.gitignore new file mode 100644 index 00000000000..7c280441649 --- /dev/null +++ b/samples/client/petstore/dart/swagger/.gitignore @@ -0,0 +1,27 @@ +# See https://www.dartlang.org/tools/private-files.html + +# Files and directories created by pub +.buildlog +.packages +.project +.pub/ +build/ +**/packages/ + +# Files created by dart2js +# (Most Dart developers will use pub build to compile Dart, use/modify these +# rules if you intend to use dart2js directly +# Convention is to use extension '.dart.js' for Dart compiled to Javascript to +# differentiate from explicit Javascript files) +*.dart.js +*.part.js +*.js.deps +*.js.map +*.info.json + +# Directory created by dartdoc +doc/api/ + +# Don't commit pubspec lock file +# (Library packages only! Remove pattern if developing an application package) +pubspec.lock diff --git a/samples/client/petstore/dart/swagger/LICENSE b/samples/client/petstore/dart/swagger/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/dart/swagger/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore/dart/git_push.sh b/samples/client/petstore/dart/swagger/git_push.sh similarity index 100% rename from samples/client/petstore/dart/git_push.sh rename to samples/client/petstore/dart/swagger/git_push.sh diff --git a/samples/client/petstore/dart/lib/api.dart b/samples/client/petstore/dart/swagger/lib/api.dart similarity index 90% rename from samples/client/petstore/dart/lib/api.dart rename to samples/client/petstore/dart/swagger/lib/api.dart index 1a0b0c84cc6..db95000d614 100644 --- a/samples/client/petstore/dart/lib/api.dart +++ b/samples/client/petstore/dart/swagger/lib/api.dart @@ -1,10 +1,11 @@ -library api; +library swagger.api; import 'dart:async'; import 'dart:convert'; import 'package:http/browser_client.dart'; import 'package:http/http.dart'; import 'package:dartson/dartson.dart'; +import 'package:dartson/transformers/date_time.dart'; import 'package:intl/intl.dart'; part 'api_client.dart'; diff --git a/samples/client/petstore/dart/lib/api/pet_api.dart b/samples/client/petstore/dart/swagger/lib/api/pet_api.dart similarity index 92% rename from samples/client/petstore/dart/lib/api/pet_api.dart rename to samples/client/petstore/dart/swagger/lib/api/pet_api.dart index 694ec340d46..45c203c51ef 100644 --- a/samples/client/petstore/dart/lib/api/pet_api.dart +++ b/samples/client/petstore/dart/swagger/lib/api/pet_api.dart @@ -1,9 +1,8 @@ -part of api; +part of swagger.api; class PetApi { - String basePath = "http://petstore.swagger.io/v2"; final ApiClient apiClient; PetApi([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; @@ -46,8 +45,7 @@ class PetApi { else { } - var response = await apiClient.invokeAPI(basePath, - path, + var response = await apiClient.invokeAPI(path, 'POST', queryParams, postBody, @@ -103,8 +101,7 @@ class PetApi { else { } - var response = await apiClient.invokeAPI(basePath, - path, + var response = await apiClient.invokeAPI(path, 'DELETE', queryParams, postBody, @@ -143,9 +140,7 @@ class PetApi { List queryParams = []; Map headerParams = {}; Map formParams = {}; - if("null" != status) { queryParams.addAll(_convertParametersForCollectionFormat("csv", "status", status)); - } List contentTypes = []; @@ -162,8 +157,7 @@ class PetApi { else { } - var response = await apiClient.invokeAPI(basePath, - path, + var response = await apiClient.invokeAPI(path, 'GET', queryParams, postBody, @@ -175,7 +169,7 @@ class PetApi { if(response.statusCode >= 400) { throw new ApiException(response.statusCode, response.body); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'List') ; + return apiClient.deserialize(response.body, 'List') as List ; } else { return null; } @@ -202,9 +196,7 @@ class PetApi { List queryParams = []; Map headerParams = {}; Map formParams = {}; - if("null" != tags) { queryParams.addAll(_convertParametersForCollectionFormat("csv", "tags", tags)); - } List contentTypes = []; @@ -221,8 +213,7 @@ class PetApi { else { } - var response = await apiClient.invokeAPI(basePath, - path, + var response = await apiClient.invokeAPI(path, 'GET', queryParams, postBody, @@ -234,7 +225,7 @@ class PetApi { if(response.statusCode >= 400) { throw new ApiException(response.statusCode, response.body); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'List') ; + return apiClient.deserialize(response.body, 'List') as List ; } else { return null; } @@ -277,8 +268,7 @@ class PetApi { else { } - var response = await apiClient.invokeAPI(basePath, - path, + var response = await apiClient.invokeAPI(path, 'GET', queryParams, postBody, @@ -290,7 +280,7 @@ class PetApi { if(response.statusCode >= 400) { throw new ApiException(response.statusCode, response.body); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'Pet') ; + return apiClient.deserialize(response.body, 'Pet') as Pet ; } else { return null; } @@ -333,8 +323,7 @@ class PetApi { else { } - var response = await apiClient.invokeAPI(basePath, - path, + var response = await apiClient.invokeAPI(path, 'PUT', queryParams, postBody, @@ -403,8 +392,7 @@ if (status != null) formParams['status'] = apiClient.parameterToString(status); } - var response = await apiClient.invokeAPI(basePath, - path, + var response = await apiClient.invokeAPI(path, 'POST', queryParams, postBody, @@ -473,8 +461,7 @@ if (status != null) } - var response = await apiClient.invokeAPI(basePath, - path, + var response = await apiClient.invokeAPI(path, 'POST', queryParams, postBody, @@ -486,7 +473,7 @@ if (status != null) if(response.statusCode >= 400) { throw new ApiException(response.statusCode, response.body); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'ApiResponse') ; + return apiClient.deserialize(response.body, 'ApiResponse') as ApiResponse ; } else { return null; } diff --git a/samples/client/petstore/dart/lib/api/store_api.dart b/samples/client/petstore/dart/swagger/lib/api/store_api.dart similarity index 91% rename from samples/client/petstore/dart/lib/api/store_api.dart rename to samples/client/petstore/dart/swagger/lib/api/store_api.dart index 0e42d534603..a2bf1bb68b9 100644 --- a/samples/client/petstore/dart/lib/api/store_api.dart +++ b/samples/client/petstore/dart/swagger/lib/api/store_api.dart @@ -1,9 +1,8 @@ -part of api; +part of swagger.api; class StoreApi { - String basePath = "http://petstore.swagger.io/v2"; final ApiClient apiClient; StoreApi([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; @@ -46,8 +45,7 @@ class StoreApi { else { } - var response = await apiClient.invokeAPI(basePath, - path, + var response = await apiClient.invokeAPI(path, 'DELETE', queryParams, postBody, @@ -99,8 +97,7 @@ class StoreApi { else { } - var response = await apiClient.invokeAPI(basePath, - path, + var response = await apiClient.invokeAPI(path, 'GET', queryParams, postBody, @@ -112,7 +109,7 @@ class StoreApi { if(response.statusCode >= 400) { throw new ApiException(response.statusCode, response.body); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'Map') ; + return apiClient.deserialize(response.body, 'Map') as Map ; } else { return null; } @@ -155,8 +152,7 @@ class StoreApi { else { } - var response = await apiClient.invokeAPI(basePath, - path, + var response = await apiClient.invokeAPI(path, 'GET', queryParams, postBody, @@ -168,7 +164,7 @@ class StoreApi { if(response.statusCode >= 400) { throw new ApiException(response.statusCode, response.body); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'Order') ; + return apiClient.deserialize(response.body, 'Order') as Order ; } else { return null; } @@ -211,8 +207,7 @@ class StoreApi { else { } - var response = await apiClient.invokeAPI(basePath, - path, + var response = await apiClient.invokeAPI(path, 'POST', queryParams, postBody, @@ -224,7 +219,7 @@ class StoreApi { if(response.statusCode >= 400) { throw new ApiException(response.statusCode, response.body); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'Order') ; + return apiClient.deserialize(response.body, 'Order') as Order ; } else { return null; } diff --git a/samples/client/petstore/dart/lib/api/user_api.dart b/samples/client/petstore/dart/swagger/lib/api/user_api.dart similarity index 93% rename from samples/client/petstore/dart/lib/api/user_api.dart rename to samples/client/petstore/dart/swagger/lib/api/user_api.dart index 34481806b95..10fecbf80f0 100644 --- a/samples/client/petstore/dart/lib/api/user_api.dart +++ b/samples/client/petstore/dart/swagger/lib/api/user_api.dart @@ -1,9 +1,8 @@ -part of api; +part of swagger.api; class UserApi { - String basePath = "http://petstore.swagger.io/v2"; final ApiClient apiClient; UserApi([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient; @@ -46,8 +45,7 @@ class UserApi { else { } - var response = await apiClient.invokeAPI(basePath, - path, + var response = await apiClient.invokeAPI(path, 'POST', queryParams, postBody, @@ -102,8 +100,7 @@ class UserApi { else { } - var response = await apiClient.invokeAPI(basePath, - path, + var response = await apiClient.invokeAPI(path, 'POST', queryParams, postBody, @@ -158,8 +155,7 @@ class UserApi { else { } - var response = await apiClient.invokeAPI(basePath, - path, + var response = await apiClient.invokeAPI(path, 'POST', queryParams, postBody, @@ -214,8 +210,7 @@ class UserApi { else { } - var response = await apiClient.invokeAPI(basePath, - path, + var response = await apiClient.invokeAPI(path, 'DELETE', queryParams, postBody, @@ -270,8 +265,7 @@ class UserApi { else { } - var response = await apiClient.invokeAPI(basePath, - path, + var response = await apiClient.invokeAPI(path, 'GET', queryParams, postBody, @@ -283,7 +277,7 @@ class UserApi { if(response.statusCode >= 400) { throw new ApiException(response.statusCode, response.body); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'User') ; + return apiClient.deserialize(response.body, 'User') as User ; } else { return null; } @@ -313,12 +307,8 @@ class UserApi { List queryParams = []; Map headerParams = {}; Map formParams = {}; - if("null" != username) { queryParams.addAll(_convertParametersForCollectionFormat("", "username", username)); - } - if("null" != password) { queryParams.addAll(_convertParametersForCollectionFormat("", "password", password)); - } List contentTypes = []; @@ -335,8 +325,7 @@ class UserApi { else { } - var response = await apiClient.invokeAPI(basePath, - path, + var response = await apiClient.invokeAPI(path, 'GET', queryParams, postBody, @@ -348,7 +337,7 @@ class UserApi { if(response.statusCode >= 400) { throw new ApiException(response.statusCode, response.body); } else if(response.body != null) { - return apiClient.deserialize(response.body, 'String') ; + return apiClient.deserialize(response.body, 'String') as String ; } else { return null; } @@ -388,8 +377,7 @@ class UserApi { else { } - var response = await apiClient.invokeAPI(basePath, - path, + var response = await apiClient.invokeAPI(path, 'GET', queryParams, postBody, @@ -447,8 +435,7 @@ class UserApi { else { } - var response = await apiClient.invokeAPI(basePath, - path, + var response = await apiClient.invokeAPI(path, 'PUT', queryParams, postBody, diff --git a/samples/client/petstore/dart/lib/api_client.dart b/samples/client/petstore/dart/swagger/lib/api_client.dart similarity index 87% rename from samples/client/petstore/dart/lib/api_client.dart rename to samples/client/petstore/dart/swagger/lib/api_client.dart index 3014e7deade..9087a80d8cc 100644 --- a/samples/client/petstore/dart/lib/api_client.dart +++ b/samples/client/petstore/dart/swagger/lib/api_client.dart @@ -1,4 +1,4 @@ -part of api; +part of swagger.api; class QueryParam { String name; @@ -9,18 +9,20 @@ class QueryParam { class ApiClient { + String basePath; var client = new BrowserClient(); Map _defaultHeaderMap = {}; Map _authentications = {}; - final dson = new Dartson.JSON(); + final dson = new Dartson.JSON() + ..addTransformer(new DateTimeParser(), DateTime); final DateFormat _dateFormatter = new DateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); final _RegList = new RegExp(r'^List<(.*)>$'); final _RegMap = new RegExp(r'^Map$'); - ApiClient() { + ApiClient({this.basePath: "http://petstore.swagger.io/v2"}) { // Setup authentications (key: authentication name, value: authentication). _authentications['petstore_auth'] = new OAuth(); _authentications['api_key'] = new ApiKeyAuth("header", "api_key"); @@ -76,20 +78,18 @@ class ApiClient { Match match; if (value is List && (match = _RegList.firstMatch(targetType)) != null) { - var valueL = value as List; var newTargetType = match[1]; - return valueL.map((v) => _deserialize(v, newTargetType)).toList(); + return value.map((v) => _deserialize(v, newTargetType)).toList(); } else if (value is Map && (match = _RegMap.firstMatch(targetType)) != null) { - var valueM = value as Map; var newTargetType = match[1]; - return new Map.fromIterables(valueM.keys, - valueM.values.map((v) => _deserialize(v, newTargetType))); + return new Map.fromIterables(value.keys, + value.values.map((v) => _deserialize(v, newTargetType))); } } } - } catch(e) { - // Just throw the ApiException below + } catch (e, stack) { + throw new ApiException.withInner(500, 'Exception during deserialization.', e, stack); } throw new ApiException(500, 'Could not find a suitable class for deserialization'); } @@ -118,10 +118,9 @@ class ApiClient { // We don't use a Map for queryParams. // If collectionFormat is 'multi' a key might appear multiple times. - Future invokeAPI(String host, - String path, + Future invokeAPI(String path, String method, - List queryParams, + Iterable queryParams, Object body, Map headerParams, Map formParams, @@ -135,7 +134,7 @@ class ApiClient { '?' + ps.join('&') : ''; - String url = host + path + queryString; + String url = basePath + path + queryString; headerParams.addAll(_defaultHeaderMap); headerParams['Content-Type'] = contentType; @@ -157,6 +156,8 @@ class ApiClient { return client.put(url, headers: headerParams, body: msgBody); case "DELETE": return client.delete(url, headers: headerParams); + case "PATCH": + return client.patch(url, headers: headerParams, body: msgBody); default: return client.get(url, headers: headerParams); } diff --git a/samples/client/petstore/dart/swagger/lib/api_exception.dart b/samples/client/petstore/dart/swagger/lib/api_exception.dart new file mode 100644 index 00000000000..b861591bec0 --- /dev/null +++ b/samples/client/petstore/dart/swagger/lib/api_exception.dart @@ -0,0 +1,23 @@ +part of swagger.api; + +class ApiException implements Exception { + int code = 0; + String message = null; + Exception innerException = null; + StackTrace stackTrace = null; + + ApiException(this.code, this.message); + + ApiException.withInner(this.code, this.message, this.innerException, this.stackTrace); + + String toString() { + if (message == null) return "ApiException"; + + if (innerException == null) { + return "ApiException $code: $message"; + } + + return "ApiException $code: $message (Inner exception: ${innerException})\n\n" + + stackTrace.toString(); + } +} diff --git a/samples/client/petstore/dart/lib/api_helper.dart b/samples/client/petstore/dart/swagger/lib/api_helper.dart similarity index 73% rename from samples/client/petstore/dart/lib/api_helper.dart rename to samples/client/petstore/dart/swagger/lib/api_helper.dart index fb25306d260..ad73218ab40 100644 --- a/samples/client/petstore/dart/lib/api_helper.dart +++ b/samples/client/petstore/dart/swagger/lib/api_helper.dart @@ -1,21 +1,21 @@ -part of api; +part of swagger.api; const _delimiters = const {'csv': ',', 'ssv': ' ', 'tsv': '\t', 'pipes': '|'}; // port from Java version -List _convertParametersForCollectionFormat( +Iterable _convertParametersForCollectionFormat( String collectionFormat, String name, dynamic value) { - var params = []; + var params = []; // preconditions if (name == null || name.isEmpty || value == null) return params; if (value is! List) { - params.add(new QueryParam(name, value as String)); + params.add(new QueryParam(name, '$value')); return params; } - List values = value as List; + List values = value as List; // get the collection format collectionFormat = (collectionFormat == null || collectionFormat.isEmpty) @@ -23,7 +23,7 @@ List _convertParametersForCollectionFormat( : collectionFormat; // default: csv if (collectionFormat == "multi") { - return values.map((v) => new QueryParam(name, v)); + return values.map((v) => new QueryParam(name, '$v')); } String delimiter = _delimiters[collectionFormat] ?? ","; diff --git a/samples/client/petstore/dart/lib/auth/api_key_auth.dart b/samples/client/petstore/dart/swagger/lib/auth/api_key_auth.dart similarity index 96% rename from samples/client/petstore/dart/lib/auth/api_key_auth.dart rename to samples/client/petstore/dart/swagger/lib/auth/api_key_auth.dart index d80d6a6a213..d46fa15e9b8 100644 --- a/samples/client/petstore/dart/lib/auth/api_key_auth.dart +++ b/samples/client/petstore/dart/swagger/lib/auth/api_key_auth.dart @@ -1,4 +1,4 @@ -part of api; +part of swagger.api; class ApiKeyAuth implements Authentication { diff --git a/samples/client/petstore/dart/lib/auth/authentication.dart b/samples/client/petstore/dart/swagger/lib/auth/authentication.dart similarity index 89% rename from samples/client/petstore/dart/lib/auth/authentication.dart rename to samples/client/petstore/dart/swagger/lib/auth/authentication.dart index c0b1f92a42d..3d6b6aadcda 100644 --- a/samples/client/petstore/dart/lib/auth/authentication.dart +++ b/samples/client/petstore/dart/swagger/lib/auth/authentication.dart @@ -1,4 +1,4 @@ -part of api; +part of swagger.api; abstract class Authentication { diff --git a/samples/client/petstore/dart/lib/auth/http_basic_auth.dart b/samples/client/petstore/dart/swagger/lib/auth/http_basic_auth.dart similarity index 94% rename from samples/client/petstore/dart/lib/auth/http_basic_auth.dart rename to samples/client/petstore/dart/swagger/lib/auth/http_basic_auth.dart index 0645d4358f5..7a118d6cdad 100644 --- a/samples/client/petstore/dart/lib/auth/http_basic_auth.dart +++ b/samples/client/petstore/dart/swagger/lib/auth/http_basic_auth.dart @@ -1,4 +1,4 @@ -part of api; +part of swagger.api; class HttpBasicAuth implements Authentication { diff --git a/samples/client/petstore/dart/lib/auth/oauth.dart b/samples/client/petstore/dart/swagger/lib/auth/oauth.dart similarity index 89% rename from samples/client/petstore/dart/lib/auth/oauth.dart rename to samples/client/petstore/dart/swagger/lib/auth/oauth.dart index e514dd85738..405c5119a45 100644 --- a/samples/client/petstore/dart/lib/auth/oauth.dart +++ b/samples/client/petstore/dart/swagger/lib/auth/oauth.dart @@ -1,4 +1,4 @@ -part of api; +part of swagger.api; class OAuth implements Authentication { diff --git a/samples/client/petstore/dart/lib/model/api_response.dart b/samples/client/petstore/dart/swagger/lib/model/api_response.dart similarity index 93% rename from samples/client/petstore/dart/lib/model/api_response.dart rename to samples/client/petstore/dart/swagger/lib/model/api_response.dart index e8ffe737861..b2ac2c2577e 100644 --- a/samples/client/petstore/dart/lib/model/api_response.dart +++ b/samples/client/petstore/dart/swagger/lib/model/api_response.dart @@ -1,4 +1,4 @@ -part of api; +part of swagger.api; @Entity() diff --git a/samples/client/petstore/dart/lib/model/category.dart b/samples/client/petstore/dart/swagger/lib/model/category.dart similarity index 91% rename from samples/client/petstore/dart/lib/model/category.dart rename to samples/client/petstore/dart/swagger/lib/model/category.dart index e39966555fb..9ab2a96fc37 100644 --- a/samples/client/petstore/dart/lib/model/category.dart +++ b/samples/client/petstore/dart/swagger/lib/model/category.dart @@ -1,4 +1,4 @@ -part of api; +part of swagger.api; @Entity() diff --git a/samples/client/petstore/dart/lib/model/order.dart b/samples/client/petstore/dart/swagger/lib/model/order.dart similarity index 96% rename from samples/client/petstore/dart/lib/model/order.dart rename to samples/client/petstore/dart/swagger/lib/model/order.dart index 1d908629b06..d7ea97b3bad 100644 --- a/samples/client/petstore/dart/lib/model/order.dart +++ b/samples/client/petstore/dart/swagger/lib/model/order.dart @@ -1,4 +1,4 @@ -part of api; +part of swagger.api; @Entity() diff --git a/samples/client/petstore/dart/lib/model/pet.dart b/samples/client/petstore/dart/swagger/lib/model/pet.dart similarity index 96% rename from samples/client/petstore/dart/lib/model/pet.dart rename to samples/client/petstore/dart/swagger/lib/model/pet.dart index 8ad328b78be..03e13743763 100644 --- a/samples/client/petstore/dart/lib/model/pet.dart +++ b/samples/client/petstore/dart/swagger/lib/model/pet.dart @@ -1,4 +1,4 @@ -part of api; +part of swagger.api; @Entity() diff --git a/samples/client/petstore/dart/lib/model/tag.dart b/samples/client/petstore/dart/swagger/lib/model/tag.dart similarity index 91% rename from samples/client/petstore/dart/lib/model/tag.dart rename to samples/client/petstore/dart/swagger/lib/model/tag.dart index 0541e12fb6f..485de92a615 100644 --- a/samples/client/petstore/dart/lib/model/tag.dart +++ b/samples/client/petstore/dart/swagger/lib/model/tag.dart @@ -1,4 +1,4 @@ -part of api; +part of swagger.api; @Entity() diff --git a/samples/client/petstore/dart/lib/model/user.dart b/samples/client/petstore/dart/swagger/lib/model/user.dart similarity index 97% rename from samples/client/petstore/dart/lib/model/user.dart rename to samples/client/petstore/dart/swagger/lib/model/user.dart index fd99a51ee58..f529d9432c1 100644 --- a/samples/client/petstore/dart/lib/model/user.dart +++ b/samples/client/petstore/dart/swagger/lib/model/user.dart @@ -1,4 +1,4 @@ -part of api; +part of swagger.api; @Entity() diff --git a/samples/client/petstore/dart/pubspec.yaml b/samples/client/petstore/dart/swagger/pubspec.yaml similarity index 100% rename from samples/client/petstore/dart/pubspec.yaml rename to samples/client/petstore/dart/swagger/pubspec.yaml From 52cfd0f86f6f989e52af130e1e8d7b96d2ddb67e Mon Sep 17 00:00:00 2001 From: Jim Schubert Date: Sun, 24 Jul 2016 11:21:06 -0400 Subject: [PATCH 150/470] [C#] RootNamespace/AssemblyName use packageName Uses packageName instead of packageTitle for RootNamespace and AssemblyName in the C# generate client project. packageTitle is intended to add additional information to AssemblyInfo.cs, and changing packageTitle to non-FQN text breaks adding new files to the project. packageTitle, per CodegenConstants description: "Specifies an AssemblyTitle for the .NET Framework global assembly attributes stored in the AssemblyInfo file." --- .../src/main/resources/csharp/Project.mustache | 4 ++-- .../petstore/csharp/SwaggerClient/IO.Swagger.sln | 10 +++++----- .../client/petstore/csharp/SwaggerClient/README.md | 14 +++++++------- .../SwaggerClient/src/IO.Swagger/IO.Swagger.csproj | 6 +++--- 4 files changed, 17 insertions(+), 17 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/Project.mustache b/modules/swagger-codegen/src/main/resources/csharp/Project.mustache index 7a4c741ca4a..2334e53d0c9 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/Project.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/Project.mustache @@ -31,8 +31,8 @@ limitations under the License. {{packageGuid}} Library Properties - {{packageTitle}} - {{packageTitle}} + {{packageName}} + {{packageName}} {{^supportsUWP}} {{targetFramework}} {{/supportsUWP}} diff --git a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln index 138eef97a42..5275707330e 100644 --- a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln +++ b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln @@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 VisualStudioVersion = 12.0.0.0 MinimumVisualStudioVersion = 10.0.0.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{B9FB8D99-748C-4BE0-9C82-114777F64157}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{1ABB7E18-6533-446C-9EEA-0E0839F5C12A}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger.Test", "src\IO.Swagger.Test\IO.Swagger.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" EndProject @@ -12,10 +12,10 @@ Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution -{B9FB8D99-748C-4BE0-9C82-114777F64157}.Debug|Any CPU.ActiveCfg = Debug|Any CPU -{B9FB8D99-748C-4BE0-9C82-114777F64157}.Debug|Any CPU.Build.0 = Debug|Any CPU -{B9FB8D99-748C-4BE0-9C82-114777F64157}.Release|Any CPU.ActiveCfg = Release|Any CPU -{B9FB8D99-748C-4BE0-9C82-114777F64157}.Release|Any CPU.Build.0 = Release|Any CPU +{1ABB7E18-6533-446C-9EEA-0E0839F5C12A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{1ABB7E18-6533-446C-9EEA-0E0839F5C12A}.Debug|Any CPU.Build.0 = Debug|Any CPU +{1ABB7E18-6533-446C-9EEA-0E0839F5C12A}.Release|Any CPU.ActiveCfg = Release|Any CPU +{1ABB7E18-6533-446C-9EEA-0E0839F5C12A}.Release|Any CPU.Build.0 = Release|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/samples/client/petstore/csharp/SwaggerClient/README.md b/samples/client/petstore/csharp/SwaggerClient/README.md index 780288fd56d..727969d5347 100644 --- a/samples/client/petstore/csharp/SwaggerClient/README.md +++ b/samples/client/petstore/csharp/SwaggerClient/README.md @@ -6,7 +6,7 @@ This C# SDK is automatically generated by the [Swagger Codegen](https://github.c - API version: 1.0.0 - SDK version: 1.0.0 -- Build date: 2016-07-21T20:13:02.982+08:00 +- Build date: 2016-07-24T11:20:06.818-04:00 - Build package: class io.swagger.codegen.languages.CSharpClientCodegen ## Frameworks supported @@ -137,12 +137,6 @@ Class | Method | HTTP request | Description ## Documentation for Authorization -### api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - ### petstore_auth - **Type**: OAuth @@ -152,3 +146,9 @@ Class | Method | HTTP request | Description - write:pets: modify pets in your account - read:pets: read your pets +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj index c3a0f1dcf95..f818f874154 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj @@ -24,11 +24,11 @@ limitations under the License. Debug AnyCPU - {B9FB8D99-748C-4BE0-9C82-114777F64157} + {1ABB7E18-6533-446C-9EEA-0E0839F5C12A} Library Properties - Swagger Library - Swagger Library + IO.Swagger + IO.Swagger v4.5 512 From aaba4b9e82e4e26b20864103c391b349fcad7ca9 Mon Sep 17 00:00:00 2001 From: jhitchcock Date: Mon, 25 Jul 2016 15:35:48 +0200 Subject: [PATCH 151/470] Html Docs 2 - API and Client Library Documentation --- .../languages/StaticHtml2Generator.java | 154 +++++ .../services/io.swagger.codegen.CodegenConfig | 1 + .../htmlDocs2/css_bootstrap.mustache | 10 + .../resources/htmlDocs2/css_prettify.mustache | 101 ++++ .../main/resources/htmlDocs2/index.mustache | 555 ++++++++++++++++++ .../resources/htmlDocs2/js_bootstrap.mustache | 8 + .../resources/htmlDocs2/js_jquery.mustache | 6 + .../resources/htmlDocs2/js_jsonref.mustache | 3 + .../htmlDocs2/js_jsonschemaview.mustache | 313 ++++++++++ .../resources/htmlDocs2/js_prettify.mustache | 32 + .../htmlDocs2/js_webfontloader.mustache | 19 + .../main/resources/htmlDocs2/param.mustache | 26 + .../main/resources/htmlDocs2/paramB.mustache | 35 ++ .../htmlDocs2/sample_android.mustache | 18 + .../htmlDocs2/sample_csharp.mustache | 51 ++ .../resources/htmlDocs2/sample_java.mustache | 41 ++ .../resources/htmlDocs2/sample_js.mustache | 43 ++ .../resources/htmlDocs2/sample_objc.mustache | 34 ++ .../resources/htmlDocs2/sample_php.mustache | 24 + .../main/resources/htmlDocs2/styles.mustache | 415 +++++++++++++ 20 files changed, 1889 insertions(+) create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtml2Generator.java create mode 100644 modules/swagger-codegen/src/main/resources/htmlDocs2/css_bootstrap.mustache create mode 100644 modules/swagger-codegen/src/main/resources/htmlDocs2/css_prettify.mustache create mode 100644 modules/swagger-codegen/src/main/resources/htmlDocs2/index.mustache create mode 100644 modules/swagger-codegen/src/main/resources/htmlDocs2/js_bootstrap.mustache create mode 100644 modules/swagger-codegen/src/main/resources/htmlDocs2/js_jquery.mustache create mode 100644 modules/swagger-codegen/src/main/resources/htmlDocs2/js_jsonref.mustache create mode 100644 modules/swagger-codegen/src/main/resources/htmlDocs2/js_jsonschemaview.mustache create mode 100644 modules/swagger-codegen/src/main/resources/htmlDocs2/js_prettify.mustache create mode 100644 modules/swagger-codegen/src/main/resources/htmlDocs2/js_webfontloader.mustache create mode 100644 modules/swagger-codegen/src/main/resources/htmlDocs2/param.mustache create mode 100644 modules/swagger-codegen/src/main/resources/htmlDocs2/paramB.mustache create mode 100644 modules/swagger-codegen/src/main/resources/htmlDocs2/sample_android.mustache create mode 100644 modules/swagger-codegen/src/main/resources/htmlDocs2/sample_csharp.mustache create mode 100644 modules/swagger-codegen/src/main/resources/htmlDocs2/sample_java.mustache create mode 100644 modules/swagger-codegen/src/main/resources/htmlDocs2/sample_js.mustache create mode 100644 modules/swagger-codegen/src/main/resources/htmlDocs2/sample_objc.mustache create mode 100644 modules/swagger-codegen/src/main/resources/htmlDocs2/sample_php.mustache create mode 100644 modules/swagger-codegen/src/main/resources/htmlDocs2/styles.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtml2Generator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtml2Generator.java new file mode 100644 index 00000000000..76351a963ca --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtml2Generator.java @@ -0,0 +1,154 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.Model; +import io.swagger.models.Operation; +import io.swagger.models.Swagger; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; + +public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfig { + private static final String ALL_OPERATIONS = ""; + protected String invokerPackage = "io.swagger.client"; + protected String groupId = "io.swagger"; + protected String artifactId = "swagger-client"; + protected String artifactVersion = "1.0.0"; + protected String sourceFolder = "src/main/scala"; + + public StaticHtml2Generator() { + super(); + outputFolder = "docs"; + embeddedTemplateDir = templateDir = "htmlDocs2"; + + defaultIncludes = new HashSet(); + + cliOptions.add(new CliOption("appName", "short name of the application")); + cliOptions.add(new CliOption("appDescription", "description of the application")); + cliOptions.add(new CliOption("infoUrl", "a URL where users can get more information about the application")); + cliOptions.add(new CliOption("infoEmail", "an email address to contact for inquiries about the application")); + cliOptions.add(new CliOption("licenseInfo", "a short description of the license")); + cliOptions.add(new CliOption("licenseUrl", "a URL pointing to the full license")); + 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)); + + additionalProperties.put("appName", "Swagger Sample"); + additionalProperties.put("appDescription", "A sample swagger server"); + additionalProperties.put("infoUrl", "https://helloreverb.com"); + additionalProperties.put("infoEmail", "hello@helloreverb.com"); + additionalProperties.put("licenseInfo", "All rights reserved"); + additionalProperties.put("licenseUrl", "http://apache.org/licenses/LICENSE-2.0.html"); + additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); + additionalProperties.put(CodegenConstants.GROUP_ID, groupId); + additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); + additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); + + supportingFiles.add(new SupportingFile("index.mustache", "", "index.html")); + reservedWords = new HashSet(); + + languageSpecificPrimitives = new HashSet(); + importMapping = new HashMap(); + } + + @Override + public CodegenType getTag() { + return CodegenType.DOCUMENTATION; + } + + @Override + public String getName() { + return "html2"; + } + + @Override + public String getHelp() { + return "Generates a static HTML file."; + } + + @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); + } + + @Override + public Map postProcessOperations(Map objs) { + Map operations = (Map) objs.get("operations"); + List operationList = (List) operations.get("operation"); + for (CodegenOperation op : operationList) { + op.httpMethod = op.httpMethod.toLowerCase(); + } + return objs; + } + + + @Override + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { + CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger); + if (op.returnType != null) { + op.returnType = normalizeType(op.returnType); + } + + //path is an unescaped variable in the mustache template api.mustache line 82 '<&path>' + op.path = sanitizePath(op.path); + + // Set vendor-extension to be used in template: + // x-codegen-hasMoreRequired + // x-codegen-hasMoreOptional + // x-codegen-hasRequiredParams + CodegenParameter lastRequired = null; + CodegenParameter lastOptional = null; + for (CodegenParameter p : op.allParams) { + if (p.required != null && p.required) { + lastRequired = p; + } else { + lastOptional = p; + } + } + for (CodegenParameter p : op.allParams) { + if (p == lastRequired) { + p.vendorExtensions.put("x-codegen-hasMoreRequired", false); + } else if (p == lastOptional) { + p.vendorExtensions.put("x-codegen-hasMoreOptional", false); + } else { + p.vendorExtensions.put("x-codegen-hasMoreRequired", true); + p.vendorExtensions.put("x-codegen-hasMoreOptional", true); + } + } + op.vendorExtensions.put("x-codegen-hasRequiredParams", lastRequired != null); + + return op; + } + + + private String sanitizePath(String p) { + //prefer replace a ', instead of a fuLL URL encode for readability + return p.replaceAll("'", "%27"); + } + + /** + * Normalize type by wrapping primitive types with single quotes. + * + * @param type Primitive type + * @return Normalized type + */ + public String normalizeType(String type) { + return type.replaceAll("\\b(Boolean|Integer|Number|String|Date)\\b", "'$1'"); + } +} 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 20a8ce8e9fb..aea2e3b1245 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 @@ -35,6 +35,7 @@ io.swagger.codegen.languages.SlimFrameworkServerCodegen io.swagger.codegen.languages.SpringCodegen io.swagger.codegen.languages.StaticDocCodegen io.swagger.codegen.languages.StaticHtmlGenerator +io.swagger.codegen.languages.StaticHtml2Generator io.swagger.codegen.languages.SwaggerGenerator io.swagger.codegen.languages.SwaggerYamlGenerator io.swagger.codegen.languages.SwiftCodegen diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/css_bootstrap.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/css_bootstrap.mustache new file mode 100644 index 00000000000..f84ec4773fd --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/css_bootstrap.mustache @@ -0,0 +1,10 @@ + +/*! + * Bootstrap v2.3.2 + * + * Copyright 2013 Twitter, Inc + * Licensed under the Apache License v2.0 + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Designed and built with all the love in the world by @mdo and @fat. + */.clearfix{*zoom:1}.clearfix:before,.clearfix:after{display:table;line-height:0;content:""}.clearfix:after{clear:both}.hide-text{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.input-block-level{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block}audio,canvas,video{display:inline-block;*display:inline;*zoom:1}audio:not([controls]){display:none}html{font-size:100%;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}a:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}a:hover,a:active{outline:0}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sup{top:-0.5em}sub{bottom:-0.25em}img{width:auto\9;height:auto;max-width:100%;vertical-align:middle;border:0;-ms-interpolation-mode:bicubic}#map_canvas img,.google-maps img{max-width:none}button,input,select,textarea{margin:0;font-size:100%;vertical-align:middle}button,input{*overflow:visible;line-height:normal}button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0}button,html input[type="button"],input[type="reset"],input[type="submit"]{cursor:pointer;-webkit-appearance:button}label,select,button,input[type="button"],input[type="reset"],input[type="submit"],input[type="radio"],input[type="checkbox"]{cursor:pointer}input[type="search"]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield}input[type="search"]::-webkit-search-decoration,input[type="search"]::-webkit-search-cancel-button{-webkit-appearance:none}textarea{overflow:auto;vertical-align:top}@media print{*{color:#000!important;text-shadow:none!important;background:transparent!important;box-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100%!important}@page{margin:.5cm}p,h2,h3{orphans:3;widows:3}h2,h3{page-break-after:avoid}}body{margin:0;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:20px;color:#333;background-color:#fff}a{color:#08c;text-decoration:none}a:hover,a:focus{color:#005580;text-decoration:underline}.img-rounded{-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.img-polaroid{padding:4px;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);-webkit-box-shadow:0 1px 3px rgba(0,0,0,0.1);-moz-box-shadow:0 1px 3px rgba(0,0,0,0.1);box-shadow:0 1px 3px rgba(0,0,0,0.1)}.img-circle{-webkit-border-radius:500px;-moz-border-radius:500px;border-radius:500px}.row{margin-left:-20px;*zoom:1}.row:before,.row:after{display:table;line-height:0;content:""}.row:after{clear:both}[class*="span"]{float:left;min-height:1px;margin-left:20px}.container,.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:940px}.span12{width:940px}.span11{width:860px}.span10{width:780px}.span9{width:700px}.span8{width:620px}.span7{width:540px}.span6{width:460px}.span5{width:380px}.span4{width:300px}.span3{width:220px}.span2{width:140px}.span1{width:60px}.offset12{margin-left:980px}.offset11{margin-left:900px}.offset10{margin-left:820px}.offset9{margin-left:740px}.offset8{margin-left:660px}.offset7{margin-left:580px}.offset6{margin-left:500px}.offset5{margin-left:420px}.offset4{margin-left:340px}.offset3{margin-left:260px}.offset2{margin-left:180px}.offset1{margin-left:100px}.row-fluid{width:100%;*zoom:1}.row-fluid:before,.row-fluid:after{display:table;line-height:0;content:""}.row-fluid:after{clear:both}.row-fluid [class*="span"]{display:block;float:left;width:100%;min-height:30px;margin-left:2.127659574468085%;*margin-left:2.074468085106383%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.row-fluid [class*="span"]:first-child{margin-left:0}.row-fluid .controls-row [class*="span"]+[class*="span"]{margin-left:2.127659574468085%}.row-fluid .span12{width:100%;*width:99.94680851063829%}.row-fluid .span11{width:91.48936170212765%;*width:91.43617021276594%}.row-fluid .span10{width:82.97872340425532%;*width:82.92553191489361%}.row-fluid .span9{width:74.46808510638297%;*width:74.41489361702126%}.row-fluid .span8{width:65.95744680851064%;*width:65.90425531914893%}.row-fluid .span7{width:57.44680851063829%;*width:57.39361702127659%}.row-fluid .span6{width:48.93617021276595%;*width:48.88297872340425%}.row-fluid .span5{width:40.42553191489362%;*width:40.37234042553192%}.row-fluid .span4{width:31.914893617021278%;*width:31.861702127659576%}.row-fluid .span3{width:23.404255319148934%;*width:23.351063829787233%}.row-fluid .span2{width:14.893617021276595%;*width:14.840425531914894%}.row-fluid .span1{width:6.382978723404255%;*width:6.329787234042553%}.row-fluid .offset12{margin-left:104.25531914893617%;*margin-left:104.14893617021275%}.row-fluid .offset12:first-child{margin-left:102.12765957446808%;*margin-left:102.02127659574467%}.row-fluid .offset11{margin-left:95.74468085106382%;*margin-left:95.6382978723404%}.row-fluid .offset11:first-child{margin-left:93.61702127659574%;*margin-left:93.51063829787232%}.row-fluid .offset10{margin-left:87.23404255319149%;*margin-left:87.12765957446807%}.row-fluid .offset10:first-child{margin-left:85.1063829787234%;*margin-left:84.99999999999999%}.row-fluid .offset9{margin-left:78.72340425531914%;*margin-left:78.61702127659572%}.row-fluid .offset9:first-child{margin-left:76.59574468085106%;*margin-left:76.48936170212764%}.row-fluid .offset8{margin-left:70.2127659574468%;*margin-left:70.10638297872339%}.row-fluid .offset8:first-child{margin-left:68.08510638297872%;*margin-left:67.9787234042553%}.row-fluid .offset7{margin-left:61.70212765957446%;*margin-left:61.59574468085106%}.row-fluid .offset7:first-child{margin-left:59.574468085106375%;*margin-left:59.46808510638297%}.row-fluid .offset6{margin-left:53.191489361702125%;*margin-left:53.085106382978715%}.row-fluid .offset6:first-child{margin-left:51.063829787234035%;*margin-left:50.95744680851063%}.row-fluid .offset5{margin-left:44.68085106382979%;*margin-left:44.57446808510638%}.row-fluid .offset5:first-child{margin-left:42.5531914893617%;*margin-left:42.4468085106383%}.row-fluid .offset4{margin-left:36.170212765957444%;*margin-left:36.06382978723405%}.row-fluid .offset4:first-child{margin-left:34.04255319148936%;*margin-left:33.93617021276596%}.row-fluid .offset3{margin-left:27.659574468085104%;*margin-left:27.5531914893617%}.row-fluid .offset3:first-child{margin-left:25.53191489361702%;*margin-left:25.425531914893618%}.row-fluid .offset2{margin-left:19.148936170212764%;*margin-left:19.04255319148936%}.row-fluid .offset2:first-child{margin-left:17.02127659574468%;*margin-left:16.914893617021278%}.row-fluid .offset1{margin-left:10.638297872340425%;*margin-left:10.53191489361702%}.row-fluid .offset1:first-child{margin-left:8.51063829787234%;*margin-left:8.404255319148938%}[class*="span"].hide,.row-fluid [class*="span"].hide{display:none}[class*="span"].pull-right,.row-fluid [class*="span"].pull-right{float:right}.container{margin-right:auto;margin-left:auto;*zoom:1}.container:before,.container:after{display:table;line-height:0;content:""}.container:after{clear:both}.container-fluid{padding-right:20px;padding-left:20px;*zoom:1}.container-fluid:before,.container-fluid:after{display:table;line-height:0;content:""}.container-fluid:after{clear:both}p{margin:0 0 10px}.lead{margin-bottom:20px;font-size:21px;font-weight:200;line-height:30px}small{font-size:85%}strong{font-weight:bold}em{font-style:italic}cite{font-style:normal}.muted{color:#999}a.muted:hover,a.muted:focus{color:#808080}.text-warning{color:#c09853}a.text-warning:hover,a.text-warning:focus{color:#a47e3c}.text-error{color:#b94a48}a.text-error:hover,a.text-error:focus{color:#953b39}.text-info{color:#3a87ad}a.text-info:hover,a.text-info:focus{color:#2d6987}.text-success{color:#468847}a.text-success:hover,a.text-success:focus{color:#356635}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}h1,h2,h3,h4,h5,h6{margin:10px 0;font-family:inherit;font-weight:bold;line-height:20px;color:inherit;text-rendering:optimizelegibility}h1 small,h2 small,h3 small,h4 small,h5 small,h6 small{font-weight:normal;line-height:1;color:#999}h1,h2,h3{line-height:40px}h1{font-size:38.5px}h2{font-size:31.5px}h3{font-size:24.5px}h4{font-size:17.5px}h5{font-size:14px}h6{font-size:11.9px}h1 small{font-size:24.5px}h2 small{font-size:17.5px}h3 small{font-size:14px}h4 small{font-size:14px}.page-header{padding-bottom:9px;margin:20px 0 30px;border-bottom:1px solid #eee}ul,ol{padding:0;margin:0 0 10px 25px}ul ul,ul ol,ol ol,ol ul{margin-bottom:0}li{line-height:20px}ul.unstyled,ol.unstyled{margin-left:0;list-style:none}ul.inline,ol.inline{margin-left:0;list-style:none}ul.inline>li,ol.inline>li{display:inline-block;*display:inline;padding-right:5px;padding-left:5px;*zoom:1}dl{margin-bottom:20px}dt,dd{line-height:20px}dt{font-weight:bold}dd{margin-left:10px}.dl-horizontal{*zoom:1}.dl-horizontal:before,.dl-horizontal:after{display:table;line-height:0;content:""}.dl-horizontal:after{clear:both}.dl-horizontal dt{float:left;width:160px;overflow:hidden;clear:left;text-align:right;text-overflow:ellipsis;white-space:nowrap}.dl-horizontal dd{margin-left:180px}hr{margin:20px 0;border:0;border-top:1px solid #eee;border-bottom:1px solid #fff}abbr[title],abbr[data-original-title]{cursor:help;border-bottom:1px dotted #999}abbr.initialism{font-size:90%;text-transform:uppercase}blockquote{padding:0 0 0 15px;margin:0 0 20px;border-left:5px solid #eee}blockquote p{margin-bottom:0;font-size:17.5px;font-weight:300;line-height:1.25}blockquote small{display:block;line-height:20px;color:#999}blockquote small:before{content:'\2014 \00A0'}blockquote.pull-right{float:right;padding-right:15px;padding-left:0;border-right:5px solid #eee;border-left:0}blockquote.pull-right p,blockquote.pull-right small{text-align:right}blockquote.pull-right small:before{content:''}blockquote.pull-right small:after{content:'\00A0 \2014'}q:before,q:after,blockquote:before,blockquote:after{content:""}address{display:block;margin-bottom:20px;font-style:normal;line-height:20px}code,pre{padding:0 3px 2px;font-family:Monaco,Menlo,Consolas,"Courier New",monospace;font-size:12px;color:#333;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}code{padding:2px 4px;color:#d14;white-space:nowrap;background-color:#f7f7f9;border:1px solid #e1e1e8}pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:20px;word-break:break-all;word-wrap:break-word;white-space:pre;white-space:pre-wrap;background-color:#f5f5f5;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.15);-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}pre.prettyprint{margin-bottom:20px}pre code{padding:0;color:inherit;white-space:pre;white-space:pre-wrap;background-color:transparent;border:0}.pre-scrollable{max-height:340px;overflow-y:scroll}form{margin:0 0 20px}fieldset{padding:0;margin:0;border:0}legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:40px;color:#333;border:0;border-bottom:1px solid #e5e5e5}legend small{font-size:15px;color:#999}label,input,button,select,textarea{font-size:14px;font-weight:normal;line-height:20px}input,button,select,textarea{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif}label{display:block;margin-bottom:5px}select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{display:inline-block;height:20px;padding:4px 6px;margin-bottom:10px;font-size:14px;line-height:20px;color:#555;vertical-align:middle;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}input,textarea,.uneditable-input{width:206px}textarea{height:auto}textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{background-color:#fff;border:1px solid #ccc;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-webkit-transition:border linear .2s,box-shadow linear .2s;-moz-transition:border linear .2s,box-shadow linear .2s;-o-transition:border linear .2s,box-shadow linear .2s;transition:border linear .2s,box-shadow linear .2s}textarea:focus,input[type="text"]:focus,input[type="password"]:focus,input[type="datetime"]:focus,input[type="datetime-local"]:focus,input[type="date"]:focus,input[type="month"]:focus,input[type="time"]:focus,input[type="week"]:focus,input[type="number"]:focus,input[type="email"]:focus,input[type="url"]:focus,input[type="search"]:focus,input[type="tel"]:focus,input[type="color"]:focus,.uneditable-input:focus{border-color:rgba(82,168,236,0.8);outline:0;outline:thin dotted \9;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6)}input[type="radio"],input[type="checkbox"]{margin:4px 0 0;margin-top:1px \9;*margin-top:0;line-height:normal}input[type="file"],input[type="image"],input[type="submit"],input[type="reset"],input[type="button"],input[type="radio"],input[type="checkbox"]{width:auto}select,input[type="file"]{height:30px;*margin-top:4px;line-height:30px}select{width:220px;background-color:#fff;border:1px solid #ccc}select[multiple],select[size]{height:auto}select:focus,input[type="file"]:focus,input[type="radio"]:focus,input[type="checkbox"]:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.uneditable-input,.uneditable-textarea{color:#999;cursor:not-allowed;background-color:#fcfcfc;border-color:#ccc;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.025);-moz-box-shadow:inset 0 1px 2px rgba(0,0,0,0.025);box-shadow:inset 0 1px 2px rgba(0,0,0,0.025)}.uneditable-input{overflow:hidden;white-space:nowrap}.uneditable-textarea{width:auto;height:auto}input:-moz-placeholder,textarea:-moz-placeholder{color:#999}input:-ms-input-placeholder,textarea:-ms-input-placeholder{color:#999}input::-webkit-input-placeholder,textarea::-webkit-input-placeholder{color:#999}.radio,.checkbox{min-height:20px;padding-left:20px}.radio input[type="radio"],.checkbox input[type="checkbox"]{float:left;margin-left:-20px}.controls>.radio:first-child,.controls>.checkbox:first-child{padding-top:5px}.radio.inline,.checkbox.inline{display:inline-block;padding-top:5px;margin-bottom:0;vertical-align:middle}.radio.inline+.radio.inline,.checkbox.inline+.checkbox.inline{margin-left:10px}.input-mini{width:60px}.input-small{width:90px}.input-medium{width:150px}.input-large{width:210px}.input-xlarge{width:270px}.input-xxlarge{width:530px}input[class*="span"],select[class*="span"],textarea[class*="span"],.uneditable-input[class*="span"],.row-fluid input[class*="span"],.row-fluid select[class*="span"],.row-fluid textarea[class*="span"],.row-fluid .uneditable-input[class*="span"]{float:none;margin-left:0}.input-append input[class*="span"],.input-append .uneditable-input[class*="span"],.input-prepend input[class*="span"],.input-prepend .uneditable-input[class*="span"],.row-fluid input[class*="span"],.row-fluid select[class*="span"],.row-fluid textarea[class*="span"],.row-fluid .uneditable-input[class*="span"],.row-fluid .input-prepend [class*="span"],.row-fluid .input-append [class*="span"]{display:inline-block}input,textarea,.uneditable-input{margin-left:0}.controls-row [class*="span"]+[class*="span"]{margin-left:20px}input.span12,textarea.span12,.uneditable-input.span12{width:926px}input.span11,textarea.span11,.uneditable-input.span11{width:846px}input.span10,textarea.span10,.uneditable-input.span10{width:766px}input.span9,textarea.span9,.uneditable-input.span9{width:686px}input.span8,textarea.span8,.uneditable-input.span8{width:606px}input.span7,textarea.span7,.uneditable-input.span7{width:526px}input.span6,textarea.span6,.uneditable-input.span6{width:446px}input.span5,textarea.span5,.uneditable-input.span5{width:366px}input.span4,textarea.span4,.uneditable-input.span4{width:286px}input.span3,textarea.span3,.uneditable-input.span3{width:206px}input.span2,textarea.span2,.uneditable-input.span2{width:126px}input.span1,textarea.span1,.uneditable-input.span1{width:46px}.controls-row{*zoom:1}.controls-row:before,.controls-row:after{display:table;line-height:0;content:""}.controls-row:after{clear:both}.controls-row [class*="span"],.row-fluid .controls-row [class*="span"]{float:left}.controls-row .checkbox[class*="span"],.controls-row .radio[class*="span"]{padding-top:5px}input[disabled],select[disabled],textarea[disabled],input[readonly],select[readonly],textarea[readonly]{cursor:not-allowed;background-color:#eee}input[type="radio"][disabled],input[type="checkbox"][disabled],input[type="radio"][readonly],input[type="checkbox"][readonly]{background-color:transparent}.control-group.warning .control-label,.control-group.warning .help-block,.control-group.warning .help-inline{color:#c09853}.control-group.warning .checkbox,.control-group.warning .radio,.control-group.warning input,.control-group.warning select,.control-group.warning textarea{color:#c09853}.control-group.warning input,.control-group.warning select,.control-group.warning textarea{border-color:#c09853;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.control-group.warning input:focus,.control-group.warning select:focus,.control-group.warning textarea:focus{border-color:#a47e3c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e;-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e}.control-group.warning .input-prepend .add-on,.control-group.warning .input-append .add-on{color:#c09853;background-color:#fcf8e3;border-color:#c09853}.control-group.error .control-label,.control-group.error .help-block,.control-group.error .help-inline{color:#b94a48}.control-group.error .checkbox,.control-group.error .radio,.control-group.error input,.control-group.error select,.control-group.error textarea{color:#b94a48}.control-group.error input,.control-group.error select,.control-group.error textarea{border-color:#b94a48;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.control-group.error input:focus,.control-group.error select:focus,.control-group.error textarea:focus{border-color:#953b39;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392;-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392}.control-group.error .input-prepend .add-on,.control-group.error .input-append .add-on{color:#b94a48;background-color:#f2dede;border-color:#b94a48}.control-group.success .control-label,.control-group.success .help-block,.control-group.success .help-inline{color:#468847}.control-group.success .checkbox,.control-group.success .radio,.control-group.success input,.control-group.success select,.control-group.success textarea{color:#468847}.control-group.success input,.control-group.success select,.control-group.success textarea{border-color:#468847;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.control-group.success input:focus,.control-group.success select:focus,.control-group.success textarea:focus{border-color:#356635;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b;-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b}.control-group.success .input-prepend .add-on,.control-group.success .input-append .add-on{color:#468847;background-color:#dff0d8;border-color:#468847}.control-group.info .control-label,.control-group.info .help-block,.control-group.info .help-inline{color:#3a87ad}.control-group.info .checkbox,.control-group.info .radio,.control-group.info input,.control-group.info select,.control-group.info textarea{color:#3a87ad}.control-group.info input,.control-group.info select,.control-group.info textarea{border-color:#3a87ad;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.control-group.info input:focus,.control-group.info select:focus,.control-group.info textarea:focus{border-color:#2d6987;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7ab5d3;-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7ab5d3;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7ab5d3}.control-group.info .input-prepend .add-on,.control-group.info .input-append .add-on{color:#3a87ad;background-color:#d9edf7;border-color:#3a87ad}input:focus:invalid,textarea:focus:invalid,select:focus:invalid{color:#b94a48;border-color:#ee5f5b}input:focus:invalid:focus,textarea:focus:invalid:focus,select:focus:invalid:focus{border-color:#e9322d;-webkit-box-shadow:0 0 6px #f8b9b7;-moz-box-shadow:0 0 6px #f8b9b7;box-shadow:0 0 6px #f8b9b7}.form-actions{padding:19px 20px 20px;margin-top:20px;margin-bottom:20px;background-color:#f5f5f5;border-top:1px solid #e5e5e5;*zoom:1}.form-actions:before,.form-actions:after{display:table;line-height:0;content:""}.form-actions:after{clear:both}.help-block,.help-inline{color:#595959}.help-block{display:block;margin-bottom:10px}.help-inline{display:inline-block;*display:inline;padding-left:5px;vertical-align:middle;*zoom:1}.input-append,.input-prepend{display:inline-block;margin-bottom:10px;font-size:0;white-space:nowrap;vertical-align:middle}.input-append input,.input-prepend input,.input-append select,.input-prepend select,.input-append .uneditable-input,.input-prepend .uneditable-input,.input-append .dropdown-menu,.input-prepend .dropdown-menu,.input-append .popover,.input-prepend .popover{font-size:14px}.input-append input,.input-prepend input,.input-append select,.input-prepend select,.input-append .uneditable-input,.input-prepend .uneditable-input{position:relative;margin-bottom:0;*margin-left:0;vertical-align:top;-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.input-append input:focus,.input-prepend input:focus,.input-append select:focus,.input-prepend select:focus,.input-append .uneditable-input:focus,.input-prepend .uneditable-input:focus{z-index:2}.input-append .add-on,.input-prepend .add-on{display:inline-block;width:auto;height:20px;min-width:16px;padding:4px 5px;font-size:14px;font-weight:normal;line-height:20px;text-align:center;text-shadow:0 1px 0 #fff;background-color:#eee;border:1px solid #ccc}.input-append .add-on,.input-prepend .add-on,.input-append .btn,.input-prepend .btn,.input-append .btn-group>.dropdown-toggle,.input-prepend .btn-group>.dropdown-toggle{vertical-align:top;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.input-append .active,.input-prepend .active{background-color:#a9dba9;border-color:#46a546}.input-prepend .add-on,.input-prepend .btn{margin-right:-1px}.input-prepend .add-on:first-child,.input-prepend .btn:first-child{-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px}.input-append input,.input-append select,.input-append .uneditable-input{-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px}.input-append input+.btn-group .btn:last-child,.input-append select+.btn-group .btn:last-child,.input-append .uneditable-input+.btn-group .btn:last-child{-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.input-append .add-on,.input-append .btn,.input-append .btn-group{margin-left:-1px}.input-append .add-on:last-child,.input-append .btn:last-child,.input-append .btn-group:last-child>.dropdown-toggle{-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.input-prepend.input-append input,.input-prepend.input-append select,.input-prepend.input-append .uneditable-input{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.input-prepend.input-append input+.btn-group .btn,.input-prepend.input-append select+.btn-group .btn,.input-prepend.input-append .uneditable-input+.btn-group .btn{-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.input-prepend.input-append .add-on:first-child,.input-prepend.input-append .btn:first-child{margin-right:-1px;-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px}.input-prepend.input-append .add-on:last-child,.input-prepend.input-append .btn:last-child{margin-left:-1px;-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.input-prepend.input-append .btn-group:first-child{margin-left:0}input.search-query{padding-right:14px;padding-right:4px \9;padding-left:14px;padding-left:4px \9;margin-bottom:0;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px}.form-search .input-append .search-query,.form-search .input-prepend .search-query{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.form-search .input-append .search-query{-webkit-border-radius:14px 0 0 14px;-moz-border-radius:14px 0 0 14px;border-radius:14px 0 0 14px}.form-search .input-append .btn{-webkit-border-radius:0 14px 14px 0;-moz-border-radius:0 14px 14px 0;border-radius:0 14px 14px 0}.form-search .input-prepend .search-query{-webkit-border-radius:0 14px 14px 0;-moz-border-radius:0 14px 14px 0;border-radius:0 14px 14px 0}.form-search .input-prepend .btn{-webkit-border-radius:14px 0 0 14px;-moz-border-radius:14px 0 0 14px;border-radius:14px 0 0 14px}.form-search input,.form-inline input,.form-horizontal input,.form-search textarea,.form-inline textarea,.form-horizontal textarea,.form-search select,.form-inline select,.form-horizontal select,.form-search .help-inline,.form-inline .help-inline,.form-horizontal .help-inline,.form-search .uneditable-input,.form-inline .uneditable-input,.form-horizontal .uneditable-input,.form-search .input-prepend,.form-inline .input-prepend,.form-horizontal .input-prepend,.form-search .input-append,.form-inline .input-append,.form-horizontal .input-append{display:inline-block;*display:inline;margin-bottom:0;vertical-align:middle;*zoom:1}.form-search .hide,.form-inline .hide,.form-horizontal .hide{display:none}.form-search label,.form-inline label,.form-search .btn-group,.form-inline .btn-group{display:inline-block}.form-search .input-append,.form-inline .input-append,.form-search .input-prepend,.form-inline .input-prepend{margin-bottom:0}.form-search .radio,.form-search .checkbox,.form-inline .radio,.form-inline .checkbox{padding-left:0;margin-bottom:0;vertical-align:middle}.form-search .radio input[type="radio"],.form-search .checkbox input[type="checkbox"],.form-inline .radio input[type="radio"],.form-inline .checkbox input[type="checkbox"]{float:left;margin-right:3px;margin-left:0}.control-group{margin-bottom:10px}legend+.control-group{margin-top:20px;-webkit-margin-top-collapse:separate}.form-horizontal .control-group{margin-bottom:20px;*zoom:1}.form-horizontal .control-group:before,.form-horizontal .control-group:after{display:table;line-height:0;content:""}.form-horizontal .control-group:after{clear:both}.form-horizontal .control-label{float:left;width:160px;padding-top:5px;text-align:right}.form-horizontal .controls{*display:inline-block;*padding-left:20px;margin-left:180px;*margin-left:0}.form-horizontal .controls:first-child{*padding-left:180px}.form-horizontal .help-block{margin-bottom:0}.form-horizontal input+.help-block,.form-horizontal select+.help-block,.form-horizontal textarea+.help-block,.form-horizontal .uneditable-input+.help-block,.form-horizontal .input-prepend+.help-block,.form-horizontal .input-append+.help-block{margin-top:10px}.form-horizontal .form-actions{padding-left:180px}table{max-width:100%;background-color:transparent;border-collapse:collapse;border-spacing:0}.table{width:100%;margin-bottom:20px}.table th,.table td{padding:8px;line-height:20px;text-align:left;vertical-align:top;border-top:1px solid #ddd}.table th{font-weight:bold}.table thead th{vertical-align:bottom}.table caption+thead tr:first-child th,.table caption+thead tr:first-child td,.table colgroup+thead tr:first-child th,.table colgroup+thead tr:first-child td,.table thead:first-child tr:first-child th,.table thead:first-child tr:first-child td{border-top:0}.table tbody+tbody{border-top:2px solid #ddd}.table .table{background-color:#fff}.table-condensed th,.table-condensed td{padding:4px 5px}.table-bordered{border:1px solid #ddd;border-collapse:separate;*border-collapse:collapse;border-left:0;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.table-bordered th,.table-bordered td{border-left:1px solid #ddd}.table-bordered caption+thead tr:first-child th,.table-bordered caption+tbody tr:first-child th,.table-bordered caption+tbody tr:first-child td,.table-bordered colgroup+thead tr:first-child th,.table-bordered colgroup+tbody tr:first-child th,.table-bordered colgroup+tbody tr:first-child td,.table-bordered thead:first-child tr:first-child th,.table-bordered tbody:first-child tr:first-child th,.table-bordered tbody:first-child tr:first-child td{border-top:0}.table-bordered thead:first-child tr:first-child>th:first-child,.table-bordered tbody:first-child tr:first-child>td:first-child,.table-bordered tbody:first-child tr:first-child>th:first-child{-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-topleft:4px}.table-bordered thead:first-child tr:first-child>th:last-child,.table-bordered tbody:first-child tr:first-child>td:last-child,.table-bordered tbody:first-child tr:first-child>th:last-child{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-moz-border-radius-topright:4px}.table-bordered thead:last-child tr:last-child>th:first-child,.table-bordered tbody:last-child tr:last-child>td:first-child,.table-bordered tbody:last-child tr:last-child>th:first-child,.table-bordered tfoot:last-child tr:last-child>td:first-child,.table-bordered tfoot:last-child tr:last-child>th:first-child{-webkit-border-bottom-left-radius:4px;border-bottom-left-radius:4px;-moz-border-radius-bottomleft:4px}.table-bordered thead:last-child tr:last-child>th:last-child,.table-bordered tbody:last-child tr:last-child>td:last-child,.table-bordered tbody:last-child tr:last-child>th:last-child,.table-bordered tfoot:last-child tr:last-child>td:last-child,.table-bordered tfoot:last-child tr:last-child>th:last-child{-webkit-border-bottom-right-radius:4px;border-bottom-right-radius:4px;-moz-border-radius-bottomright:4px}.table-bordered tfoot+tbody:last-child tr:last-child td:first-child{-webkit-border-bottom-left-radius:0;border-bottom-left-radius:0;-moz-border-radius-bottomleft:0}.table-bordered tfoot+tbody:last-child tr:last-child td:last-child{-webkit-border-bottom-right-radius:0;border-bottom-right-radius:0;-moz-border-radius-bottomright:0}.table-bordered caption+thead tr:first-child th:first-child,.table-bordered caption+tbody tr:first-child td:first-child,.table-bordered colgroup+thead tr:first-child th:first-child,.table-bordered colgroup+tbody tr:first-child td:first-child{-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-topleft:4px}.table-bordered caption+thead tr:first-child th:last-child,.table-bordered caption+tbody tr:first-child td:last-child,.table-bordered colgroup+thead tr:first-child th:last-child,.table-bordered colgroup+tbody tr:first-child td:last-child{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-moz-border-radius-topright:4px}.table-striped tbody>tr:nth-child(odd)>td,.table-striped tbody>tr:nth-child(odd)>th{background-color:#f9f9f9}.table-hover tbody tr:hover>td,.table-hover tbody tr:hover>th{background-color:#f5f5f5}table td[class*="span"],table th[class*="span"],.row-fluid table td[class*="span"],.row-fluid table th[class*="span"]{display:table-cell;float:none;margin-left:0}.table td.span1,.table th.span1{float:none;width:44px;margin-left:0}.table td.span2,.table th.span2{float:none;width:124px;margin-left:0}.table td.span3,.table th.span3{float:none;width:204px;margin-left:0}.table td.span4,.table th.span4{float:none;width:284px;margin-left:0}.table td.span5,.table th.span5{float:none;width:364px;margin-left:0}.table td.span6,.table th.span6{float:none;width:444px;margin-left:0}.table td.span7,.table th.span7{float:none;width:524px;margin-left:0}.table td.span8,.table th.span8{float:none;width:604px;margin-left:0}.table td.span9,.table th.span9{float:none;width:684px;margin-left:0}.table td.span10,.table th.span10{float:none;width:764px;margin-left:0}.table td.span11,.table th.span11{float:none;width:844px;margin-left:0}.table td.span12,.table th.span12{float:none;width:924px;margin-left:0}.table tbody tr.success>td{background-color:#dff0d8}.table tbody tr.error>td{background-color:#f2dede}.table tbody tr.warning>td{background-color:#fcf8e3}.table tbody tr.info>td{background-color:#d9edf7}.table-hover tbody tr.success:hover>td{background-color:#d0e9c6}.table-hover tbody tr.error:hover>td{background-color:#ebcccc}.table-hover tbody tr.warning:hover>td{background-color:#faf2cc}.table-hover tbody tr.info:hover>td{background-color:#c4e3f3}[class^="icon-"],[class*=" icon-"]{display:inline-block;width:14px;height:14px;margin-top:1px;*margin-right:.3em;line-height:14px;vertical-align:text-top;background-image:url("../img/glyphicons-halflings.png");background-position:14px 14px;background-repeat:no-repeat}.icon-white,.nav-pills>.active>a>[class^="icon-"],.nav-pills>.active>a>[class*=" icon-"],.nav-list>.active>a>[class^="icon-"],.nav-list>.active>a>[class*=" icon-"],.navbar-inverse .nav>.active>a>[class^="icon-"],.navbar-inverse .nav>.active>a>[class*=" icon-"],.dropdown-menu>li>a:hover>[class^="icon-"],.dropdown-menu>li>a:focus>[class^="icon-"],.dropdown-menu>li>a:hover>[class*=" icon-"],.dropdown-menu>li>a:focus>[class*=" icon-"],.dropdown-menu>.active>a>[class^="icon-"],.dropdown-menu>.active>a>[class*=" icon-"],.dropdown-submenu:hover>a>[class^="icon-"],.dropdown-submenu:focus>a>[class^="icon-"],.dropdown-submenu:hover>a>[class*=" icon-"],.dropdown-submenu:focus>a>[class*=" icon-"]{background-image:url("../img/glyphicons-halflings-white.png")}.icon-glass{background-position:0 0}.icon-music{background-position:-24px 0}.icon-search{background-position:-48px 0}.icon-envelope{background-position:-72px 0}.icon-heart{background-position:-96px 0}.icon-star{background-position:-120px 0}.icon-star-empty{background-position:-144px 0}.icon-user{background-position:-168px 0}.icon-film{background-position:-192px 0}.icon-th-large{background-position:-216px 0}.icon-th{background-position:-240px 0}.icon-th-list{background-position:-264px 0}.icon-ok{background-position:-288px 0}.icon-remove{background-position:-312px 0}.icon-zoom-in{background-position:-336px 0}.icon-zoom-out{background-position:-360px 0}.icon-off{background-position:-384px 0}.icon-signal{background-position:-408px 0}.icon-cog{background-position:-432px 0}.icon-trash{background-position:-456px 0}.icon-home{background-position:0 -24px}.icon-file{background-position:-24px -24px}.icon-time{background-position:-48px -24px}.icon-road{background-position:-72px -24px}.icon-download-alt{background-position:-96px -24px}.icon-download{background-position:-120px -24px}.icon-upload{background-position:-144px -24px}.icon-inbox{background-position:-168px -24px}.icon-play-circle{background-position:-192px -24px}.icon-repeat{background-position:-216px -24px}.icon-refresh{background-position:-240px -24px}.icon-list-alt{background-position:-264px -24px}.icon-lock{background-position:-287px -24px}.icon-flag{background-position:-312px -24px}.icon-headphones{background-position:-336px -24px}.icon-volume-off{background-position:-360px -24px}.icon-volume-down{background-position:-384px -24px}.icon-volume-up{background-position:-408px -24px}.icon-qrcode{background-position:-432px -24px}.icon-barcode{background-position:-456px -24px}.icon-tag{background-position:0 -48px}.icon-tags{background-position:-25px -48px}.icon-book{background-position:-48px -48px}.icon-bookmark{background-position:-72px -48px}.icon-print{background-position:-96px -48px}.icon-camera{background-position:-120px -48px}.icon-font{background-position:-144px -48px}.icon-bold{background-position:-167px -48px}.icon-italic{background-position:-192px -48px}.icon-text-height{background-position:-216px -48px}.icon-text-width{background-position:-240px -48px}.icon-align-left{background-position:-264px -48px}.icon-align-center{background-position:-288px -48px}.icon-align-right{background-position:-312px -48px}.icon-align-justify{background-position:-336px -48px}.icon-list{background-position:-360px -48px}.icon-indent-left{background-position:-384px -48px}.icon-indent-right{background-position:-408px -48px}.icon-facetime-video{background-position:-432px -48px}.icon-picture{background-position:-456px -48px}.icon-pencil{background-position:0 -72px}.icon-map-marker{background-position:-24px -72px}.icon-adjust{background-position:-48px -72px}.icon-tint{background-position:-72px -72px}.icon-edit{background-position:-96px -72px}.icon-share{background-position:-120px -72px}.icon-check{background-position:-144px -72px}.icon-move{background-position:-168px -72px}.icon-step-backward{background-position:-192px -72px}.icon-fast-backward{background-position:-216px -72px}.icon-backward{background-position:-240px -72px}.icon-play{background-position:-264px -72px}.icon-pause{background-position:-288px -72px}.icon-stop{background-position:-312px -72px}.icon-forward{background-position:-336px -72px}.icon-fast-forward{background-position:-360px -72px}.icon-step-forward{background-position:-384px -72px}.icon-eject{background-position:-408px -72px}.icon-chevron-left{background-position:-432px -72px}.icon-chevron-right{background-position:-456px -72px}.icon-plus-sign{background-position:0 -96px}.icon-minus-sign{background-position:-24px -96px}.icon-remove-sign{background-position:-48px -96px}.icon-ok-sign{background-position:-72px -96px}.icon-question-sign{background-position:-96px -96px}.icon-info-sign{background-position:-120px -96px}.icon-screenshot{background-position:-144px -96px}.icon-remove-circle{background-position:-168px -96px}.icon-ok-circle{background-position:-192px -96px}.icon-ban-circle{background-position:-216px -96px}.icon-arrow-left{background-position:-240px -96px}.icon-arrow-right{background-position:-264px -96px}.icon-arrow-up{background-position:-289px -96px}.icon-arrow-down{background-position:-312px -96px}.icon-share-alt{background-position:-336px -96px}.icon-resize-full{background-position:-360px -96px}.icon-resize-small{background-position:-384px -96px}.icon-plus{background-position:-408px -96px}.icon-minus{background-position:-433px -96px}.icon-asterisk{background-position:-456px -96px}.icon-exclamation-sign{background-position:0 -120px}.icon-gift{background-position:-24px -120px}.icon-leaf{background-position:-48px -120px}.icon-fire{background-position:-72px -120px}.icon-eye-open{background-position:-96px -120px}.icon-eye-close{background-position:-120px -120px}.icon-warning-sign{background-position:-144px -120px}.icon-plane{background-position:-168px -120px}.icon-calendar{background-position:-192px -120px}.icon-random{width:16px;background-position:-216px -120px}.icon-comment{background-position:-240px -120px}.icon-magnet{background-position:-264px -120px}.icon-chevron-up{background-position:-288px -120px}.icon-chevron-down{background-position:-313px -119px}.icon-retweet{background-position:-336px -120px}.icon-shopping-cart{background-position:-360px -120px}.icon-folder-close{width:16px;background-position:-384px -120px}.icon-folder-open{width:16px;background-position:-408px -120px}.icon-resize-vertical{background-position:-432px -119px}.icon-resize-horizontal{background-position:-456px -118px}.icon-hdd{background-position:0 -144px}.icon-bullhorn{background-position:-24px -144px}.icon-bell{background-position:-48px -144px}.icon-certificate{background-position:-72px -144px}.icon-thumbs-up{background-position:-96px -144px}.icon-thumbs-down{background-position:-120px -144px}.icon-hand-right{background-position:-144px -144px}.icon-hand-left{background-position:-168px -144px}.icon-hand-up{background-position:-192px -144px}.icon-hand-down{background-position:-216px -144px}.icon-circle-arrow-right{background-position:-240px -144px}.icon-circle-arrow-left{background-position:-264px -144px}.icon-circle-arrow-up{background-position:-288px -144px}.icon-circle-arrow-down{background-position:-312px -144px}.icon-globe{background-position:-336px -144px}.icon-wrench{background-position:-360px -144px}.icon-tasks{background-position:-384px -144px}.icon-filter{background-position:-408px -144px}.icon-briefcase{background-position:-432px -144px}.icon-fullscreen{background-position:-456px -144px}.dropup,.dropdown{position:relative}.dropdown-toggle{*margin-bottom:-3px}.dropdown-toggle:active,.open .dropdown-toggle{outline:0}.caret{display:inline-block;width:0;height:0;vertical-align:top;border-top:4px solid #000;border-right:4px solid transparent;border-left:4px solid transparent;content:""}.dropdown .caret{margin-top:8px;margin-left:2px}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;list-style:none;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);*border-right-width:2px;*border-bottom-width:2px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,0.2);-moz-box-shadow:0 5px 10px rgba(0,0,0,0.2);box-shadow:0 5px 10px rgba(0,0,0,0.2);-webkit-background-clip:padding-box;-moz-background-clip:padding;background-clip:padding-box}.dropdown-menu.pull-right{right:0;left:auto}.dropdown-menu .divider{*width:100%;height:1px;margin:9px 1px;*margin:-5px 0 5px;overflow:hidden;background-color:#e5e5e5;border-bottom:1px solid #fff}.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:normal;line-height:20px;color:#333;white-space:nowrap}.dropdown-menu>li>a:hover,.dropdown-menu>li>a:focus,.dropdown-submenu:hover>a,.dropdown-submenu:focus>a{color:#fff;text-decoration:none;background-color:#0081c2;background-image:-moz-linear-gradient(top,#08c,#0077b3);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#0077b3));background-image:-webkit-linear-gradient(top,#08c,#0077b3);background-image:-o-linear-gradient(top,#08c,#0077b3);background-image:linear-gradient(to bottom,#08c,#0077b3);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0077b3',GradientType=0)}.dropdown-menu>.active>a,.dropdown-menu>.active>a:hover,.dropdown-menu>.active>a:focus{color:#fff;text-decoration:none;background-color:#0081c2;background-image:-moz-linear-gradient(top,#08c,#0077b3);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#0077b3));background-image:-webkit-linear-gradient(top,#08c,#0077b3);background-image:-o-linear-gradient(top,#08c,#0077b3);background-image:linear-gradient(to bottom,#08c,#0077b3);background-repeat:repeat-x;outline:0;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0077b3',GradientType=0)}.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{color:#999}.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{text-decoration:none;cursor:default;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.open{*z-index:1000}.open>.dropdown-menu{display:block}.dropdown-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:990}.pull-right>.dropdown-menu{right:0;left:auto}.dropup .caret,.navbar-fixed-bottom .dropdown .caret{border-top:0;border-bottom:4px solid #000;content:""}.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:1px}.dropdown-submenu{position:relative}.dropdown-submenu>.dropdown-menu{top:0;left:100%;margin-top:-6px;margin-left:-1px;-webkit-border-radius:0 6px 6px 6px;-moz-border-radius:0 6px 6px 6px;border-radius:0 6px 6px 6px}.dropdown-submenu:hover>.dropdown-menu{display:block}.dropup .dropdown-submenu>.dropdown-menu{top:auto;bottom:0;margin-top:0;margin-bottom:-2px;-webkit-border-radius:5px 5px 5px 0;-moz-border-radius:5px 5px 5px 0;border-radius:5px 5px 5px 0}.dropdown-submenu>a:after{display:block;float:right;width:0;height:0;margin-top:5px;margin-right:-10px;border-color:transparent;border-left-color:#ccc;border-style:solid;border-width:5px 0 5px 5px;content:" "}.dropdown-submenu:hover>a:after{border-left-color:#fff}.dropdown-submenu.pull-left{float:none}.dropdown-submenu.pull-left>.dropdown-menu{left:-100%;margin-left:10px;-webkit-border-radius:6px 0 6px 6px;-moz-border-radius:6px 0 6px 6px;border-radius:6px 0 6px 6px}.dropdown .dropdown-menu .nav-header{padding-right:20px;padding-left:20px}.typeahead{z-index:1051;margin-top:2px;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);box-shadow:inset 0 1px 1px rgba(0,0,0,0.05)}.well blockquote{border-color:#ddd;border-color:rgba(0,0,0,0.15)}.well-large{padding:24px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.well-small{padding:9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.fade{opacity:0;-webkit-transition:opacity .15s linear;-moz-transition:opacity .15s linear;-o-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{position:relative;height:0;overflow:hidden;-webkit-transition:height .35s ease;-moz-transition:height .35s ease;-o-transition:height .35s ease;transition:height .35s ease}.collapse.in{height:auto}.close{float:right;font-size:20px;font-weight:bold;line-height:20px;color:#000;text-shadow:0 1px 0 #fff;opacity:.2;filter:alpha(opacity=20)}.close:hover,.close:focus{color:#000;text-decoration:none;cursor:pointer;opacity:.4;filter:alpha(opacity=40)}button.close{padding:0;cursor:pointer;background:transparent;border:0;-webkit-appearance:none}.btn{display:inline-block;*display:inline;padding:4px 12px;margin-bottom:0;*margin-left:.3em;font-size:14px;line-height:20px;color:#333;text-align:center;text-shadow:0 1px 1px rgba(255,255,255,0.75);vertical-align:middle;cursor:pointer;background-color:#f5f5f5;*background-color:#e6e6e6;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;border:1px solid #ccc;*border:0;border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);*zoom:1;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-right:0;padding-left:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,0.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;*background-color:#04c;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary:active,.btn-primary.active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#faa732;*background-color:#f89406;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450',endColorstr='#fff89406',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active,.btn-warning.disabled,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning:active,.btn-warning.active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#da4f49;*background-color:#bd362f;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeat:repeat-x;border-color:#bd362f #bd362f #802420;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b',endColorstr='#ffbd362f',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active,.btn-danger.disabled,.btn-danger[disabled]{color:#fff;background-color:#bd362f;*background-color:#a9302a}.btn-danger:active,.btn-danger.active{background-color:#942a25 \9}.btn-success{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#5bb75b;*background-color:#51a351;background-image:-moz-linear-gradient(top,#62c462,#51a351);background-image:-webkit-gradient(linear,0 0,0 100%,from(#62c462),to(#51a351));background-image:-webkit-linear-gradient(top,#62c462,#51a351);background-image:-o-linear-gradient(top,#62c462,#51a351);background-image:linear-gradient(to bottom,#62c462,#51a351);background-repeat:repeat-x;border-color:#51a351 #51a351 #387038;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462',endColorstr='#ff51a351',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active,.btn-success.disabled,.btn-success[disabled]{color:#fff;background-color:#51a351;*background-color:#499249}.btn-success:active,.btn-success.active{background-color:#408140 \9}.btn-info{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#49afcd;*background-color:#2f96b4;background-image:-moz-linear-gradient(top,#5bc0de,#2f96b4);background-image:-webkit-gradient(linear,0 0,0 100%,from(#5bc0de),to(#2f96b4));background-image:-webkit-linear-gradient(top,#5bc0de,#2f96b4);background-image:-o-linear-gradient(top,#5bc0de,#2f96b4);background-image:linear-gradient(to bottom,#5bc0de,#2f96b4);background-repeat:repeat-x;border-color:#2f96b4 #2f96b4 #1f6377;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de',endColorstr='#ff2f96b4',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active,.btn-info.disabled,.btn-info[disabled]{color:#fff;background-color:#2f96b4;*background-color:#2a85a0}.btn-info:active,.btn-info.active{background-color:#24748c \9}.btn-inverse{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#363636;*background-color:#222;background-image:-moz-linear-gradient(top,#444,#222);background-image:-webkit-gradient(linear,0 0,0 100%,from(#444),to(#222));background-image:-webkit-linear-gradient(top,#444,#222);background-image:-o-linear-gradient(top,#444,#222);background-image:linear-gradient(to bottom,#444,#222);background-repeat:repeat-x;border-color:#222 #222 #000;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff444444',endColorstr='#ff222222',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-inverse:hover,.btn-inverse:focus,.btn-inverse:active,.btn-inverse.active,.btn-inverse.disabled,.btn-inverse[disabled]{color:#fff;background-color:#222;*background-color:#151515}.btn-inverse:active,.btn-inverse.active{background-color:#080808 \9}button.btn,input[type="submit"].btn{*padding-top:3px;*padding-bottom:3px}button.btn::-moz-focus-inner,input[type="submit"].btn::-moz-focus-inner{padding:0;border:0}button.btn.btn-large,input[type="submit"].btn.btn-large{*padding-top:7px;*padding-bottom:7px}button.btn.btn-small,input[type="submit"].btn.btn-small{*padding-top:3px;*padding-bottom:3px}button.btn.btn-mini,input[type="submit"].btn.btn-mini{*padding-top:1px;*padding-bottom:1px}.btn-link,.btn-link:active,.btn-link[disabled]{background-color:transparent;background-image:none;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-link{color:#08c;cursor:pointer;border-color:transparent;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.btn-link:hover,.btn-link:focus{color:#005580;text-decoration:underline;background-color:transparent}.btn-link[disabled]:hover,.btn-link[disabled]:focus{color:#333;text-decoration:none}.btn-group{position:relative;display:inline-block;*display:inline;*margin-left:.3em;font-size:0;white-space:nowrap;vertical-align:middle;*zoom:1}.btn-group:first-child{*margin-left:0}.btn-group+.btn-group{margin-left:5px}.btn-toolbar{margin-top:10px;margin-bottom:10px;font-size:0}.btn-toolbar>.btn+.btn,.btn-toolbar>.btn-group+.btn,.btn-toolbar>.btn+.btn-group{margin-left:5px}.btn-group>.btn{position:relative;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.btn-group>.btn+.btn{margin-left:-1px}.btn-group>.btn,.btn-group>.dropdown-menu,.btn-group>.popover{font-size:14px}.btn-group>.btn-mini{font-size:10.5px}.btn-group>.btn-small{font-size:11.9px}.btn-group>.btn-large{font-size:17.5px}.btn-group>.btn:first-child{margin-left:0;-webkit-border-bottom-left-radius:4px;border-bottom-left-radius:4px;-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-bottomleft:4px;-moz-border-radius-topleft:4px}.btn-group>.btn:last-child,.btn-group>.dropdown-toggle{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-webkit-border-bottom-right-radius:4px;border-bottom-right-radius:4px;-moz-border-radius-topright:4px;-moz-border-radius-bottomright:4px}.btn-group>.btn.large:first-child{margin-left:0;-webkit-border-bottom-left-radius:6px;border-bottom-left-radius:6px;-webkit-border-top-left-radius:6px;border-top-left-radius:6px;-moz-border-radius-bottomleft:6px;-moz-border-radius-topleft:6px}.btn-group>.btn.large:last-child,.btn-group>.large.dropdown-toggle{-webkit-border-top-right-radius:6px;border-top-right-radius:6px;-webkit-border-bottom-right-radius:6px;border-bottom-right-radius:6px;-moz-border-radius-topright:6px;-moz-border-radius-bottomright:6px}.btn-group>.btn:hover,.btn-group>.btn:focus,.btn-group>.btn:active,.btn-group>.btn.active{z-index:2}.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0}.btn-group>.btn+.dropdown-toggle{*padding-top:5px;padding-right:8px;*padding-bottom:5px;padding-left:8px;-webkit-box-shadow:inset 1px 0 0 rgba(255,255,255,0.125),inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 1px 0 0 rgba(255,255,255,0.125),inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 1px 0 0 rgba(255,255,255,0.125),inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05)}.btn-group>.btn-mini+.dropdown-toggle{*padding-top:2px;padding-right:5px;*padding-bottom:2px;padding-left:5px}.btn-group>.btn-small+.dropdown-toggle{*padding-top:5px;*padding-bottom:4px}.btn-group>.btn-large+.dropdown-toggle{*padding-top:7px;padding-right:12px;*padding-bottom:7px;padding-left:12px}.btn-group.open .dropdown-toggle{background-image:none;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05)}.btn-group.open .btn.dropdown-toggle{background-color:#e6e6e6}.btn-group.open .btn-primary.dropdown-toggle{background-color:#04c}.btn-group.open .btn-warning.dropdown-toggle{background-color:#f89406}.btn-group.open .btn-danger.dropdown-toggle{background-color:#bd362f}.btn-group.open .btn-success.dropdown-toggle{background-color:#51a351}.btn-group.open .btn-info.dropdown-toggle{background-color:#2f96b4}.btn-group.open .btn-inverse.dropdown-toggle{background-color:#222}.btn .caret{margin-top:8px;margin-left:0}.btn-large .caret{margin-top:6px}.btn-large .caret{border-top-width:5px;border-right-width:5px;border-left-width:5px}.btn-mini .caret,.btn-small .caret{margin-top:8px}.dropup .btn-large .caret{border-bottom-width:5px}.btn-primary .caret,.btn-warning .caret,.btn-danger .caret,.btn-info .caret,.btn-success .caret,.btn-inverse .caret{border-top-color:#fff;border-bottom-color:#fff}.btn-group-vertical{display:inline-block;*display:inline;*zoom:1}.btn-group-vertical>.btn{display:block;float:none;max-width:100%;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.btn-group-vertical>.btn+.btn{margin-top:-1px;margin-left:0}.btn-group-vertical>.btn:first-child{-webkit-border-radius:4px 4px 0 0;-moz-border-radius:4px 4px 0 0;border-radius:4px 4px 0 0}.btn-group-vertical>.btn:last-child{-webkit-border-radius:0 0 4px 4px;-moz-border-radius:0 0 4px 4px;border-radius:0 0 4px 4px}.btn-group-vertical>.btn-large:first-child{-webkit-border-radius:6px 6px 0 0;-moz-border-radius:6px 6px 0 0;border-radius:6px 6px 0 0}.btn-group-vertical>.btn-large:last-child{-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px}.alert{padding:8px 35px 8px 14px;margin-bottom:20px;text-shadow:0 1px 0 rgba(255,255,255,0.5);background-color:#fcf8e3;border:1px solid #fbeed5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.alert,.alert h4{color:#c09853}.alert h4{margin:0}.alert .close{position:relative;top:-2px;right:-21px;line-height:20px}.alert-success{color:#468847;background-color:#dff0d8;border-color:#d6e9c6}.alert-success h4{color:#468847}.alert-danger,.alert-error{color:#b94a48;background-color:#f2dede;border-color:#eed3d7}.alert-danger h4,.alert-error h4{color:#b94a48}.alert-info{color:#3a87ad;background-color:#d9edf7;border-color:#bce8f1}.alert-info h4{color:#3a87ad}.alert-block{padding-top:14px;padding-bottom:14px}.alert-block>p,.alert-block>ul{margin-bottom:0}.alert-block p+p{margin-top:5px}.nav{margin-bottom:20px;margin-left:0;list-style:none}.nav>li>a{display:block}.nav>li>a:hover,.nav>li>a:focus{text-decoration:none;background-color:#eee}.nav>li>a>img{max-width:none}.nav>.pull-right{float:right}.nav-header{display:block;padding:3px 15px;font-size:11px;font-weight:bold;line-height:20px;color:#999;text-shadow:0 1px 0 rgba(255,255,255,0.5);text-transform:uppercase}.nav li+.nav-header{margin-top:9px}.nav-list{padding-right:15px;padding-left:15px;margin-bottom:0}.nav-list>li>a,.nav-list .nav-header{margin-right:-15px;margin-left:-15px;text-shadow:0 1px 0 rgba(255,255,255,0.5)}.nav-list>li>a{padding:3px 15px}.nav-list>.active>a,.nav-list>.active>a:hover,.nav-list>.active>a:focus{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.2);background-color:#08c}.nav-list [class^="icon-"],.nav-list [class*=" icon-"]{margin-right:2px}.nav-list .divider{*width:100%;height:1px;margin:9px 1px;*margin:-5px 0 5px;overflow:hidden;background-color:#e5e5e5;border-bottom:1px solid #fff}.nav-tabs,.nav-pills{*zoom:1}.nav-tabs:before,.nav-pills:before,.nav-tabs:after,.nav-pills:after{display:table;line-height:0;content:""}.nav-tabs:after,.nav-pills:after{clear:both}.nav-tabs>li,.nav-pills>li{float:left}.nav-tabs>li>a,.nav-pills>li>a{padding-right:12px;padding-left:12px;margin-right:2px;line-height:14px}.nav-tabs{border-bottom:1px solid #ddd}.nav-tabs>li{margin-bottom:-1px}.nav-tabs>li>a{padding-top:8px;padding-bottom:8px;line-height:20px;border:1px solid transparent;-webkit-border-radius:4px 4px 0 0;-moz-border-radius:4px 4px 0 0;border-radius:4px 4px 0 0}.nav-tabs>li>a:hover,.nav-tabs>li>a:focus{border-color:#eee #eee #ddd}.nav-tabs>.active>a,.nav-tabs>.active>a:hover,.nav-tabs>.active>a:focus{color:#555;cursor:default;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent}.nav-pills>li>a{padding-top:8px;padding-bottom:8px;margin-top:2px;margin-bottom:2px;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px}.nav-pills>.active>a,.nav-pills>.active>a:hover,.nav-pills>.active>a:focus{color:#fff;background-color:#08c}.nav-stacked>li{float:none}.nav-stacked>li>a{margin-right:0}.nav-tabs.nav-stacked{border-bottom:0}.nav-tabs.nav-stacked>li>a{border:1px solid #ddd;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.nav-tabs.nav-stacked>li:first-child>a{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-topright:4px;-moz-border-radius-topleft:4px}.nav-tabs.nav-stacked>li:last-child>a{-webkit-border-bottom-right-radius:4px;border-bottom-right-radius:4px;-webkit-border-bottom-left-radius:4px;border-bottom-left-radius:4px;-moz-border-radius-bottomright:4px;-moz-border-radius-bottomleft:4px}.nav-tabs.nav-stacked>li>a:hover,.nav-tabs.nav-stacked>li>a:focus{z-index:2;border-color:#ddd}.nav-pills.nav-stacked>li>a{margin-bottom:3px}.nav-pills.nav-stacked>li:last-child>a{margin-bottom:1px}.nav-tabs .dropdown-menu{-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px}.nav-pills .dropdown-menu{-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.nav .dropdown-toggle .caret{margin-top:6px;border-top-color:#08c;border-bottom-color:#08c}.nav .dropdown-toggle:hover .caret,.nav .dropdown-toggle:focus .caret{border-top-color:#005580;border-bottom-color:#005580}.nav-tabs .dropdown-toggle .caret{margin-top:8px}.nav .active .dropdown-toggle .caret{border-top-color:#fff;border-bottom-color:#fff}.nav-tabs .active .dropdown-toggle .caret{border-top-color:#555;border-bottom-color:#555}.nav>.dropdown.active>a:hover,.nav>.dropdown.active>a:focus{cursor:pointer}.nav-tabs .open .dropdown-toggle,.nav-pills .open .dropdown-toggle,.nav>li.dropdown.open.active>a:hover,.nav>li.dropdown.open.active>a:focus{color:#fff;background-color:#999;border-color:#999}.nav li.dropdown.open .caret,.nav li.dropdown.open.active .caret,.nav li.dropdown.open a:hover .caret,.nav li.dropdown.open a:focus .caret{border-top-color:#fff;border-bottom-color:#fff;opacity:1;filter:alpha(opacity=100)}.tabs-stacked .open>a:hover,.tabs-stacked .open>a:focus{border-color:#999}.tabbable{*zoom:1}.tabbable:before,.tabbable:after{display:table;line-height:0;content:""}.tabbable:after{clear:both}.tab-content{overflow:auto}.tabs-below>.nav-tabs,.tabs-right>.nav-tabs,.tabs-left>.nav-tabs{border-bottom:0}.tab-content>.tab-pane,.pill-content>.pill-pane{display:none}.tab-content>.active,.pill-content>.active{display:block}.tabs-below>.nav-tabs{border-top:1px solid #ddd}.tabs-below>.nav-tabs>li{margin-top:-1px;margin-bottom:0}.tabs-below>.nav-tabs>li>a{-webkit-border-radius:0 0 4px 4px;-moz-border-radius:0 0 4px 4px;border-radius:0 0 4px 4px}.tabs-below>.nav-tabs>li>a:hover,.tabs-below>.nav-tabs>li>a:focus{border-top-color:#ddd;border-bottom-color:transparent}.tabs-below>.nav-tabs>.active>a,.tabs-below>.nav-tabs>.active>a:hover,.tabs-below>.nav-tabs>.active>a:focus{border-color:transparent #ddd #ddd #ddd}.tabs-left>.nav-tabs>li,.tabs-right>.nav-tabs>li{float:none}.tabs-left>.nav-tabs>li>a,.tabs-right>.nav-tabs>li>a{min-width:74px;margin-right:0;margin-bottom:3px}.tabs-left>.nav-tabs{float:left;margin-right:19px;border-right:1px solid #ddd}.tabs-left>.nav-tabs>li>a{margin-right:-1px;-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px}.tabs-left>.nav-tabs>li>a:hover,.tabs-left>.nav-tabs>li>a:focus{border-color:#eee #ddd #eee #eee}.tabs-left>.nav-tabs .active>a,.tabs-left>.nav-tabs .active>a:hover,.tabs-left>.nav-tabs .active>a:focus{border-color:#ddd transparent #ddd #ddd;*border-right-color:#fff}.tabs-right>.nav-tabs{float:right;margin-left:19px;border-left:1px solid #ddd}.tabs-right>.nav-tabs>li>a{margin-left:-1px;-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.tabs-right>.nav-tabs>li>a:hover,.tabs-right>.nav-tabs>li>a:focus{border-color:#eee #eee #eee #ddd}.tabs-right>.nav-tabs .active>a,.tabs-right>.nav-tabs .active>a:hover,.tabs-right>.nav-tabs .active>a:focus{border-color:#ddd #ddd #ddd transparent;*border-left-color:#fff}.nav>.disabled>a{color:#999}.nav>.disabled>a:hover,.nav>.disabled>a:focus{text-decoration:none;cursor:default;background-color:transparent}.navbar{*position:relative;*z-index:2;margin-bottom:20px;overflow:visible}.navbar-inner{min-height:40px;padding-right:20px;padding-left:20px;background-color:#fafafa;background-image:-moz-linear-gradient(top,#fff,#f2f2f2);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#f2f2f2));background-image:-webkit-linear-gradient(top,#fff,#f2f2f2);background-image:-o-linear-gradient(top,#fff,#f2f2f2);background-image:linear-gradient(to bottom,#fff,#f2f2f2);background-repeat:repeat-x;border:1px solid #d4d4d4;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#fff2f2f2',GradientType=0);*zoom:1;-webkit-box-shadow:0 1px 4px rgba(0,0,0,0.065);-moz-box-shadow:0 1px 4px rgba(0,0,0,0.065);box-shadow:0 1px 4px rgba(0,0,0,0.065)}.navbar-inner:before,.navbar-inner:after{display:table;line-height:0;content:""}.navbar-inner:after{clear:both}.navbar .container{width:auto}.nav-collapse.collapse{height:auto;overflow:visible}.navbar .brand{display:block;float:left;padding:10px 20px 10px;margin-left:-20px;font-size:20px;font-weight:200;color:#777;text-shadow:0 1px 0 #fff}.navbar .brand:hover,.navbar .brand:focus{text-decoration:none}.navbar-text{margin-bottom:0;line-height:40px;color:#777}.navbar-link{color:#777}.navbar-link:hover,.navbar-link:focus{color:#333}.navbar .divider-vertical{height:40px;margin:0 9px;border-right:1px solid #fff;border-left:1px solid #f2f2f2}.navbar .btn,.navbar .btn-group{margin-top:5px}.navbar .btn-group .btn,.navbar .input-prepend .btn,.navbar .input-append .btn,.navbar .input-prepend .btn-group,.navbar .input-append .btn-group{margin-top:0}.navbar-form{margin-bottom:0;*zoom:1}.navbar-form:before,.navbar-form:after{display:table;line-height:0;content:""}.navbar-form:after{clear:both}.navbar-form input,.navbar-form select,.navbar-form .radio,.navbar-form .checkbox{margin-top:5px}.navbar-form input,.navbar-form select,.navbar-form .btn{display:inline-block;margin-bottom:0}.navbar-form input[type="image"],.navbar-form input[type="checkbox"],.navbar-form input[type="radio"]{margin-top:3px}.navbar-form .input-append,.navbar-form .input-prepend{margin-top:5px;white-space:nowrap}.navbar-form .input-append input,.navbar-form .input-prepend input{margin-top:0}.navbar-search{position:relative;float:left;margin-top:5px;margin-bottom:0}.navbar-search .search-query{padding:4px 14px;margin-bottom:0;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:13px;font-weight:normal;line-height:1;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px}.navbar-static-top{position:static;margin-bottom:0}.navbar-static-top .navbar-inner{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.navbar-fixed-top,.navbar-fixed-bottom{position:fixed;right:0;left:0;z-index:1030;margin-bottom:0}.navbar-fixed-top .navbar-inner,.navbar-static-top .navbar-inner{border-width:0 0 1px}.navbar-fixed-bottom .navbar-inner{border-width:1px 0 0}.navbar-fixed-top .navbar-inner,.navbar-fixed-bottom .navbar-inner{padding-right:0;padding-left:0;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:940px}.navbar-fixed-top{top:0}.navbar-fixed-top .navbar-inner,.navbar-static-top .navbar-inner{-webkit-box-shadow:0 1px 10px rgba(0,0,0,0.1);-moz-box-shadow:0 1px 10px rgba(0,0,0,0.1);box-shadow:0 1px 10px rgba(0,0,0,0.1)}.navbar-fixed-bottom{bottom:0}.navbar-fixed-bottom .navbar-inner{-webkit-box-shadow:0 -1px 10px rgba(0,0,0,0.1);-moz-box-shadow:0 -1px 10px rgba(0,0,0,0.1);box-shadow:0 -1px 10px rgba(0,0,0,0.1)}.navbar .nav{position:relative;left:0;display:block;float:left;margin:0 10px 0 0}.navbar .nav.pull-right{float:right;margin-right:0}.navbar .nav>li{float:left}.navbar .nav>li>a{float:none;padding:10px 15px 10px;color:#777;text-decoration:none;text-shadow:0 1px 0 #fff}.navbar .nav .dropdown-toggle .caret{margin-top:8px}.navbar .nav>li>a:focus,.navbar .nav>li>a:hover{color:#333;text-decoration:none;background-color:transparent}.navbar .nav>.active>a,.navbar .nav>.active>a:hover,.navbar .nav>.active>a:focus{color:#555;text-decoration:none;background-color:#e5e5e5;-webkit-box-shadow:inset 0 3px 8px rgba(0,0,0,0.125);-moz-box-shadow:inset 0 3px 8px rgba(0,0,0,0.125);box-shadow:inset 0 3px 8px rgba(0,0,0,0.125)}.navbar .btn-navbar{display:none;float:right;padding:7px 10px;margin-right:5px;margin-left:5px;color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#ededed;*background-color:#e5e5e5;background-image:-moz-linear-gradient(top,#f2f2f2,#e5e5e5);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f2f2f2),to(#e5e5e5));background-image:-webkit-linear-gradient(top,#f2f2f2,#e5e5e5);background-image:-o-linear-gradient(top,#f2f2f2,#e5e5e5);background-image:linear-gradient(to bottom,#f2f2f2,#e5e5e5);background-repeat:repeat-x;border-color:#e5e5e5 #e5e5e5 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2f2f2',endColorstr='#ffe5e5e5',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.075);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.075);box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.075)}.navbar .btn-navbar:hover,.navbar .btn-navbar:focus,.navbar .btn-navbar:active,.navbar .btn-navbar.active,.navbar .btn-navbar.disabled,.navbar .btn-navbar[disabled]{color:#fff;background-color:#e5e5e5;*background-color:#d9d9d9}.navbar .btn-navbar:active,.navbar .btn-navbar.active{background-color:#ccc \9}.navbar .btn-navbar .icon-bar{display:block;width:18px;height:2px;background-color:#f5f5f5;-webkit-border-radius:1px;-moz-border-radius:1px;border-radius:1px;-webkit-box-shadow:0 1px 0 rgba(0,0,0,0.25);-moz-box-shadow:0 1px 0 rgba(0,0,0,0.25);box-shadow:0 1px 0 rgba(0,0,0,0.25)}.btn-navbar .icon-bar+.icon-bar{margin-top:3px}.navbar .nav>li>.dropdown-menu:before{position:absolute;top:-7px;left:9px;display:inline-block;border-right:7px solid transparent;border-bottom:7px solid #ccc;border-left:7px solid transparent;border-bottom-color:rgba(0,0,0,0.2);content:''}.navbar .nav>li>.dropdown-menu:after{position:absolute;top:-6px;left:10px;display:inline-block;border-right:6px solid transparent;border-bottom:6px solid #fff;border-left:6px solid transparent;content:''}.navbar-fixed-bottom .nav>li>.dropdown-menu:before{top:auto;bottom:-7px;border-top:7px solid #ccc;border-bottom:0;border-top-color:rgba(0,0,0,0.2)}.navbar-fixed-bottom .nav>li>.dropdown-menu:after{top:auto;bottom:-6px;border-top:6px solid #fff;border-bottom:0}.navbar .nav li.dropdown>a:hover .caret,.navbar .nav li.dropdown>a:focus .caret{border-top-color:#333;border-bottom-color:#333}.navbar .nav li.dropdown.open>.dropdown-toggle,.navbar .nav li.dropdown.active>.dropdown-toggle,.navbar .nav li.dropdown.open.active>.dropdown-toggle{color:#555;background-color:#e5e5e5}.navbar .nav li.dropdown>.dropdown-toggle .caret{border-top-color:#777;border-bottom-color:#777}.navbar .nav li.dropdown.open>.dropdown-toggle .caret,.navbar .nav li.dropdown.active>.dropdown-toggle .caret,.navbar .nav li.dropdown.open.active>.dropdown-toggle .caret{border-top-color:#555;border-bottom-color:#555}.navbar .pull-right>li>.dropdown-menu,.navbar .nav>li>.dropdown-menu.pull-right{right:0;left:auto}.navbar .pull-right>li>.dropdown-menu:before,.navbar .nav>li>.dropdown-menu.pull-right:before{right:12px;left:auto}.navbar .pull-right>li>.dropdown-menu:after,.navbar .nav>li>.dropdown-menu.pull-right:after{right:13px;left:auto}.navbar .pull-right>li>.dropdown-menu .dropdown-menu,.navbar .nav>li>.dropdown-menu.pull-right .dropdown-menu{right:100%;left:auto;margin-right:-1px;margin-left:0;-webkit-border-radius:6px 0 6px 6px;-moz-border-radius:6px 0 6px 6px;border-radius:6px 0 6px 6px}.navbar-inverse .navbar-inner{background-color:#1b1b1b;background-image:-moz-linear-gradient(top,#222,#111);background-image:-webkit-gradient(linear,0 0,0 100%,from(#222),to(#111));background-image:-webkit-linear-gradient(top,#222,#111);background-image:-o-linear-gradient(top,#222,#111);background-image:linear-gradient(to bottom,#222,#111);background-repeat:repeat-x;border-color:#252525;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff222222',endColorstr='#ff111111',GradientType=0)}.navbar-inverse .brand,.navbar-inverse .nav>li>a{color:#999;text-shadow:0 -1px 0 rgba(0,0,0,0.25)}.navbar-inverse .brand:hover,.navbar-inverse .nav>li>a:hover,.navbar-inverse .brand:focus,.navbar-inverse .nav>li>a:focus{color:#fff}.navbar-inverse .brand{color:#999}.navbar-inverse .navbar-text{color:#999}.navbar-inverse .nav>li>a:focus,.navbar-inverse .nav>li>a:hover{color:#fff;background-color:transparent}.navbar-inverse .nav .active>a,.navbar-inverse .nav .active>a:hover,.navbar-inverse .nav .active>a:focus{color:#fff;background-color:#111}.navbar-inverse .navbar-link{color:#999}.navbar-inverse .navbar-link:hover,.navbar-inverse .navbar-link:focus{color:#fff}.navbar-inverse .divider-vertical{border-right-color:#222;border-left-color:#111}.navbar-inverse .nav li.dropdown.open>.dropdown-toggle,.navbar-inverse .nav li.dropdown.active>.dropdown-toggle,.navbar-inverse .nav li.dropdown.open.active>.dropdown-toggle{color:#fff;background-color:#111}.navbar-inverse .nav li.dropdown>a:hover .caret,.navbar-inverse .nav li.dropdown>a:focus .caret{border-top-color:#fff;border-bottom-color:#fff}.navbar-inverse .nav li.dropdown>.dropdown-toggle .caret{border-top-color:#999;border-bottom-color:#999}.navbar-inverse .nav li.dropdown.open>.dropdown-toggle .caret,.navbar-inverse .nav li.dropdown.active>.dropdown-toggle .caret,.navbar-inverse .nav li.dropdown.open.active>.dropdown-toggle .caret{border-top-color:#fff;border-bottom-color:#fff}.navbar-inverse .navbar-search .search-query{color:#fff;background-color:#515151;border-color:#111;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1),0 1px 0 rgba(255,255,255,0.15);-moz-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1),0 1px 0 rgba(255,255,255,0.15);box-shadow:inset 0 1px 2px rgba(0,0,0,0.1),0 1px 0 rgba(255,255,255,0.15);-webkit-transition:none;-moz-transition:none;-o-transition:none;transition:none}.navbar-inverse .navbar-search .search-query:-moz-placeholder{color:#ccc}.navbar-inverse .navbar-search .search-query:-ms-input-placeholder{color:#ccc}.navbar-inverse .navbar-search .search-query::-webkit-input-placeholder{color:#ccc}.navbar-inverse .navbar-search .search-query:focus,.navbar-inverse .navbar-search .search-query.focused{padding:5px 15px;color:#333;text-shadow:0 1px 0 #fff;background-color:#fff;border:0;outline:0;-webkit-box-shadow:0 0 3px rgba(0,0,0,0.15);-moz-box-shadow:0 0 3px rgba(0,0,0,0.15);box-shadow:0 0 3px rgba(0,0,0,0.15)}.navbar-inverse .btn-navbar{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#0e0e0e;*background-color:#040404;background-image:-moz-linear-gradient(top,#151515,#040404);background-image:-webkit-gradient(linear,0 0,0 100%,from(#151515),to(#040404));background-image:-webkit-linear-gradient(top,#151515,#040404);background-image:-o-linear-gradient(top,#151515,#040404);background-image:linear-gradient(to bottom,#151515,#040404);background-repeat:repeat-x;border-color:#040404 #040404 #000;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff151515',endColorstr='#ff040404',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.navbar-inverse .btn-navbar:hover,.navbar-inverse .btn-navbar:focus,.navbar-inverse .btn-navbar:active,.navbar-inverse .btn-navbar.active,.navbar-inverse .btn-navbar.disabled,.navbar-inverse .btn-navbar[disabled]{color:#fff;background-color:#040404;*background-color:#000}.navbar-inverse .btn-navbar:active,.navbar-inverse .btn-navbar.active{background-color:#000 \9}.breadcrumb{padding:8px 15px;margin:0 0 20px;list-style:none;background-color:#f5f5f5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.breadcrumb>li{display:inline-block;*display:inline;text-shadow:0 1px 0 #fff;*zoom:1}.breadcrumb>li>.divider{padding:0 5px;color:#ccc}.breadcrumb>.active{color:#999}.pagination{margin:20px 0}.pagination ul{display:inline-block;*display:inline;margin-bottom:0;margin-left:0;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*zoom:1;-webkit-box-shadow:0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,0.05);box-shadow:0 1px 2px rgba(0,0,0,0.05)}.pagination ul>li{display:inline}.pagination ul>li>a,.pagination ul>li>span{float:left;padding:4px 12px;line-height:20px;text-decoration:none;background-color:#fff;border:1px solid #ddd;border-left-width:0}.pagination ul>li>a:hover,.pagination ul>li>a:focus,.pagination ul>.active>a,.pagination ul>.active>span{background-color:#f5f5f5}.pagination ul>.active>a,.pagination ul>.active>span{color:#999;cursor:default}.pagination ul>.disabled>span,.pagination ul>.disabled>a,.pagination ul>.disabled>a:hover,.pagination ul>.disabled>a:focus{color:#999;cursor:default;background-color:transparent}.pagination ul>li:first-child>a,.pagination ul>li:first-child>span{border-left-width:1px;-webkit-border-bottom-left-radius:4px;border-bottom-left-radius:4px;-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-bottomleft:4px;-moz-border-radius-topleft:4px}.pagination ul>li:last-child>a,.pagination ul>li:last-child>span{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-webkit-border-bottom-right-radius:4px;border-bottom-right-radius:4px;-moz-border-radius-topright:4px;-moz-border-radius-bottomright:4px}.pagination-centered{text-align:center}.pagination-right{text-align:right}.pagination-large ul>li>a,.pagination-large ul>li>span{padding:11px 19px;font-size:17.5px}.pagination-large ul>li:first-child>a,.pagination-large ul>li:first-child>span{-webkit-border-bottom-left-radius:6px;border-bottom-left-radius:6px;-webkit-border-top-left-radius:6px;border-top-left-radius:6px;-moz-border-radius-bottomleft:6px;-moz-border-radius-topleft:6px}.pagination-large ul>li:last-child>a,.pagination-large ul>li:last-child>span{-webkit-border-top-right-radius:6px;border-top-right-radius:6px;-webkit-border-bottom-right-radius:6px;border-bottom-right-radius:6px;-moz-border-radius-topright:6px;-moz-border-radius-bottomright:6px}.pagination-mini ul>li:first-child>a,.pagination-small ul>li:first-child>a,.pagination-mini ul>li:first-child>span,.pagination-small ul>li:first-child>span{-webkit-border-bottom-left-radius:3px;border-bottom-left-radius:3px;-webkit-border-top-left-radius:3px;border-top-left-radius:3px;-moz-border-radius-bottomleft:3px;-moz-border-radius-topleft:3px}.pagination-mini ul>li:last-child>a,.pagination-small ul>li:last-child>a,.pagination-mini ul>li:last-child>span,.pagination-small ul>li:last-child>span{-webkit-border-top-right-radius:3px;border-top-right-radius:3px;-webkit-border-bottom-right-radius:3px;border-bottom-right-radius:3px;-moz-border-radius-topright:3px;-moz-border-radius-bottomright:3px}.pagination-small ul>li>a,.pagination-small ul>li>span{padding:2px 10px;font-size:11.9px}.pagination-mini ul>li>a,.pagination-mini ul>li>span{padding:0 6px;font-size:10.5px}.pager{margin:20px 0;text-align:center;list-style:none;*zoom:1}.pager:before,.pager:after{display:table;line-height:0;content:""}.pager:after{clear:both}.pager li{display:inline}.pager li>a,.pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px}.pager li>a:hover,.pager li>a:focus{text-decoration:none;background-color:#f5f5f5}.pager .next>a,.pager .next>span{float:right}.pager .previous>a,.pager .previous>span{float:left}.pager .disabled>a,.pager .disabled>a:hover,.pager .disabled>a:focus,.pager .disabled>span{color:#999;cursor:default;background-color:#fff}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000}.modal-backdrop.fade{opacity:0}.modal-backdrop,.modal-backdrop.fade.in{opacity:.8;filter:alpha(opacity=80)}.modal{position:fixed;top:10%;left:50%;z-index:1050;width:560px;margin-left:-280px;background-color:#fff;border:1px solid #999;border:1px solid rgba(0,0,0,0.3);*border:1px solid #999;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;outline:0;-webkit-box-shadow:0 3px 7px rgba(0,0,0,0.3);-moz-box-shadow:0 3px 7px rgba(0,0,0,0.3);box-shadow:0 3px 7px rgba(0,0,0,0.3);-webkit-background-clip:padding-box;-moz-background-clip:padding-box;background-clip:padding-box}.modal.fade{top:-25%;-webkit-transition:opacity .3s linear,top .3s ease-out;-moz-transition:opacity .3s linear,top .3s ease-out;-o-transition:opacity .3s linear,top .3s ease-out;transition:opacity .3s linear,top .3s ease-out}.modal.fade.in{top:10%}.modal-header{padding:9px 15px;border-bottom:1px solid #eee}.modal-header .close{margin-top:2px}.modal-header h3{margin:0;line-height:30px}.modal-body{position:relative;max-height:400px;padding:15px;overflow-y:auto}.modal-form{margin-bottom:0}.modal-footer{padding:14px 15px 15px;margin-bottom:0;text-align:right;background-color:#f5f5f5;border-top:1px solid #ddd;-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px;*zoom:1;-webkit-box-shadow:inset 0 1px 0 #fff;-moz-box-shadow:inset 0 1px 0 #fff;box-shadow:inset 0 1px 0 #fff}.modal-footer:before,.modal-footer:after{display:table;line-height:0;content:""}.modal-footer:after{clear:both}.modal-footer .btn+.btn{margin-bottom:0;margin-left:5px}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}.tooltip{position:absolute;z-index:1030;display:block;font-size:11px;line-height:1.4;opacity:0;filter:alpha(opacity=0);visibility:visible}.tooltip.in{opacity:.8;filter:alpha(opacity=80)}.tooltip.top{padding:5px 0;margin-top:-3px}.tooltip.right{padding:0 5px;margin-left:3px}.tooltip.bottom{padding:5px 0;margin-top:3px}.tooltip.left{padding:0 5px;margin-left:-3px}.tooltip-inner{max-width:200px;padding:8px;color:#fff;text-align:center;text-decoration:none;background-color:#000;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-top-color:#000;border-width:5px 5px 0}.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-right-color:#000;border-width:5px 5px 5px 0}.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-left-color:#000;border-width:5px 0 5px 5px}.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-bottom-color:#000;border-width:0 5px 5px}.popover{position:absolute;top:0;left:0;z-index:1010;display:none;max-width:276px;padding:1px;text-align:left;white-space:normal;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,0.2);-moz-box-shadow:0 5px 10px rgba(0,0,0,0.2);box-shadow:0 5px 10px rgba(0,0,0,0.2);-webkit-background-clip:padding-box;-moz-background-clip:padding;background-clip:padding-box}.popover.top{margin-top:-10px}.popover.right{margin-left:10px}.popover.bottom{margin-top:10px}.popover.left{margin-left:-10px}.popover-title{padding:8px 14px;margin:0;font-size:14px;font-weight:normal;line-height:18px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;-webkit-border-radius:5px 5px 0 0;-moz-border-radius:5px 5px 0 0;border-radius:5px 5px 0 0}.popover-title:empty{display:none}.popover-content{padding:9px 14px}.popover .arrow,.popover .arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.popover .arrow{border-width:11px}.popover .arrow:after{border-width:10px;content:""}.popover.top .arrow{bottom:-11px;left:50%;margin-left:-11px;border-top-color:#999;border-top-color:rgba(0,0,0,0.25);border-bottom-width:0}.popover.top .arrow:after{bottom:1px;margin-left:-10px;border-top-color:#fff;border-bottom-width:0}.popover.right .arrow{top:50%;left:-11px;margin-top:-11px;border-right-color:#999;border-right-color:rgba(0,0,0,0.25);border-left-width:0}.popover.right .arrow:after{bottom:-10px;left:1px;border-right-color:#fff;border-left-width:0}.popover.bottom .arrow{top:-11px;left:50%;margin-left:-11px;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,0.25);border-top-width:0}.popover.bottom .arrow:after{top:1px;margin-left:-10px;border-bottom-color:#fff;border-top-width:0}.popover.left .arrow{top:50%;right:-11px;margin-top:-11px;border-left-color:#999;border-left-color:rgba(0,0,0,0.25);border-right-width:0}.popover.left .arrow:after{right:1px;bottom:-10px;border-left-color:#fff;border-right-width:0}.thumbnails{margin-left:-20px;list-style:none;*zoom:1}.thumbnails:before,.thumbnails:after{display:table;line-height:0;content:""}.thumbnails:after{clear:both}.row-fluid .thumbnails{margin-left:0}.thumbnails>li{float:left;margin-bottom:20px;margin-left:20px}.thumbnail{display:block;padding:4px;line-height:20px;border:1px solid #ddd;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:0 1px 3px rgba(0,0,0,0.055);-moz-box-shadow:0 1px 3px rgba(0,0,0,0.055);box-shadow:0 1px 3px rgba(0,0,0,0.055);-webkit-transition:all .2s ease-in-out;-moz-transition:all .2s ease-in-out;-o-transition:all .2s ease-in-out;transition:all .2s ease-in-out}a.thumbnail:hover,a.thumbnail:focus{border-color:#08c;-webkit-box-shadow:0 1px 4px rgba(0,105,214,0.25);-moz-box-shadow:0 1px 4px rgba(0,105,214,0.25);box-shadow:0 1px 4px rgba(0,105,214,0.25)}.thumbnail>img{display:block;max-width:100%;margin-right:auto;margin-left:auto}.thumbnail .caption{padding:9px;color:#555}.media,.media-body{overflow:hidden;*overflow:visible;zoom:1}.media,.media .media{margin-top:15px}.media:first-child{margin-top:0}.media-object{display:block}.media-heading{margin:0 0 5px}.media>.pull-left{margin-right:10px}.media>.pull-right{margin-left:10px}.media-list{margin-left:0;list-style:none}.label,.badge{display:inline-block;padding:2px 4px;font-size:11.844px;font-weight:bold;line-height:14px;color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);white-space:nowrap;vertical-align:baseline;background-color:#999}.label{-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.badge{padding-right:9px;padding-left:9px;-webkit-border-radius:9px;-moz-border-radius:9px;border-radius:9px}.label:empty,.badge:empty{display:none}a.label:hover,a.label:focus,a.badge:hover,a.badge:focus{color:#fff;text-decoration:none;cursor:pointer}.label-important,.badge-important{background-color:#b94a48}.label-important[href],.badge-important[href]{background-color:#953b39}.label-warning,.badge-warning{background-color:#f89406}.label-warning[href],.badge-warning[href]{background-color:#c67605}.label-success,.badge-success{background-color:#468847}.label-success[href],.badge-success[href]{background-color:#356635}.label-info,.badge-info{background-color:#3a87ad}.label-info[href],.badge-info[href]{background-color:#2d6987}.label-inverse,.badge-inverse{background-color:#333}.label-inverse[href],.badge-inverse[href]{background-color:#1a1a1a}.btn .label,.btn .badge{position:relative;top:-1px}.btn-mini .label,.btn-mini .badge{top:0}@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-moz-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-ms-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-o-keyframes progress-bar-stripes{from{background-position:0 0}to{background-position:40px 0}}@keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}.progress{height:20px;margin-bottom:20px;overflow:hidden;background-color:#f7f7f7;background-image:-moz-linear-gradient(top,#f5f5f5,#f9f9f9);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f5f5f5),to(#f9f9f9));background-image:-webkit-linear-gradient(top,#f5f5f5,#f9f9f9);background-image:-o-linear-gradient(top,#f5f5f5,#f9f9f9);background-image:linear-gradient(to bottom,#f5f5f5,#f9f9f9);background-repeat:repeat-x;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5',endColorstr='#fff9f9f9',GradientType=0);-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);-moz-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);box-shadow:inset 0 1px 2px rgba(0,0,0,0.1)}.progress .bar{float:left;width:0;height:100%;font-size:12px;color:#fff;text-align:center;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#0e90d2;background-image:-moz-linear-gradient(top,#149bdf,#0480be);background-image:-webkit-gradient(linear,0 0,0 100%,from(#149bdf),to(#0480be));background-image:-webkit-linear-gradient(top,#149bdf,#0480be);background-image:-o-linear-gradient(top,#149bdf,#0480be);background-image:linear-gradient(to bottom,#149bdf,#0480be);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff149bdf',endColorstr='#ff0480be',GradientType=0);-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);-moz-box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;-webkit-transition:width .6s ease;-moz-transition:width .6s ease;-o-transition:width .6s ease;transition:width .6s ease}.progress .bar+.bar{-webkit-box-shadow:inset 1px 0 0 rgba(0,0,0,0.15),inset 0 -1px 0 rgba(0,0,0,0.15);-moz-box-shadow:inset 1px 0 0 rgba(0,0,0,0.15),inset 0 -1px 0 rgba(0,0,0,0.15);box-shadow:inset 1px 0 0 rgba(0,0,0,0.15),inset 0 -1px 0 rgba(0,0,0,0.15)}.progress-striped .bar{background-color:#149bdf;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);-webkit-background-size:40px 40px;-moz-background-size:40px 40px;-o-background-size:40px 40px;background-size:40px 40px}.progress.active .bar{-webkit-animation:progress-bar-stripes 2s linear infinite;-moz-animation:progress-bar-stripes 2s linear infinite;-ms-animation:progress-bar-stripes 2s linear infinite;-o-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.progress-danger .bar,.progress .bar-danger{background-color:#dd514c;background-image:-moz-linear-gradient(top,#ee5f5b,#c43c35);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#c43c35));background-image:-webkit-linear-gradient(top,#ee5f5b,#c43c35);background-image:-o-linear-gradient(top,#ee5f5b,#c43c35);background-image:linear-gradient(to bottom,#ee5f5b,#c43c35);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b',endColorstr='#ffc43c35',GradientType=0)}.progress-danger.progress-striped .bar,.progress-striped .bar-danger{background-color:#ee5f5b;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-success .bar,.progress .bar-success{background-color:#5eb95e;background-image:-moz-linear-gradient(top,#62c462,#57a957);background-image:-webkit-gradient(linear,0 0,0 100%,from(#62c462),to(#57a957));background-image:-webkit-linear-gradient(top,#62c462,#57a957);background-image:-o-linear-gradient(top,#62c462,#57a957);background-image:linear-gradient(to bottom,#62c462,#57a957);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462',endColorstr='#ff57a957',GradientType=0)}.progress-success.progress-striped .bar,.progress-striped .bar-success{background-color:#62c462;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-info .bar,.progress .bar-info{background-color:#4bb1cf;background-image:-moz-linear-gradient(top,#5bc0de,#339bb9);background-image:-webkit-gradient(linear,0 0,0 100%,from(#5bc0de),to(#339bb9));background-image:-webkit-linear-gradient(top,#5bc0de,#339bb9);background-image:-o-linear-gradient(top,#5bc0de,#339bb9);background-image:linear-gradient(to bottom,#5bc0de,#339bb9);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de',endColorstr='#ff339bb9',GradientType=0)}.progress-info.progress-striped .bar,.progress-striped .bar-info{background-color:#5bc0de;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-warning .bar,.progress .bar-warning{background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450',endColorstr='#fff89406',GradientType=0)}.progress-warning.progress-striped .bar,.progress-striped .bar-warning{background-color:#fbb450;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.accordion{margin-bottom:20px}.accordion-group{margin-bottom:2px;border:1px solid #e5e5e5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.accordion-heading{border-bottom:0}.accordion-heading .accordion-toggle{display:block;padding:8px 15px}.accordion-toggle{cursor:pointer}.accordion-inner{padding:9px 15px;border-top:1px solid #e5e5e5}.carousel{position:relative;margin-bottom:20px;line-height:1}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-inner>.item{position:relative;display:none;-webkit-transition:.6s ease-in-out left;-moz-transition:.6s ease-in-out left;-o-transition:.6s ease-in-out left;transition:.6s ease-in-out left}.carousel-inner>.item>img,.carousel-inner>.item>a>img{display:block;line-height:1}.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev{display:block}.carousel-inner>.active{left:0}.carousel-inner>.next,.carousel-inner>.prev{position:absolute;top:0;width:100%}.carousel-inner>.next{left:100%}.carousel-inner>.prev{left:-100%}.carousel-inner>.next.left,.carousel-inner>.prev.right{left:0}.carousel-inner>.active.left{left:-100%}.carousel-inner>.active.right{left:100%}.carousel-control{position:absolute;top:40%;left:15px;width:40px;height:40px;margin-top:-20px;font-size:60px;font-weight:100;line-height:30px;color:#fff;text-align:center;background:#222;border:3px solid #fff;-webkit-border-radius:23px;-moz-border-radius:23px;border-radius:23px;opacity:.5;filter:alpha(opacity=50)}.carousel-control.right{right:15px;left:auto}.carousel-control:hover,.carousel-control:focus{color:#fff;text-decoration:none;opacity:.9;filter:alpha(opacity=90)}.carousel-indicators{position:absolute;top:15px;right:15px;z-index:5;margin:0;list-style:none}.carousel-indicators li{display:block;float:left;width:10px;height:10px;margin-left:5px;text-indent:-999px;background-color:#ccc;background-color:rgba(255,255,255,0.25);border-radius:5px}.carousel-indicators .active{background-color:#fff}.carousel-caption{position:absolute;right:0;bottom:0;left:0;padding:15px;background:#333;background:rgba(0,0,0,0.75)}.carousel-caption h4,.carousel-caption p{line-height:20px;color:#fff}.carousel-caption h4{margin:0 0 5px}.carousel-caption p{margin-bottom:0}.hero-unit{padding:60px;margin-bottom:30px;font-size:18px;font-weight:200;line-height:30px;color:inherit;background-color:#eee;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.hero-unit h1{margin-bottom:0;font-size:60px;line-height:1;letter-spacing:-1px;color:inherit}.hero-unit li{line-height:30px}.pull-right{float:right}.pull-left{float:left}.hide{display:none}.show{display:block}.invisible{visibility:hidden}.affix{position:fixed} diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/css_prettify.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/css_prettify.mustache new file mode 100644 index 00000000000..35687dd18e4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/css_prettify.mustache @@ -0,0 +1,101 @@ +/* Pretty printing styles. Used with prettify.js. */ +/* Vim sunburst theme by David Leibovic */ +pre .str { + color: #65B042; +} +/* string - green */ +pre .kwd { + color: #E28964; +} +/* keyword - dark pink */ +pre .com { + color: #AEAEAE; + font-style: italic; +} +/* comment - gray */ +pre .typ { + color: #89bdff; +} +/* type - light blue */ +pre .lit { + color: #3387CC; +} +/* literal - blue */ +pre .pun { + color: #fff; +} +/* punctuation - white */ +pre .pln { + color: #fff; +} +/* plaintext - white */ +pre .tag { + color: #89bdff; +} +/* html/xml tag - light blue */ +pre .atn { + color: #bdb76b; +} +/* html/xml attribute name - khaki */ +pre .atv { + color: #65B042; +} +/* html/xml attribute value - green */ +pre .dec { + color: #3387CC; +} +/* decimal - blue */ +/* Specify class=linenums on a pre to get line numbering */ +ol.linenums { + margin-top: 0; + margin-bottom: 0; + color: #AEAEAE; +} +/* IE indents via margin-left */ +li.L0, +li.L1, +li.L2, +li.L3, +li.L5, +li.L6, +li.L7, +li.L8 { + list-style-type: none; +} +/* Alternate shading for lines */ +@media print { + pre .str { + color: #060; + } + pre .kwd { + color: #006; + font-weight: bold; + } + pre .com { + color: #600; + font-style: italic; + } + pre .typ { + color: #404; + font-weight: bold; + } + pre .lit { + color: #044; + } + pre .pun { + color: #440; + } + pre .pln { + color: #000; + } + pre .tag { + color: #006; + font-weight: bold; + } + pre .atn { + color: #404; + } + pre .atv { + color: #060; + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/index.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/index.mustache new file mode 100644 index 00000000000..5a0c8c03a36 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/index.mustache @@ -0,0 +1,555 @@ + + + + + {{{appName}}} + + + + + +{{>js_jquery}} + +{{>js_prettify}} +{{>js_bootstrap}} + + + + + + + + + + +
+
+
+ +
+
+
+
+

{{{appName}}}

+
+
+
+ +
+ + {{#apiInfo}} + + {{#apis}} + {{#operations}} +
+

{{baseName}}

+ {{#operation}} + + + + + + + +
+ +
+
+

{{nickname}}

+
+
+ +
+
+ +

+

{{notes}}

+

+
+ +
{{path}}
+ +

+

Usage and SDK Samples

+

+ + + +
+
+

+curl -X {{httpMethod}} -H "apiKey: [[apiKey]]" -H "apiSecret: [[apiSecret]]" "{{basePath}}{{path}}{{#hasQueryParams}}?{{#queryParams}}{{^-first}}&{{/-first}}{{paramName}}={{vendorExtensions.x-eg}}{{/queryParams}}{{/hasQueryParams}}"
+
+
+
+
+ +
+

+{{>sample_java}}
+                                                  
+
+ + +
+

+{{>sample_android}}
+                                                  
+
+ + + + +
+

+{{>sample_objc}}
+                                                    
+
+
+

+{{>sample_js}}
+                                                    
+
+ + + +
+

+{{>sample_csharp}}
+                                                    
+
+ + +
+

+{{>sample_php}}
+                                                  
+
+ +
+ + + + + +

Parameters

+ + + + {{#hasPathParams}} +
Path parameters
+ + + + + + + {{#pathParams}} + {{>param}} + {{/pathParams}} +
NameDescription
+ {{/hasPathParams}} + + {{#hasHeaderParams}} +
Header parameters
+ + + + + + + {{#headerParams}} + {{>param}} + {{/headerParams}} + +
NameDescription
+ {{/hasHeaderParams}} + + + {{#hasBodyParam}} +
Body parameters
+ + + + + + + {{#bodyParams}} + {{>paramB}} + {{/bodyParams}} + +
NameDescription
+ {{/hasBodyParam}} + + {{#hasQueryParams}} +
Query parameters
+ + + + + + + {{#queryParams}} + {{>param}} + {{/queryParams}} +
NameDescription
+ {{/hasQueryParams}} + +

Responses

+ {{#responses}} + +

Status: {{code}} - {{message}}

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + {{#examples}} +
+
{{example}}
+
+ {{/examples}} + + +
+ + + + {{/responses}} + + + + + + +
+ +
+ +
+ + {{/operation}} +
+ + {{/operations}} + {{/apis}} + + {{/apiInfo}} + + + + +
+ + + + + + + +
+
+ Generated {{generatedDate}} +
+
+
+
+
+ + + + + + +{{>js_jsonschemaview}} +{{>js_jsonref}} +{{>js_webfontloader}} + + + + + + + + diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/js_bootstrap.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/js_bootstrap.mustache new file mode 100644 index 00000000000..66770d8b78e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/js_bootstrap.mustache @@ -0,0 +1,8 @@ + diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/js_jquery.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/js_jquery.mustache new file mode 100644 index 00000000000..7e1f8503efe --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/js_jquery.mustache @@ -0,0 +1,6 @@ + diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/js_jsonref.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/js_jsonref.mustache new file mode 100644 index 00000000000..406ba0003fc --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/js_jsonref.mustache @@ -0,0 +1,3 @@ + diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/js_jsonschemaview.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/js_jsonschemaview.mustache new file mode 100644 index 00000000000..d0893c18cd2 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/js_jsonschemaview.mustache @@ -0,0 +1,313 @@ + diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/js_prettify.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/js_prettify.mustache new file mode 100644 index 00000000000..74e8a7b3373 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/js_prettify.mustache @@ -0,0 +1,32 @@ + diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/js_webfontloader.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/js_webfontloader.mustache new file mode 100644 index 00000000000..5c0716cd1f2 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/js_webfontloader.mustache @@ -0,0 +1,19 @@ + diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/param.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/param.mustache new file mode 100644 index 00000000000..69cf16352ca --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/param.mustache @@ -0,0 +1,26 @@ +{{paramName}}{{^required}}{{/required}}{{#required}}*{{/required}} + + + + +
+ + diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/paramB.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/paramB.mustache new file mode 100644 index 00000000000..03aa9ef4d43 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/paramB.mustache @@ -0,0 +1,35 @@ +{{paramName}} {{^required}}{{/required}}{{#required}}*{{/required}} + + + + +
+ + diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_android.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_android.mustache new file mode 100644 index 00000000000..cb23590bf53 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_android.mustache @@ -0,0 +1,18 @@ +import {{{package}}}.{{{classname}}}; + +public class {{{classname}}}Example { + + public static void main(String[] args) { + {{{classname}}} apiInstance = new {{{classname}}}(); + {{#allParams}} + {{{dataType}}} {{{paramName}}} = {{{example}}}; // {{{dataType}}} | {{{description}}} + {{/allParams}} + try { + {{#returnType}}{{{returnType}}} result = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{{paramName}}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} + System.out.println(result);{{/returnType}} + } catch (ApiException e) { + System.err.println("Exception when calling {{{classname}}}#{{{operationId}}}"); + e.printStackTrace(); + } + } +} diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_csharp.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_csharp.mustache new file mode 100644 index 00000000000..fd7a75d0da2 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_csharp.mustache @@ -0,0 +1,51 @@ +using System; +using System.Diagnostics; +using {{packageName}}.Api; +using {{packageName}}.Client; +{{#modelPackage}} +using {{{.}}}; +{{/modelPackage}} + +namespace Example +{ + public class {{operationId}}Example + { + public void main() + { + {{#hasAuthMethods}}{{#authMethods}}{{#isBasic}} + // Configure HTTP basic authorization: {{{name}}} + Configuration.Default.Username = "YOUR_USERNAME"; + Configuration.Default.Password = "YOUR_PASSWORD";{{/isBasic}}{{#isApiKey}} + // Configure API key authorization: {{{name}}} + Configuration.Default.ApiKey.Add("{{{keyParamName}}}", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // Configuration.Default.ApiKeyPrefix.Add("{{{keyParamName}}}", "Bearer");{{/isApiKey}}{{#isOAuth}} + // Configure OAuth2 access token for authorization: {{{name}}} + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN";{{/isOAuth}}{{/authMethods}} + {{/hasAuthMethods}} + + var apiInstance = new {{classname}}(); + {{#allParams}} + {{#isPrimitiveType}} + var {{paramName}} = {{example}}; // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + {{/isPrimitiveType}} + {{^isPrimitiveType}} + var {{paramName}} = new {{{dataType}}}(); // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + {{/isPrimitiveType}} + {{/allParams}} + + try + { + {{#summary}} + // {{{.}}} + {{/summary}} + {{#returnType}}{{{.}}} result = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} + Debug.WriteLine(result);{{/returnType}} + } + catch (Exception e) + { + Debug.Print("Exception when calling {{classname}}.{{operationId}}: " + e.Message ); + } + } + } +} diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_java.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_java.mustache new file mode 100644 index 00000000000..160916ed81f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_java.mustache @@ -0,0 +1,41 @@ +import {{{invokerPackage}}}.*; +import {{{invokerPackage}}}.auth.*; +import {{{invokerPackage}}}.model.*; +import {{{package}}}.{{{classname}}}; + +import java.io.File; +import java.util.*; + +public class {{{classname}}}Example { + + public static void main(String[] args) { + {{#hasAuthMethods}}ApiClient defaultClient = Configuration.getDefaultApiClient(); + {{#authMethods}}{{#isBasic}} + // Configure HTTP basic authorization: {{{name}}} + HttpBasicAuth {{{name}}} = (HttpBasicAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setUsername("YOUR USERNAME"); + {{{name}}}.setPassword("YOUR PASSWORD");{{/isBasic}}{{#isApiKey}} + // Configure API key authorization: {{{name}}} + ApiKeyAuth {{{name}}} = (ApiKeyAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //{{{name}}}.setApiKeyPrefix("Token");{{/isApiKey}}{{#isOAuth}} + // Configure OAuth2 access token for authorization: {{{name}}} + OAuth {{{name}}} = (OAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setAccessToken("YOUR ACCESS TOKEN");{{/isOAuth}} + {{/authMethods}} + {{/hasAuthMethods}} + + {{{classname}}} apiInstance = new {{{classname}}}(); + {{#allParams}} + {{{dataType}}} {{{paramName}}} = {{{example}}}; // {{{dataType}}} | {{{description}}} + {{/allParams}} + try { + {{#returnType}}{{{returnType}}} result = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{{paramName}}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} + System.out.println(result);{{/returnType}} + } catch (ApiException e) { + System.err.println("Exception when calling {{{classname}}}#{{{operationId}}}"); + e.printStackTrace(); + } + } +} diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_js.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_js.mustache new file mode 100644 index 00000000000..8c77656a1a6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_js.mustache @@ -0,0 +1,43 @@ +var {{{moduleName}}} = require('{{{projectName}}}'); +{{#hasAuthMethods}} +var defaultClient = {{{moduleName}}}.ApiClient.instance; +{{#authMethods}}{{#isBasic}} +// Configure HTTP basic authorization: {{{name}}} +var {{{name}}} = defaultClient.authentications['{{{name}}}']; +{{{name}}}.username = 'YOUR USERNAME' +{{{name}}}.password = 'YOUR PASSWORD'{{/isBasic}}{{#isApiKey}} +// Configure API key authorization: {{{name}}} +var {{{name}}} = defaultClient.authentications['{{{name}}}']; +{{{name}}}.apiKey = "YOUR API KEY" +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//{{{name}}}.apiKeyPrefix['{{{keyParamName}}}'] = "Token"{{/isApiKey}}{{#isOAuth}} +// Configure OAuth2 access token for authorization: {{{name}}} +var {{{name}}} = defaultClient.authentications['{{{name}}}']; +{{{name}}}.accessToken = "YOUR ACCESS TOKEN"{{/isOAuth}} +{{/authMethods}} +{{/hasAuthMethods}} + +var api = new {{{moduleName}}}.{{{classname}}}(){{#hasParams}} +{{#vendorExtensions.x-codegen-hasRequiredParams}}{{#allParams}}{{#required}} +var {{{paramName}}} = {{{example}}}; // {{=< >=}}{<&dataType>}<={{ }}=> {{{description}}} +{{/required}}{{/allParams}}{{/vendorExtensions.x-codegen-hasRequiredParams}}{{#hasOptionalParams}} +var opts = { {{#allParams}}{{^required}} + '{{{paramName}}}': {{{example}}}{{#vendorExtensions.x-codegen-hasMoreOptional}},{{/vendorExtensions.x-codegen-hasMoreOptional}} // {{=< >=}}{<&dataType>}<={{ }}=> {{{description}}}{{/required}}{{/allParams}} +};{{/hasOptionalParams}}{{/hasParams}} +{{#usePromises}} +api.{{{operationId}}}({{#allParams}}{{#required}}{{{paramName}}}{{#vendorExtensions.x-codegen-hasMoreRequired}}, {{/vendorExtensions.x-codegen-hasMoreRequired}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{{#vendorExtensions.x-codegen-hasRequiredParams}}, {{/vendorExtensions.x-codegen-hasRequiredParams}}opts{{/hasOptionalParams}}).then(function({{#returnType}}data{{/returnType}}) { + {{#returnType}}console.log('API called successfully. Returned data: ' + data);{{/returnType}}{{^returnType}}console.log('API called successfully.');{{/returnType}} +}, function(error) { + console.error(error); +}); + +{{/usePromises}}{{^usePromises}} +var callback = function(error, data, response) { + if (error) { + console.error(error); + } else { + {{#returnType}}console.log('API called successfully. Returned data: ' + data);{{/returnType}}{{^returnType}}console.log('API called successfully.');{{/returnType}} + } +}; +api.{{{operationId}}}({{#allParams}}{{#required}}{{{paramName}}}{{#vendorExtensions.x-codegen-hasMoreRequired}}, {{/vendorExtensions.x-codegen-hasMoreRequired}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{{#vendorExtensions.x-codegen-hasRequiredParams}}, {{/vendorExtensions.x-codegen-hasRequiredParams}}opts{{/hasOptionalParams}}{{#hasParams}}, {{/hasParams}}callback); +{{/usePromises}} diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_objc.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_objc.mustache new file mode 100644 index 00000000000..88aa2b08b74 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_objc.mustache @@ -0,0 +1,34 @@ +{{#hasAuthMethods}} +{{classPrefix}}Configuration *apiConfig = [{{classPrefix}}Configuration sharedConfig]; +{{#authMethods}}{{#isBasic}}// Configure HTTP basic authorization (authentication scheme: {{{name}}}) +[apiConfig setUsername:@"YOUR_USERNAME"]; +[apiConfig setPassword:@"YOUR_PASSWORD"]; +{{/isBasic}}{{#isApiKey}} +// Configure API key authorization: (authentication scheme: {{{name}}}) +[apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"{{{keyParamName}}}"]; +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +//[apiConfig setApiKeyPrefix:@"Bearer" forApiKeyIdentifier:@"{{{keyParamName}}}"]; +{{/isApiKey}}{{#isOAuth}} +// Configure OAuth2 access token for authorization: (authentication scheme: {{{name}}}) +[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; +{{/isOAuth}}{{/authMethods}} +{{/hasAuthMethods}} + +{{#allParams}}{{{dataType}}} *{{paramName}} = {{{example}}}; // {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} +{{/allParams}} + +{{classname}} *apiInstance = [[{{classname}} alloc] init]; + +{{#summary}}// {{{.}}} +{{/summary}}[apiInstance {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} + {{paramName}}{{/secondaryParam}}:{{paramName}}{{/allParams}} + {{#hasParams}}completionHandler: {{/hasParams}}^({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error) { +{{#returnType}} + if (output) { + NSLog(@"%@", output); + } +{{/returnType}} + if (error) { + NSLog(@"Error: %@", error); + } + }]; diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_php.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_php.mustache new file mode 100644 index 00000000000..bb589426f81 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_php.mustache @@ -0,0 +1,24 @@ +setUsername('YOUR_USERNAME'); +{{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setPassword('YOUR_PASSWORD');{{/isBasic}}{{#isApiKey}} +// Configure API key authorization: {{{name}}} +{{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setApiKey('{{{keyParamName}}}', 'YOUR_API_KEY'); +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +// {{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setApiKeyPrefix('{{{keyParamName}}}', 'Bearer');{{/isApiKey}}{{#isOAuth}} +// Configure OAuth2 access token for authorization: {{{name}}} +{{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN');{{/isOAuth}}{{/authMethods}} +{{/hasAuthMethods}} + +$api_instance = new {{invokerPackage}}\Api\{{classname}}(); +{{#allParams}}${{paramName}} = {{{example}}}; // {{{dataType}}} | {{{description}}} +{{/allParams}} + +try { + {{#returnType}}$result = {{/returnType}}$api_instance->{{{operationId}}}({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} + print_r($result);{{/returnType}} +} catch (Exception $e) { + echo 'Exception when calling {{classname}}->{{operationId}}: ', $e->getMessage(), PHP_EOL; +} diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/styles.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/styles.mustache new file mode 100644 index 00000000000..6b515e10980 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/styles.mustache @@ -0,0 +1,415 @@ +/* ------------------------------------------------------------------------------------------ + * Content + * ------------------------------------------------------------------------------------------ */ +body { + min-width: 980px; +} + +body, p, a, div, th, td { + font-family: "Source Sans Pro", sans-serif; + font-weight: 400; + font-size: 16px; + text-shadow: none !important; +} + +td.code { + font-size: 14px; + font-family: "Source Code Pro", monospace; + font-style: normal; + font-weight: 400; +} + +#content { + padding-top: 16px; + z-Index: -1; + margin-left: 270px; +} + +p { + color: #808080; +} + +h1 { + font-family: "Source Sans Pro Semibold", sans-serif; + font-weight: normal; + font-size: 44px; + line-height: 50px; + margin: 0 0 10px 0; + padding: 0; +} + +h2 { + font-family: "Source Sans Pro", sans-serif; + font-weight: normal; + font-size: 24px; + line-height: 40px; + margin: 0 0 20px 0; + padding: 0; +} + +section { + border-top: 1px solid #ebebeb; + padding: 30px 0; +} + +section h1 { + font-family: "Source Sans Pro", sans-serif; + font-weight: 700; + font-size: 32px; + line-height: 40px; + padding-bottom: 14px; + margin: 0 0 20px 0; + padding: 0; +} + +article { + padding: 14px 0 30px 0; +} + +article h1 { + font-family: "Source Sans Pro Bold", sans-serif; + font-weight: 600; + font-size: 24px; + line-height: 26px; +} + +article h2 { + font-family: "Source Sans Pro", sans-serif; + font-weight: 600; + font-size: 18px; + line-height: 24px; + margin: 0 0 10px 0; +} + +article h3 { + font-family: "Source Sans Pro", sans-serif; + font-weight: 600; + font-size: 16px; + line-height: 18px; + margin: 0 0 10px 0; +} + +article h4 { + font-family: "Source Sans Pro", sans-serif; + font-weight: 600; + font-size: 14px; + line-height: 16px; + margin: 0 0 8px 0; +} + +table { + border-collapse: collapse; + width: 100%; + margin: 0 0 20px 0; +} + +th { + background-color: #f5f5f5; + text-align: left; + font-family: "Source Sans Pro", sans-serif; + font-weight: 700; + padding: 4px 8px; + border: #e0e0e0 1px solid; +} + +td { + vertical-align: top; + padding: 2px 8px; + border: #e0e0e0 1px solid; +} + +#generator .content { + color: #b0b0b0; + border-top: 1px solid #ebebeb; + padding: 10px 0; +} + +.label-optional { + float: right; +} + +.open-left { + right: 0; + left: auto; +} + +/* ------------------------------------------------------------------------------------------ + * apidoc - intro + * ------------------------------------------------------------------------------------------ */ + +#apidoc .apidoc { + border-top: 1px solid #ebebeb; + padding: 30px 0; +} + +#apidoc h1 { + font-family: "Source Sans Pro", sans-serif; + font-weight: 700; + font-size: 32px; + line-height: 40px; + padding-bottom: 14px; + margin: 0 0 20px 0; + padding: 0; +} + +#apidoc h2 { + font-family: "Source Sans Pro Bold", sans-serif; + font-weight: 600; + font-size: 22px; + line-height: 26px; + padding-top: 14px; +} + +/* ------------------------------------------------------------------------------------------ + * pre / code + * ------------------------------------------------------------------------------------------ */ +pre { + background-color: #292b36; + color: #ffffff; + padding: 10px; + border-radius: 6px; + position: relative; + margin: 10px 0 20px 0; +} + +code.language-text { + word-wrap: break-word; +} + +pre.language-json { + overflow: auto; +} + +pre.language-html { + margin: 40px 0 20px 0; +} + +pre.language-html:before { + content: attr(data-type); + position: absolute; + top: -30px; + left: 0; + font-family: "Source Sans Pro", sans-serif; + font-weight: 600; + font-size: 15px; + display: inline-block; + padding: 2px 5px; + border-radius: 6px; + text-transform: uppercase; + background-color: #3387CC; + color: #ffffff; +} + +pre.language-html[data-type="get"]:before { + background-color: green; +} + +pre.language-html[data-type="put"]:before { + background-color: #e5c500; +} + +pre.language-html[data-type="post"]:before { + background-color: #4070ec; +} + +pre.language-html[data-type="delete"]:before { + background-color: #ed0039; +} + +pre.language-api .str { + color: #ffffff; +} + +pre.language-api .pln, +pre.language-api .pun { + color: #65B042; +} + +pre code { + display: block; + font-size: 14px; + font-family: "Source Code Pro", monospace; + font-style: normal; + font-weight: 400; +} + +pre code.sample-request-response-json { + white-space: pre-wrap; + max-height: 500px; + overflow: auto; +} + +/* ------------------------------------------------------------------------------------------ + * Sidenav + * ------------------------------------------------------------------------------------------ */ +.sidenav { + width: 228px; + margin: 0; + padding: 20px; + position: fixed; + top: 0; + left: 0; + bottom: 0; + overflow-x: hidden; + overflow-y: auto; + background-color: #f5f5f5; + z-index: 10; +} + +.sidenav > li > a { + display: block; + width: 192px; + margin: 0; + padding: 2px 11px; + border: 0; + border-left: transparent 4px solid; + border-right: transparent 4px solid; + font-family: "Source Sans Pro", sans-serif; + font-weight: 400; + font-size: 14px; +} + +.sidenav > li.nav-header > a { + padding: 5px 15px; + border: 1px solid #e5e5e5; + width: 190px; + font-family: "Source Sans Pro", sans-serif; + font-weight: 700; + font-size: 16px; + background-color: #4c8eca; + color: #fff; +} + +.sidenav > li.nav-header.active > a { + background-color: #4c8eca; + color: #fff; +} + + +00427D + +.sidenav > .active > a { + position: relative; + z-index: 2; +} + +.sidenav > li > a:hover { + background-color: #ffffff; +} + +.sidenav > li.has-modifications a { + border-right: #60d060 4px solid; +} + +.sidenav > li.is-new a { + border-left: #e5e5e5 4px solid; +} + + + +/* ------------------------------------------------------------------------------------------ + * Tabs + * ------------------------------------------------------------------------------------------ */ +ul.nav-tabs { + margin: 0; +} + +/* ------------------------------------------------------------------------------------------ + * Print + * ------------------------------------------------------------------------------------------ */ + +@media print { + + #sidenav, + #version, + #versions, + section .version, + section .versions { + display: none; + } + + #content { + margin-left: 0; + } + + a { + text-decoration: none; + color: inherit; + } + + a:after { + content: " [" attr(href) "] "; + } + + p { + color: #000000 + } + + pre { + background-color: #ffffff; + color: #000000; + padding: 10px; + border: #808080 1px solid; + border-radius: 6px; + position: relative; + margin: 10px 0 20px 0; + } + +} /* /@media print */ + + +.doc-chapter +{ +display:none; +background-color: #eee; +border-radius: 1px; +padding: 10px; +margin-bottom: 20px; +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/*! + * json-schema-view-js + * https://github.com/mohsen1/json-schema-view-js#readme + * Version: 0.4.1 - 2015-11-12T17:19:27.615Z + * License: MIT + */.json-schema-view .toggle-handle:after,.json-schema-view.json-schema-view-dark .toggle-handle:after,json-schema-view .toggle-handle:after,json-schema-view[json-schema-view-dark] .toggle-handle:after{content:"\25BC"}.json-schema-view .title,.json-schema-view.json-schema-view-dark .title,json-schema-view .title,json-schema-view[json-schema-view-dark] .title{font-weight:700;cursor:pointer}.json-schema-view,json-schema-view{font-family:monospace;font-size:0;display:table-cell}.json-schema-view>*,json-schema-view>*{font-size:14px}.json-schema-view .toggle-handle,json-schema-view .toggle-handle{cursor:pointer;margin:auto .3em;font-size:10px;display:inline-block;transform-origin:50% 40%;transition:transform 150ms ease-in}.json-schema-view .toggle-handle,.json-schema-view .toggle-handle:hover,json-schema-view .toggle-handle,json-schema-view .toggle-handle:hover{text-decoration:none;color:#333}.json-schema-view .description,json-schema-view .description{color:gray;font-style:italic} + .pattern { + color: blue; + } + .default { + color: black; + } + .required { + color:black; + } + .json-schema-view .title,.json-schema-view .title:hover,json-schema-view .title,json-schema-view .title:hover{text-decoration:none;color:#333}.json-schema-view .brace,.json-schema-view .bracket,.json-schema-view .title,json-schema-view .brace,json-schema-view .bracket,json-schema-view .title{color:#333}.json-schema-view .property,json-schema-view .property{font-size:0;display:table-row}.json-schema-view .property>*,json-schema-view .property>*{font-size:14px;padding:.2em}.json-schema-view .name,json-schema-view .name{color:#00f;display:table-cell;vertical-align:top}.json-schema-view .type,json-schema-view .type{color:green}.json-schema-view .type-any,json-schema-view .type-any{color:#33f}.json-schema-view .required,json-schema-view .required{color:red}.json-schema-view .inner,json-schema-view .inner{padding-left:18px}.json-schema-view.collapsed .description,.json-schema-view.collapsed .property,json-schema-view.collapsed .description,json-schema-view.collapsed .property{display:none}.json-schema-view.collapsed .closeing.brace,json-schema-view.collapsed .closeing.brace{display:inline-block}.json-schema-view.collapsed .toggle-handle,json-schema-view.collapsed .toggle-handle{transform:rotate(-90deg)}.json-schema-view.json-schema-view-dark,json-schema-view[json-schema-view-dark]{font-family:monospace;font-size:0;display:table-cell}.json-schema-view.json-schema-view-dark>*,json-schema-view[json-schema-view-dark]>*{font-size:14px}.json-schema-view.json-schema-view-dark .toggle-handle,json-schema-view[json-schema-view-dark] .toggle-handle{cursor:pointer;margin:auto .3em;font-size:10px;display:inline-block;transform-origin:50% 40%;transition:transform 150ms ease-in}.json-schema-view.json-schema-view-dark .toggle-handle,.json-schema-view.json-schema-view-dark .toggle-handle:hover,json-schema-view[json-schema-view-dark] .toggle-handle,json-schema-view[json-schema-view-dark] .toggle-handle:hover{text-decoration:none;color:#eee}.json-schema-view.json-schema-view-dark .description,json-schema-view[json-schema-view-dark] .description{color:gray;font-style:italic}.json-schema-view.json-schema-view-dark .title,.json-schema-view.json-schema-view-dark .title:hover,json-schema-view[json-schema-view-dark] .title,json-schema-view[json-schema-view-dark] .title:hover{text-decoration:none;color:#eee}.json-schema-view.json-schema-view-dark .brace,.json-schema-view.json-schema-view-dark .bracket,.json-schema-view.json-schema-view-dark .title,json-schema-view[json-schema-view-dark] .brace,json-schema-view[json-schema-view-dark] .bracket,json-schema-view[json-schema-view-dark] .title{color:#eee}.json-schema-view.json-schema-view-dark .property,json-schema-view[json-schema-view-dark] .property{font-size:0;display:table-row}.json-schema-view.json-schema-view-dark .property>*,json-schema-view[json-schema-view-dark] .property>*{font-size:14px;padding:.2em}.json-schema-view.json-schema-view-dark .name,json-schema-view[json-schema-view-dark] .name{color:#add8e6;display:table-cell;vertical-align:top}.json-schema-view.json-schema-view-dark .type,json-schema-view[json-schema-view-dark] .type{color:#90ee90}.json-schema-view.json-schema-view-dark .type-any,json-schema-view[json-schema-view-dark] .type-any{color:#d4ebf2}.json-schema-view.json-schema-view-dark .required,json-schema-view[json-schema-view-dark] .required{color:#fe0000}.json-schema-view.json-schema-view-dark .inner,json-schema-view[json-schema-view-dark] .inner{padding-left:18px}.json-schema-view.json-schema-view-dark.collapsed .description,.json-schema-view.json-schema-view-dark.collapsed .property,json-schema-view[json-schema-view-dark].collapsed .description,json-schema-view[json-schema-view-dark].collapsed .property{display:none}.json-schema-view.json-schema-view-dark.collapsed .closeing.brace,json-schema-view[json-schema-view-dark].collapsed .closeing.brace{display:inline-block}.json-schema-view.json-schema-view-dark.collapsed .toggle-handle,json-schema-view[json-schema-view-dark].collapsed .toggle-handle{transform:rotate(-90deg)} From 30c2503f9f9a7cad8f3a4c6c2cba9fbf8a0d0e81 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 26 Jul 2016 14:10:48 +0800 Subject: [PATCH 152/470] [C#][NancyFX] Better "Add" for Dictionary and using {{packageName}} for NancyFX (#3449) * use square bucket for C# dictionary * use packageName for nancyfx generator, update info to debug for log * use packageName for nancyfx generator, update info to debug for log --- bin/nancyfx-petstore-server.sh | 31 +++ bin/windows/nancyfx-petstore-server.bat | 2 +- .../languages/NancyFXServerCodegen.java | 8 +- .../resources/csharp/Configuration.mustache | 12 +- .../main/resources/nancyfx/Project.mustache | 2 +- .../csharp/SwaggerClient/IO.Swagger.sln | 10 +- .../petstore/csharp/SwaggerClient/README.md | 14 +- .../src/IO.Swagger/Client/Configuration.cs | 12 +- .../src/IO.Swagger/IO.Swagger.csproj | 2 +- .../petstore/nancyfx/.swagger-codegen-ignore | 23 ++ .../server/petstore/nancyfx/IO.Swagger.sln | 10 +- samples/server/petstore/nancyfx/LICENSE | 201 ++++++++++++++++++ .../nancyfx/src/IO.Swagger/IO.Swagger.csproj | 8 +- .../nancyfx/src/IO.Swagger/IO.Swagger.nuspec | 2 +- .../src/IO.Swagger/Models/ApiResponse.cs | 185 ++++++++++++++++ .../nancyfx/src/IO.Swagger/Models/Order.cs | 1 + .../src/IO.Swagger/Modules/PetModule.cs | 65 +++--- .../src/IO.Swagger/Modules/StoreModule.cs | 14 +- .../src/IO.Swagger/Modules/UserModule.cs | 36 ++-- .../nancyfx/src/IO.Swagger/packages.config | 2 +- 20 files changed, 547 insertions(+), 93 deletions(-) create mode 100755 bin/nancyfx-petstore-server.sh create mode 100644 samples/server/petstore/nancyfx/.swagger-codegen-ignore create mode 100644 samples/server/petstore/nancyfx/LICENSE create mode 100644 samples/server/petstore/nancyfx/src/IO.Swagger/Models/ApiResponse.cs diff --git a/bin/nancyfx-petstore-server.sh b/bin/nancyfx-petstore-server.sh new file mode 100755 index 00000000000..20797fa0c1f --- /dev/null +++ b/bin/nancyfx-petstore-server.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/nancyfx -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l nancyfx -o samples/server/petstore/nancyfx" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/windows/nancyfx-petstore-server.bat b/bin/windows/nancyfx-petstore-server.bat index fff39d8e86a..cfd16120caf 100644 --- a/bin/windows/nancyfx-petstore-server.bat +++ b/bin/windows/nancyfx-petstore-server.bat @@ -5,6 +5,6 @@ If Not Exist %executable% ( ) REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l nancyfx -o samples\server\petstore\nancyfx\ +set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore.yaml -l nancyfx -o samples\server\petstore\nancyfx\ java %JAVA_OPTS% -jar %executable% %ags% diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java index 3eec3751364..571bcdef920 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java @@ -222,7 +222,7 @@ public Map postProcessAllModels(final Map models } private void postProcessParentModels(final Map models) { - log.info("Processing parents: " + parentModels); + log.debug("Processing parents: " + parentModels); for (final String parent : parentModels) { final CodegenModel parentModel = modelByName(parent, models); parentModel.hasChildren = true; @@ -301,7 +301,7 @@ public String toEnumVarName(final String name, final String datatype) { } else { result = enumName; } - log.info(String.format("toEnumVarName('%s', %s) = '%s'", name, datatype, enumName)); + log.debug(String.format("toEnumVarName('%s', %s) = '%s'", name, datatype, enumName)); return result; } @@ -313,7 +313,7 @@ public String toApiName(final String name) { } else { apiName = capitalize(name); } - log.info(String.format("toApiName('%s') = '%s'", name, apiName)); + log.debug(String.format("toApiName('%s') = '%s'", name, apiName)); return apiName; } @@ -334,7 +334,7 @@ public String toModelImport(final String name) { } else { result = null; } - log.info(String.format("toModelImport('%s') = '%s'", name, result)); + log.debug(String.format("toModelImport('%s') = '%s'", name, result)); return result; } diff --git a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache index b8cd6c1b330..108b85e48f8 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache @@ -158,9 +158,7 @@ namespace {{packageName}}.Client /// public void AddDefaultHeader(string key, string value) { - if (_defaultHeaderMap.ContainsKey(key)) - _defaultHeaderMap.Remove(key); - _defaultHeaderMap.Add(key, value); + _defaultHeaderMap[key] = value; } /// @@ -171,9 +169,7 @@ namespace {{packageName}}.Client /// public void AddApiKey(string key, string value) { - if (ApiKey.ContainsKey(key)) - ApiKey.Remove(key); - ApiKey.Add(key, value); + ApiKey[key] = value; } /// @@ -183,9 +179,7 @@ namespace {{packageName}}.Client /// Api Key value. public void AddApiKeyPrefix(string key, string value) { - if (ApiKeyPrefix.ContainsKey(key)) - ApiKeyPrefix.Remove(key); - ApiKeyPrefix.Add(key, value); + ApiKeyPrefix[key] = value; } /// diff --git a/modules/swagger-codegen/src/main/resources/nancyfx/Project.mustache b/modules/swagger-codegen/src/main/resources/nancyfx/Project.mustache index 5b63a52feb2..c4a06b60070 100644 --- a/modules/swagger-codegen/src/main/resources/nancyfx/Project.mustache +++ b/modules/swagger-codegen/src/main/resources/nancyfx/Project.mustache @@ -7,7 +7,7 @@ Library Properties {{packageName}}.{{packageContext}} - {{packageTitle}} + {{packageName}} {{^supportsUWP}} v4.5 {{/supportsUWP}} diff --git a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln index 5275707330e..95d7c51d31d 100644 --- a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln +++ b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln @@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 VisualStudioVersion = 12.0.0.0 MinimumVisualStudioVersion = 10.0.0.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{1ABB7E18-6533-446C-9EEA-0E0839F5C12A}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{B7B26355-6F11-47C6-AB34-6237A673E486}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger.Test", "src\IO.Swagger.Test\IO.Swagger.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" EndProject @@ -12,10 +12,10 @@ Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution -{1ABB7E18-6533-446C-9EEA-0E0839F5C12A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU -{1ABB7E18-6533-446C-9EEA-0E0839F5C12A}.Debug|Any CPU.Build.0 = Debug|Any CPU -{1ABB7E18-6533-446C-9EEA-0E0839F5C12A}.Release|Any CPU.ActiveCfg = Release|Any CPU -{1ABB7E18-6533-446C-9EEA-0E0839F5C12A}.Release|Any CPU.Build.0 = Release|Any CPU +{B7B26355-6F11-47C6-AB34-6237A673E486}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{B7B26355-6F11-47C6-AB34-6237A673E486}.Debug|Any CPU.Build.0 = Debug|Any CPU +{B7B26355-6F11-47C6-AB34-6237A673E486}.Release|Any CPU.ActiveCfg = Release|Any CPU +{B7B26355-6F11-47C6-AB34-6237A673E486}.Release|Any CPU.Build.0 = Release|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/samples/client/petstore/csharp/SwaggerClient/README.md b/samples/client/petstore/csharp/SwaggerClient/README.md index 727969d5347..6fb2bcf28f3 100644 --- a/samples/client/petstore/csharp/SwaggerClient/README.md +++ b/samples/client/petstore/csharp/SwaggerClient/README.md @@ -6,7 +6,7 @@ This C# SDK is automatically generated by the [Swagger Codegen](https://github.c - API version: 1.0.0 - SDK version: 1.0.0 -- Build date: 2016-07-24T11:20:06.818-04:00 +- Build date: 2016-07-26T00:22:48.731+08:00 - Build package: class io.swagger.codegen.languages.CSharpClientCodegen ## Frameworks supported @@ -137,6 +137,12 @@ Class | Method | HTTP request | Description ## Documentation for Authorization +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + ### petstore_auth - **Type**: OAuth @@ -146,9 +152,3 @@ Class | Method | HTTP request | Description - write:pets: modify pets in your account - read:pets: read your pets -### api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/Configuration.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/Configuration.cs index fcefd40a36c..12f87d6e6fa 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/Configuration.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/Configuration.cs @@ -179,9 +179,7 @@ public Dictionary DefaultHeader /// public void AddDefaultHeader(string key, string value) { - if (_defaultHeaderMap.ContainsKey(key)) - _defaultHeaderMap.Remove(key); - _defaultHeaderMap.Add(key, value); + _defaultHeaderMap[key] = value; } /// @@ -192,9 +190,7 @@ public void AddDefaultHeader(string key, string value) /// public void AddApiKey(string key, string value) { - if (ApiKey.ContainsKey(key)) - ApiKey.Remove(key); - ApiKey.Add(key, value); + ApiKey[key] = value; } /// @@ -204,9 +200,7 @@ public void AddApiKey(string key, string value) /// Api Key value. public void AddApiKeyPrefix(string key, string value) { - if (ApiKeyPrefix.ContainsKey(key)) - ApiKeyPrefix.Remove(key); - ApiKeyPrefix.Add(key, value); + ApiKeyPrefix[key] = value; } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj index f818f874154..e84766657af 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj @@ -24,7 +24,7 @@ limitations under the License. Debug AnyCPU - {1ABB7E18-6533-446C-9EEA-0E0839F5C12A} + {B7B26355-6F11-47C6-AB34-6237A673E486} Library Properties IO.Swagger diff --git a/samples/server/petstore/nancyfx/.swagger-codegen-ignore b/samples/server/petstore/nancyfx/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/nancyfx/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/nancyfx/IO.Swagger.sln b/samples/server/petstore/nancyfx/IO.Swagger.sln index 896f0bd86f6..87b0eca9e40 100644 --- a/samples/server/petstore/nancyfx/IO.Swagger.sln +++ b/samples/server/petstore/nancyfx/IO.Swagger.sln @@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 VisualStudioVersion = 12.0.0.0 MinimumVisualStudioVersion = 10.0.0.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{1DE2DD8D-1AFB-4BC2-9FB5-04DE7DCA1353}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{4E6FF76E-03ED-499F-B05C-4315904C488E}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -10,10 +10,10 @@ Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution -{1DE2DD8D-1AFB-4BC2-9FB5-04DE7DCA1353}.Debug|Any CPU.ActiveCfg = Debug|Any CPU -{1DE2DD8D-1AFB-4BC2-9FB5-04DE7DCA1353}.Debug|Any CPU.Build.0 = Debug|Any CPU -{1DE2DD8D-1AFB-4BC2-9FB5-04DE7DCA1353}.Release|Any CPU.ActiveCfg = Release|Any CPU -{1DE2DD8D-1AFB-4BC2-9FB5-04DE7DCA1353}.Release|Any CPU.Build.0 = Release|Any CPU +{4E6FF76E-03ED-499F-B05C-4315904C488E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{4E6FF76E-03ED-499F-B05C-4315904C488E}.Debug|Any CPU.Build.0 = Debug|Any CPU +{4E6FF76E-03ED-499F-B05C-4315904C488E}.Release|Any CPU.ActiveCfg = Release|Any CPU +{4E6FF76E-03ED-499F-B05C-4315904C488E}.Release|Any CPU.Build.0 = Release|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/samples/server/petstore/nancyfx/LICENSE b/samples/server/petstore/nancyfx/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/server/petstore/nancyfx/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj b/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj index 46fb435d419..694e6c1ad4d 100644 --- a/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj @@ -3,11 +3,11 @@ Debug AnyCPU - {1DE2DD8D-1AFB-4BC2-9FB5-04DE7DCA1353} + {4E6FF76E-03ED-499F-B05C-4315904C488E} Library Properties IO.Swagger.v2 - + IO.Swagger v4.5 512 @@ -39,8 +39,8 @@ ..\..\packages\NodaTime.1.3.1\lib\net35-Client\NodaTime.dll True - - ..\..\packages\Sharpility.1.2.1\lib\net45\Sharpility.dll + + ..\..\packages\Sharpility.1.2.2\lib\net45\Sharpility.dll True diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.nuspec b/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.nuspec index f6ab1af8e9b..889fe96ab03 100644 --- a/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.nuspec +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.nuspec @@ -8,7 +8,7 @@ swagger-codegen false NancyFx IO.Swagger API - http://helloreverb.com/terms/ + http://swagger.io/terms/ http://www.apache.org/licenses/LICENSE-2.0.html \ No newline at end of file diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/Models/ApiResponse.cs b/samples/server/petstore/nancyfx/src/IO.Swagger/Models/ApiResponse.cs new file mode 100644 index 00000000000..8eb40938412 --- /dev/null +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/Models/ApiResponse.cs @@ -0,0 +1,185 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using Sharpility.Extensions; +using NodaTime; + +namespace IO.Swagger.v2.Models +{ + /// + /// ApiResponse + /// + public sealed class ApiResponse: IEquatable + { + /// + /// Code + /// + public int? Code { get; private set; } + + /// + /// Type + /// + public string Type { get; private set; } + + /// + /// Message + /// + public string Message { get; private set; } + + + /// + /// Empty constructor required by some serializers. + /// Use ApiResponse.Builder() for instance creation instead. + /// + [Obsolete] + public ApiResponse() + { + } + + private ApiResponse(int? Code, string Type, string Message) + { + + this.Code = Code; + + this.Type = Type; + + this.Message = Message; + + } + + /// + /// Returns builder of ApiResponse. + /// + /// ApiResponseBuilder + public static ApiResponseBuilder Builder() + { + return new ApiResponseBuilder(); + } + + /// + /// Returns ApiResponseBuilder with properties set. + /// Use it to change properties. + /// + /// ApiResponseBuilder + public ApiResponseBuilder With() + { + return Builder() + .Code(Code) + .Type(Type) + .Message(Message); + } + + public override string ToString() + { + return this.PropertiesToString(); + } + + public override bool Equals(object obj) + { + return this.EqualsByProperties(obj); + } + + public bool Equals(ApiResponse other) + { + return Equals((object) other); + } + + public override int GetHashCode() + { + return this.PropertiesHash(); + } + + /// + /// Implementation of == operator for (ApiResponse. + /// + /// Compared (ApiResponse + /// Compared (ApiResponse + /// true if compared items are equals, false otherwise + public static bool operator == (ApiResponse left, ApiResponse right) + { + return Equals(left, right); + } + + /// + /// Implementation of != operator for (ApiResponse. + /// + /// Compared (ApiResponse + /// Compared (ApiResponse + /// true if compared items are not equals, false otherwise + public static bool operator != (ApiResponse left, ApiResponse right) + { + return !Equals(left, right); + } + + /// + /// Builder of ApiResponse. + /// + public sealed class ApiResponseBuilder + { + private int? _Code; + private string _Type; + private string _Message; + + internal ApiResponseBuilder() + { + SetupDefaults(); + } + + private void SetupDefaults() + { + } + + /// + /// Sets value for ApiResponse.Code property. + /// + /// Code + public ApiResponseBuilder Code(int? value) + { + _Code = value; + return this; + } + + /// + /// Sets value for ApiResponse.Type property. + /// + /// Type + public ApiResponseBuilder Type(string value) + { + _Type = value; + return this; + } + + /// + /// Sets value for ApiResponse.Message property. + /// + /// Message + public ApiResponseBuilder Message(string value) + { + _Message = value; + return this; + } + + + /// + /// Builds instance of ApiResponse. + /// + /// ApiResponse + public ApiResponse Build() + { + Validate(); + return new ApiResponse( + Code: _Code, + Type: _Type, + Message: _Message + ); + } + + private void Validate() + { + } + } + + + } +} diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/Models/Order.cs b/samples/server/petstore/nancyfx/src/IO.Swagger/Models/Order.cs index 22245ee5bfe..7404b483830 100644 --- a/samples/server/petstore/nancyfx/src/IO.Swagger/Models/Order.cs +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/Models/Order.cs @@ -155,6 +155,7 @@ internal OrderBuilder() private void SetupDefaults() { + _Complete = false; } /// diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/PetModule.cs b/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/PetModule.cs index f3ab9ee2892..3f47101563f 100644 --- a/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/PetModule.cs +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/PetModule.cs @@ -9,6 +9,10 @@ namespace IO.Swagger.v2.Modules { + /// + /// Status values that need to be considered for filter + /// + public enum FindPetsByStatusList<StatusEnum> { }; /// /// Module processing requests of Pet domain. @@ -24,8 +28,10 @@ public PetModule(PetService service) : base("/v2") Post["/pet"] = parameters => { var body = this.Bind(); + Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'AddPet'"); + service.AddPet(Context, body); - return new Response { ContentType = "application/json"}; + return new Response { ContentType = "application/xml"}; }; Delete["/pet/{petId}"] = parameters => @@ -35,18 +41,22 @@ public PetModule(PetService service) : base("/v2") Preconditions.IsNotNull(petId, "Required parameter: 'petId' is missing at 'DeletePet'"); service.DeletePet(Context, petId, apiKey); - return new Response { ContentType = "application/json"}; + return new Response { ContentType = "application/xml"}; }; Get["/pet/findByStatus"] = parameters => { - var status = Parameters.ValueOf>(parameters, Context.Request, "status", ParameterType.Query); + var status = Parameters.ValueOf(parameters, Context.Request, "status", ParameterType.Query); + Preconditions.IsNotNull(status, "Required parameter: 'status' is missing at 'FindPetsByStatus'"); + return service.FindPetsByStatus(Context, status); }; Get["/pet/findByTags"] = parameters => { var tags = Parameters.ValueOf>(parameters, Context.Request, "tags", ParameterType.Query); + Preconditions.IsNotNull(tags, "Required parameter: 'tags' is missing at 'FindPetsByTags'"); + return service.FindPetsByTags(Context, tags); }; @@ -61,19 +71,21 @@ public PetModule(PetService service) : base("/v2") Put["/pet"] = parameters => { var body = this.Bind(); + Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'UpdatePet'"); + service.UpdatePet(Context, body); - return new Response { ContentType = "application/json"}; + return new Response { ContentType = "application/xml"}; }; Post["/pet/{petId}"] = parameters => { - var petId = Parameters.ValueOf(parameters, Context.Request, "petId", ParameterType.Path); + var petId = Parameters.ValueOf(parameters, Context.Request, "petId", ParameterType.Path); var name = Parameters.ValueOf(parameters, Context.Request, "name", ParameterType.Undefined); var status = Parameters.ValueOf(parameters, Context.Request, "status", ParameterType.Undefined); Preconditions.IsNotNull(petId, "Required parameter: 'petId' is missing at 'UpdatePetWithForm'"); service.UpdatePetWithForm(Context, petId, name, status); - return new Response { ContentType = "application/json"}; + return new Response { ContentType = "application/xml"}; }; Post["/pet/{petId}/uploadImage"] = parameters => @@ -83,8 +95,7 @@ public PetModule(PetService service) : base("/v2") var file = Parameters.ValueOf(parameters, Context.Request, "file", ParameterType.Undefined); Preconditions.IsNotNull(petId, "Required parameter: 'petId' is missing at 'UploadFile'"); - service.UploadFile(Context, petId, additionalMetadata, file); - return new Response { ContentType = "application/json"}; + return service.UploadFile(Context, petId, additionalMetadata, file); }; } } @@ -98,7 +109,7 @@ public interface PetService /// /// /// Context of request - /// Pet object that needs to be added to the store (optional) + /// Pet object that needs to be added to the store /// void AddPet(NancyContext context, Pet body); @@ -112,26 +123,26 @@ public interface PetService void DeletePet(NancyContext context, long? petId, string apiKey); /// - /// Multiple status values can be provided with comma seperated strings + /// Multiple status values can be provided with comma separated strings /// /// Context of request - /// Status values that need to be considered for filter (optional, default to available) + /// Status values that need to be considered for filter /// List<Pet> - List FindPetsByStatus(NancyContext context, List status); + List FindPetsByStatus(NancyContext context, FindPetsByStatusList<StatusEnum>? status); /// - /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. /// /// Context of request - /// Tags to filter by (optional) + /// Tags to filter by /// List<Pet> List FindPetsByTags(NancyContext context, List tags); /// - /// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + /// Returns a single pet /// /// Context of request - /// ID of pet that needs to be fetched + /// ID of pet to return /// Pet Pet GetPetById(NancyContext context, long? petId); @@ -139,7 +150,7 @@ public interface PetService /// /// /// Context of request - /// Pet object that needs to be added to the store (optional) + /// Pet object that needs to be added to the store /// void UpdatePet(NancyContext context, Pet body); @@ -151,7 +162,7 @@ public interface PetService /// Updated name of the pet (optional) /// Updated status of the pet (optional) /// - void UpdatePetWithForm(NancyContext context, string petId, string name, string status); + void UpdatePetWithForm(NancyContext context, long? petId, string name, string status); /// /// @@ -160,8 +171,8 @@ public interface PetService /// ID of pet to update /// Additional data to pass to server (optional) /// file to upload (optional) - /// - void UploadFile(NancyContext context, long? petId, string additionalMetadata, System.IO.Stream file); + /// ApiResponse + ApiResponse UploadFile(NancyContext context, long? petId, string additionalMetadata, System.IO.Stream file); } /// @@ -179,7 +190,7 @@ public virtual void DeletePet(NancyContext context, long? petId, string apiKey) DeletePet(petId, apiKey); } - public virtual List FindPetsByStatus(NancyContext context, List status) + public virtual List FindPetsByStatus(NancyContext context, FindPetsByStatusList<StatusEnum>? status) { return FindPetsByStatus(status); } @@ -199,21 +210,21 @@ public virtual void UpdatePet(NancyContext context, Pet body) UpdatePet(body); } - public virtual void UpdatePetWithForm(NancyContext context, string petId, string name, string status) + public virtual void UpdatePetWithForm(NancyContext context, long? petId, string name, string status) { UpdatePetWithForm(petId, name, status); } - public virtual void UploadFile(NancyContext context, long? petId, string additionalMetadata, System.IO.Stream file) + public virtual ApiResponse UploadFile(NancyContext context, long? petId, string additionalMetadata, System.IO.Stream file) { - UploadFile(petId, additionalMetadata, file); + return UploadFile(petId, additionalMetadata, file); } protected abstract void AddPet(Pet body); protected abstract void DeletePet(long? petId, string apiKey); - protected abstract List FindPetsByStatus(List status); + protected abstract List FindPetsByStatus(FindPetsByStatusList<StatusEnum>? status); protected abstract List FindPetsByTags(List tags); @@ -221,9 +232,9 @@ public virtual void UploadFile(NancyContext context, long? petId, string additio protected abstract void UpdatePet(Pet body); - protected abstract void UpdatePetWithForm(string petId, string name, string status); + protected abstract void UpdatePetWithForm(long? petId, string name, string status); - protected abstract void UploadFile(long? petId, string additionalMetadata, System.IO.Stream file); + protected abstract ApiResponse UploadFile(long? petId, string additionalMetadata, System.IO.Stream file); } } diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/StoreModule.cs b/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/StoreModule.cs index 06f397db408..e5eed7a2485 100644 --- a/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/StoreModule.cs +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/StoreModule.cs @@ -27,7 +27,7 @@ public StoreModule(StoreService service) : base("/v2") Preconditions.IsNotNull(orderId, "Required parameter: 'orderId' is missing at 'DeleteOrder'"); service.DeleteOrder(Context, orderId); - return new Response { ContentType = "application/json"}; + return new Response { ContentType = "application/xml"}; }; Get["/store/inventory"] = parameters => @@ -38,7 +38,7 @@ public StoreModule(StoreService service) : base("/v2") Get["/store/order/{orderId}"] = parameters => { - var orderId = Parameters.ValueOf(parameters, Context.Request, "orderId", ParameterType.Path); + var orderId = Parameters.ValueOf(parameters, Context.Request, "orderId", ParameterType.Path); Preconditions.IsNotNull(orderId, "Required parameter: 'orderId' is missing at 'GetOrderById'"); return service.GetOrderById(Context, orderId); @@ -47,6 +47,8 @@ public StoreModule(StoreService service) : base("/v2") Post["/store/order"] = parameters => { var body = this.Bind(); + Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'PlaceOrder'"); + return service.PlaceOrder(Context, body); }; } @@ -78,13 +80,13 @@ public interface StoreService /// Context of request /// ID of pet that needs to be fetched /// Order - Order GetOrderById(NancyContext context, string orderId); + Order GetOrderById(NancyContext context, long? orderId); /// /// /// /// Context of request - /// order placed for purchasing the pet (optional) + /// order placed for purchasing the pet /// Order Order PlaceOrder(NancyContext context, Order body); } @@ -104,7 +106,7 @@ public virtual void DeleteOrder(NancyContext context, string orderId) return GetInventory(); } - public virtual Order GetOrderById(NancyContext context, string orderId) + public virtual Order GetOrderById(NancyContext context, long? orderId) { return GetOrderById(orderId); } @@ -118,7 +120,7 @@ public virtual Order PlaceOrder(NancyContext context, Order body) protected abstract Dictionary GetInventory(); - protected abstract Order GetOrderById(string orderId); + protected abstract Order GetOrderById(long? orderId); protected abstract Order PlaceOrder(Order body); } diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/UserModule.cs b/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/UserModule.cs index 8350479ef12..978013f17bb 100644 --- a/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/UserModule.cs +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/UserModule.cs @@ -24,22 +24,28 @@ public UserModule(UserService service) : base("/v2") Post["/user"] = parameters => { var body = this.Bind(); + Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'CreateUser'"); + service.CreateUser(Context, body); - return new Response { ContentType = "application/json"}; + return new Response { ContentType = "application/xml"}; }; Post["/user/createWithArray"] = parameters => { var body = this.Bind>(); + Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'CreateUsersWithArrayInput'"); + service.CreateUsersWithArrayInput(Context, body); - return new Response { ContentType = "application/json"}; + return new Response { ContentType = "application/xml"}; }; Post["/user/createWithList"] = parameters => { var body = this.Bind>(); + Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'CreateUsersWithListInput'"); + service.CreateUsersWithListInput(Context, body); - return new Response { ContentType = "application/json"}; + return new Response { ContentType = "application/xml"}; }; Delete["/user/{username}"] = parameters => @@ -48,7 +54,7 @@ public UserModule(UserService service) : base("/v2") Preconditions.IsNotNull(username, "Required parameter: 'username' is missing at 'DeleteUser'"); service.DeleteUser(Context, username); - return new Response { ContentType = "application/json"}; + return new Response { ContentType = "application/xml"}; }; Get["/user/{username}"] = parameters => @@ -63,6 +69,10 @@ public UserModule(UserService service) : base("/v2") { var username = Parameters.ValueOf(parameters, Context.Request, "username", ParameterType.Query); var password = Parameters.ValueOf(parameters, Context.Request, "password", ParameterType.Query); + Preconditions.IsNotNull(username, "Required parameter: 'username' is missing at 'LoginUser'"); + + Preconditions.IsNotNull(password, "Required parameter: 'password' is missing at 'LoginUser'"); + return service.LoginUser(Context, username, password); }; @@ -70,7 +80,7 @@ public UserModule(UserService service) : base("/v2") { service.LogoutUser(Context); - return new Response { ContentType = "application/json"}; + return new Response { ContentType = "application/xml"}; }; Put["/user/{username}"] = parameters => @@ -79,8 +89,10 @@ public UserModule(UserService service) : base("/v2") var body = this.Bind(); Preconditions.IsNotNull(username, "Required parameter: 'username' is missing at 'UpdateUser'"); + Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'UpdateUser'"); + service.UpdateUser(Context, username, body); - return new Response { ContentType = "application/json"}; + return new Response { ContentType = "application/xml"}; }; } } @@ -94,7 +106,7 @@ public interface UserService /// This can only be done by the logged in user. /// /// Context of request - /// Created user object (optional) + /// Created user object /// void CreateUser(NancyContext context, User body); @@ -102,7 +114,7 @@ public interface UserService /// /// /// Context of request - /// List of user object (optional) + /// List of user object /// void CreateUsersWithArrayInput(NancyContext context, List body); @@ -110,7 +122,7 @@ public interface UserService /// /// /// Context of request - /// List of user object (optional) + /// List of user object /// void CreateUsersWithListInput(NancyContext context, List body); @@ -134,8 +146,8 @@ public interface UserService /// /// /// Context of request - /// The user name for login (optional) - /// The password for login in clear text (optional) + /// The user name for login + /// The password for login in clear text /// string string LoginUser(NancyContext context, string username, string password); @@ -151,7 +163,7 @@ public interface UserService /// /// Context of request /// name that need to be deleted - /// Updated user object (optional) + /// Updated user object /// void UpdateUser(NancyContext context, string username, User body); } diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/packages.config b/samples/server/petstore/nancyfx/src/IO.Swagger/packages.config index 6d8651cdcf4..2575d1b4d77 100644 --- a/samples/server/petstore/nancyfx/src/IO.Swagger/packages.config +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/packages.config @@ -2,6 +2,6 @@ - + \ No newline at end of file From 9489f7d3eb6048796dbf867bbade2b525ed71d40 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 26 Jul 2016 14:40:29 +0800 Subject: [PATCH 153/470] clear import mapping for gnereators that do not use it --- .../io/swagger/codegen/DefaultGenerator.java | 1 + .../languages/AbstractCSharpCodegen.java | 3 + .../AbstractTypeScriptClientCodegen.java | 5 + .../languages/CsharpDotNet2ClientCodegen.java | 5 + .../codegen/languages/DartClientCodegen.java | 5 + .../languages/GroovyClientCodegen.java | 4 + .../codegen/languages/PerlClientCodegen.java | 5 + .../codegen/languages/PhpClientCodegen.java | 5 + .../languages/PythonClientCodegen.java | 4 + .../codegen/languages/RubyClientCodegen.java | 5 + .../languages/SlimFrameworkServerCodegen.java | 4 + .../codegen/languages/StaticDocCodegen.java | 5 + .../TypeScriptFetchClientCodegen.java | 5 + .../TypeScriptNodeClientCodegen.java | 5 + ...ith-fake-endpoints-models-for-testing.yaml | 5 + .../csharp/SwaggerClient/IO.Swagger.sln | 10 +- .../petstore/csharp/SwaggerClient/README.md | 3 +- .../csharp/SwaggerClient/docs/List.md | 9 + .../src/IO.Swagger.Test/Model/ListTests.cs | 90 +++++++ .../src/IO.Swagger/IO.Swagger.csproj | 2 +- .../src/IO.Swagger/Model/List.cs | 126 ++++++++++ .../petstore/php/SwaggerClient-php/README.md | 35 ++- .../php/SwaggerClient-php/docs/Api/FakeApi.md | 44 ++++ .../SwaggerClient-php/docs/Model/Client.md | 10 + .../SwaggerClient-php/docs/Model/ModelList.md | 10 + .../php/SwaggerClient-php/lib/Api/FakeApi.php | 82 ++++++ .../SwaggerClient-php/lib/Model/Client.php | 237 ++++++++++++++++++ .../SwaggerClient-php/lib/Model/ModelList.php | 237 ++++++++++++++++++ .../lib/ObjectSerializer.php | 2 +- .../test/Model/ClientTest.php | 106 ++++++++ .../test/Model/ModelListTest.php | 106 ++++++++ samples/client/petstore/python/README.md | 25 +- samples/client/petstore/python/docs/Client.md | 10 + .../client/petstore/python/docs/FakeApi.md | 46 ++++ samples/client/petstore/python/docs/List.md | 10 + .../petstore/python/petstore_api/__init__.py | 2 + .../python/petstore_api/apis/fake_api.py | 104 ++++++++ .../python/petstore_api/models/__init__.py | 2 + .../python/petstore_api/models/client.py | 125 +++++++++ .../python/petstore_api/models/list.py | 125 +++++++++ .../petstore/python/test/test_client.py | 53 ++++ .../client/petstore/python/test/test_list.py | 53 ++++ samples/client/petstore/ruby/README.md | 3 +- samples/client/petstore/ruby/docs/List.md | 8 + samples/client/petstore/ruby/lib/petstore.rb | 1 + .../petstore/ruby/lib/petstore/models/list.rb | 199 +++++++++++++++ .../petstore/ruby/spec/models/list_spec.rb | 53 ++++ 47 files changed, 1948 insertions(+), 46 deletions(-) create mode 100644 samples/client/petstore/csharp/SwaggerClient/docs/List.md create mode 100644 samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ListTests.cs create mode 100644 samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/List.cs create mode 100644 samples/client/petstore/php/SwaggerClient-php/docs/Model/Client.md create mode 100644 samples/client/petstore/php/SwaggerClient-php/docs/Model/ModelList.md create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Model/Client.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelList.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/test/Model/ClientTest.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/test/Model/ModelListTest.php create mode 100644 samples/client/petstore/python/docs/Client.md create mode 100644 samples/client/petstore/python/docs/List.md create mode 100644 samples/client/petstore/python/petstore_api/models/client.py create mode 100644 samples/client/petstore/python/petstore_api/models/list.py create mode 100644 samples/client/petstore/python/test/test_client.py create mode 100644 samples/client/petstore/python/test/test_list.py create mode 100644 samples/client/petstore/ruby/docs/List.md create mode 100644 samples/client/petstore/ruby/lib/petstore/models/list.rb create mode 100644 samples/client/petstore/ruby/spec/models/list_spec.rb diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index 0851a2e6f40..6594869cfd1 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -280,6 +280,7 @@ private Model getParent(Model model) { try { //don't generate models that have an import mapping if(config.importMapping().containsKey(name)) { + LOGGER.info("Model " + name + " not imported due to import mapping"); continue; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java index f2db3b5e095..ad28fe98783 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java @@ -41,6 +41,9 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co public AbstractCSharpCodegen() { super(); + // C# does not use import mapping + importMapping.clear(); + outputFolder = "generated-code" + File.separator + this.getName(); embeddedTemplateDir = templateDir = this.getName(); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java index 3a0d836fafb..87fb026b40a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java @@ -26,6 +26,11 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp public AbstractTypeScriptClientCodegen() { super(); + + // clear import mapping (from default generator) as TS does not use it + // at the moment + importMapping.clear(); + supportsInheritance = true; setReservedWordsLowerCase(Arrays.asList( // local variable names used in API methods (endpoints) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java index d13c6c851da..0750a667b3a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java @@ -24,6 +24,11 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege public CsharpDotNet2ClientCodegen() { super(); + + // clear import mapping (from default generator) as C# (2.0) does not use it + // at the moment + importMapping.clear(); + outputFolder = "generated-code" + File.separator + "CsharpDotNet2"; modelTemplateFiles.put("model.mustache", ".cs"); apiTemplateFiles.put("api.mustache", ".cs"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java index 4ad6e85d772..3cf6c439aea 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java @@ -28,6 +28,11 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { public DartClientCodegen() { super(); + + // clear import mapping (from default generator) as dart does not use it + // at the moment + importMapping.clear(); + outputFolder = "generated-code/dart"; modelTemplateFiles.put("model.mustache", ".dart"); apiTemplateFiles.put("api.mustache", ".dart"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GroovyClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GroovyClientCodegen.java index 84874b4060f..033dceeb669 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GroovyClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GroovyClientCodegen.java @@ -12,6 +12,10 @@ public class GroovyClientCodegen extends AbstractJavaCodegen { public GroovyClientCodegen() { super(); + // clear import mapping (from default generator) as groovy does not use it + // at the moment + importMapping.clear(); + sourceFolder = projectFolder + File.separator + "groovy"; outputFolder = "generated-code/groovy"; modelTemplateFiles.put("model.mustache", ".groovy"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java index 15ec94188e1..00fbf9e651f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java @@ -42,6 +42,11 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { public PerlClientCodegen() { super(); + + // clear import mapping (from default generator) as perl does not use it + // at the moment + importMapping.clear(); + modelPackage = File.separatorChar + "Object"; outputFolder = "generated-code" + File.separatorChar + "perl"; modelTemplateFiles.put("object.mustache", ".pm"); 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 feaf63d4e39..c907fec94f1 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 @@ -50,6 +50,11 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { public PhpClientCodegen() { super(); + // clear import mapping (from default generator) as php does not use it + // at the moment + importMapping.clear(); + + supportsInheritance = true; outputFolder = "generated-code" + File.separator + "php"; modelTemplateFiles.put("model.mustache", ".php"); 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 f42e662d0fa..aba01835481 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 @@ -33,6 +33,10 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig public PythonClientCodegen() { super(); + // clear import mapping (from default generator) as python does not use it + // at the moment + importMapping.clear(); + modelPackage = "models"; apiPackage = "api"; outputFolder = "generated-code" + File.separatorChar + "python"; 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 e58199e1b70..66f7b2f09b7 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 @@ -54,6 +54,11 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { public RubyClientCodegen() { super(); + + // clear import mapping (from default generator) as ruby does not use it + // at the moment + importMapping.clear(); + modelPackage = "models"; apiPackage = "api"; outputFolder = "generated-code" + File.separator + "ruby"; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SlimFrameworkServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SlimFrameworkServerCodegen.java index 1a21b6609d8..6eb5beb9e61 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SlimFrameworkServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SlimFrameworkServerCodegen.java @@ -30,6 +30,10 @@ public class SlimFrameworkServerCodegen extends DefaultCodegen implements Codege public SlimFrameworkServerCodegen() { super(); + // clear import mapping (from default generator) as slim does not use it + // at the moment + importMapping.clear(); + invokerPackage = camelize("SwaggerServer"); //String packagePath = "SwaggerServer"; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java index c64fcfb04ef..b2b1e6c9a63 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java @@ -18,6 +18,11 @@ public class StaticDocCodegen extends DefaultCodegen implements CodegenConfig { public StaticDocCodegen() { super(); + + // clear import mapping (from default generator) as this generator does not use it + // at the moment + importMapping.clear(); + outputFolder = "docs"; modelTemplateFiles.put("model.mustache", ".html"); apiTemplateFiles.put("operation.mustache", ".html"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java index cf25259e61c..1207af099c8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java @@ -15,6 +15,11 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege public TypeScriptFetchClientCodegen() { super(); + + // clear import mapping (from default generator) as TS does not use it + // at the moment + importMapping.clear(); + outputFolder = "generated-code/typescript-fetch"; embeddedTemplateDir = templateDir = "TypeScript-Fetch"; this.cliOptions.add(new CliOption(NPM_NAME, "The name under which you want to publish generated npm package")); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java index db9e2fcf2ad..67a6ed0b422 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java @@ -26,6 +26,11 @@ public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen public TypeScriptNodeClientCodegen() { super(); + + // clear import mapping (from default generator) as TS does not use it + // at the moment + importMapping.clear(); + outputFolder = "generated-code/typescript-node"; embeddedTemplateDir = templateDir = "typescript-node"; diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml index e6a3a83e477..0bd6faecdb2 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml @@ -1040,6 +1040,11 @@ definitions: type: object additionalProperties: $ref: '#/definitions/Animal' + List: + type: object + properties: + 123-list: + type: string Client: type: object properties: diff --git a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln index 95d7c51d31d..28a3d31c548 100644 --- a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln +++ b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln @@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 VisualStudioVersion = 12.0.0.0 MinimumVisualStudioVersion = 10.0.0.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{B7B26355-6F11-47C6-AB34-6237A673E486}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{C95ADC68-F3D8-41D1-BA8A-6C0754E6BB54}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger.Test", "src\IO.Swagger.Test\IO.Swagger.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" EndProject @@ -12,10 +12,10 @@ Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution -{B7B26355-6F11-47C6-AB34-6237A673E486}.Debug|Any CPU.ActiveCfg = Debug|Any CPU -{B7B26355-6F11-47C6-AB34-6237A673E486}.Debug|Any CPU.Build.0 = Debug|Any CPU -{B7B26355-6F11-47C6-AB34-6237A673E486}.Release|Any CPU.ActiveCfg = Release|Any CPU -{B7B26355-6F11-47C6-AB34-6237A673E486}.Release|Any CPU.Build.0 = Release|Any CPU +{C95ADC68-F3D8-41D1-BA8A-6C0754E6BB54}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{C95ADC68-F3D8-41D1-BA8A-6C0754E6BB54}.Debug|Any CPU.Build.0 = Debug|Any CPU +{C95ADC68-F3D8-41D1-BA8A-6C0754E6BB54}.Release|Any CPU.ActiveCfg = Release|Any CPU +{C95ADC68-F3D8-41D1-BA8A-6C0754E6BB54}.Release|Any CPU.Build.0 = Release|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/samples/client/petstore/csharp/SwaggerClient/README.md b/samples/client/petstore/csharp/SwaggerClient/README.md index 6fb2bcf28f3..d890bfa20f0 100644 --- a/samples/client/petstore/csharp/SwaggerClient/README.md +++ b/samples/client/petstore/csharp/SwaggerClient/README.md @@ -6,7 +6,7 @@ This C# SDK is automatically generated by the [Swagger Codegen](https://github.c - API version: 1.0.0 - SDK version: 1.0.0 -- Build date: 2016-07-26T00:22:48.731+08:00 +- Build date: 2016-07-26T14:25:16.509+08:00 - Build package: class io.swagger.codegen.languages.CSharpClientCodegen ## Frameworks supported @@ -120,6 +120,7 @@ Class | Method | HTTP request | Description - [Model.EnumTest](docs/EnumTest.md) - [Model.FormatTest](docs/FormatTest.md) - [Model.HasOnlyReadOnly](docs/HasOnlyReadOnly.md) + - [Model.List](docs/List.md) - [Model.MapTest](docs/MapTest.md) - [Model.MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - [Model.Model200Response](docs/Model200Response.md) diff --git a/samples/client/petstore/csharp/SwaggerClient/docs/List.md b/samples/client/petstore/csharp/SwaggerClient/docs/List.md new file mode 100644 index 00000000000..d7555b7e7ac --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/docs/List.md @@ -0,0 +1,9 @@ +# IO.Swagger.Model.List +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_123List** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ListTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ListTests.cs new file mode 100644 index 00000000000..52037b2af00 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ListTests.cs @@ -0,0 +1,90 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing List + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class ListTests + { + // TODO uncomment below to declare an instance variable for List + //private List instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of List + //instance = new List(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of List + /// + [Test] + public void ListInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" List + //Assert.IsInstanceOfType (instance, "variable 'instance' is a List"); + } + + /// + /// Test the property '_123List' + /// + [Test] + public void _123ListTest() + { + // TODO unit test for the property '_123List' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj index e84766657af..8956caaa138 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj @@ -24,7 +24,7 @@ limitations under the License. Debug AnyCPU - {B7B26355-6F11-47C6-AB34-6237A673E486} + {C95ADC68-F3D8-41D1-BA8A-6C0754E6BB54} Library Properties IO.Swagger diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/List.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/List.cs new file mode 100644 index 00000000000..bab8dae979c --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/List.cs @@ -0,0 +1,126 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace IO.Swagger.Model +{ + /// + /// List + /// + [DataContract] + public partial class List : IEquatable + { + /// + /// Initializes a new instance of the class. + /// + /// _123List. + public List(string _123List = null) + { + this._123List = _123List; + } + + /// + /// Gets or Sets _123List + /// + [DataMember(Name="123-list", EmitDefaultValue=false)] + public string _123List { get; set; } + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class List {\n"); + sb.Append(" _123List: ").Append(_123List).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as List); + } + + /// + /// Returns true if List instances are equal + /// + /// Instance of List to be compared + /// Boolean + public bool Equals(List other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this._123List == other._123List || + this._123List != null && + this._123List.Equals(other._123List) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this._123List != null) + hash = hash * 59 + this._123List.GetHashCode(); + return hash; + } + } + } + +} diff --git a/samples/client/petstore/php/SwaggerClient-php/README.md b/samples/client/petstore/php/SwaggerClient-php/README.md index 23b5fc1b4f0..52723cf2abb 100644 --- a/samples/client/petstore/php/SwaggerClient-php/README.md +++ b/samples/client/petstore/php/SwaggerClient-php/README.md @@ -4,7 +4,7 @@ This spec is mainly for testing Petstore server and contains fake endpoints, mod This PHP package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: - API version: 1.0.0 -- Build date: 2016-07-06T12:05:01.729-07:00 +- Build date: 2016-07-26T14:38:19.243+08:00 - Build package: class io.swagger.codegen.languages.PhpClientCodegen ## Requirements @@ -58,23 +58,13 @@ Please follow the [installation procedure](#installation--usage) and then run th require_once(__DIR__ . '/vendor/autoload.php'); $api_instance = new Swagger\Client\Api\FakeApi(); -$number = 3.4; // float | None -$double = 1.2; // double | None -$string = "string_example"; // string | None -$byte = "B"; // string | None -$integer = 56; // int | None -$int32 = 56; // int | None -$int64 = 789; // int | None -$float = 3.4; // float | None -$binary = "B"; // string | None -$date = new \DateTime(); // \DateTime | None -$date_time = new \DateTime(); // \DateTime | None -$password = "password_example"; // string | None +$body = new \Swagger\Client\Model\Client(); // \Swagger\Client\Model\Client | client model try { - $api_instance->testEndpointParameters($number, $double, $string, $byte, $integer, $int32, $int64, $float, $binary, $date, $date_time, $password); + $result = $api_instance->testClientModel($body); + print_r($result); } catch (Exception $e) { - echo 'Exception when calling FakeApi->testEndpointParameters: ', $e->getMessage(), PHP_EOL; + echo 'Exception when calling FakeApi->testClientModel: ', $e->getMessage(), PHP_EOL; } ?> @@ -86,6 +76,7 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- +*FakeApi* | [**testClientModel**](docs/Api/FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model *FakeApi* | [**testEndpointParameters**](docs/Api/FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 *FakeApi* | [**testEnumQueryParameters**](docs/Api/FakeApi.md#testenumqueryparameters) | **GET** /fake | To test enum query parameters *PetApi* | [**addPet**](docs/Api/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store @@ -121,6 +112,7 @@ Class | Method | HTTP request | Description - [ArrayTest](docs/Model/ArrayTest.md) - [Cat](docs/Model/Cat.md) - [Category](docs/Model/Category.md) + - [Client](docs/Model/Client.md) - [Dog](docs/Model/Dog.md) - [EnumClass](docs/Model/EnumClass.md) - [EnumTest](docs/Model/EnumTest.md) @@ -129,6 +121,7 @@ Class | Method | HTTP request | Description - [MapTest](docs/Model/MapTest.md) - [MixedPropertiesAndAdditionalPropertiesClass](docs/Model/MixedPropertiesAndAdditionalPropertiesClass.md) - [Model200Response](docs/Model/Model200Response.md) + - [ModelList](docs/Model/ModelList.md) - [ModelReturn](docs/Model/ModelReturn.md) - [Name](docs/Model/Name.md) - [NumberOnly](docs/Model/NumberOnly.md) @@ -143,6 +136,12 @@ Class | Method | HTTP request | Description ## Documentation For Authorization +## api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + ## petstore_auth - **Type**: OAuth @@ -152,12 +151,6 @@ Class | Method | HTTP request | Description - **write:pets**: modify pets in your account - **read:pets**: read your pets -## api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - ## Author diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Api/FakeApi.md b/samples/client/petstore/php/SwaggerClient-php/docs/Api/FakeApi.md index 3ca55218e36..fa913078437 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/Api/FakeApi.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Api/FakeApi.md @@ -4,10 +4,54 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- +[**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters +# **testClientModel** +> \Swagger\Client\Model\Client testClientModel($body) + +To test \"client\" model + +### Example +```php +testClientModel($body); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling FakeApi->testClientModel: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**\Swagger\Client\Model\Client**](../Model/\Swagger\Client\Model\Client.md)| client model | + +### Return type + +[**\Swagger\Client\Model\Client**](../Model/Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + # **testEndpointParameters** > testEndpointParameters($number, $double, $string, $byte, $integer, $int32, $int64, $float, $binary, $date, $date_time, $password) diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Model/Client.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/Client.md new file mode 100644 index 00000000000..f6047a62471 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Model/Client.md @@ -0,0 +1,10 @@ +# Client + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**client** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Model/ModelList.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/ModelList.md new file mode 100644 index 00000000000..e18ba4e123d --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Model/ModelList.md @@ -0,0 +1,10 @@ +# ModelList + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_123_list** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index f644572884a..0029ff14950 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -102,6 +102,88 @@ public function setApiClient(\Swagger\Client\ApiClient $apiClient) return $this; } + /** + * Operation testClientModel + * + * To test \"client\" model + * + * @param \Swagger\Client\Model\Client $body client model (required) + * @return \Swagger\Client\Model\Client + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function testClientModel($body) + { + list($response) = $this->testClientModelWithHttpInfo($body); + return $response; + } + + /** + * Operation testClientModelWithHttpInfo + * + * To test \"client\" model + * + * @param \Swagger\Client\Model\Client $body client model (required) + * @return Array of \Swagger\Client\Model\Client, HTTP status code, HTTP response headers (array of strings) + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function testClientModelWithHttpInfo($body) + { + // verify the required parameter 'body' is set + if ($body === null) { + throw new \InvalidArgumentException('Missing the required parameter $body when calling testClientModel'); + } + // parse inputs + $resourcePath = "/fake"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json')); + + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + + // body params + $_tempBody = null; + if (isset($body)) { + $_tempBody = $body; + } + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { + $httpBody = $formParams; // for HTTP post (form) + } + // make the API Call + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( + $resourcePath, + 'PATCH', + $queryParams, + $httpBody, + $headerParams, + '\Swagger\Client\Model\Client', + '/fake' + ); + + return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Client', $httpHeader), $statusCode, $httpHeader); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Client', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; + } + + throw $e; + } + } + /** * Operation testEndpointParameters * diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Client.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Client.php new file mode 100644 index 00000000000..ef606fe751d --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Client.php @@ -0,0 +1,237 @@ + 'string' + ); + + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of attributes where the key is the local name, and the value is the original name + * @var string[] + */ + protected static $attributeMap = array( + 'client' => 'client' + ); + + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * @var string[] + */ + protected static $setters = array( + 'client' => 'setClient' + ); + + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * @var string[] + */ + protected static $getters = array( + 'client' => 'getClient' + ); + + public static function getters() + { + return self::$getters; + } + + + + + + /** + * Associative array for storing property values + * @var mixed[] + */ + protected $container = array(); + + /** + * Constructor + * @param mixed[] $data Associated array of property value initalizing the model + */ + public function __construct(array $data = null) + { + $this->container['client'] = isset($data['client']) ? $data['client'] : null; + } + + /** + * show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalid_properties = array(); + return $invalid_properties; + } + + /** + * validate all the properties in the model + * return true if all passed + * + * @return bool True if all properteis are valid + */ + public function valid() + { + return true; + } + + + /** + * Gets client + * @return string + */ + public function getClient() + { + return $this->container['client']; + } + + /** + * Sets client + * @param string $client + * @return $this + */ + public function setClient($client) + { + $this->container['client'] = $client; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * @param integer $offset Offset + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * @param integer $offset Offset + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * @param integer $offset Offset + * @param mixed $value Value to be set + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * @param integer $offset Offset + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); + } + + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelList.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelList.php new file mode 100644 index 00000000000..94413c5ec75 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelList.php @@ -0,0 +1,237 @@ + 'string' + ); + + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of attributes where the key is the local name, and the value is the original name + * @var string[] + */ + protected static $attributeMap = array( + '_123_list' => '123-list' + ); + + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * @var string[] + */ + protected static $setters = array( + '_123_list' => 'set123List' + ); + + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * @var string[] + */ + protected static $getters = array( + '_123_list' => 'get123List' + ); + + public static function getters() + { + return self::$getters; + } + + + + + + /** + * Associative array for storing property values + * @var mixed[] + */ + protected $container = array(); + + /** + * Constructor + * @param mixed[] $data Associated array of property value initalizing the model + */ + public function __construct(array $data = null) + { + $this->container['_123_list'] = isset($data['_123_list']) ? $data['_123_list'] : null; + } + + /** + * show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalid_properties = array(); + return $invalid_properties; + } + + /** + * validate all the properties in the model + * return true if all passed + * + * @return bool True if all properteis are valid + */ + public function valid() + { + return true; + } + + + /** + * Gets _123_list + * @return string + */ + public function get123List() + { + return $this->container['_123_list']; + } + + /** + * Sets _123_list + * @param string $_123_list + * @return $this + */ + public function set123List($_123_list) + { + $this->container['_123_list'] = $_123_list; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * @param integer $offset Offset + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * @param integer $offset Offset + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * @param integer $offset Offset + * @param mixed $value Value to be set + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * @param integer $offset Offset + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); + } + + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php index ce77aa6c3b3..fe68a3877d6 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -264,7 +264,7 @@ public static function deserialize($data, $class, $httpHeaders = null, $discrimi } else { return null; } - } elseif (in_array($class, array('void', 'bool', 'string', 'double', 'byte', 'mixed', 'integer', 'float', 'int', 'DateTime', 'number', 'boolean', 'object'))) { + } elseif (in_array($class, array('integer', 'int', 'void', 'number', 'object', 'double', 'float', 'byte', 'DateTime', 'string', 'mixed', 'boolean', 'bool'))) { settype($data, $class); return $data; } elseif ($class === '\SplFileObject') { diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/ClientTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/ClientTest.php new file mode 100644 index 00000000000..3871e02c455 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/ClientTest.php @@ -0,0 +1,106 @@ +test_endpoint_parameters: %s\n" % e + print "Exception when calling FakeApi->test_client_model: %s\n" % e ``` @@ -79,6 +69,7 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- +*FakeApi* | [**test_client_model**](docs/FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model *FakeApi* | [**test_endpoint_parameters**](docs/FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 *FakeApi* | [**test_enum_query_parameters**](docs/FakeApi.md#test_enum_query_parameters) | **GET** /fake | To test enum query parameters *PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store @@ -114,11 +105,13 @@ Class | Method | HTTP request | Description - [ArrayTest](docs/ArrayTest.md) - [Cat](docs/Cat.md) - [Category](docs/Category.md) + - [Client](docs/Client.md) - [Dog](docs/Dog.md) - [EnumClass](docs/EnumClass.md) - [EnumTest](docs/EnumTest.md) - [FormatTest](docs/FormatTest.md) - [HasOnlyReadOnly](docs/HasOnlyReadOnly.md) + - [List](docs/List.md) - [MapTest](docs/MapTest.md) - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - [Model200Response](docs/Model200Response.md) diff --git a/samples/client/petstore/python/docs/Client.md b/samples/client/petstore/python/docs/Client.md new file mode 100644 index 00000000000..88e99384f92 --- /dev/null +++ b/samples/client/petstore/python/docs/Client.md @@ -0,0 +1,10 @@ +# Client + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**client** | **str** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python/docs/FakeApi.md b/samples/client/petstore/python/docs/FakeApi.md index 7c818407a76..a3ab6376e6f 100644 --- a/samples/client/petstore/python/docs/FakeApi.md +++ b/samples/client/petstore/python/docs/FakeApi.md @@ -4,10 +4,56 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- +[**test_client_model**](FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model [**test_endpoint_parameters**](FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**test_enum_query_parameters**](FakeApi.md#test_enum_query_parameters) | **GET** /fake | To test enum query parameters +# **test_client_model** +> Client test_client_model(body) + +To test \"client\" model + +### Example +```python +import time +import petstore_api +from petstore_api.rest import ApiException +from pprint import pprint + +# create an instance of the API class +api_instance = petstore_api.FakeApi() +body = petstore_api.Client() # Client | client model + +try: + # To test \"client\" model + api_response = api_instance.test_client_model(body) + pprint(api_response) +except ApiException as e: + print "Exception when calling FakeApi->test_client_model: %s\n" % e +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Client**](Client.md)| client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **test_endpoint_parameters** > test_endpoint_parameters(number, double, string, byte, integer=integer, int32=int32, int64=int64, float=float, binary=binary, date=date, date_time=date_time, password=password) diff --git a/samples/client/petstore/python/docs/List.md b/samples/client/petstore/python/docs/List.md new file mode 100644 index 00000000000..11f4f3a05f3 --- /dev/null +++ b/samples/client/petstore/python/docs/List.md @@ -0,0 +1,10 @@ +# List + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_123_list** | **str** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python/petstore_api/__init__.py b/samples/client/petstore/python/petstore_api/__init__.py index 650b1db0399..18d1b8f5237 100644 --- a/samples/client/petstore/python/petstore_api/__init__.py +++ b/samples/client/petstore/python/petstore_api/__init__.py @@ -34,11 +34,13 @@ from .models.array_test import ArrayTest from .models.cat import Cat from .models.category import Category +from .models.client import Client from .models.dog import Dog from .models.enum_class import EnumClass from .models.enum_test import EnumTest from .models.format_test import FormatTest from .models.has_only_read_only import HasOnlyReadOnly +from .models.list import List from .models.map_test import MapTest from .models.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass from .models.model_200_response import Model200Response diff --git a/samples/client/petstore/python/petstore_api/apis/fake_api.py b/samples/client/petstore/python/petstore_api/apis/fake_api.py index 5e8fc3d1195..c0cc973fc06 100644 --- a/samples/client/petstore/python/petstore_api/apis/fake_api.py +++ b/samples/client/petstore/python/petstore_api/apis/fake_api.py @@ -51,6 +51,110 @@ def __init__(self, api_client=None): config.api_client = ApiClient() self.api_client = config.api_client + def test_client_model(self, body, **kwargs): + """ + To test \"client\" model + + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please define a `callback` function + to be invoked when receiving the response. + >>> def callback_function(response): + >>> pprint(response) + >>> + >>> thread = api.test_client_model(body, callback=callback_function) + + :param callback function: The callback function + for asynchronous request. (optional) + :param Client body: client model (required) + :return: Client + If the method is called asynchronously, + returns the request thread. + """ + kwargs['_return_http_data_only'] = True + if kwargs.get('callback'): + return self.test_client_model_with_http_info(body, **kwargs) + else: + (data) = self.test_client_model_with_http_info(body, **kwargs) + return data + + def test_client_model_with_http_info(self, body, **kwargs): + """ + To test \"client\" model + + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please define a `callback` function + to be invoked when receiving the response. + >>> def callback_function(response): + >>> pprint(response) + >>> + >>> thread = api.test_client_model_with_http_info(body, callback=callback_function) + + :param callback function: The callback function + for asynchronous request. (optional) + :param Client body: client model (required) + :return: Client + If the method is called asynchronously, + returns the request thread. + """ + + all_params = ['body'] + all_params.append('callback') + all_params.append('_return_http_data_only') + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method test_client_model" % key + ) + params[key] = val + del params['kwargs'] + # verify the required parameter 'body' is set + if ('body' not in params) or (params['body'] is None): + raise ValueError("Missing the required parameter `body` when calling `test_client_model`") + + resource_path = '/fake'.replace('{format}', 'json') + path_params = {} + + query_params = {} + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if 'body' in params: + body_params = params['body'] + + # HTTP header `Accept` + header_params['Accept'] = self.api_client.\ + select_header_accept(['application/json']) + if not header_params['Accept']: + del header_params['Accept'] + + # HTTP header `Content-Type` + header_params['Content-Type'] = self.api_client.\ + select_header_content_type(['application/json']) + + # Authentication setting + auth_settings = [] + + return self.api_client.call_api(resource_path, 'PATCH', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='Client', + auth_settings=auth_settings, + callback=params.get('callback'), + _return_http_data_only=params.get('_return_http_data_only')) + def test_endpoint_parameters(self, number, double, string, byte, **kwargs): """ Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 diff --git a/samples/client/petstore/python/petstore_api/models/__init__.py b/samples/client/petstore/python/petstore_api/models/__init__.py index 56620212e46..d2289156d99 100644 --- a/samples/client/petstore/python/petstore_api/models/__init__.py +++ b/samples/client/petstore/python/petstore_api/models/__init__.py @@ -34,11 +34,13 @@ from .array_test import ArrayTest from .cat import Cat from .category import Category +from .client import Client from .dog import Dog from .enum_class import EnumClass from .enum_test import EnumTest from .format_test import FormatTest from .has_only_read_only import HasOnlyReadOnly +from .list import List from .map_test import MapTest from .mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass from .model_200_response import Model200Response diff --git a/samples/client/petstore/python/petstore_api/models/client.py b/samples/client/petstore/python/petstore_api/models/client.py new file mode 100644 index 00000000000..1621eb5ea42 --- /dev/null +++ b/samples/client/petstore/python/petstore_api/models/client.py @@ -0,0 +1,125 @@ +# coding: utf-8 + +""" + Swagger Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +""" + +from pprint import pformat +from six import iteritems +import re + + +class Client(object): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self, client=None): + """ + Client - a model defined in Swagger + + :param dict swaggerTypes: The key is attribute name + and the value is attribute type. + :param dict attributeMap: The key is attribute name + and the value is json key in definition. + """ + self.swagger_types = { + 'client': 'str' + } + + self.attribute_map = { + 'client': 'client' + } + + self._client = client + + @property + def client(self): + """ + Gets the client of this Client. + + + :return: The client of this Client. + :rtype: str + """ + return self._client + + @client.setter + def client(self, client): + """ + Sets the client of this Client. + + + :param client: The client of this Client. + :type: str + """ + + self._client = client + + def to_dict(self): + """ + Returns the model properties as a dict + """ + result = {} + + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value + )) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict(map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") else item, + value.items() + )) + else: + result[attr] = value + + return result + + def to_str(self): + """ + Returns the string representation of the model + """ + return pformat(self.to_dict()) + + def __repr__(self): + """ + For `print` and `pprint` + """ + return self.to_str() + + def __eq__(self, other): + """ + Returns true if both objects are equal + """ + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """ + Returns true if both objects are not equal + """ + return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/list.py b/samples/client/petstore/python/petstore_api/models/list.py new file mode 100644 index 00000000000..927aca7091f --- /dev/null +++ b/samples/client/petstore/python/petstore_api/models/list.py @@ -0,0 +1,125 @@ +# coding: utf-8 + +""" + Swagger Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +""" + +from pprint import pformat +from six import iteritems +import re + + +class List(object): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self, _123_list=None): + """ + List - a model defined in Swagger + + :param dict swaggerTypes: The key is attribute name + and the value is attribute type. + :param dict attributeMap: The key is attribute name + and the value is json key in definition. + """ + self.swagger_types = { + '_123_list': 'str' + } + + self.attribute_map = { + '_123_list': '123-list' + } + + self.__123_list = _123_list + + @property + def _123_list(self): + """ + Gets the _123_list of this List. + + + :return: The _123_list of this List. + :rtype: str + """ + return self.__123_list + + @_123_list.setter + def _123_list(self, _123_list): + """ + Sets the _123_list of this List. + + + :param _123_list: The _123_list of this List. + :type: str + """ + + self.__123_list = _123_list + + def to_dict(self): + """ + Returns the model properties as a dict + """ + result = {} + + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value + )) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict(map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") else item, + value.items() + )) + else: + result[attr] = value + + return result + + def to_str(self): + """ + Returns the string representation of the model + """ + return pformat(self.to_dict()) + + def __repr__(self): + """ + For `print` and `pprint` + """ + return self.to_str() + + def __eq__(self, other): + """ + Returns true if both objects are equal + """ + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """ + Returns true if both objects are not equal + """ + return not self == other diff --git a/samples/client/petstore/python/test/test_client.py b/samples/client/petstore/python/test/test_client.py new file mode 100644 index 00000000000..fe52aafed9b --- /dev/null +++ b/samples/client/petstore/python/test/test_client.py @@ -0,0 +1,53 @@ +# coding: utf-8 + +""" + Swagger Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +""" + +from __future__ import absolute_import + +import os +import sys +import unittest + +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.client import Client + + +class TestClient(unittest.TestCase): + """ Client unit test stubs """ + + def setUp(self): + pass + + def tearDown(self): + pass + + def testClient(self): + """ + Test Client + """ + model = petstore_api.models.client.Client() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python/test/test_list.py b/samples/client/petstore/python/test/test_list.py new file mode 100644 index 00000000000..5558d752cd0 --- /dev/null +++ b/samples/client/petstore/python/test/test_list.py @@ -0,0 +1,53 @@ +# coding: utf-8 + +""" + Swagger Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +""" + +from __future__ import absolute_import + +import os +import sys +import unittest + +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.list import List + + +class TestList(unittest.TestCase): + """ List unit test stubs """ + + def setUp(self): + pass + + def tearDown(self): + pass + + def testList(self): + """ + Test List + """ + model = petstore_api.models.list.List() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index 5db4a41148b..2c850599fd5 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -8,7 +8,7 @@ This SDK is automatically generated by the [Swagger Codegen](https://github.com/ - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-07-19T11:36:39.517-07:00 +- Build date: 2016-07-26T14:38:12.507+08:00 - Build package: class io.swagger.codegen.languages.RubyClientCodegen ## Installation @@ -118,6 +118,7 @@ Class | Method | HTTP request | Description - [Petstore::EnumTest](docs/EnumTest.md) - [Petstore::FormatTest](docs/FormatTest.md) - [Petstore::HasOnlyReadOnly](docs/HasOnlyReadOnly.md) + - [Petstore::List](docs/List.md) - [Petstore::MapTest](docs/MapTest.md) - [Petstore::MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - [Petstore::Model200Response](docs/Model200Response.md) diff --git a/samples/client/petstore/ruby/docs/List.md b/samples/client/petstore/ruby/docs/List.md new file mode 100644 index 00000000000..211d299f671 --- /dev/null +++ b/samples/client/petstore/ruby/docs/List.md @@ -0,0 +1,8 @@ +# Petstore::List + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_123_list** | **String** | | [optional] + + diff --git a/samples/client/petstore/ruby/lib/petstore.rb b/samples/client/petstore/ruby/lib/petstore.rb index 82832d892e4..49a03b71e2d 100644 --- a/samples/client/petstore/ruby/lib/petstore.rb +++ b/samples/client/petstore/ruby/lib/petstore.rb @@ -43,6 +43,7 @@ require 'petstore/models/enum_test' require 'petstore/models/format_test' require 'petstore/models/has_only_read_only' +require 'petstore/models/list' require 'petstore/models/map_test' require 'petstore/models/mixed_properties_and_additional_properties_class' require 'petstore/models/model_200_response' diff --git a/samples/client/petstore/ruby/lib/petstore/models/list.rb b/samples/client/petstore/ruby/lib/petstore/models/list.rb new file mode 100644 index 00000000000..f2f34430ce7 --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/models/list.rb @@ -0,0 +1,199 @@ +=begin +#Swagger Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end + +require 'date' + +module Petstore + + class List + attr_accessor :_123_list + + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'_123_list' => :'123-list' + } + end + + # Attribute type mapping. + def self.swagger_types + { + :'_123_list' => :'String' + } + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + return unless attributes.is_a?(Hash) + + # convert string to symbol for hash key + attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} + + if attributes.has_key?(:'123-list') + self._123_list = attributes[:'123-list'] + end + + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properies with the reasons + def list_invalid_properties + invalid_properties = Array.new + return invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + return true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + _123_list == o._123_list + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Fixnum] Hash code + def hash + [_123_list].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.swagger_types.each_pair do |key, type| + if type =~ /^Array<(.*)>/i + # check to ensure the input is an array given that the the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end # or else data not found in attributes(hash), not an issue as the data can be optional + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :DateTime + DateTime.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :BOOLEAN + if value.to_s =~ /^(true|t|yes|y|1)$/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + temp_model = Petstore.const_get(type).new + temp_model.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + next if value.nil? + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map{ |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby/spec/models/list_spec.rb b/samples/client/petstore/ruby/spec/models/list_spec.rb new file mode 100644 index 00000000000..0ae7af9569b --- /dev/null +++ b/samples/client/petstore/ruby/spec/models/list_spec.rb @@ -0,0 +1,53 @@ +=begin +#Swagger Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::List +# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) +# Please update as you see appropriate +describe 'List' do + before do + # run before each test + @instance = Petstore::List.new + end + + after do + # run after each test + end + + describe 'test an instance of List' do + it 'should create an instact of List' do + expect(@instance).to be_instance_of(Petstore::List) + end + end + describe 'test attribute "_123_list"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end + From b3403015fd3893388ac25df916dd9f38009ed53c Mon Sep 17 00:00:00 2001 From: Yi Date: Tue, 26 Jul 2016 02:49:33 -0400 Subject: [PATCH 154/470] fix scalatra path with basepath (#1425) (#3448) --- .../src/main/resources/scalatra/Bootstrap.mustache | 2 +- .../src/main/resources/scalatra/api.mustache | 6 +++--- .../scalatra/src/main/scala/ScalatraBootstrap.scala | 8 ++++---- .../src/main/scala/com/wordnik/client/api/PetApi.scala | 8 ++++---- .../src/main/scala/com/wordnik/client/api/StoreApi.scala | 6 +++--- .../src/main/scala/com/wordnik/client/api/UserApi.scala | 4 ++-- 6 files changed, 17 insertions(+), 17 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/scalatra/Bootstrap.mustache b/modules/swagger-codegen/src/main/resources/scalatra/Bootstrap.mustache index afb0dd162d1..483ee4e5444 100644 --- a/modules/swagger-codegen/src/main/resources/scalatra/Bootstrap.mustache +++ b/modules/swagger-codegen/src/main/resources/scalatra/Bootstrap.mustache @@ -12,7 +12,7 @@ class ScalatraBootstrap extends LifeCycle { override def init(context: ServletContext) { implicit val system = ActorSystem("appActorSystem") try { - {{#apiInfo}}{{#apis}}context mount (new {{classname}}, "/{{baseName}}/*") + {{#apiInfo}}{{#apis}}context mount (new {{classname}}, "{{basePathWithoutHost}}/{{baseName}}/*") {{/apis}}{{/apiInfo}} context mount (new ResourcesApp, "/api-docs/*") } catch { diff --git a/modules/swagger-codegen/src/main/resources/scalatra/api.mustache b/modules/swagger-codegen/src/main/resources/scalatra/api.mustache index d7b36246a82..a5e281f6280 100644 --- a/modules/swagger-codegen/src/main/resources/scalatra/api.mustache +++ b/modules/swagger-codegen/src/main/resources/scalatra/api.mustache @@ -16,14 +16,14 @@ import org.scalatra.servlet.{FileUploadSupport, MultipartConfig, SizeConstraintE import scala.collection.JavaConverters._ -class {{classname}} (implicit val swagger: Swagger) extends ScalatraServlet +class {{classname}} (implicit val swagger: Swagger) extends ScalatraServlet with FileUploadSupport with JacksonJsonSupport with SwaggerSupport { protected implicit val jsonFormats: Formats = DefaultFormats protected val applicationDescription: String = "{{classname}}" - override protected val applicationName: Option[String] = Some("{{baseName}}") + override protected val applicationName: Option[String] = Some("{{basePathWithoutHost}}/{{baseName}}") before() { contentType = formats("json") @@ -51,4 +51,4 @@ class {{classname}} (implicit val swagger: Swagger) extends ScalatraServlet {{/operation}} {{/operations}} -} \ No newline at end of file +} diff --git a/samples/server/petstore/scalatra/src/main/scala/ScalatraBootstrap.scala b/samples/server/petstore/scalatra/src/main/scala/ScalatraBootstrap.scala index 445cb7783ab..9b49fe13b15 100644 --- a/samples/server/petstore/scalatra/src/main/scala/ScalatraBootstrap.scala +++ b/samples/server/petstore/scalatra/src/main/scala/ScalatraBootstrap.scala @@ -34,10 +34,10 @@ class ScalatraBootstrap extends LifeCycle { override def init(context: ServletContext) { implicit val system = ActorSystem("appActorSystem") try { - context mount (new PetApi, "/Pet/*") - context mount (new StoreApi, "/Store/*") - context mount (new UserApi, "/User/*") - + context mount (new PetApi, "/v2/Pet/*") + context mount (new StoreApi, "/v2/Store/*") + context mount (new UserApi, "/v2/User/*") + context mount (new ResourcesApp, "/api-docs/*") } catch { case e: Throwable => e.printStackTrace() diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala index 9a7d43dd686..73ac60b6cd3 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala @@ -46,7 +46,7 @@ class PetApi(implicit val swagger: Swagger) extends ScalatraServlet protected implicit val jsonFormats: Formats = DefaultFormats protected val applicationDescription: String = "PetApi" - override protected val applicationName: Option[String] = Some("Pet") + override protected val applicationName: Option[String] = Some("/v2/Pet") before() { contentType = formats("json") @@ -89,7 +89,7 @@ class PetApi(implicit val swagger: Swagger) extends ScalatraServlet get("/pet/findByStatus", operation(findPetsByStatusOperation)) { val statusString = params.getAs[String]("status") - val status = if ("csv".equals("default")) { + val status = if ("multi".equals("default")) { statusString match { case Some(str) => str.split(",") case None => List() @@ -108,7 +108,7 @@ class PetApi(implicit val swagger: Swagger) extends ScalatraServlet get("/pet/findByTags", operation(findPetsByTagsOperation)) { val tagsString = params.getAs[String]("tags") - val tags = if ("csv".equals("default")) { + val tags = if ("multi".equals("default")) { tagsString match { case Some(str) => str.split(",") case None => List() @@ -181,4 +181,4 @@ class PetApi(implicit val swagger: Swagger) extends ScalatraServlet println("file: " + file) } -} \ No newline at end of file +} diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/StoreApi.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/StoreApi.scala index 5427c63f88e..c2ac0af6e8b 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/StoreApi.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/StoreApi.scala @@ -44,7 +44,7 @@ class StoreApi(implicit val swagger: Swagger) extends ScalatraServlet protected implicit val jsonFormats: Formats = DefaultFormats protected val applicationDescription: String = "StoreApi" - override protected val applicationName: Option[String] = Some("Store") + override protected val applicationName: Option[String] = Some("/v2/Store") before() { contentType = formats("json") @@ -53,7 +53,7 @@ class StoreApi(implicit val swagger: Swagger) extends ScalatraServlet val deleteOrderOperation = (apiOperation[Unit]("deleteOrder") summary "Delete purchase order by ID" - parameters (pathParam[String]("orderId").description("")) + parameters (pathParam[Long]("orderId").description("")) ) delete("/store/order/{orderId}", operation(deleteOrderOperation)) { @@ -95,4 +95,4 @@ class StoreApi(implicit val swagger: Swagger) extends ScalatraServlet println("body: " + body) } -} \ No newline at end of file +} diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/UserApi.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/UserApi.scala index cff4a915b68..c0dadc2375f 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/UserApi.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/UserApi.scala @@ -44,7 +44,7 @@ class UserApi(implicit val swagger: Swagger) extends ScalatraServlet protected implicit val jsonFormats: Formats = DefaultFormats protected val applicationDescription: String = "UserApi" - override protected val applicationName: Option[String] = Some("User") + override protected val applicationName: Option[String] = Some("/v2/User") before() { contentType = formats("json") @@ -151,4 +151,4 @@ class UserApi(implicit val swagger: Swagger) extends ScalatraServlet println("body: " + body) } -} \ No newline at end of file +} From 81f5108bac931eeb4cb4c7690ce6da9b0410fd90 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 26 Jul 2016 16:04:54 +0800 Subject: [PATCH 155/470] [Scala][Scalatra] Include scalatra pestore in the CI tests (#3456) * add CI coverage for scalatra server * move scalatra test to the end --- pom.xml | 13 + samples/server/petstore/scalatra/pom.xml | 32 ++ samples/server/petstore/scalatra/sbt | 525 ------------------ .../src/main/scala/ScalatraBootstrap.scala | 2 +- 4 files changed, 46 insertions(+), 526 deletions(-) create mode 100644 samples/server/petstore/scalatra/pom.xml delete mode 100755 samples/server/petstore/scalatra/sbt diff --git a/pom.xml b/pom.xml index df2a36a91db..f58b4ca35f6 100644 --- a/pom.xml +++ b/pom.xml @@ -580,6 +580,18 @@ samples/client/petstore/spring-cloud + + scalatra-server + + + env + java + + + + samples/server/petstore/scalatra + + samples @@ -617,6 +629,7 @@ samples/server/petstore/jaxrs/jersey2 samples/server/petstore/jaxrs-resteasy/default samples/server/petstore/jaxrs-resteasy/joda + samples/server/petstore/scalatra diff --git a/samples/server/petstore/scalatra/pom.xml b/samples/server/petstore/scalatra/pom.xml new file mode 100644 index 00000000000..bc1a6f92cdf --- /dev/null +++ b/samples/server/petstore/scalatra/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + com.wordnik + scalatra-server + pom + 1.0-SNAPSHOT + Scalatra server + + + + org.codehaus.mojo + exec-maven-plugin + 1.5.0 + + + sbt-test + integration-test + + exec + + + /usr/local/bin/sbt + + test + + + + + + + + diff --git a/samples/server/petstore/scalatra/sbt b/samples/server/petstore/scalatra/sbt deleted file mode 100755 index 08e58821219..00000000000 --- a/samples/server/petstore/scalatra/sbt +++ /dev/null @@ -1,525 +0,0 @@ -#!/usr/bin/env bash -# -# A more capable sbt runner, coincidentally also called sbt. -# Author: Paul Phillips - -# todo - make this dynamic -declare -r sbt_release_version="0.13.6" -declare -r sbt_unreleased_version="0.13.6" -declare -r buildProps="project/build.properties" - -declare sbt_jar sbt_dir sbt_create sbt_version -declare scala_version sbt_explicit_version -declare verbose noshare batch trace_level log_level -declare sbt_saved_stty debugUs - -echoerr () { echo >&2 "$@"; } -vlog () { [[ -n "$verbose" ]] && echoerr "$@"; } - -# spaces are possible, e.g. sbt.version = 0.13.0 -build_props_sbt () { - [[ -r "$buildProps" ]] && \ - grep '^sbt\.version' "$buildProps" | tr '=' ' ' | awk '{ print $2; }' -} - -update_build_props_sbt () { - local ver="$1" - local old="$(build_props_sbt)" - - [[ -r "$buildProps" ]] && [[ "$ver" != "$old" ]] && { - perl -pi -e "s/^sbt\.version\b.*\$/sbt.version=${ver}/" "$buildProps" - grep -q '^sbt.version[ =]' "$buildProps" || printf "\nsbt.version=%s\n" "$ver" >> "$buildProps" - - vlog "!!!" - vlog "!!! Updated file $buildProps setting sbt.version to: $ver" - vlog "!!! Previous value was: $old" - vlog "!!!" - } -} - -set_sbt_version () { - sbt_version="${sbt_explicit_version:-$(build_props_sbt)}" - [[ -n "$sbt_version" ]] || sbt_version=$sbt_release_version - export sbt_version -} - -# restore stty settings (echo in particular) -onSbtRunnerExit() { - [[ -n "$sbt_saved_stty" ]] || return - vlog "" - vlog "restoring stty: $sbt_saved_stty" - stty "$sbt_saved_stty" - unset sbt_saved_stty -} - -# save stty and trap exit, to ensure echo is reenabled if we are interrupted. -trap onSbtRunnerExit EXIT -sbt_saved_stty="$(stty -g 2>/dev/null)" -vlog "Saved stty: $sbt_saved_stty" - -# this seems to cover the bases on OSX, and someone will -# have to tell me about the others. -get_script_path () { - local path="$1" - [[ -L "$path" ]] || { echo "$path" ; return; } - - local target="$(readlink "$path")" - if [[ "${target:0:1}" == "/" ]]; then - echo "$target" - else - echo "${path%/*}/$target" - fi -} - -die() { - echo "Aborting: $@" - exit 1 -} - -make_url () { - version="$1" - - case "$version" in - 0.7.*) echo "http://simple-build-tool.googlecode.com/files/sbt-launch-0.7.7.jar" ;; - 0.10.* ) echo "$sbt_launch_repo/org.scala-tools.sbt/sbt-launch/$version/sbt-launch.jar" ;; - 0.11.[12]) echo "$sbt_launch_repo/org.scala-tools.sbt/sbt-launch/$version/sbt-launch.jar" ;; - *) echo "$sbt_launch_repo/org.scala-sbt/sbt-launch/$version/sbt-launch.jar" ;; - esac -} - -init_default_option_file () { - local overriding_var="${!1}" - local default_file="$2" - if [[ ! -r "$default_file" && "$overriding_var" =~ ^@(.*)$ ]]; then - local envvar_file="${BASH_REMATCH[1]}" - if [[ -r "$envvar_file" ]]; then - default_file="$envvar_file" - fi - fi - echo "$default_file" -} - -declare -r cms_opts="-XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC" -declare -r jit_opts="-XX:ReservedCodeCacheSize=256m -XX:+TieredCompilation" -declare -r default_jvm_opts_common="-Xms512m -Xmx1536m -Xss2m $jit_opts $cms_opts" -declare -r noshare_opts="-Dsbt.global.base=project/.sbtboot -Dsbt.boot.directory=project/.boot -Dsbt.ivy.home=project/.ivy" -declare -r latest_28="2.8.2" -declare -r latest_29="2.9.3" -declare -r latest_210="2.10.4" -declare -r latest_211="2.11.2" - -declare -r script_path="$(get_script_path "$BASH_SOURCE")" -declare -r script_name="${script_path##*/}" - -# some non-read-onlies set with defaults -declare java_cmd="java" -declare sbt_opts_file="$(init_default_option_file SBT_OPTS .sbtopts)" -declare jvm_opts_file="$(init_default_option_file JVM_OPTS .jvmopts)" -declare sbt_launch_repo="http://typesafe.artifactoryonline.com/typesafe/ivy-releases" - -# pull -J and -D options to give to java. -declare -a residual_args -declare -a java_args -declare -a scalac_args -declare -a sbt_commands - -# args to jvm/sbt via files or environment variables -declare -a extra_jvm_opts extra_sbt_opts - -# if set, use JAVA_HOME over java found in path -[[ -e "$JAVA_HOME/bin/java" ]] && java_cmd="$JAVA_HOME/bin/java" - -# directory to store sbt launchers -declare sbt_launch_dir="$HOME/.sbt/launchers" -[[ -d "$sbt_launch_dir" ]] || mkdir -p "$sbt_launch_dir" -[[ -w "$sbt_launch_dir" ]] || sbt_launch_dir="$(mktemp -d -t sbt_extras_launchers.XXXXXX)" - -java_version () { - local version=$("$java_cmd" -version 2>&1 | grep -e 'java version' | awk '{ print $3 }' | tr -d \") - vlog "Detected Java version: $version" - echo "${version:2:1}" -} - -# MaxPermSize critical on pre-8 jvms but incurs noisy warning on 8+ -default_jvm_opts () { - local v="$(java_version)" - if [[ $v -ge 8 ]]; then - echo "$default_jvm_opts_common" - else - echo "-XX:MaxPermSize=384m $default_jvm_opts_common" - fi -} - -build_props_scala () { - if [[ -r "$buildProps" ]]; then - versionLine="$(grep '^build.scala.versions' "$buildProps")" - versionString="${versionLine##build.scala.versions=}" - echo "${versionString%% .*}" - fi -} - -execRunner () { - # print the arguments one to a line, quoting any containing spaces - vlog "# Executing command line:" && { - for arg; do - if [[ -n "$arg" ]]; then - if printf "%s\n" "$arg" | grep -q ' '; then - printf >&2 "\"%s\"\n" "$arg" - else - printf >&2 "%s\n" "$arg" - fi - fi - done - vlog "" - } - - [[ -n "$batch" ]] && exec /dev/null; then - curl --fail --silent "$url" --output "$jar" - elif which wget >/dev/null; then - wget --quiet -O "$jar" "$url" - fi - } && [[ -r "$jar" ]] -} - -acquire_sbt_jar () { - sbt_url="$(jar_url "$sbt_version")" - sbt_jar="$(jar_file "$sbt_version")" - - [[ -r "$sbt_jar" ]] || download_url "$sbt_url" "$sbt_jar" -} - -usage () { - cat < display stack traces with a max of frames (default: -1, traces suppressed) - -debug-inc enable debugging log for the incremental compiler - -no-colors disable ANSI color codes - -sbt-create start sbt even if current directory contains no sbt project - -sbt-dir path to global settings/plugins directory (default: ~/.sbt/) - -sbt-boot path to shared boot directory (default: ~/.sbt/boot in 0.11+) - -ivy path to local Ivy repository (default: ~/.ivy2) - -no-share use all local caches; no sharing - -offline put sbt in offline mode - -jvm-debug Turn on JVM debugging, open at the given port. - -batch Disable interactive mode - -prompt Set the sbt prompt; in expr, 's' is the State and 'e' is Extracted - - # sbt version (default: sbt.version from $buildProps if present, otherwise $sbt_release_version) - -sbt-force-latest force the use of the latest release of sbt: $sbt_release_version - -sbt-version use the specified version of sbt (default: $sbt_release_version) - -sbt-dev use the latest pre-release version of sbt: $sbt_unreleased_version - -sbt-jar use the specified jar as the sbt launcher - -sbt-launch-dir directory to hold sbt launchers (default: ~/.sbt/launchers) - -sbt-launch-repo repo url for downloading sbt launcher jar (default: $sbt_launch_repo) - - # scala version (default: as chosen by sbt) - -28 use $latest_28 - -29 use $latest_29 - -210 use $latest_210 - -211 use $latest_211 - -scala-home use the scala build at the specified directory - -scala-version use the specified version of scala - -binary-version use the specified scala version when searching for dependencies - - # java version (default: java from PATH, currently $(java -version 2>&1 | grep version)) - -java-home alternate JAVA_HOME - - # passing options to the jvm - note it does NOT use JAVA_OPTS due to pollution - # The default set is used if JVM_OPTS is unset and no -jvm-opts file is found - $(default_jvm_opts) - JVM_OPTS environment variable holding either the jvm args directly, or - the reference to a file containing jvm args if given path is prepended by '@' (e.g. '@/etc/jvmopts') - Note: "@"-file is overridden by local '.jvmopts' or '-jvm-opts' argument. - -jvm-opts file containing jvm args (if not given, .jvmopts in project root is used if present) - -Dkey=val pass -Dkey=val directly to the jvm - -J-X pass option -X directly to the jvm (-J is stripped) - - # passing options to sbt, OR to this runner - SBT_OPTS environment variable holding either the sbt args directly, or - the reference to a file containing sbt args if given path is prepended by '@' (e.g. '@/etc/sbtopts') - Note: "@"-file is overridden by local '.sbtopts' or '-sbt-opts' argument. - -sbt-opts file containing sbt args (if not given, .sbtopts in project root is used if present) - -S-X add -X to sbt's scalacOptions (-S is stripped) -EOM -} - -addJava () { - vlog "[addJava] arg = '$1'" - java_args=( "${java_args[@]}" "$1" ) -} -addSbt () { - vlog "[addSbt] arg = '$1'" - sbt_commands=( "${sbt_commands[@]}" "$1" ) -} -setThisBuild () { - vlog "[addBuild] args = '$@'" - local key="$1" && shift - addSbt "set $key in ThisBuild := $@" -} - -addScalac () { - vlog "[addScalac] arg = '$1'" - scalac_args=( "${scalac_args[@]}" "$1" ) -} -addResidual () { - vlog "[residual] arg = '$1'" - residual_args=( "${residual_args[@]}" "$1" ) -} -addResolver () { - addSbt "set resolvers += $1" -} -addDebugger () { - addJava "-Xdebug" - addJava "-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=$1" -} -setScalaVersion () { - [[ "$1" == *"-SNAPSHOT" ]] && addResolver 'Resolver.sonatypeRepo("snapshots")' - addSbt "++ $1" -} - -process_args () -{ - require_arg () { - local type="$1" - local opt="$2" - local arg="$3" - - if [[ -z "$arg" ]] || [[ "${arg:0:1}" == "-" ]]; then - die "$opt requires <$type> argument" - fi - } - while [[ $# -gt 0 ]]; do - case "$1" in - -h|-help) usage; exit 1 ;; - -v) verbose=true && shift ;; - -d) addSbt "--debug" && shift ;; - -w) addSbt "--warn" && shift ;; - -q) addSbt "--error" && shift ;; - -x) debugUs=true && shift ;; - -trace) require_arg integer "$1" "$2" && trace_level="$2" && shift 2 ;; - -ivy) require_arg path "$1" "$2" && addJava "-Dsbt.ivy.home=$2" && shift 2 ;; - -no-colors) addJava "-Dsbt.log.noformat=true" && shift ;; - -no-share) noshare=true && shift ;; - -sbt-boot) require_arg path "$1" "$2" && addJava "-Dsbt.boot.directory=$2" && shift 2 ;; - -sbt-dir) require_arg path "$1" "$2" && sbt_dir="$2" && shift 2 ;; - -debug-inc) addJava "-Dxsbt.inc.debug=true" && shift ;; - -offline) addSbt "set offline := true" && shift ;; - -jvm-debug) require_arg port "$1" "$2" && addDebugger "$2" && shift 2 ;; - -batch) batch=true && shift ;; - -prompt) require_arg "expr" "$1" "$2" && setThisBuild shellPrompt "(s => { val e = Project.extract(s) ; $2 })" && shift 2 ;; - - -sbt-create) sbt_create=true && shift ;; - -sbt-jar) require_arg path "$1" "$2" && sbt_jar="$2" && shift 2 ;; - -sbt-version) require_arg version "$1" "$2" && sbt_explicit_version="$2" && shift 2 ;; - -sbt-force-latest) sbt_explicit_version="$sbt_release_version" && shift ;; - -sbt-dev) sbt_explicit_version="$sbt_unreleased_version" && shift ;; - -sbt-launch-dir) require_arg path "$1" "$2" && sbt_launch_dir="$2" && shift 2 ;; - -sbt-launch-repo) require_arg path "$1" "$2" && sbt_launch_repo="$2" && shift 2 ;; - -scala-version) require_arg version "$1" "$2" && setScalaVersion "$2" && shift 2 ;; - -binary-version) require_arg version "$1" "$2" && setThisBuild scalaBinaryVersion "\"$2\"" && shift 2 ;; - -scala-home) require_arg path "$1" "$2" && setThisBuild scalaHome "Some(file(\"$2\"))" && shift 2 ;; - -java-home) require_arg path "$1" "$2" && java_cmd="$2/bin/java" && shift 2 ;; - -sbt-opts) require_arg path "$1" "$2" && sbt_opts_file="$2" && shift 2 ;; - -jvm-opts) require_arg path "$1" "$2" && jvm_opts_file="$2" && shift 2 ;; - - -D*) addJava "$1" && shift ;; - -J*) addJava "${1:2}" && shift ;; - -S*) addScalac "${1:2}" && shift ;; - -28) setScalaVersion "$latest_28" && shift ;; - -29) setScalaVersion "$latest_29" && shift ;; - -210) setScalaVersion "$latest_210" && shift ;; - -211) setScalaVersion "$latest_211" && shift ;; - - *) addResidual "$1" && shift ;; - esac - done -} - -# process the direct command line arguments -process_args "$@" - -# skip #-styled comments and blank lines -readConfigFile() { - while read line; do - [[ $line =~ ^# ]] || [[ -z $line ]] || echo "$line" - done < "$1" -} - -# if there are file/environment sbt_opts, process again so we -# can supply args to this runner -if [[ -r "$sbt_opts_file" ]]; then - vlog "Using sbt options defined in file $sbt_opts_file" - while read opt; do extra_sbt_opts+=("$opt"); done < <(readConfigFile "$sbt_opts_file") -elif [[ -n "$SBT_OPTS" && ! ("$SBT_OPTS" =~ ^@.*) ]]; then - vlog "Using sbt options defined in variable \$SBT_OPTS" - extra_sbt_opts=( $SBT_OPTS ) -else - vlog "No extra sbt options have been defined" -fi - -[[ -n "${extra_sbt_opts[*]}" ]] && process_args "${extra_sbt_opts[@]}" - -# reset "$@" to the residual args -set -- "${residual_args[@]}" -argumentCount=$# - -# set sbt version -set_sbt_version - -# only exists in 0.12+ -setTraceLevel() { - case "$sbt_version" in - "0.7."* | "0.10."* | "0.11."* ) echoerr "Cannot set trace level in sbt version $sbt_version" ;; - *) setThisBuild traceLevel $trace_level ;; - esac -} - -# set scalacOptions if we were given any -S opts -[[ ${#scalac_args[@]} -eq 0 ]] || addSbt "set scalacOptions in ThisBuild += \"${scalac_args[@]}\"" - -# Update build.properties on disk to set explicit version - sbt gives us no choice -[[ -n "$sbt_explicit_version" ]] && update_build_props_sbt "$sbt_explicit_version" -vlog "Detected sbt version $sbt_version" - -[[ -n "$scala_version" ]] && vlog "Overriding scala version to $scala_version" - -# no args - alert them there's stuff in here -(( argumentCount > 0 )) || { - vlog "Starting $script_name: invoke with -help for other options" - residual_args=( shell ) -} - -# verify this is an sbt dir or -create was given -[[ -r ./build.sbt || -d ./project || -n "$sbt_create" ]] || { - cat < e.printStackTrace() From 743219aa08375f0a1b240c85e0b57e570188e516 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 26 Jul 2016 23:05:08 +0800 Subject: [PATCH 156/470] fix apikey issue with go client --- .../src/main/resources/go/api.mustache | 22 ++++++++++------ .../client/petstore/go/go-petstore/README.md | 14 +++++------ .../petstore/go/go-petstore/api_client.go | 2 +- .../client/petstore/go/go-petstore/pet_api.go | 25 ++++++------------- .../client/petstore/go/go-petstore/pom.xml | 6 ++--- .../petstore/go/go-petstore/store_api.go | 7 +----- .../petstore/go/go-petstore/user_api.go | 8 ------ 7 files changed, 35 insertions(+), 49 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/go/api.mustache b/modules/swagger-codegen/src/main/resources/go/api.mustache index 6ddb9ee2753..9880c5b3b99 100644 --- a/modules/swagger-codegen/src/main/resources/go/api.mustache +++ b/modules/swagger-codegen/src/main/resources/go/api.mustache @@ -58,22 +58,30 @@ func (a {{{classname}}}) {{{nickname}}}({{#allParams}}{{paramName}} {{{dataType} var fileName string var fileBytes []byte {{#authMethods}} - // authentication ({{name}}) required -{{#isApiKey}}{{#isKeyInHeader}} + // authentication '({{name}})' required +{{#isApiKey}} +{{#isKeyInHeader}} // set key with prefix in header headerParams["{{keyParamName}}"] = a.Configuration.GetAPIKeyWithPrefix("{{keyParamName}}") -{{/isKeyInHeader}}{{#isKeyInQuery}} - // set key with prefix in querystring{{#hasKeyParamName}} +{{/isKeyInHeader}} +{{#isKeyInQuery}} + // set key with prefix in query string queryParams["{{keyParamName}}"] = a.Configuration.GetAPIKeyWithPrefix("{{keyParamName}}") -{{/hasKeyParamName}}{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}} +{{/isKeyInQuery}} +{{/isApiKey}} +{{#isBasic}} // http basic authentication required if a.Configuration.Username != "" || a.Configuration.Password != ""{ headerParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString() - }{{/isBasic}}{{#isOAuth}} + } +{{/isBasic}} +{{#isOAuth}} // oauth required if a.Configuration.AccessToken != ""{ headerParams["Authorization"] = "Bearer " + a.Configuration.AccessToken - }{{/isOAuth}}{{/authMethods}} + } +{{/isOAuth}} +{{/authMethods}} // add default headers if any for key := range a.Configuration.DefaultHeader { headerParams[key] = a.Configuration.DefaultHeader[key] diff --git a/samples/client/petstore/go/go-petstore/README.md b/samples/client/petstore/go/go-petstore/README.md index 5d6a957aa1e..dd7d1da39ed 100644 --- a/samples/client/petstore/go/go-petstore/README.md +++ b/samples/client/petstore/go/go-petstore/README.md @@ -7,7 +7,7 @@ This API client was generated by the [swagger-codegen](https://github.com/swagge - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-05-26T21:47:25.590-07:00 +- Build date: 2016-07-26T22:50:03.821+08:00 - Build package: class io.swagger.codegen.languages.GoClientCodegen ## Installation @@ -57,6 +57,12 @@ Class | Method | HTTP request | Description ## Documentation For Authorization +## api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + ## petstore_auth - **Type**: OAuth @@ -66,12 +72,6 @@ Class | Method | HTTP request | Description - **write:pets**: modify pets in your account - **read:pets**: read your pets -## api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - ## Author diff --git a/samples/client/petstore/go/go-petstore/api_client.go b/samples/client/petstore/go/go-petstore/api_client.go index 132ca3949fb..ea1fec2f8c5 100644 --- a/samples/client/petstore/go/go-petstore/api_client.go +++ b/samples/client/petstore/go/go-petstore/api_client.go @@ -115,7 +115,7 @@ func (c *APIClient) ParameterToString(obj interface{},collectionFormat string) s } } - return obj.(string) + return fmt.Sprintf("%v", obj) } func prepareRequest(postBody interface{}, diff --git a/samples/client/petstore/go/go-petstore/pet_api.go b/samples/client/petstore/go/go-petstore/pet_api.go index 07dc51eb90e..d02ac6955a0 100644 --- a/samples/client/petstore/go/go-petstore/pet_api.go +++ b/samples/client/petstore/go/go-petstore/pet_api.go @@ -76,8 +76,7 @@ func (a PetApi) AddPet(body Pet) (*APIResponse, error) { var postBody interface{} var fileName string var fileBytes []byte - // authentication (petstore_auth) required - + // authentication '(petstore_auth)' required // oauth required if a.Configuration.AccessToken != ""{ headerParams["Authorization"] = "Bearer " + a.Configuration.AccessToken @@ -145,8 +144,7 @@ func (a PetApi) DeletePet(petId int64, apiKey string) (*APIResponse, error) { var postBody interface{} var fileName string var fileBytes []byte - // authentication (petstore_auth) required - + // authentication '(petstore_auth)' required // oauth required if a.Configuration.AccessToken != ""{ headerParams["Authorization"] = "Bearer " + a.Configuration.AccessToken @@ -213,8 +211,7 @@ func (a PetApi) FindPetsByStatus(status []string) ([]Pet, *APIResponse, error) { var postBody interface{} var fileName string var fileBytes []byte - // authentication (petstore_auth) required - + // authentication '(petstore_auth)' required // oauth required if a.Configuration.AccessToken != ""{ headerParams["Authorization"] = "Bearer " + a.Configuration.AccessToken @@ -285,8 +282,7 @@ func (a PetApi) FindPetsByTags(tags []string) ([]Pet, *APIResponse, error) { var postBody interface{} var fileName string var fileBytes []byte - // authentication (petstore_auth) required - + // authentication '(petstore_auth)' required // oauth required if a.Configuration.AccessToken != ""{ headerParams["Authorization"] = "Bearer " + a.Configuration.AccessToken @@ -358,11 +354,9 @@ func (a PetApi) GetPetById(petId int64) (*Pet, *APIResponse, error) { var postBody interface{} var fileName string var fileBytes []byte - // authentication (api_key) required - + // authentication '(api_key)' required // set key with prefix in header headerParams["api_key"] = a.Configuration.GetAPIKeyWithPrefix("api_key") - // add default headers if any for key := range a.Configuration.DefaultHeader { headerParams[key] = a.Configuration.DefaultHeader[key] @@ -421,8 +415,7 @@ func (a PetApi) UpdatePet(body Pet) (*APIResponse, error) { var postBody interface{} var fileName string var fileBytes []byte - // authentication (petstore_auth) required - + // authentication '(petstore_auth)' required // oauth required if a.Configuration.AccessToken != ""{ headerParams["Authorization"] = "Bearer " + a.Configuration.AccessToken @@ -491,8 +484,7 @@ func (a PetApi) UpdatePetWithForm(petId int64, name string, status string) (*API var postBody interface{} var fileName string var fileBytes []byte - // authentication (petstore_auth) required - + // authentication '(petstore_auth)' required // oauth required if a.Configuration.AccessToken != ""{ headerParams["Authorization"] = "Bearer " + a.Configuration.AccessToken @@ -561,8 +553,7 @@ func (a PetApi) UploadFile(petId int64, additionalMetadata string, file *os.File var postBody interface{} var fileName string var fileBytes []byte - // authentication (petstore_auth) required - + // authentication '(petstore_auth)' required // oauth required if a.Configuration.AccessToken != ""{ headerParams["Authorization"] = "Bearer " + a.Configuration.AccessToken diff --git a/samples/client/petstore/go/go-petstore/pom.xml b/samples/client/petstore/go/go-petstore/pom.xml index 7680ed95cff..ab57225649c 100644 --- a/samples/client/petstore/go/go-petstore/pom.xml +++ b/samples/client/petstore/go/go-petstore/pom.xml @@ -41,7 +41,7 @@ - go-get-sling + go-get-resty pre-integration-test exec @@ -50,7 +50,7 @@ go get - github.com/dghubble/sling + github.com/go-resty/resty @@ -72,4 +72,4 @@ - \ No newline at end of file + diff --git a/samples/client/petstore/go/go-petstore/store_api.go b/samples/client/petstore/go/go-petstore/store_api.go index e2de74695ee..93a34d3470a 100644 --- a/samples/client/petstore/go/go-petstore/store_api.go +++ b/samples/client/petstore/go/go-petstore/store_api.go @@ -75,7 +75,6 @@ func (a StoreApi) DeleteOrder(orderId string) (*APIResponse, error) { var postBody interface{} var fileName string var fileBytes []byte - // add default headers if any for key := range a.Configuration.DefaultHeader { headerParams[key] = a.Configuration.DefaultHeader[key] @@ -129,11 +128,9 @@ func (a StoreApi) GetInventory() (*map[string]int32, *APIResponse, error) { var postBody interface{} var fileName string var fileBytes []byte - // authentication (api_key) required - + // authentication '(api_key)' required // set key with prefix in header headerParams["api_key"] = a.Configuration.GetAPIKeyWithPrefix("api_key") - // add default headers if any for key := range a.Configuration.DefaultHeader { headerParams[key] = a.Configuration.DefaultHeader[key] @@ -192,7 +189,6 @@ func (a StoreApi) GetOrderById(orderId int64) (*Order, *APIResponse, error) { var postBody interface{} var fileName string var fileBytes []byte - // add default headers if any for key := range a.Configuration.DefaultHeader { headerParams[key] = a.Configuration.DefaultHeader[key] @@ -251,7 +247,6 @@ func (a StoreApi) PlaceOrder(body Order) (*Order, *APIResponse, error) { var postBody interface{} var fileName string var fileBytes []byte - // add default headers if any for key := range a.Configuration.DefaultHeader { headerParams[key] = a.Configuration.DefaultHeader[key] diff --git a/samples/client/petstore/go/go-petstore/user_api.go b/samples/client/petstore/go/go-petstore/user_api.go index 2cd9ed6605c..3ef993addb9 100644 --- a/samples/client/petstore/go/go-petstore/user_api.go +++ b/samples/client/petstore/go/go-petstore/user_api.go @@ -74,7 +74,6 @@ func (a UserApi) CreateUser(body User) (*APIResponse, error) { var postBody interface{} var fileName string var fileBytes []byte - // add default headers if any for key := range a.Configuration.DefaultHeader { headerParams[key] = a.Configuration.DefaultHeader[key] @@ -136,7 +135,6 @@ func (a UserApi) CreateUsersWithArrayInput(body []User) (*APIResponse, error) { var postBody interface{} var fileName string var fileBytes []byte - // add default headers if any for key := range a.Configuration.DefaultHeader { headerParams[key] = a.Configuration.DefaultHeader[key] @@ -198,7 +196,6 @@ func (a UserApi) CreateUsersWithListInput(body []User) (*APIResponse, error) { var postBody interface{} var fileName string var fileBytes []byte - // add default headers if any for key := range a.Configuration.DefaultHeader { headerParams[key] = a.Configuration.DefaultHeader[key] @@ -261,7 +258,6 @@ func (a UserApi) DeleteUser(username string) (*APIResponse, error) { var postBody interface{} var fileName string var fileBytes []byte - // add default headers if any for key := range a.Configuration.DefaultHeader { headerParams[key] = a.Configuration.DefaultHeader[key] @@ -321,7 +317,6 @@ func (a UserApi) GetUserByName(username string) (*User, *APIResponse, error) { var postBody interface{} var fileName string var fileBytes []byte - // add default headers if any for key := range a.Configuration.DefaultHeader { headerParams[key] = a.Configuration.DefaultHeader[key] @@ -385,7 +380,6 @@ func (a UserApi) LoginUser(username string, password string) (*string, *APIRespo var postBody interface{} var fileName string var fileBytes []byte - // add default headers if any for key := range a.Configuration.DefaultHeader { headerParams[key] = a.Configuration.DefaultHeader[key] @@ -441,7 +435,6 @@ func (a UserApi) LogoutUser() (*APIResponse, error) { var postBody interface{} var fileName string var fileBytes []byte - // add default headers if any for key := range a.Configuration.DefaultHeader { headerParams[key] = a.Configuration.DefaultHeader[key] @@ -506,7 +499,6 @@ func (a UserApi) UpdateUser(username string, body User) (*APIResponse, error) { var postBody interface{} var fileName string var fileBytes []byte - // add default headers if any for key := range a.Configuration.DefaultHeader { headerParams[key] = a.Configuration.DefaultHeader[key] From 39228c7c94a529097ab44d7bb279bbddec921005 Mon Sep 17 00:00:00 2001 From: Neil O'Toole Date: Tue, 26 Jul 2016 15:07:57 -0600 Subject: [PATCH 157/470] #3459 removed check for required params --- modules/swagger-codegen/src/main/resources/go/api.mustache | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/go/api.mustache b/modules/swagger-codegen/src/main/resources/go/api.mustache index 9880c5b3b99..34990c680dd 100644 --- a/modules/swagger-codegen/src/main/resources/go/api.mustache +++ b/modules/swagger-codegen/src/main/resources/go/api.mustache @@ -45,11 +45,7 @@ func (a {{{classname}}}) {{{nickname}}}({{#allParams}}{{paramName}} {{{dataType} // create path and map variables path := a.Configuration.BasePath + "{{path}}"{{#pathParams}} path = strings.Replace(path, "{"+"{{baseName}}"+"}", fmt.Sprintf("%v", {{paramName}}), -1){{/pathParams}} -{{#allParams}}{{#required}} - // verify the required parameter '{{paramName}}' is set - if &{{paramName}} == nil { - return {{#returnType}}{{#isListContainer}}*{{/isListContainer}}new({{{returnType}}}), {{/returnType}}nil, errors.New("Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}") - }{{/required}}{{/allParams}} + headerParams := make(map[string]string) queryParams := url.Values{} From 154d0fc9de993b0e7bd1c55b0c4ed70e22da80ee Mon Sep 17 00:00:00 2001 From: Neil O'Toole Date: Tue, 26 Jul 2016 18:11:36 -0600 Subject: [PATCH 158/470] #3462 using base name in request instead of caseified paramName --- modules/swagger-codegen/src/main/resources/go/api.mustache | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/go/api.mustache b/modules/swagger-codegen/src/main/resources/go/api.mustache index 34990c680dd..fe10035beeb 100644 --- a/modules/swagger-codegen/src/main/resources/go/api.mustache +++ b/modules/swagger-codegen/src/main/resources/go/api.mustache @@ -88,14 +88,14 @@ func (a {{{classname}}}) {{{nickname}}}({{#allParams}}{{paramName}} {{{dataType} var collectionFormat = "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}" if collectionFormat == "multi" { for _, value := range {{paramName}} { - queryParams.Add("{{paramName}}", value) + queryParams.Add("{{baseName}}", value) } } else { - queryParams.Add("{{paramName}}", a.Configuration.APIClient.ParameterToString({{paramName}}, collectionFormat)) + queryParams.Add("{{baseName}}", a.Configuration.APIClient.ParameterToString({{paramName}}, collectionFormat)) } {{/isListContainer}} {{^isListContainer}} - queryParams.Add("{{paramName}}", a.Configuration.APIClient.ParameterToString({{paramName}}, "")) + queryParams.Add("{{baseName}}", a.Configuration.APIClient.ParameterToString({{paramName}}, "")) {{/isListContainer}} {{/queryParams}}{{/hasQueryParams}} From c23b473636f5263cf4e5bc426ef4a29b99c4c33f Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 27 Jul 2016 16:19:23 +0800 Subject: [PATCH 159/470] [Go] update travis config to run Go Petstore tests (#3465) * update pom to include go ci * fix pom * add gopath * update GOPATH * reorder pom client, server test sequence * remove debug echo in travis --- .travis.yml | 3 ++ pom.xml | 37 +++++++++++++------ .../client/petstore/go/go-petstore/README.md | 2 +- .../client/petstore/go/go-petstore/pom.xml | 6 +-- samples/client/petstore/go/pom.xml | 2 +- 5 files changed, 34 insertions(+), 16 deletions(-) diff --git a/.travis.yml b/.travis.yml index 123e520bddc..c590f2a0090 100644 --- a/.travis.yml +++ b/.travis.yml @@ -28,6 +28,9 @@ before_install: - cat /etc/hosts install: + # Add Godeps dependencies to GOPATH and PATH + - export GOPATH="${TRAVIS_BUILD_DIR}/Godeps/_workspace" + - export PATH="${TRAVIS_BUILD_DIR}/Godeps/_workspace/bin:$PATH" script: - mvn verify -Psamples diff --git a/pom.xml b/pom.xml index f58b4ca35f6..22c62aeadc4 100644 --- a/pom.xml +++ b/pom.xml @@ -544,6 +544,18 @@ samples/client/petstore/ruby + + go-client + + + env + java + + + + samples/client/petstore/go + + spring-mvc @@ -603,33 +615,36 @@ + samples/client/petstore/ruby - samples/client/petstore/python - samples/client/petstore/typescript-fetch/tests/default - samples/client/petstore/typescript-fetch/builds/default - samples/client/petstore/typescript-fetch/builds/es6-target - samples/client/petstore/typescript-fetch/builds/with-npm-version - samples/client/petstore/typescript-angular - samples/client/petstore/typescript-node/npm samples/client/petstore/android/volley samples/client/petstore/clojure - samples/client/petstore/java/jersey1 + samples/client/petstore/go samples/client/petstore/java/feign + samples/client/petstore/java/jersey1 samples/client/petstore/java/jersey2 samples/client/petstore/java/okhttp-gson samples/client/petstore/java/retrofit samples/client/petstore/java/retrofit2 samples/client/petstore/java/retrofit2rx samples/client/petstore/javascript + samples/client/petstore/python samples/client/petstore/scala - samples/server/petstore/spring-mvc - samples/server/petstore/springboot - samples/client/petstore/spring-cloud + samples/client/petstore/typescript-fetch/builds/default + samples/client/petstore/typescript-fetch/builds/es6-target + samples/client/petstore/typescript-fetch/builds/with-npm-version + samples/client/petstore/typescript-fetch/tests/default + samples/client/petstore/typescript-angular + samples/client/petstore/typescript-node/npm + samples/server/petstore/jaxrs/jersey1 samples/server/petstore/jaxrs/jersey2 samples/server/petstore/jaxrs-resteasy/default samples/server/petstore/jaxrs-resteasy/joda samples/server/petstore/scalatra + samples/server/petstore/spring-mvc + samples/client/petstore/spring-cloud + samples/server/petstore/springboot diff --git a/samples/client/petstore/go/go-petstore/README.md b/samples/client/petstore/go/go-petstore/README.md index dd7d1da39ed..b5fe36b2cb3 100644 --- a/samples/client/petstore/go/go-petstore/README.md +++ b/samples/client/petstore/go/go-petstore/README.md @@ -7,7 +7,7 @@ This API client was generated by the [swagger-codegen](https://github.com/swagge - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-07-26T22:50:03.821+08:00 +- Build date: 2016-07-27T14:47:08.029+08:00 - Build package: class io.swagger.codegen.languages.GoClientCodegen ## Installation diff --git a/samples/client/petstore/go/go-petstore/pom.xml b/samples/client/petstore/go/go-petstore/pom.xml index ab57225649c..7680ed95cff 100644 --- a/samples/client/petstore/go/go-petstore/pom.xml +++ b/samples/client/petstore/go/go-petstore/pom.xml @@ -41,7 +41,7 @@ - go-get-resty + go-get-sling pre-integration-test exec @@ -50,7 +50,7 @@ go get - github.com/go-resty/resty + github.com/dghubble/sling @@ -72,4 +72,4 @@ - + \ No newline at end of file diff --git a/samples/client/petstore/go/pom.xml b/samples/client/petstore/go/pom.xml index 7ecbbc7e198..028ef60a6f4 100644 --- a/samples/client/petstore/go/pom.xml +++ b/samples/client/petstore/go/pom.xml @@ -4,7 +4,7 @@ Goswagger pom 1.0.0 - Goswagger + Go Petstore Client From 3cd37bf5e935140b32191d7c314a1389aea9c406 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 27 Jul 2016 18:07:35 +0800 Subject: [PATCH 160/470] fix casting issue with ModelImpl in Haskell --- .../languages/HaskellServantCodegen.java | 5 + .../haskell-servant/.swagger-codegen-ignore | 23 ++ .../server/petstore/haskell-servant/LICENSE | 5 +- .../lib/SwaggerPetstore/API.hs | 255 ++++++++++++++++++ .../lib/SwaggerPetstore/Types.hs | 119 ++++++++ 5 files changed, 404 insertions(+), 3 deletions(-) create mode 100644 samples/server/petstore/haskell-servant/.swagger-codegen-ignore create mode 100644 samples/server/petstore/haskell-servant/lib/SwaggerPetstore/API.hs create mode 100644 samples/server/petstore/haskell-servant/lib/SwaggerPetstore/Types.hs diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java index 59d9658ab75..f485d7c33bf 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java @@ -471,6 +471,11 @@ public CodegenModel fromModel(String name, Model mod, Map allDefi // Create newtypes for things with non-object types String dataOrNewtype = "data"; + // check if it's a ModelImpl before casting + if (!(mod instanceof ModelImpl)) { + return model; + } + String modelType = ((ModelImpl) mod).getType(); if(modelType != "object" && typeMapping.containsKey(modelType)) { String newtype = typeMapping.get(modelType); diff --git a/samples/server/petstore/haskell-servant/.swagger-codegen-ignore b/samples/server/petstore/haskell-servant/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/haskell-servant/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/haskell-servant/LICENSE b/samples/server/petstore/haskell-servant/LICENSE index b0033f5f837..8dada3edaf5 100644 --- a/samples/server/petstore/haskell-servant/LICENSE +++ b/samples/server/petstore/haskell-servant/LICENSE @@ -1,4 +1,3 @@ - Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ @@ -179,7 +178,7 @@ APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" + boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a @@ -187,7 +186,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright 2015 Masahiro Yamauchi + Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/samples/server/petstore/haskell-servant/lib/SwaggerPetstore/API.hs b/samples/server/petstore/haskell-servant/lib/SwaggerPetstore/API.hs new file mode 100644 index 00000000000..75f53f95395 --- /dev/null +++ b/samples/server/petstore/haskell-servant/lib/SwaggerPetstore/API.hs @@ -0,0 +1,255 @@ +{-# LANGUAGE DataKinds, TypeFamilies, TypeOperators, FlexibleInstances, OverloadedStrings, ViewPatterns #-} +{-# LANGUAGE RecordWildCards, GeneralizedNewtypeDeriving, DeriveTraversable, FlexibleContexts, DeriveGeneric #-} +{-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-unused-imports -fcontext-stack=328 #-} +module SwaggerPetstore.API ( + -- * Client and Server + ServerConfig(..), + SwaggerPetstoreBackend, + createSwaggerPetstoreClient, + runSwaggerPetstoreServer, + runSwaggerPetstoreClient, + runSwaggerPetstoreClientWithManager, + SwaggerPetstoreClient, + -- ** Servant + SwaggerPetstoreAPI, + ) where + +import SwaggerPetstore.Types + +import Data.Aeson (Value) +import Data.Coerce (coerce) +import Servant.API +import Servant (serve, ServantErr) +import Web.HttpApiData +import qualified Network.Wai.Handler.Warp as Warp +import qualified Data.Text as T +import Data.Text (Text) +import Servant.Common.BaseUrl(BaseUrl(..)) +import Servant.Client (ServantError, client, Scheme(Http)) +import Data.Proxy (Proxy(..)) +import Control.Monad.IO.Class +import Data.Function ((&)) +import GHC.Exts (IsString(..)) +import qualified Data.Map as Map +import GHC.Generics (Generic) +import Data.Monoid ((<>)) +import Servant.API.Verbs (Verb, StdMethod(..)) +import Control.Monad.Except (ExceptT) +import Network.HTTP.Client (Manager, newManager, defaultManagerSettings) +import Network.HTTP.Types.Method (methodOptions) + +instance ReflectMethod 'OPTIONS where + reflectMethod _ = methodOptions + + + +data FormUpdatePetWithForm = FormUpdatePetWithForm + { updatePetWithFormName :: Text + , updatePetWithFormStatus :: Text + } deriving (Show, Eq, Generic) + +instance FromFormUrlEncoded FormUpdatePetWithForm where + fromFormUrlEncoded inputs = FormUpdatePetWithForm <$> lookupEither "name" inputs <*> lookupEither "status" inputs +instance ToFormUrlEncoded FormUpdatePetWithForm where + toFormUrlEncoded value = [("name", toQueryParam $ updatePetWithFormName value), ("status", toQueryParam $ updatePetWithFormStatus value)] + +data FormUploadFile = FormUploadFile + { uploadFileAdditionalMetadata :: Text + , uploadFileFile :: FilePath + } deriving (Show, Eq, Generic) + +instance FromFormUrlEncoded FormUploadFile where + fromFormUrlEncoded inputs = FormUploadFile <$> lookupEither "additionalMetadata" inputs <*> lookupEither "file" inputs +instance ToFormUrlEncoded FormUploadFile where + toFormUrlEncoded value = [("additionalMetadata", toQueryParam $ uploadFileAdditionalMetadata value), ("file", toQueryParam $ uploadFileFile value)] + + +-- For the form data code generation. +lookupEither :: FromHttpApiData b => Text -> [(Text, Text)] -> Either Text b +lookupEither key assocs = + case lookup key assocs of + Nothing -> Left $ "Could not find parameter " <> key <> " in form data" + Just value -> parseQueryParam value + +-- | Servant type-level API, generated from the Swagger spec for SwaggerPetstore. +type SwaggerPetstoreAPI + = "pet" :> ReqBody '[JSON] Pet :> Verb 'POST 200 '[JSON] () -- 'addPet' route + :<|> "pet" :> Capture "petId" Integer :> Header "api_key" Text :> Verb 'DELETE 200 '[JSON] () -- 'deletePet' route + :<|> "pet" :> "findByStatus" :> QueryParam "status" (QueryList 'CommaSeparated (Text)) :> Verb 'GET 200 '[JSON] [Pet] -- 'findPetsByStatus' route + :<|> "pet" :> "findByTags" :> QueryParam "tags" (QueryList 'CommaSeparated (Text)) :> Verb 'GET 200 '[JSON] [Pet] -- 'findPetsByTags' route + :<|> "pet" :> Capture "petId" Integer :> Verb 'GET 200 '[JSON] Pet -- 'getPetById' route + :<|> "pet" :> ReqBody '[JSON] Pet :> Verb 'PUT 200 '[JSON] () -- 'updatePet' route + :<|> "pet" :> Capture "petId" Integer :> ReqBody '[FormUrlEncoded] FormUpdatePetWithForm :> Verb 'POST 200 '[JSON] () -- 'updatePetWithForm' route + :<|> "pet" :> Capture "petId" Integer :> "uploadImage" :> ReqBody '[FormUrlEncoded] FormUploadFile :> Verb 'POST 200 '[JSON] ApiResponse -- 'uploadFile' route + :<|> "store" :> "order" :> Capture "orderId" Text :> Verb 'DELETE 200 '[JSON] () -- 'deleteOrder' route + :<|> "store" :> "inventory" :> Verb 'GET 200 '[JSON] (Map.Map String Int) -- 'getInventory' route + :<|> "store" :> "order" :> Capture "orderId" Integer :> Verb 'GET 200 '[JSON] Order -- 'getOrderById' route + :<|> "store" :> "order" :> ReqBody '[JSON] Order :> Verb 'POST 200 '[JSON] Order -- 'placeOrder' route + :<|> "user" :> ReqBody '[JSON] User :> Verb 'POST 200 '[JSON] () -- 'createUser' route + :<|> "user" :> "createWithArray" :> ReqBody '[JSON] [User] :> Verb 'POST 200 '[JSON] () -- 'createUsersWithArrayInput' route + :<|> "user" :> "createWithList" :> ReqBody '[JSON] [User] :> Verb 'POST 200 '[JSON] () -- 'createUsersWithListInput' route + :<|> "user" :> Capture "username" Text :> Verb 'DELETE 200 '[JSON] () -- 'deleteUser' route + :<|> "user" :> Capture "username" Text :> Verb 'GET 200 '[JSON] User -- 'getUserByName' route + :<|> "user" :> "login" :> QueryParam "username" Text :> QueryParam "password" Text :> Verb 'GET 200 '[JSON] Text -- 'loginUser' route + :<|> "user" :> "logout" :> Verb 'GET 200 '[JSON] () -- 'logoutUser' route + :<|> "user" :> Capture "username" Text :> ReqBody '[JSON] User :> Verb 'PUT 200 '[JSON] () -- 'updateUser' route + +-- | Server or client configuration, specifying the host and port to query or serve on. +data ServerConfig = ServerConfig { + configHost :: String, -- ^ Hostname to serve on, e.g. "127.0.0.1" + configPort :: Int -- ^ Port to serve on, e.g. 8080 + } deriving (Eq, Ord, Show, Read) + +-- | List of elements parsed from a query. +newtype QueryList (p :: CollectionFormat) a = QueryList { fromQueryList :: [a] } + deriving (Functor, Applicative, Monad, Foldable, Traversable) + +-- | Formats in which a list can be encoded into a HTTP path. +data CollectionFormat = CommaSeparated -- ^ CSV format for multiple parameters. + | SpaceSeparated -- ^ Also called "SSV" + | TabSeparated -- ^ Also called "TSV" + | PipeSeparated -- ^ `value1|value2|value2` + | MultiParamArray -- ^ Using multiple GET parameters, e.g. `foo=bar&foo=baz`. Only for GET params. + +instance FromHttpApiData a => FromHttpApiData (QueryList 'CommaSeparated a) where + parseQueryParam = parseSeparatedQueryList ',' + +instance FromHttpApiData a => FromHttpApiData (QueryList 'TabSeparated a) where + parseQueryParam = parseSeparatedQueryList '\t' + +instance FromHttpApiData a => FromHttpApiData (QueryList 'SpaceSeparated a) where + parseQueryParam = parseSeparatedQueryList ' ' + +instance FromHttpApiData a => FromHttpApiData (QueryList 'PipeSeparated a) where + parseQueryParam = parseSeparatedQueryList '|' + +instance FromHttpApiData a => FromHttpApiData (QueryList 'MultiParamArray a) where + parseQueryParam = error "unimplemented FromHttpApiData for MultiParamArray collection format" + +parseSeparatedQueryList :: FromHttpApiData a => Char -> Text -> Either Text (QueryList p a) +parseSeparatedQueryList char = fmap QueryList . mapM parseQueryParam . T.split (== char) + +instance ToHttpApiData a => ToHttpApiData (QueryList 'CommaSeparated a) where + toQueryParam = formatSeparatedQueryList ',' + +instance ToHttpApiData a => ToHttpApiData (QueryList 'TabSeparated a) where + toQueryParam = formatSeparatedQueryList '\t' + +instance ToHttpApiData a => ToHttpApiData (QueryList 'SpaceSeparated a) where + toQueryParam = formatSeparatedQueryList ' ' + +instance ToHttpApiData a => ToHttpApiData (QueryList 'PipeSeparated a) where + toQueryParam = formatSeparatedQueryList '|' + +instance ToHttpApiData a => ToHttpApiData (QueryList 'MultiParamArray a) where + toQueryParam = error "unimplemented ToHttpApiData for MultiParamArray collection format" + +formatSeparatedQueryList :: ToHttpApiData a => Char -> QueryList p a -> Text +formatSeparatedQueryList char = T.intercalate (T.singleton char) . map toQueryParam . fromQueryList + + +-- | Backend for SwaggerPetstore. +-- The backend can be used both for the client and the server. The client generated from the SwaggerPetstore Swagger spec +-- is a backend that executes actions by sending HTTP requests (see @createSwaggerPetstoreClient@). Alternatively, provided +-- a backend, the API can be served using @runSwaggerPetstoreServer@. +data SwaggerPetstoreBackend m = SwaggerPetstoreBackend { + addPet :: Pet -> m (){- ^ -}, + deletePet :: Integer -> Maybe Text -> m (){- ^ -}, + findPetsByStatus :: Maybe [Text] -> m [Pet]{- ^ Multiple status values can be provided with comma separated strings -}, + findPetsByTags :: Maybe [Text] -> m [Pet]{- ^ Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. -}, + getPetById :: Integer -> m Pet{- ^ Returns a single pet -}, + updatePet :: Pet -> m (){- ^ -}, + updatePetWithForm :: Integer -> FormUpdatePetWithForm -> m (){- ^ -}, + uploadFile :: Integer -> FormUploadFile -> m ApiResponse{- ^ -}, + deleteOrder :: Text -> m (){- ^ For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors -}, + getInventory :: m (Map.Map String Int){- ^ Returns a map of status codes to quantities -}, + getOrderById :: Integer -> m Order{- ^ For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions -}, + placeOrder :: Order -> m Order{- ^ -}, + createUser :: User -> m (){- ^ This can only be done by the logged in user. -}, + createUsersWithArrayInput :: [User] -> m (){- ^ -}, + createUsersWithListInput :: [User] -> m (){- ^ -}, + deleteUser :: Text -> m (){- ^ This can only be done by the logged in user. -}, + getUserByName :: Text -> m User{- ^ -}, + loginUser :: Maybe Text -> Maybe Text -> m Text{- ^ -}, + logoutUser :: m (){- ^ -}, + updateUser :: Text -> User -> m (){- ^ This can only be done by the logged in user. -} + } + +newtype SwaggerPetstoreClient a = SwaggerPetstoreClient { runClient :: Manager -> BaseUrl -> ExceptT ServantError IO a } + deriving Functor + +instance Applicative SwaggerPetstoreClient where + pure x = SwaggerPetstoreClient (\_ _ -> pure x) + (SwaggerPetstoreClient f) <*> (SwaggerPetstoreClient x) = SwaggerPetstoreClient (\manager url -> f manager url <*> x manager url) + +instance Monad SwaggerPetstoreClient where + (SwaggerPetstoreClient a) >>= f = SwaggerPetstoreClient (\manager url -> do + value <- a manager url + runClient (f value) manager url) + +instance MonadIO SwaggerPetstoreClient where + liftIO io = SwaggerPetstoreClient (\_ _ -> liftIO io) + +createSwaggerPetstoreClient :: SwaggerPetstoreBackend SwaggerPetstoreClient +createSwaggerPetstoreClient = SwaggerPetstoreBackend{..} + where + ((coerce -> addPet) :<|> + (coerce -> deletePet) :<|> + (coerce -> findPetsByStatus) :<|> + (coerce -> findPetsByTags) :<|> + (coerce -> getPetById) :<|> + (coerce -> updatePet) :<|> + (coerce -> updatePetWithForm) :<|> + (coerce -> uploadFile) :<|> + (coerce -> deleteOrder) :<|> + (coerce -> getInventory) :<|> + (coerce -> getOrderById) :<|> + (coerce -> placeOrder) :<|> + (coerce -> createUser) :<|> + (coerce -> createUsersWithArrayInput) :<|> + (coerce -> createUsersWithListInput) :<|> + (coerce -> deleteUser) :<|> + (coerce -> getUserByName) :<|> + (coerce -> loginUser) :<|> + (coerce -> logoutUser) :<|> + (coerce -> updateUser)) = client (Proxy :: Proxy SwaggerPetstoreAPI) + +-- | Run requests in the SwaggerPetstoreClient monad. +runSwaggerPetstoreClient :: ServerConfig -> SwaggerPetstoreClient a -> ExceptT ServantError IO a +runSwaggerPetstoreClient clientConfig cl = do + manager <- liftIO $ newManager defaultManagerSettings + runSwaggerPetstoreClientWithManager manager clientConfig cl + +-- | Run requests in the SwaggerPetstoreClient monad using a custom manager. +runSwaggerPetstoreClientWithManager :: Manager -> ServerConfig -> SwaggerPetstoreClient a -> ExceptT ServantError IO a +runSwaggerPetstoreClientWithManager manager clientConfig cl = + runClient cl manager $ BaseUrl Http (configHost clientConfig) (configPort clientConfig) "" + +-- | Run the SwaggerPetstore server at the provided host and port. +runSwaggerPetstoreServer :: MonadIO m => ServerConfig -> SwaggerPetstoreBackend (ExceptT ServantErr IO) -> m () +runSwaggerPetstoreServer ServerConfig{..} backend = + liftIO $ Warp.runSettings warpSettings $ serve (Proxy :: Proxy SwaggerPetstoreAPI) (serverFromBackend backend) + + where + warpSettings = Warp.defaultSettings & Warp.setPort configPort & Warp.setHost (fromString configHost) + serverFromBackend SwaggerPetstoreBackend{..} = + (coerce addPet :<|> + coerce deletePet :<|> + coerce findPetsByStatus :<|> + coerce findPetsByTags :<|> + coerce getPetById :<|> + coerce updatePet :<|> + coerce updatePetWithForm :<|> + coerce uploadFile :<|> + coerce deleteOrder :<|> + coerce getInventory :<|> + coerce getOrderById :<|> + coerce placeOrder :<|> + coerce createUser :<|> + coerce createUsersWithArrayInput :<|> + coerce createUsersWithListInput :<|> + coerce deleteUser :<|> + coerce getUserByName :<|> + coerce loginUser :<|> + coerce logoutUser :<|> + coerce updateUser) diff --git a/samples/server/petstore/haskell-servant/lib/SwaggerPetstore/Types.hs b/samples/server/petstore/haskell-servant/lib/SwaggerPetstore/Types.hs new file mode 100644 index 00000000000..cb88243d957 --- /dev/null +++ b/samples/server/petstore/haskell-servant/lib/SwaggerPetstore/Types.hs @@ -0,0 +1,119 @@ +{-# LANGUAGE DeriveGeneric #-} +{-# LANGUAGE GeneralizedNewtypeDeriving #-} +{-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-unused-imports #-} + +module SwaggerPetstore.Types ( + ApiResponse (..), + Category (..), + Order (..), + Pet (..), + Tag (..), + User (..), + ) where + +import Data.List (stripPrefix) +import Data.Maybe (fromMaybe) +import Data.Aeson (Value, FromJSON(..), ToJSON(..), genericToJSON, genericParseJSON) +import Data.Aeson.Types (Options(..), defaultOptions) +import Data.Text (Text) +import qualified Data.Text as T +import qualified Data.Map as Map +import GHC.Generics (Generic) +import Data.Function ((&)) + + +-- | +data ApiResponse = ApiResponse + { apiResponseCode :: Int -- ^ + , apiResponseType_ :: Text -- ^ + , apiResponseMessage :: Text -- ^ + } deriving (Show, Eq, Generic) + +instance FromJSON ApiResponse where + parseJSON = genericParseJSON (removeFieldLabelPrefix True "apiResponse") +instance ToJSON ApiResponse where + toJSON = genericToJSON (removeFieldLabelPrefix False "apiResponse") + +-- | +data Category = Category + { categoryId :: Integer -- ^ + , categoryName :: Text -- ^ + } deriving (Show, Eq, Generic) + +instance FromJSON Category where + parseJSON = genericParseJSON (removeFieldLabelPrefix True "category") +instance ToJSON Category where + toJSON = genericToJSON (removeFieldLabelPrefix False "category") + +-- | +data Order = Order + { orderId :: Integer -- ^ + , orderPetId :: Integer -- ^ + , orderQuantity :: Int -- ^ + , orderShipDate :: Integer -- ^ + , orderStatus :: Text -- ^ Order Status + , orderComplete :: Bool -- ^ + } deriving (Show, Eq, Generic) + +instance FromJSON Order where + parseJSON = genericParseJSON (removeFieldLabelPrefix True "order") +instance ToJSON Order where + toJSON = genericToJSON (removeFieldLabelPrefix False "order") + +-- | +data Pet = Pet + { petId :: Integer -- ^ + , petCategory :: Category -- ^ + , petName :: Text -- ^ + , petPhotoUrls :: [Text] -- ^ + , petTags :: [Tag] -- ^ + , petStatus :: Text -- ^ pet status in the store + } deriving (Show, Eq, Generic) + +instance FromJSON Pet where + parseJSON = genericParseJSON (removeFieldLabelPrefix True "pet") +instance ToJSON Pet where + toJSON = genericToJSON (removeFieldLabelPrefix False "pet") + +-- | +data Tag = Tag + { tagId :: Integer -- ^ + , tagName :: Text -- ^ + } deriving (Show, Eq, Generic) + +instance FromJSON Tag where + parseJSON = genericParseJSON (removeFieldLabelPrefix True "tag") +instance ToJSON Tag where + toJSON = genericToJSON (removeFieldLabelPrefix False "tag") + +-- | +data User = User + { userId :: Integer -- ^ + , userUsername :: Text -- ^ + , userFirstName :: Text -- ^ + , userLastName :: Text -- ^ + , userEmail :: Text -- ^ + , userPassword :: Text -- ^ + , userPhone :: Text -- ^ + , userUserStatus :: Int -- ^ User Status + } deriving (Show, Eq, Generic) + +instance FromJSON User where + parseJSON = genericParseJSON (removeFieldLabelPrefix True "user") +instance ToJSON User where + toJSON = genericToJSON (removeFieldLabelPrefix False "user") + +-- Remove a field label prefix during JSON parsing. +-- Also perform any replacements for special characters. +removeFieldLabelPrefix :: Bool -> String -> Options +removeFieldLabelPrefix forParsing prefix = + defaultOptions + { fieldLabelModifier = fromMaybe (error ("did not find prefix " ++ prefix)) . stripPrefix prefix . replaceSpecialChars + } + where + replaceSpecialChars field = foldl (&) field (map mkCharReplacement specialChars) + specialChars = [("#", "'Hash"), ("!", "'Exclamation"), ("&", "'Ampersand"), ("@", "'At"), ("$", "'Dollar"), ("%", "'Percent"), ("*", "'Star"), ("+", "'Plus"), ("-", "'Dash"), (":", "'Colon"), ("^", "'Caret"), ("|", "'Pipe"), (">", "'GreaterThan"), ("=", "'Equal"), ("<", "'LessThan")] + mkCharReplacement (replaceStr, searchStr) = T.unpack . replacer (T.pack searchStr) (T.pack replaceStr) . T.pack + replacer = if forParsing then flip T.replace else T.replace + + From 926d4a2b76d4e7a7bc8e2bc510672d59e99ff6ca Mon Sep 17 00:00:00 2001 From: Karsten Hinz Date: Wed, 27 Jul 2016 13:06:05 +0200 Subject: [PATCH 161/470] improved Multipart/form-data file upload support this code will fix #3389 ( change of content Type to MediaType.APPLICATION_OCTET_STREAM_TYPE) + possibility for multi file upload (as List) --- .../src/main/resources/Java/ApiClient.mustache | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index c4e2538b4c3..beb646ec22f 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -497,9 +497,16 @@ public class ApiClient { if (contentType.startsWith("multipart/form-data")) { FormDataMultiPart mp = new FormDataMultiPart(); for (Entry param: formParams.entrySet()) { - if (param.getValue() instanceof File) { + if( param.getValue() instanceof List && !( ( List ) param.getValue() ).isEmpty() + && ( ( List ) param.getValue() ).get( 0 ) instanceof File ) { + @SuppressWarnings( "unchecked" ) + List files = ( List ) param.getValue(); + for( File file : files ) { + mp.bodyPart( new FileDataBodyPart( param.getKey(), file, MediaType.APPLICATION_OCTET_STREAM_TYPE ) ); + } + } elseif (param.getValue() instanceof File) { File file = (File) param.getValue(); - mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.MULTIPART_FORM_DATA_TYPE)); + mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.APPLICATION_OCTET_STREAM_TYPE)); } else { mp.field(param.getKey(), parameterToString(param.getValue()), MediaType.MULTIPART_FORM_DATA_TYPE); } From 75403f1900c391dec3fc622cb9568eff92281f05 Mon Sep 17 00:00:00 2001 From: Neil O'Toole Date: Wed, 27 Jul 2016 09:35:04 -0600 Subject: [PATCH 162/470] removed unused import --- modules/swagger-codegen/src/main/resources/go/api.mustache | 1 - 1 file changed, 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/go/api.mustache b/modules/swagger-codegen/src/main/resources/go/api.mustache index fe10035beeb..db14fa0f157 100644 --- a/modules/swagger-codegen/src/main/resources/go/api.mustache +++ b/modules/swagger-codegen/src/main/resources/go/api.mustache @@ -5,7 +5,6 @@ package {{packageName}} import ( "strings" "fmt" - "errors" "net/url" {{#imports}}"{{import}}" {{/imports}} From 3b4465d9994271b3a230436b3af0e6ffaea27f19 Mon Sep 17 00:00:00 2001 From: cbornet Date: Wed, 27 Jul 2016 18:05:48 +0200 Subject: [PATCH 163/470] add fluent methods to add items to list and put items to maps --- bin/java-petstore-jersey1.sh | 2 +- .../src/main/resources/Java/pojo.mustache | 14 ++++++++++++++ .../client/model/AdditionalPropertiesClass.java | 10 ++++++++++ .../client/model/ArrayOfArrayOfNumberOnly.java | 5 +++++ .../swagger/client/model/ArrayOfNumberOnly.java | 5 +++++ .../java/io/swagger/client/model/ArrayTest.java | 15 +++++++++++++++ .../java/io/swagger/client/model/MapTest.java | 10 ++++++++++ ...xedPropertiesAndAdditionalPropertiesClass.java | 5 +++++ .../main/java/io/swagger/client/model/Pet.java | 10 ++++++++++ .../client/model/AdditionalPropertiesClass.java | 10 ++++++++++ .../client/model/ArrayOfArrayOfNumberOnly.java | 5 +++++ .../swagger/client/model/ArrayOfNumberOnly.java | 5 +++++ .../java/io/swagger/client/model/ArrayTest.java | 15 +++++++++++++++ .../java/io/swagger/client/model/MapTest.java | 10 ++++++++++ ...xedPropertiesAndAdditionalPropertiesClass.java | 5 +++++ .../main/java/io/swagger/client/model/Pet.java | 10 ++++++++++ .../client/model/AdditionalPropertiesClass.java | 10 ++++++++++ .../client/model/ArrayOfArrayOfNumberOnly.java | 5 +++++ .../swagger/client/model/ArrayOfNumberOnly.java | 5 +++++ .../java/io/swagger/client/model/ArrayTest.java | 15 +++++++++++++++ .../java/io/swagger/client/model/MapTest.java | 10 ++++++++++ ...xedPropertiesAndAdditionalPropertiesClass.java | 5 +++++ .../main/java/io/swagger/client/model/Pet.java | 10 ++++++++++ .../client/model/AdditionalPropertiesClass.java | 10 ++++++++++ .../client/model/ArrayOfArrayOfNumberOnly.java | 5 +++++ .../swagger/client/model/ArrayOfNumberOnly.java | 5 +++++ .../java/io/swagger/client/model/ArrayTest.java | 15 +++++++++++++++ .../java/io/swagger/client/model/MapTest.java | 10 ++++++++++ ...xedPropertiesAndAdditionalPropertiesClass.java | 5 +++++ .../main/java/io/swagger/client/model/Pet.java | 10 ++++++++++ .../client/model/AdditionalPropertiesClass.java | 10 ++++++++++ .../client/model/ArrayOfArrayOfNumberOnly.java | 5 +++++ .../swagger/client/model/ArrayOfNumberOnly.java | 5 +++++ .../java/io/swagger/client/model/ArrayTest.java | 15 +++++++++++++++ .../java/io/swagger/client/model/MapTest.java | 10 ++++++++++ ...xedPropertiesAndAdditionalPropertiesClass.java | 5 +++++ .../main/java/io/swagger/client/model/Pet.java | 10 ++++++++++ .../client/model/AdditionalPropertiesClass.java | 10 ++++++++++ .../client/model/ArrayOfArrayOfNumberOnly.java | 5 +++++ .../swagger/client/model/ArrayOfNumberOnly.java | 5 +++++ .../java/io/swagger/client/model/ArrayTest.java | 15 +++++++++++++++ .../java/io/swagger/client/model/MapTest.java | 10 ++++++++++ ...xedPropertiesAndAdditionalPropertiesClass.java | 5 +++++ .../main/java/io/swagger/client/model/Pet.java | 10 ++++++++++ .../client/model/AdditionalPropertiesClass.java | 10 ++++++++++ .../client/model/ArrayOfArrayOfNumberOnly.java | 5 +++++ .../swagger/client/model/ArrayOfNumberOnly.java | 5 +++++ .../java/io/swagger/client/model/ArrayTest.java | 15 +++++++++++++++ .../java/io/swagger/client/model/MapTest.java | 10 ++++++++++ ...xedPropertiesAndAdditionalPropertiesClass.java | 5 +++++ .../main/java/io/swagger/client/model/Pet.java | 10 ++++++++++ .../client/model/AdditionalPropertiesClass.java | 10 ++++++++++ .../client/model/ArrayOfArrayOfNumberOnly.java | 5 +++++ .../swagger/client/model/ArrayOfNumberOnly.java | 5 +++++ .../java/io/swagger/client/model/ArrayTest.java | 15 +++++++++++++++ .../java/io/swagger/client/model/MapTest.java | 10 ++++++++++ ...xedPropertiesAndAdditionalPropertiesClass.java | 5 +++++ .../main/java/io/swagger/client/model/Pet.java | 10 ++++++++++ 58 files changed, 495 insertions(+), 1 deletion(-) diff --git a/bin/java-petstore-jersey1.sh b/bin/java-petstore-jersey1.sh index 27aa0f826ba..7ba472365e1 100755 --- a/bin/java-petstore-jersey1.sh +++ b/bin/java-petstore-jersey1.sh @@ -26,7 +26,7 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -o samples/client/petstore/java/jersey1 -DhideGenerationTimestamp=true --library=jersey1" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/Java -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -o samples/client/petstore/java/jersey1 -DhideGenerationTimestamp=true --library=jersey1" echo "Removing files and folders under samples/client/petstore/java/jersey1/src/main" rm -rf samples/client/petstore/java/jersey1/src/main diff --git a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache index 4cebdb967ab..b9038c47245 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache @@ -32,6 +32,20 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali this.{{name}} = {{name}}; return this; } + {{#isListContainer}} + + public {{classname}} add{{nameInCamelCase}}Item({{{items.datatypeWithEnum}}} {{name}}Item) { + this.{{name}}.add({{name}}Item); + return this; + } + {{/isListContainer}} + {{#isMapContainer}} + + public {{classname}} put{{nameInCamelCase}}Item(String key, {{{items.datatypeWithEnum}}} {{name}}Item) { + this.{{name}}.put(key, {{name}}Item); + return this; + } + {{/isMapContainer}} {{/isReadOnly}} /** diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 1e2d40891a2..8f4540613cf 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -50,6 +50,11 @@ public AdditionalPropertiesClass mapProperty(Map mapProperty) { return this; } + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + this.mapProperty.put(key, mapPropertyItem); + return this; + } + /** * Get mapProperty * @return mapProperty @@ -68,6 +73,11 @@ public AdditionalPropertiesClass mapOfMapProperty(Map mapOfMapPropertyItem) { + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + /** * Get mapOfMapProperty * @return mapOfMapProperty diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 4d0dc41ee70..7dfc2cf1c64 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -47,6 +47,11 @@ public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArr return this; } + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + /** * Get arrayArrayNumber * @return arrayArrayNumber diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index bd3f05a2ad4..d99dfdac794 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -47,6 +47,11 @@ public ArrayOfNumberOnly arrayNumber(List arrayNumber) { return this; } + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + this.arrayNumber.add(arrayNumberItem); + return this; + } + /** * Get arrayNumber * @return arrayNumber diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayTest.java index 900b8375eb0..9e7308f6a8c 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayTest.java @@ -53,6 +53,11 @@ public ArrayTest arrayOfString(List arrayOfString) { return this; } + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + /** * Get arrayOfString * @return arrayOfString @@ -71,6 +76,11 @@ public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { return this; } + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + /** * Get arrayArrayOfInteger * @return arrayArrayOfInteger @@ -89,6 +99,11 @@ public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) return this; } + public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + /** * Get arrayArrayOfModel * @return arrayArrayOfModel diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MapTest.java index 6c0fc91ac41..0a06e712779 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MapTest.java @@ -70,6 +70,11 @@ public MapTest mapMapOfString(Map> mapMapOfString) { return this; } + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + /** * Get mapMapOfString * @return mapMapOfString @@ -88,6 +93,11 @@ public MapTest mapOfEnumString(Map mapOfEnumString) { return this; } + public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + /** * Get mapOfEnumString * @return mapOfEnumString diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index c37d141f972..2138c72b648 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -91,6 +91,11 @@ public MixedPropertiesAndAdditionalPropertiesClass map(Map map) return this; } + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + this.map.put(key, mapItem); + return this; + } + /** * Get map * @return map diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java index b468ebf1237..f69ca6ad4b1 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java @@ -139,6 +139,11 @@ public Pet photoUrls(List photoUrls) { return this; } + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + /** * Get photoUrls * @return photoUrls @@ -157,6 +162,11 @@ public Pet tags(List tags) { return this; } + public Pet addTagsItem(Tag tagsItem) { + this.tags.add(tagsItem); + return this; + } + /** * Get tags * @return tags diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 1e2d40891a2..8f4540613cf 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -50,6 +50,11 @@ public AdditionalPropertiesClass mapProperty(Map mapProperty) { return this; } + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + this.mapProperty.put(key, mapPropertyItem); + return this; + } + /** * Get mapProperty * @return mapProperty @@ -68,6 +73,11 @@ public AdditionalPropertiesClass mapOfMapProperty(Map mapOfMapPropertyItem) { + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + /** * Get mapOfMapProperty * @return mapOfMapProperty diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 4d0dc41ee70..7dfc2cf1c64 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -47,6 +47,11 @@ public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArr return this; } + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + /** * Get arrayArrayNumber * @return arrayArrayNumber diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index bd3f05a2ad4..d99dfdac794 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -47,6 +47,11 @@ public ArrayOfNumberOnly arrayNumber(List arrayNumber) { return this; } + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + this.arrayNumber.add(arrayNumberItem); + return this; + } + /** * Get arrayNumber * @return arrayNumber diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayTest.java index 900b8375eb0..9e7308f6a8c 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayTest.java @@ -53,6 +53,11 @@ public ArrayTest arrayOfString(List arrayOfString) { return this; } + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + /** * Get arrayOfString * @return arrayOfString @@ -71,6 +76,11 @@ public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { return this; } + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + /** * Get arrayArrayOfInteger * @return arrayArrayOfInteger @@ -89,6 +99,11 @@ public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) return this; } + public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + /** * Get arrayArrayOfModel * @return arrayArrayOfModel diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MapTest.java index 6c0fc91ac41..0a06e712779 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MapTest.java @@ -70,6 +70,11 @@ public MapTest mapMapOfString(Map> mapMapOfString) { return this; } + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + /** * Get mapMapOfString * @return mapMapOfString @@ -88,6 +93,11 @@ public MapTest mapOfEnumString(Map mapOfEnumString) { return this; } + public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + /** * Get mapOfEnumString * @return mapOfEnumString diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index c37d141f972..2138c72b648 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -91,6 +91,11 @@ public MixedPropertiesAndAdditionalPropertiesClass map(Map map) return this; } + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + this.map.put(key, mapItem); + return this; + } + /** * Get map * @return map diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Pet.java index b468ebf1237..f69ca6ad4b1 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Pet.java @@ -139,6 +139,11 @@ public Pet photoUrls(List photoUrls) { return this; } + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + /** * Get photoUrls * @return photoUrls @@ -157,6 +162,11 @@ public Pet tags(List tags) { return this; } + public Pet addTagsItem(Tag tagsItem) { + this.tags.add(tagsItem); + return this; + } + /** * Get tags * @return tags diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 1e2d40891a2..8f4540613cf 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -50,6 +50,11 @@ public AdditionalPropertiesClass mapProperty(Map mapProperty) { return this; } + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + this.mapProperty.put(key, mapPropertyItem); + return this; + } + /** * Get mapProperty * @return mapProperty @@ -68,6 +73,11 @@ public AdditionalPropertiesClass mapOfMapProperty(Map mapOfMapPropertyItem) { + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + /** * Get mapOfMapProperty * @return mapOfMapProperty diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 4d0dc41ee70..7dfc2cf1c64 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -47,6 +47,11 @@ public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArr return this; } + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + /** * Get arrayArrayNumber * @return arrayArrayNumber diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index bd3f05a2ad4..d99dfdac794 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -47,6 +47,11 @@ public ArrayOfNumberOnly arrayNumber(List arrayNumber) { return this; } + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + this.arrayNumber.add(arrayNumberItem); + return this; + } + /** * Get arrayNumber * @return arrayNumber diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayTest.java index 900b8375eb0..9e7308f6a8c 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayTest.java @@ -53,6 +53,11 @@ public ArrayTest arrayOfString(List arrayOfString) { return this; } + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + /** * Get arrayOfString * @return arrayOfString @@ -71,6 +76,11 @@ public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { return this; } + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + /** * Get arrayArrayOfInteger * @return arrayArrayOfInteger @@ -89,6 +99,11 @@ public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) return this; } + public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + /** * Get arrayArrayOfModel * @return arrayArrayOfModel diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MapTest.java index 6c0fc91ac41..0a06e712779 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MapTest.java @@ -70,6 +70,11 @@ public MapTest mapMapOfString(Map> mapMapOfString) { return this; } + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + /** * Get mapMapOfString * @return mapMapOfString @@ -88,6 +93,11 @@ public MapTest mapOfEnumString(Map mapOfEnumString) { return this; } + public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + /** * Get mapOfEnumString * @return mapOfEnumString diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 8e72ca437b9..9881b898258 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -91,6 +91,11 @@ public MixedPropertiesAndAdditionalPropertiesClass map(Map map) return this; } + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + this.map.put(key, mapItem); + return this; + } + /** * Get map * @return map diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Pet.java index b468ebf1237..f69ca6ad4b1 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Pet.java @@ -139,6 +139,11 @@ public Pet photoUrls(List photoUrls) { return this; } + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + /** * Get photoUrls * @return photoUrls @@ -157,6 +162,11 @@ public Pet tags(List tags) { return this; } + public Pet addTagsItem(Tag tagsItem) { + this.tags.add(tagsItem); + return this; + } + /** * Get tags * @return tags diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 1e2d40891a2..8f4540613cf 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -50,6 +50,11 @@ public AdditionalPropertiesClass mapProperty(Map mapProperty) { return this; } + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + this.mapProperty.put(key, mapPropertyItem); + return this; + } + /** * Get mapProperty * @return mapProperty @@ -68,6 +73,11 @@ public AdditionalPropertiesClass mapOfMapProperty(Map mapOfMapPropertyItem) { + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + /** * Get mapOfMapProperty * @return mapOfMapProperty diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 4d0dc41ee70..7dfc2cf1c64 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -47,6 +47,11 @@ public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArr return this; } + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + /** * Get arrayArrayNumber * @return arrayArrayNumber diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index bd3f05a2ad4..d99dfdac794 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -47,6 +47,11 @@ public ArrayOfNumberOnly arrayNumber(List arrayNumber) { return this; } + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + this.arrayNumber.add(arrayNumberItem); + return this; + } + /** * Get arrayNumber * @return arrayNumber diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayTest.java index 900b8375eb0..9e7308f6a8c 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayTest.java @@ -53,6 +53,11 @@ public ArrayTest arrayOfString(List arrayOfString) { return this; } + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + /** * Get arrayOfString * @return arrayOfString @@ -71,6 +76,11 @@ public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { return this; } + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + /** * Get arrayArrayOfInteger * @return arrayArrayOfInteger @@ -89,6 +99,11 @@ public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) return this; } + public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + /** * Get arrayArrayOfModel * @return arrayArrayOfModel diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MapTest.java index 6c0fc91ac41..0a06e712779 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MapTest.java @@ -70,6 +70,11 @@ public MapTest mapMapOfString(Map> mapMapOfString) { return this; } + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + /** * Get mapMapOfString * @return mapMapOfString @@ -88,6 +93,11 @@ public MapTest mapOfEnumString(Map mapOfEnumString) { return this; } + public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + /** * Get mapOfEnumString * @return mapOfEnumString diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index c37d141f972..2138c72b648 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -91,6 +91,11 @@ public MixedPropertiesAndAdditionalPropertiesClass map(Map map) return this; } + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + this.map.put(key, mapItem); + return this; + } + /** * Get map * @return map diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java index b468ebf1237..f69ca6ad4b1 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java @@ -139,6 +139,11 @@ public Pet photoUrls(List photoUrls) { return this; } + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + /** * Get photoUrls * @return photoUrls @@ -157,6 +162,11 @@ public Pet tags(List tags) { return this; } + public Pet addTagsItem(Tag tagsItem) { + this.tags.add(tagsItem); + return this; + } + /** * Get tags * @return tags diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 1943e013fa1..7b1955e7601 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -50,6 +50,11 @@ public AdditionalPropertiesClass mapProperty(Map mapProperty) { return this; } + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + this.mapProperty.put(key, mapPropertyItem); + return this; + } + /** * Get mapProperty * @return mapProperty @@ -68,6 +73,11 @@ public AdditionalPropertiesClass mapOfMapProperty(Map mapOfMapPropertyItem) { + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + /** * Get mapOfMapProperty * @return mapOfMapProperty diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 5446c2c439b..81ba53bf660 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -47,6 +47,11 @@ public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArr return this; } + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + /** * Get arrayArrayNumber * @return arrayArrayNumber diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index c9257a5d3ee..e4860d0f095 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -47,6 +47,11 @@ public ArrayOfNumberOnly arrayNumber(List arrayNumber) { return this; } + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + this.arrayNumber.add(arrayNumberItem); + return this; + } + /** * Get arrayNumber * @return arrayNumber diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java index 8d58870bcdc..22fb331103f 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java @@ -53,6 +53,11 @@ public ArrayTest arrayOfString(List arrayOfString) { return this; } + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + /** * Get arrayOfString * @return arrayOfString @@ -71,6 +76,11 @@ public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { return this; } + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + /** * Get arrayArrayOfInteger * @return arrayArrayOfInteger @@ -89,6 +99,11 @@ public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) return this; } + public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + /** * Get arrayArrayOfModel * @return arrayArrayOfModel diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MapTest.java index 61bdb6b2c65..0ab3cb990e0 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MapTest.java @@ -72,6 +72,11 @@ public MapTest mapMapOfString(Map> mapMapOfString) { return this; } + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + /** * Get mapMapOfString * @return mapMapOfString @@ -90,6 +95,11 @@ public MapTest mapOfEnumString(Map mapOfEnumString) { return this; } + public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + /** * Get mapOfEnumString * @return mapOfEnumString diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 6e587b1bf97..192175a03af 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -91,6 +91,11 @@ public MixedPropertiesAndAdditionalPropertiesClass map(Map map) return this; } + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + this.map.put(key, mapItem); + return this; + } + /** * Get map * @return map diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java index b80fdeaf923..5aad989d5b1 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java @@ -142,6 +142,11 @@ public Pet photoUrls(List photoUrls) { return this; } + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + /** * Get photoUrls * @return photoUrls @@ -160,6 +165,11 @@ public Pet tags(List tags) { return this; } + public Pet addTagsItem(Tag tagsItem) { + this.tags.add(tagsItem); + return this; + } + /** * Get tags * @return tags diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 1943e013fa1..7b1955e7601 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -50,6 +50,11 @@ public AdditionalPropertiesClass mapProperty(Map mapProperty) { return this; } + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + this.mapProperty.put(key, mapPropertyItem); + return this; + } + /** * Get mapProperty * @return mapProperty @@ -68,6 +73,11 @@ public AdditionalPropertiesClass mapOfMapProperty(Map mapOfMapPropertyItem) { + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + /** * Get mapOfMapProperty * @return mapOfMapProperty diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 5446c2c439b..81ba53bf660 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -47,6 +47,11 @@ public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArr return this; } + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + /** * Get arrayArrayNumber * @return arrayArrayNumber diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index c9257a5d3ee..e4860d0f095 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -47,6 +47,11 @@ public ArrayOfNumberOnly arrayNumber(List arrayNumber) { return this; } + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + this.arrayNumber.add(arrayNumberItem); + return this; + } + /** * Get arrayNumber * @return arrayNumber diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayTest.java index 8d58870bcdc..22fb331103f 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayTest.java @@ -53,6 +53,11 @@ public ArrayTest arrayOfString(List arrayOfString) { return this; } + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + /** * Get arrayOfString * @return arrayOfString @@ -71,6 +76,11 @@ public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { return this; } + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + /** * Get arrayArrayOfInteger * @return arrayArrayOfInteger @@ -89,6 +99,11 @@ public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) return this; } + public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + /** * Get arrayArrayOfModel * @return arrayArrayOfModel diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MapTest.java index 61bdb6b2c65..0ab3cb990e0 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MapTest.java @@ -72,6 +72,11 @@ public MapTest mapMapOfString(Map> mapMapOfString) { return this; } + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + /** * Get mapMapOfString * @return mapMapOfString @@ -90,6 +95,11 @@ public MapTest mapOfEnumString(Map mapOfEnumString) { return this; } + public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + /** * Get mapOfEnumString * @return mapOfEnumString diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 6e587b1bf97..192175a03af 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -91,6 +91,11 @@ public MixedPropertiesAndAdditionalPropertiesClass map(Map map) return this; } + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + this.map.put(key, mapItem); + return this; + } + /** * Get map * @return map diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Pet.java index b80fdeaf923..5aad989d5b1 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Pet.java @@ -142,6 +142,11 @@ public Pet photoUrls(List photoUrls) { return this; } + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + /** * Get photoUrls * @return photoUrls @@ -160,6 +165,11 @@ public Pet tags(List tags) { return this; } + public Pet addTagsItem(Tag tagsItem) { + this.tags.add(tagsItem); + return this; + } + /** * Get tags * @return tags diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 1943e013fa1..7b1955e7601 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -50,6 +50,11 @@ public AdditionalPropertiesClass mapProperty(Map mapProperty) { return this; } + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + this.mapProperty.put(key, mapPropertyItem); + return this; + } + /** * Get mapProperty * @return mapProperty @@ -68,6 +73,11 @@ public AdditionalPropertiesClass mapOfMapProperty(Map mapOfMapPropertyItem) { + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + /** * Get mapOfMapProperty * @return mapOfMapProperty diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 5446c2c439b..81ba53bf660 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -47,6 +47,11 @@ public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArr return this; } + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + /** * Get arrayArrayNumber * @return arrayArrayNumber diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index c9257a5d3ee..e4860d0f095 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -47,6 +47,11 @@ public ArrayOfNumberOnly arrayNumber(List arrayNumber) { return this; } + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + this.arrayNumber.add(arrayNumberItem); + return this; + } + /** * Get arrayNumber * @return arrayNumber diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayTest.java index 8d58870bcdc..22fb331103f 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayTest.java @@ -53,6 +53,11 @@ public ArrayTest arrayOfString(List arrayOfString) { return this; } + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + /** * Get arrayOfString * @return arrayOfString @@ -71,6 +76,11 @@ public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { return this; } + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + /** * Get arrayArrayOfInteger * @return arrayArrayOfInteger @@ -89,6 +99,11 @@ public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) return this; } + public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + /** * Get arrayArrayOfModel * @return arrayArrayOfModel diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MapTest.java index 61bdb6b2c65..0ab3cb990e0 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MapTest.java @@ -72,6 +72,11 @@ public MapTest mapMapOfString(Map> mapMapOfString) { return this; } + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + /** * Get mapMapOfString * @return mapMapOfString @@ -90,6 +95,11 @@ public MapTest mapOfEnumString(Map mapOfEnumString) { return this; } + public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + /** * Get mapOfEnumString * @return mapOfEnumString diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 6e587b1bf97..192175a03af 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -91,6 +91,11 @@ public MixedPropertiesAndAdditionalPropertiesClass map(Map map) return this; } + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + this.map.put(key, mapItem); + return this; + } + /** * Get map * @return map diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Pet.java index b80fdeaf923..5aad989d5b1 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Pet.java @@ -142,6 +142,11 @@ public Pet photoUrls(List photoUrls) { return this; } + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + /** * Get photoUrls * @return photoUrls @@ -160,6 +165,11 @@ public Pet tags(List tags) { return this; } + public Pet addTagsItem(Tag tagsItem) { + this.tags.add(tagsItem); + return this; + } + /** * Get tags * @return tags diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 1943e013fa1..7b1955e7601 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -50,6 +50,11 @@ public AdditionalPropertiesClass mapProperty(Map mapProperty) { return this; } + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + this.mapProperty.put(key, mapPropertyItem); + return this; + } + /** * Get mapProperty * @return mapProperty @@ -68,6 +73,11 @@ public AdditionalPropertiesClass mapOfMapProperty(Map mapOfMapPropertyItem) { + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + /** * Get mapOfMapProperty * @return mapOfMapProperty diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 5446c2c439b..81ba53bf660 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -47,6 +47,11 @@ public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArr return this; } + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + /** * Get arrayArrayNumber * @return arrayArrayNumber diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index c9257a5d3ee..e4860d0f095 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -47,6 +47,11 @@ public ArrayOfNumberOnly arrayNumber(List arrayNumber) { return this; } + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + this.arrayNumber.add(arrayNumberItem); + return this; + } + /** * Get arrayNumber * @return arrayNumber diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayTest.java index 8d58870bcdc..22fb331103f 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayTest.java @@ -53,6 +53,11 @@ public ArrayTest arrayOfString(List arrayOfString) { return this; } + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + /** * Get arrayOfString * @return arrayOfString @@ -71,6 +76,11 @@ public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { return this; } + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + /** * Get arrayArrayOfInteger * @return arrayArrayOfInteger @@ -89,6 +99,11 @@ public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) return this; } + public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + /** * Get arrayArrayOfModel * @return arrayArrayOfModel diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MapTest.java index 61bdb6b2c65..0ab3cb990e0 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MapTest.java @@ -72,6 +72,11 @@ public MapTest mapMapOfString(Map> mapMapOfString) { return this; } + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + /** * Get mapMapOfString * @return mapMapOfString @@ -90,6 +95,11 @@ public MapTest mapOfEnumString(Map mapOfEnumString) { return this; } + public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + /** * Get mapOfEnumString * @return mapOfEnumString diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 6e587b1bf97..192175a03af 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -91,6 +91,11 @@ public MixedPropertiesAndAdditionalPropertiesClass map(Map map) return this; } + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + this.map.put(key, mapItem); + return this; + } + /** * Get map * @return map diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Pet.java index b80fdeaf923..5aad989d5b1 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Pet.java @@ -142,6 +142,11 @@ public Pet photoUrls(List photoUrls) { return this; } + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + /** * Get photoUrls * @return photoUrls @@ -160,6 +165,11 @@ public Pet tags(List tags) { return this; } + public Pet addTagsItem(Tag tagsItem) { + this.tags.add(tagsItem); + return this; + } + /** * Get tags * @return tags From 46a222088e281210915753450f81c6a29dae1810 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 28 Jul 2016 00:24:36 +0800 Subject: [PATCH 164/470] update go petstore sample --- .../client/petstore/go/go-petstore/README.md | 2 +- .../client/petstore/go/go-petstore/pet_api.go | 33 ----------------- .../petstore/go/go-petstore/store_api.go | 13 ------- .../petstore/go/go-petstore/user_api.go | 37 ------------------- 4 files changed, 1 insertion(+), 84 deletions(-) diff --git a/samples/client/petstore/go/go-petstore/README.md b/samples/client/petstore/go/go-petstore/README.md index b5fe36b2cb3..df913068a79 100644 --- a/samples/client/petstore/go/go-petstore/README.md +++ b/samples/client/petstore/go/go-petstore/README.md @@ -7,7 +7,7 @@ This API client was generated by the [swagger-codegen](https://github.com/swagge - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-07-27T14:47:08.029+08:00 +- Build date: 2016-07-28T00:24:08.914+08:00 - Build package: class io.swagger.codegen.languages.GoClientCodegen ## Installation diff --git a/samples/client/petstore/go/go-petstore/pet_api.go b/samples/client/petstore/go/go-petstore/pet_api.go index d02ac6955a0..61819f1be78 100644 --- a/samples/client/petstore/go/go-petstore/pet_api.go +++ b/samples/client/petstore/go/go-petstore/pet_api.go @@ -25,7 +25,6 @@ package petstore import ( "strings" "fmt" - "errors" "net/url" "os" "io/ioutil" @@ -65,10 +64,6 @@ func (a PetApi) AddPet(body Pet) (*APIResponse, error) { // create path and map variables path := a.Configuration.BasePath + "/pet" - // verify the required parameter 'body' is set - if &body == nil { - return nil, errors.New("Missing required parameter 'body' when calling PetApi->AddPet") - } headerParams := make(map[string]string) queryParams := url.Values{} @@ -133,10 +128,6 @@ func (a PetApi) DeletePet(petId int64, apiKey string) (*APIResponse, error) { path := a.Configuration.BasePath + "/pet/{petId}" path = strings.Replace(path, "{"+"petId"+"}", fmt.Sprintf("%v", petId), -1) - // verify the required parameter 'petId' is set - if &petId == nil { - return nil, errors.New("Missing required parameter 'petId' when calling PetApi->DeletePet") - } headerParams := make(map[string]string) queryParams := url.Values{} @@ -200,10 +191,6 @@ func (a PetApi) FindPetsByStatus(status []string) ([]Pet, *APIResponse, error) { // create path and map variables path := a.Configuration.BasePath + "/pet/findByStatus" - // verify the required parameter 'status' is set - if &status == nil { - return *new([]Pet), nil, errors.New("Missing required parameter 'status' when calling PetApi->FindPetsByStatus") - } headerParams := make(map[string]string) queryParams := url.Values{} @@ -271,10 +258,6 @@ func (a PetApi) FindPetsByTags(tags []string) ([]Pet, *APIResponse, error) { // create path and map variables path := a.Configuration.BasePath + "/pet/findByTags" - // verify the required parameter 'tags' is set - if &tags == nil { - return *new([]Pet), nil, errors.New("Missing required parameter 'tags' when calling PetApi->FindPetsByTags") - } headerParams := make(map[string]string) queryParams := url.Values{} @@ -343,10 +326,6 @@ func (a PetApi) GetPetById(petId int64) (*Pet, *APIResponse, error) { path := a.Configuration.BasePath + "/pet/{petId}" path = strings.Replace(path, "{"+"petId"+"}", fmt.Sprintf("%v", petId), -1) - // verify the required parameter 'petId' is set - if &petId == nil { - return new(Pet), nil, errors.New("Missing required parameter 'petId' when calling PetApi->GetPetById") - } headerParams := make(map[string]string) queryParams := url.Values{} @@ -404,10 +383,6 @@ func (a PetApi) UpdatePet(body Pet) (*APIResponse, error) { // create path and map variables path := a.Configuration.BasePath + "/pet" - // verify the required parameter 'body' is set - if &body == nil { - return nil, errors.New("Missing required parameter 'body' when calling PetApi->UpdatePet") - } headerParams := make(map[string]string) queryParams := url.Values{} @@ -473,10 +448,6 @@ func (a PetApi) UpdatePetWithForm(petId int64, name string, status string) (*API path := a.Configuration.BasePath + "/pet/{petId}" path = strings.Replace(path, "{"+"petId"+"}", fmt.Sprintf("%v", petId), -1) - // verify the required parameter 'petId' is set - if &petId == nil { - return nil, errors.New("Missing required parameter 'petId' when calling PetApi->UpdatePetWithForm") - } headerParams := make(map[string]string) queryParams := url.Values{} @@ -542,10 +513,6 @@ func (a PetApi) UploadFile(petId int64, additionalMetadata string, file *os.File path := a.Configuration.BasePath + "/pet/{petId}/uploadImage" path = strings.Replace(path, "{"+"petId"+"}", fmt.Sprintf("%v", petId), -1) - // verify the required parameter 'petId' is set - if &petId == nil { - return new(ModelApiResponse), nil, errors.New("Missing required parameter 'petId' when calling PetApi->UploadFile") - } headerParams := make(map[string]string) queryParams := url.Values{} diff --git a/samples/client/petstore/go/go-petstore/store_api.go b/samples/client/petstore/go/go-petstore/store_api.go index 93a34d3470a..09d3a179b0b 100644 --- a/samples/client/petstore/go/go-petstore/store_api.go +++ b/samples/client/petstore/go/go-petstore/store_api.go @@ -25,7 +25,6 @@ package petstore import ( "strings" "fmt" - "errors" "net/url" "encoding/json" ) @@ -64,10 +63,6 @@ func (a StoreApi) DeleteOrder(orderId string) (*APIResponse, error) { path := a.Configuration.BasePath + "/store/order/{orderId}" path = strings.Replace(path, "{"+"orderId"+"}", fmt.Sprintf("%v", orderId), -1) - // verify the required parameter 'orderId' is set - if &orderId == nil { - return nil, errors.New("Missing required parameter 'orderId' when calling StoreApi->DeleteOrder") - } headerParams := make(map[string]string) queryParams := url.Values{} @@ -178,10 +173,6 @@ func (a StoreApi) GetOrderById(orderId int64) (*Order, *APIResponse, error) { path := a.Configuration.BasePath + "/store/order/{orderId}" path = strings.Replace(path, "{"+"orderId"+"}", fmt.Sprintf("%v", orderId), -1) - // verify the required parameter 'orderId' is set - if &orderId == nil { - return new(Order), nil, errors.New("Missing required parameter 'orderId' when calling StoreApi->GetOrderById") - } headerParams := make(map[string]string) queryParams := url.Values{} @@ -236,10 +227,6 @@ func (a StoreApi) PlaceOrder(body Order) (*Order, *APIResponse, error) { // create path and map variables path := a.Configuration.BasePath + "/store/order" - // verify the required parameter 'body' is set - if &body == nil { - return new(Order), nil, errors.New("Missing required parameter 'body' when calling StoreApi->PlaceOrder") - } headerParams := make(map[string]string) queryParams := url.Values{} diff --git a/samples/client/petstore/go/go-petstore/user_api.go b/samples/client/petstore/go/go-petstore/user_api.go index 3ef993addb9..e591fd01ef9 100644 --- a/samples/client/petstore/go/go-petstore/user_api.go +++ b/samples/client/petstore/go/go-petstore/user_api.go @@ -25,7 +25,6 @@ package petstore import ( "strings" "fmt" - "errors" "net/url" "encoding/json" ) @@ -63,10 +62,6 @@ func (a UserApi) CreateUser(body User) (*APIResponse, error) { // create path and map variables path := a.Configuration.BasePath + "/user" - // verify the required parameter 'body' is set - if &body == nil { - return nil, errors.New("Missing required parameter 'body' when calling UserApi->CreateUser") - } headerParams := make(map[string]string) queryParams := url.Values{} @@ -124,10 +119,6 @@ func (a UserApi) CreateUsersWithArrayInput(body []User) (*APIResponse, error) { // create path and map variables path := a.Configuration.BasePath + "/user/createWithArray" - // verify the required parameter 'body' is set - if &body == nil { - return nil, errors.New("Missing required parameter 'body' when calling UserApi->CreateUsersWithArrayInput") - } headerParams := make(map[string]string) queryParams := url.Values{} @@ -185,10 +176,6 @@ func (a UserApi) CreateUsersWithListInput(body []User) (*APIResponse, error) { // create path and map variables path := a.Configuration.BasePath + "/user/createWithList" - // verify the required parameter 'body' is set - if &body == nil { - return nil, errors.New("Missing required parameter 'body' when calling UserApi->CreateUsersWithListInput") - } headerParams := make(map[string]string) queryParams := url.Values{} @@ -247,10 +234,6 @@ func (a UserApi) DeleteUser(username string) (*APIResponse, error) { path := a.Configuration.BasePath + "/user/{username}" path = strings.Replace(path, "{"+"username"+"}", fmt.Sprintf("%v", username), -1) - // verify the required parameter 'username' is set - if &username == nil { - return nil, errors.New("Missing required parameter 'username' when calling UserApi->DeleteUser") - } headerParams := make(map[string]string) queryParams := url.Values{} @@ -306,10 +289,6 @@ func (a UserApi) GetUserByName(username string) (*User, *APIResponse, error) { path := a.Configuration.BasePath + "/user/{username}" path = strings.Replace(path, "{"+"username"+"}", fmt.Sprintf("%v", username), -1) - // verify the required parameter 'username' is set - if &username == nil { - return new(User), nil, errors.New("Missing required parameter 'username' when calling UserApi->GetUserByName") - } headerParams := make(map[string]string) queryParams := url.Values{} @@ -365,14 +344,6 @@ func (a UserApi) LoginUser(username string, password string) (*string, *APIRespo // create path and map variables path := a.Configuration.BasePath + "/user/login" - // verify the required parameter 'username' is set - if &username == nil { - return new(string), nil, errors.New("Missing required parameter 'username' when calling UserApi->LoginUser") - } - // verify the required parameter 'password' is set - if &password == nil { - return new(string), nil, errors.New("Missing required parameter 'password' when calling UserApi->LoginUser") - } headerParams := make(map[string]string) queryParams := url.Values{} @@ -484,14 +455,6 @@ func (a UserApi) UpdateUser(username string, body User) (*APIResponse, error) { path := a.Configuration.BasePath + "/user/{username}" path = strings.Replace(path, "{"+"username"+"}", fmt.Sprintf("%v", username), -1) - // verify the required parameter 'username' is set - if &username == nil { - return nil, errors.New("Missing required parameter 'username' when calling UserApi->UpdateUser") - } - // verify the required parameter 'body' is set - if &body == nil { - return nil, errors.New("Missing required parameter 'body' when calling UserApi->UpdateUser") - } headerParams := make(map[string]string) queryParams := url.Values{} From 8d4cfcae78bf76584efccb480f18443d049447ff Mon Sep 17 00:00:00 2001 From: Cliffano Subagio Date: Thu, 28 Jul 2016 23:06:57 +1000 Subject: [PATCH 165/470] Add maven-javadoc-plugin in pom.xml of generated Java client. --- modules/swagger-codegen/src/main/resources/Java/pom.mustache | 5 +++++ samples/client/petstore/java/jersey1/pom.xml | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/modules/swagger-codegen/src/main/resources/Java/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/pom.mustache index 95712934525..99a12b6391d 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pom.mustache @@ -107,6 +107,11 @@ {{/java8}} + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 + diff --git a/samples/client/petstore/java/jersey1/pom.xml b/samples/client/petstore/java/jersey1/pom.xml index c4cb68e99f4..e40088ac44c 100644 --- a/samples/client/petstore/java/jersey1/pom.xml +++ b/samples/client/petstore/java/jersey1/pom.xml @@ -101,6 +101,11 @@ 1.7 + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 + From b2cb215741ffc70c2e33499b19cca5a80c55d4c4 Mon Sep 17 00:00:00 2001 From: philicious Date: Thu, 28 Jul 2016 19:29:33 +0200 Subject: [PATCH 166/470] Qt5: added missing data type handler for QByteArray to SWGHelper --- .../resources/qt5cpp/helpers-body.mustache | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-body.mustache b/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-body.mustache index fc5af8e0ae3..fb7b29b0107 100644 --- a/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-body.mustache +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-body.mustache @@ -94,6 +94,27 @@ setValue(void* value, QJsonValue obj, QString type, QString complexType) { qDebug() << "Can't set value because the target pointer is NULL"; } } + else if (QStringLiteral("QByteArray").compare(type) == 0) { + QByteArray **val = static_cast(value); + + if(val != NULL) { + if(!obj.isNull()) { + // create a new value and return + delete *val; + + *val = new QByteArray(QByteArray::fromBase64(QByteArray::fromStdString(obj.toString().toStdString()))); + return; + } + else { + // set target to NULL + delete *val; + *val = NULL; + } + } + else { + qDebug() << "Can't set value because the target pointer is NULL"; + } + } else if(type.startsWith("SWG") && obj.isObject()) { // complex type QJsonObject jsonObj = obj.toObject(); @@ -221,6 +242,10 @@ toJsonValue(QString name, void* value, QJsonObject* output, QString type) { QDateTime* datetime = static_cast(value); output->insert(name, QJsonValue(datetime->toString(Qt::ISODate))); } + else if(QStringLiteral("QByteArray").compare(type) == 0) { + QByteArray* byteArray = static_cast(value); + output->insert(name, QJsonValue(QString(byteArray->toBase64()))); + } } void From a67f168fa626725a2c503220ff6af9a411106655 Mon Sep 17 00:00:00 2001 From: philicious Date: Thu, 28 Jul 2016 19:34:45 +0200 Subject: [PATCH 167/470] Qt5: add handling for swagger type-format "byte" to Qt5 generator --- .../main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java index 46999eccbe1..742b057003b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java @@ -124,6 +124,7 @@ public Qt5CPPGenerator() { //TODO binary should be mapped to byte array // mapped to String as a workaround typeMapping.put("binary", "QString"); + typeMapping.put("ByteArray", "QByteArray"); importMapping = new HashMap(); @@ -138,6 +139,7 @@ public Qt5CPPGenerator() { systemIncludes.add("QMap"); systemIncludes.add("QDate"); systemIncludes.add("QDateTime"); + systemIncludes.add("QByteArray"); } /** From 33b33cb3843060292d8874ff53917520ab558781 Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 29 Jul 2016 08:04:46 +0800 Subject: [PATCH 168/470] add Skurt to company list --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 13fd7068d63..47270cf6603 100644 --- a/README.md +++ b/README.md @@ -786,6 +786,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [Revault Sàrl](http://revault.ch) - [Royal Bank of Canada (RBC)](http://www.rbc.com/canada.html) - [SCOOP Software GmbH](http://www.scoop-software.de) +- [Skurt](http://www.skurt.com) - [SmartRecruiters](https://www.smartrecruiters.com/) - [StyleRecipe](http://stylerecipe.co.jp) - [Svenska Spel AB](https://www.svenskaspel.se/) From aa584972476e71740de9ef41b877bf8d5407f31d Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 29 Jul 2016 10:38:51 +0800 Subject: [PATCH 169/470] add decentfox --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 47270cf6603..97b1fa3bf5d 100644 --- a/README.md +++ b/README.md @@ -753,7 +753,8 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [CloudBoost](https://www.CloudBoost.io/) - [Conplement](http://www.conplement.de/) - [Cupix](http://www.cupix.com) -- [DBBest Technologies](https://www.dbbest.com) +- [DBBest Technologies](https://www.dbbest.com) +- [DecentFoX](http://decentfox.com/) - [DocuSign](https://www.docusign.com) - [Ergon](http://www.ergon.ch/) - [eureka](http://eure.jp/) From c3771533367e8cc41f410babffef6d9aa0db23ab Mon Sep 17 00:00:00 2001 From: jhitchcock Date: Fri, 29 Jul 2016 12:09:03 +0200 Subject: [PATCH 170/470] Confluence Wiki Documentation --- .../languages/ConfluenceWikiGenerator.java | 95 +++++++++++++++++++ .../services/io.swagger.codegen.CodegenConfig | 1 + .../confluenceWikiDocs/index.mustache | 94 ++++++++++++++++++ .../confluenceWikiDocs/param.mustache | 1 + 4 files changed, 191 insertions(+) create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ConfluenceWikiGenerator.java create mode 100644 modules/swagger-codegen/src/main/resources/confluenceWikiDocs/index.mustache create mode 100644 modules/swagger-codegen/src/main/resources/confluenceWikiDocs/param.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ConfluenceWikiGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ConfluenceWikiGenerator.java new file mode 100644 index 00000000000..747dcdfd769 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ConfluenceWikiGenerator.java @@ -0,0 +1,95 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; + +public class ConfluenceWikiGenerator extends DefaultCodegen implements CodegenConfig { + private static final String ALL_OPERATIONS = ""; + protected String invokerPackage = "io.swagger.client"; + protected String groupId = "io.swagger"; + protected String artifactId = "swagger-client"; + protected String artifactVersion = "1.0.0"; + + public ConfluenceWikiGenerator() { + super(); + outputFolder = "docs"; + embeddedTemplateDir = templateDir = "confluenceWikiDocs"; + + defaultIncludes = new HashSet(); + + cliOptions.add(new CliOption("appName", "short name of the application")); + cliOptions.add(new CliOption("appDescription", "description of the application")); + cliOptions.add(new CliOption("infoUrl", "a URL where users can get more information about the application")); + cliOptions.add(new CliOption("infoEmail", "an email address to contact for inquiries about the application")); + cliOptions.add(new CliOption("licenseInfo", "a short description of the license")); + cliOptions.add(new CliOption("licenseUrl", "a URL pointing to the full license")); + 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)); + + additionalProperties.put("appName", "Swagger Sample"); + additionalProperties.put("appDescription", "A sample swagger server"); + additionalProperties.put("infoUrl", "https://helloreverb.com"); + additionalProperties.put("infoEmail", "hello@helloreverb.com"); + additionalProperties.put("licenseInfo", "All rights reserved"); + additionalProperties.put("licenseUrl", "http://apache.org/licenses/LICENSE-2.0.html"); + additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); + additionalProperties.put(CodegenConstants.GROUP_ID, groupId); + additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); + additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); + + supportingFiles.add(new SupportingFile("index.mustache", "", "confluence-markup.txt")); + reservedWords = new HashSet(); + + languageSpecificPrimitives = new HashSet(); + importMapping = new HashMap(); + } + + @Override + public CodegenType getTag() { + return CodegenType.DOCUMENTATION; + } + + @Override + public String getName() { + return "cwiki"; + } + + @Override + public String getHelp() { + return "Generates confluence wiki markup."; + } + + @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); + } + + @Override + public Map postProcessOperations(Map objs) { + Map operations = (Map) objs.get("operations"); + List operationList = (List) operations.get("operation"); + for (CodegenOperation op : operationList) { + op.httpMethod = op.httpMethod.toLowerCase(); + } + return objs; + } +} 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 20a8ce8e9fb..a8e8e6bbc77 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 @@ -1,6 +1,7 @@ io.swagger.codegen.languages.AndroidClientCodegen io.swagger.codegen.languages.AspNet5ServerCodegen io.swagger.codegen.languages.AsyncScalaClientCodegen +io.swagger.codegen.languages.ConfluenceWikiGenerator io.swagger.codegen.languages.CSharpClientCodegen io.swagger.codegen.languages.CppRestClientCodegen io.swagger.codegen.languages.DartClientCodegen diff --git a/modules/swagger-codegen/src/main/resources/confluenceWikiDocs/index.mustache b/modules/swagger-codegen/src/main/resources/confluenceWikiDocs/index.mustache new file mode 100644 index 00000000000..0a90ab4c549 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/confluenceWikiDocs/index.mustache @@ -0,0 +1,94 @@ +h1. {{{appName}}} {{{appDescription}}} + +{{#version}}*Version:* {{{version}}}{{/version}} + +---- + +{toc:printable=true|style=square|minLevel=2|maxLevel=3|type=list|outline=false|include=.*} + +h2. Endpoints +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} + h3. {{nickname}} + {status:colour=Yellow|title={{httpMethod}}|subtle=false} + {code} + {{httpMethod}} {{path}} + {code} + *Summary:* {{summary}} + *Description:* {{notes}} + + + h4. Parameters + {{#hasPathParams}} + h5. Path Parameters + ||Name||Description||Required||Default||Pattern|| + {{#pathParams}}{{>param}} + {{/pathParams}} + {{/hasPathParams}} + + {{#hasBodyParam}} + h5. Body Parameter + ||Name||Description||Required||Default||Pattern|| + {{#bodyParams}}{{>param}} + {{/bodyParams}} + {{/hasBodyParam}} + + {{#hasHeaderParam}} + h5. Header Parameters + ||Name||Description||Required||Default||Pattern|| + {{#headerParam}}{{>param}} + {{/headerParam}} + {{/hasHeaderParam}} + + {{#hasQueryParams}} + h5. Query Parameters + ||Name||Description||Required||Default||Pattern|| + {{#queryParams}}{{>param}} + {{/queryParams}} + {{/hasQueryParams}} + + + + + h4. Responses + {{#responses}} + *Status Code:* {{code}} + *Message:* {{message}} + {code:title=Response Type} +{{{dataType}}} + {code} + See [#models] + + {{#hasExamples}} + {{#examples}} + {code:title=Example {{{contentType}}} |collapse=true } + {{{example}}} +{code} + {{/examples}} + {{/hasExamples}} + + + {code:title=Response Schema |collapse=true} +{{{jsonSchema}}} + {code} + {{#examples}} + {code:title=Example {{{contentType}}} |collapse=true } +{{{example}}} + {code} + {{/examples}} + {{/responses}} + ---- +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + +h2. Models + +{{#models}} + {{#model}} + h3. {{classname}} + ||Field Name||Required||Type||Description|| + {{#vars}} |{{name}} |{{#isNotRequired}}(x){{/isNotRequired}} |{{datatype}} |{{description}} | + {{/vars}} + {{/model}} +{{/models}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/confluenceWikiDocs/param.mustache b/modules/swagger-codegen/src/main/resources/confluenceWikiDocs/param.mustache new file mode 100644 index 00000000000..fd7d3166c37 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/confluenceWikiDocs/param.mustache @@ -0,0 +1 @@ +|{{paramName}} |{{description}} |{{^required}}(x){{/required}}{{#required}}(/){{/required}} |{{defaultValue}} | {{pattern}} | \ No newline at end of file From f2ebb08b33dd906309bbdf73e6c40f56429e7d30 Mon Sep 17 00:00:00 2001 From: Jack Wink Date: Fri, 29 Jul 2016 21:57:08 -0700 Subject: [PATCH 171/470] [Swift] Use the latest Alamofire (3.4.1) This commit updates the Swift client templates to be compatible with the latest version of Alamofire. It bumps the dependency version in the podspec and names the argument when calling `responseData`. We found that XCode was having trouble with the overloaded methods and needed the named argument for hinting. --- .../src/main/resources/swift/AlamofireImplementations.mustache | 2 +- .../swagger-codegen/src/main/resources/swift/Podspec.mustache | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache index cabf67567b5..baa6d8aa72a 100644 --- a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache @@ -90,7 +90,7 @@ class AlamofireRequestBuilder: RequestBuilder { switch T.self { case is NSData.Type: - validatedRequest.responseData({ (dataResponse) in + validatedRequest.responseData(completionHandler: { (dataResponse) in cleanupRequest() if (dataResponse.result.isFailure) { diff --git a/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache index 2289e7f6f01..f893182d9ab 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', '~> 3.1.1'{{/usePromiseKit}} - s.dependency 'Alamofire', '~> 3.1.5' + s.dependency 'Alamofire', '~> 3.4.1' end From be6c661fa0417e38569cc489c40ce63784366e62 Mon Sep 17 00:00:00 2001 From: Jack Wink Date: Sat, 30 Jul 2016 12:19:06 -0700 Subject: [PATCH 172/470] [Swift] Update samples to use latest Alamofire In order to run the integration tests, we needed to generate updated clients. --- .../swift/default/PetstoreClient.podspec | 2 +- .../Classes/Swaggers/APIs/PetAPI.swift | 106 +-- .../Classes/Swaggers/APIs/StoreAPI.swift | 64 +- .../Classes/Swaggers/APIs/UserAPI.swift | 36 +- .../Swaggers/AlamofireImplementations.swift | 2 +- .../SwaggerClientTests/Pods/Alamofire/LICENSE | 2 +- .../Pods/Alamofire/README.md | 294 ++++-- .../Pods/Alamofire/Source/Alamofire.swift | 36 +- .../Pods/Alamofire/Source/Download.swift | 38 +- .../Pods/Alamofire/Source/Error.swift | 56 +- .../Pods/Alamofire/Source/Manager.swift | 181 +++- .../Alamofire/Source/MultipartFormData.swift | 78 +- .../Source/NetworkReachabilityManager.swift | 244 +++++ .../Pods/Alamofire/Source/Notifications.swift | 47 + .../Alamofire/Source/ParameterEncoding.swift | 64 +- .../Pods/Alamofire/Source/Request.swift | 122 ++- .../Pods/Alamofire/Source/Response.swift | 52 +- .../Source/ResponseSerialization.swift | 109 ++- .../Pods/Alamofire/Source/Result.swift | 36 +- .../Alamofire/Source/ServerTrustPolicy.swift | 36 +- .../Pods/Alamofire/Source/Stream.swift | 40 +- .../Pods/Alamofire/Source/Timeline.swift | 138 +++ .../Pods/Alamofire/Source/Upload.swift | 38 +- .../Pods/Alamofire/Source/Validation.swift | 63 +- .../PetstoreClient.podspec.json | 2 +- .../SwaggerClientTests/Pods/Manifest.lock | 10 +- .../Pods/Pods.xcodeproj/project.pbxproj | 392 ++++---- .../Target Support Files/Alamofire/Info.plist | 2 +- ...ds-SwaggerClient-acknowledgements.markdown | 2 +- .../Pods-SwaggerClient-acknowledgements.plist | 2 +- .../swift/promisekit/PetstoreClient.podspec | 4 +- .../Classes/Swaggers/APIs.swift | 3 + .../Swaggers/AlamofireImplementations.swift | 82 +- .../Classes/Swaggers/Extensions.swift | 11 + .../Classes/Swaggers/Models.swift | 6 + .../SwaggerClientTests/Pods/Alamofire/LICENSE | 2 +- .../Pods/Alamofire/README.md | 294 ++++-- .../Pods/Alamofire/Source/Alamofire.swift | 36 +- .../Pods/Alamofire/Source/Download.swift | 38 +- .../Pods/Alamofire/Source/Error.swift | 56 +- .../Pods/Alamofire/Source/Manager.swift | 181 +++- .../Alamofire/Source/MultipartFormData.swift | 78 +- .../Source/NetworkReachabilityManager.swift | 244 +++++ .../Pods/Alamofire/Source/Notifications.swift | 47 + .../Alamofire/Source/ParameterEncoding.swift | 64 +- .../Pods/Alamofire/Source/Request.swift | 122 ++- .../Pods/Alamofire/Source/Response.swift | 52 +- .../Source/ResponseSerialization.swift | 109 ++- .../Pods/Alamofire/Source/Result.swift | 36 +- .../Alamofire/Source/ServerTrustPolicy.swift | 36 +- .../Pods/Alamofire/Source/Stream.swift | 40 +- .../Pods/Alamofire/Source/Timeline.swift | 138 +++ .../Pods/Alamofire/Source/Upload.swift | 38 +- .../Pods/Alamofire/Source/Validation.swift | 63 +- .../PetstoreClient.podspec.json | 4 +- .../SwaggerClientTests/Pods/Manifest.lock | 22 +- .../Pods/OMGHTTPURLRQ/README.markdown | 6 +- .../Pods/OMGHTTPURLRQ/Sources/OMGHTTPURLRQ.m | 5 +- .../Pods/Pods.xcodeproj/project.pbxproj | 856 +++++++++--------- .../Target Support Files/Alamofire/Info.plist | 2 +- .../OMGHTTPURLRQ/Info.plist | 2 +- ...ds-SwaggerClient-acknowledgements.markdown | 4 +- .../Pods-SwaggerClient-acknowledgements.plist | 4 +- .../Pods-SwaggerClient-resources.sh | 4 +- .../Pods-SwaggerClientTests-resources.sh | 4 +- .../SwaggerClient.xcodeproj/project.pbxproj | 36 +- 66 files changed, 3343 insertions(+), 1680 deletions(-) create mode 100644 samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/NetworkReachabilityManager.swift create mode 100644 samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Notifications.swift create mode 100644 samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Timeline.swift create mode 100644 samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/NetworkReachabilityManager.swift create mode 100644 samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Notifications.swift create mode 100644 samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Timeline.swift diff --git a/samples/client/petstore/swift/default/PetstoreClient.podspec b/samples/client/petstore/swift/default/PetstoreClient.podspec index d1c9460ba1a..baff671c998 100644 --- a/samples/client/petstore/swift/default/PetstoreClient.podspec +++ b/samples/client/petstore/swift/default/PetstoreClient.podspec @@ -9,5 +9,5 @@ Pod::Spec.new do |s| s.homepage = 'https://github.com/swagger-api/swagger-codegen' s.summary = 'PetstoreClient' s.source_files = 'PetstoreClient/Classes/Swaggers/**/*.swift' - s.dependency 'Alamofire', '~> 3.1.5' + s.dependency 'Alamofire', '~> 3.4.1' end diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index 6e4ddc4227b..cdbd4323e70 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -108,13 +108,13 @@ public class PetAPI: APIBase { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{contentType=application/json, example={ + - examples: [{example={ "name" : "Puma", "type" : "Dog", "color" : "Black", "gender" : "Female", "breed" : "Mixed" -}}] +}, contentType=application/json}] - parameter status: (query) Status values that need to be considered for filter (optional, default to available) @@ -157,20 +157,20 @@ public class PetAPI: APIBase { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{contentType=application/json, example=[ { - "photoUrls" : [ "aeiou" ], - "name" : "doggie", + - examples: [{example=[ { + "tags" : [ { + "id" : 123456789, + "name" : "aeiou" + } ], "id" : 123456789, "category" : { - "name" : "aeiou", - "id" : 123456789 + "id" : 123456789, + "name" : "aeiou" }, - "tags" : [ { - "name" : "aeiou", - "id" : 123456789 - } ], - "status" : "aeiou" -} ]}, {contentType=application/xml, example= + "status" : "aeiou", + "name" : "doggie", + "photoUrls" : [ "aeiou" ] +} ], contentType=application/json}, {example= 123456 doggie @@ -179,21 +179,21 @@ public class PetAPI: APIBase { string -}] - - examples: [{contentType=application/json, example=[ { - "photoUrls" : [ "aeiou" ], - "name" : "doggie", +, contentType=application/xml}] + - examples: [{example=[ { + "tags" : [ { + "id" : 123456789, + "name" : "aeiou" + } ], "id" : 123456789, "category" : { - "name" : "aeiou", - "id" : 123456789 + "id" : 123456789, + "name" : "aeiou" }, - "tags" : [ { - "name" : "aeiou", - "id" : 123456789 - } ], - "status" : "aeiou" -} ]}, {contentType=application/xml, example= + "status" : "aeiou", + "name" : "doggie", + "photoUrls" : [ "aeiou" ] +} ], contentType=application/json}, {example= 123456 doggie @@ -202,7 +202,7 @@ public class PetAPI: APIBase { string -}] +, contentType=application/xml}] - parameter tags: (query) Tags to filter by (optional) @@ -242,26 +242,26 @@ public class PetAPI: APIBase { Find pet by ID - GET /pet/{petId} - Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - - OAuth: - - type: oauth2 - - name: petstore_auth - API Key: - type: apiKey api_key - name: api_key - - examples: [{contentType=application/json, example={ - "photoUrls" : [ "aeiou" ], - "name" : "doggie", + - OAuth: + - type: oauth2 + - name: petstore_auth + - examples: [{example={ + "tags" : [ { + "id" : 123456789, + "name" : "aeiou" + } ], "id" : 123456789, "category" : { - "name" : "aeiou", - "id" : 123456789 + "id" : 123456789, + "name" : "aeiou" }, - "tags" : [ { - "name" : "aeiou", - "id" : 123456789 - } ], - "status" : "aeiou" -}}, {contentType=application/xml, example= + "status" : "aeiou", + "name" : "doggie", + "photoUrls" : [ "aeiou" ] +}, contentType=application/json}, {example= 123456 doggie @@ -270,21 +270,21 @@ public class PetAPI: APIBase { string -}] - - examples: [{contentType=application/json, example={ - "photoUrls" : [ "aeiou" ], - "name" : "doggie", +, contentType=application/xml}] + - examples: [{example={ + "tags" : [ { + "id" : 123456789, + "name" : "aeiou" + } ], "id" : 123456789, "category" : { - "name" : "aeiou", - "id" : 123456789 + "id" : 123456789, + "name" : "aeiou" }, - "tags" : [ { - "name" : "aeiou", - "id" : 123456789 - } ], - "status" : "aeiou" -}}, {contentType=application/xml, example= + "status" : "aeiou", + "name" : "doggie", + "photoUrls" : [ "aeiou" ] +}, contentType=application/json}, {example= 123456 doggie @@ -293,7 +293,7 @@ public class PetAPI: APIBase { string -}] +, contentType=application/xml}] - parameter petId: (path) ID of pet that needs to be fetched diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index c51d8d37357..1c575eb79f8 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -67,12 +67,12 @@ public class StoreAPI: APIBase { - API Key: - type: apiKey api_key - name: api_key - - examples: [{contentType=application/json, example={ + - examples: [{example={ "key" : 123 -}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}] - - examples: [{contentType=application/json, example={ +}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}] + - examples: [{example={ "key" : 123 -}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}] +}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}] - returns: RequestBuilder<[String:Int32]> */ @@ -108,36 +108,36 @@ public class StoreAPI: APIBase { Find purchase order by ID - GET /store/order/{orderId} - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - - examples: [{contentType=application/json, example={ - "petId" : 123456789, - "quantity" : 123, + - examples: [{example={ "id" : 123456789, - "shipDate" : "2000-01-23T04:56:07.000+00:00", + "petId" : 123456789, "complete" : true, - "status" : "aeiou" -}}, {contentType=application/xml, example= + "status" : "aeiou", + "quantity" : 123, + "shipDate" : "2000-01-23T04:56:07.000+00:00" +}, contentType=application/json}, {example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -}] - - examples: [{contentType=application/json, example={ - "petId" : 123456789, - "quantity" : 123, +, contentType=application/xml}] + - examples: [{example={ "id" : 123456789, - "shipDate" : "2000-01-23T04:56:07.000+00:00", + "petId" : 123456789, "complete" : true, - "status" : "aeiou" -}}, {contentType=application/xml, example= + "status" : "aeiou", + "quantity" : 123, + "shipDate" : "2000-01-23T04:56:07.000+00:00" +}, contentType=application/json}, {example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -}] +, contentType=application/xml}] - parameter orderId: (path) ID of pet that needs to be fetched @@ -176,36 +176,36 @@ public class StoreAPI: APIBase { Place an order for a pet - POST /store/order - - - examples: [{contentType=application/json, example={ - "petId" : 123456789, - "quantity" : 123, + - examples: [{example={ "id" : 123456789, - "shipDate" : "2000-01-23T04:56:07.000+00:00", + "petId" : 123456789, "complete" : true, - "status" : "aeiou" -}}, {contentType=application/xml, example= + "status" : "aeiou", + "quantity" : 123, + "shipDate" : "2000-01-23T04:56:07.000+00:00" +}, contentType=application/json}, {example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -}] - - examples: [{contentType=application/json, example={ - "petId" : 123456789, - "quantity" : 123, +, contentType=application/xml}] + - examples: [{example={ "id" : 123456789, - "shipDate" : "2000-01-23T04:56:07.000+00:00", + "petId" : 123456789, "complete" : true, - "status" : "aeiou" -}}, {contentType=application/xml, example= + "status" : "aeiou", + "quantity" : 123, + "shipDate" : "2000-01-23T04:56:07.000+00:00" +}, contentType=application/json}, {example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -}] +, contentType=application/xml}] - parameter body: (body) order placed for purchasing the pet (optional) diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index d6df7754683..a7497487f85 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -167,16 +167,16 @@ public class UserAPI: APIBase { Get user by user name - GET /user/{username} - - - examples: [{contentType=application/json, example={ - "firstName" : "aeiou", + - examples: [{example={ + "id" : 123456789, "lastName" : "aeiou", - "password" : "aeiou", - "userStatus" : 123, "phone" : "aeiou", - "id" : 123456789, + "username" : "aeiou", "email" : "aeiou", - "username" : "aeiou" -}}, {contentType=application/xml, example= + "userStatus" : 123, + "firstName" : "aeiou", + "password" : "aeiou" +}, contentType=application/json}, {example= 123456 string string @@ -185,17 +185,17 @@ public class UserAPI: APIBase { string string 0 -}] - - examples: [{contentType=application/json, example={ - "firstName" : "aeiou", +, contentType=application/xml}] + - examples: [{example={ + "id" : 123456789, "lastName" : "aeiou", - "password" : "aeiou", - "userStatus" : 123, "phone" : "aeiou", - "id" : 123456789, + "username" : "aeiou", "email" : "aeiou", - "username" : "aeiou" -}}, {contentType=application/xml, example= + "userStatus" : 123, + "firstName" : "aeiou", + "password" : "aeiou" +}, contentType=application/json}, {example= 123456 string string @@ -204,7 +204,7 @@ public class UserAPI: APIBase { string string 0 -}] +, contentType=application/xml}] - parameter username: (path) The name that needs to be fetched. Use user1 for testing. @@ -244,8 +244,8 @@ public class UserAPI: APIBase { Logs user into the system - GET /user/login - - - examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] - - examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] + - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}] + - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}] - parameter username: (query) The user name for login (optional) - parameter password: (query) The password for login in clear text (optional) diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index cabf67567b5..baa6d8aa72a 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -90,7 +90,7 @@ class AlamofireRequestBuilder: RequestBuilder { switch T.self { case is NSData.Type: - validatedRequest.responseData({ (dataResponse) in + validatedRequest.responseData(completionHandler: { (dataResponse) in cleanupRequest() if (dataResponse.result.isFailure) { diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/LICENSE b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/LICENSE index bf300e4482e..4cfbf72a4d8 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/LICENSE +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/README.md b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/README.md index bcc0ff4bd05..56a6771636c 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/README.md +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/README.md @@ -1,7 +1,7 @@ ![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/assets/alamofire.png) [![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg)](https://travis-ci.org/Alamofire/Alamofire) -[![Cocoapods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.svg) +[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.svg) [![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) [![Platform](https://img.shields.io/cocoapods/p/Alamofire.svg?style=flat)](http://cocoadocs.org/docsets/Alamofire) [![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat)](http://twitter.com/AlamofireSF) @@ -22,10 +22,17 @@ Alamofire is an HTTP networking library written in Swift. - [x] Comprehensive Unit Test Coverage - [x] [Complete Documentation](http://cocoadocs.org/docsets/Alamofire) +## Component Libraries + +In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem. + +* [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache and a priority-based image downloading system. +* [AlamofireNetworkActivityIndicator](https://github.com/Alamofire/AlamofireNetworkActivityIndicator) - Controls the visibility of the network activity indicator on iOS using Alamofire. It contains configurable delay timers to help mitigate flicker and can support `NSURLSession` instances not managed by Alamofire. + ## Requirements - iOS 8.0+ / Mac OS X 10.9+ / tvOS 9.0+ / watchOS 2.0+ -- Xcode 7.2+ +- Xcode 7.3+ ## Migration Guides @@ -60,10 +67,12 @@ To integrate Alamofire into your Xcode project using CocoaPods, specify it in yo ```ruby source 'https://github.com/CocoaPods/Specs.git' -platform :ios, '8.0' +platform :ios, '9.0' use_frameworks! -pod 'Alamofire', '~> 3.0' +target '' do + pod 'Alamofire', '~> 3.4' +end ``` Then, run the following command: @@ -86,7 +95,7 @@ $ brew install carthage To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: ```ogdl -github "Alamofire/Alamofire" ~> 3.0 +github "Alamofire/Alamofire" ~> 3.4 ``` Run `carthage update` to build the framework and drag the built `Alamofire.framework` into your Xcode project. @@ -161,6 +170,38 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) > Rather than blocking execution to wait for a response from the server, a [callback](http://en.wikipedia.org/wiki/Callback_%28computer_programming%29) is specified to handle the response once it's received. The result of a request is only available inside the scope of a response handler. Any execution contingent on the response or data received from the server must be done within a handler. +### Validation + +By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling `validate` before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type. + +#### Manual Validation + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .validate(statusCode: 200..<300) + .validate(contentType: ["application/json"]) + .response { response in + print(response) + } +``` + +#### Automatic Validation + +Automatically validates status code within `200...299` range, and that the `Content-Type` header of the response matches the `Accept` header of the request, if one is provided. + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .validate() + .responseJSON { response in + switch response.result { + case .Success: + print("Validation Successful") + case .Failure(let error): + print(error) + } + } +``` + ### Response Serialization **Built-in Response Methods** @@ -175,6 +216,7 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) ```swift Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .validate() .response { request, response, data, error in print(request) print(response) @@ -183,12 +225,13 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) } ``` -> The `response` serializer does NOT evaluate any of the response data. It merely forwards on all the information directly from the URL session delegate. We strongly encourage you to leverage the other responser serializers taking advantage of `Response` and `Result` types. +> The `response` serializer does NOT evaluate any of the response data. It merely forwards on all the information directly from the URL session delegate. We strongly encourage you to leverage the other response serializers taking advantage of `Response` and `Result` types. #### Response Data Handler ```swift Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .validate() .responseData { response in print(response.request) print(response.response) @@ -200,6 +243,7 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) ```swift Alamofire.request(.GET, "https://httpbin.org/get") + .validate() .responseString { response in print("Success: \(response.result.isSuccess)") print("Response String: \(response.result.value)") @@ -210,6 +254,7 @@ Alamofire.request(.GET, "https://httpbin.org/get") ```swift Alamofire.request(.GET, "https://httpbin.org/get") + .validate() .responseJSON { response in debugPrint(response) } @@ -221,6 +266,7 @@ Response handlers can even be chained: ```swift Alamofire.request(.GET, "https://httpbin.org/get") + .validate() .responseString { response in print("Response String: \(response.result.value)") } @@ -332,7 +378,7 @@ Adding a custom HTTP header to a `Request` is supported directly in the global ` ```swift let headers = [ "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", - "Content-Type": "application/x-www-form-urlencoded" + "Accept": "application/json" ] Alamofire.request(.GET, "https://httpbin.org/get", headers: headers) @@ -374,6 +420,7 @@ Alamofire.upload(.POST, "https://httpbin.org/post", file: fileURL) print("Total bytes written on main queue: \(totalBytesWritten)") } } + .validate() .responseJSON { response in debugPrint(response) } @@ -540,38 +587,25 @@ Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)") } ``` -### Validation - -By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling `validate` before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type. - -#### Manual Validation - -```swift -Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) - .validate(statusCode: 200..<300) - .validate(contentType: ["application/json"]) - .response { response in - print(response) - } -``` - -#### Automatic Validation +### Timeline -Automatically validates status code within `200...299` range, and that the `Content-Type` header of the response matches the `Accept` header of the request, if one is provided. +Alamofire collects timings throughout the lifecycle of a `Request` and creates a `Timeline` object exposed as a property on a `Response`. ```swift Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) .validate() .responseJSON { response in - switch response.result { - case .Success: - print("Validation Successful") - case .Failure(let error): - print(error) - } + print(response.timeline) } ``` +The above reports the following `Timeline` info: + +- `Latency`: 0.428 seconds +- `Request Duration`: 0.428 seconds +- `Serialization Duration`: 0.001 seconds +- `Total Duration`: 0.429 seconds + ### Printable ```swift @@ -679,6 +713,20 @@ Requests can be suspended, resumed, and cancelled: ### Response Serialization +#### Handling Errors + +Before implementing custom response serializers or object serialization methods, it's important to be prepared to handle any errors that may occur. Alamofire recommends handling these through the use of either your own `NSError` creation methods, or a simple `enum` that conforms to `ErrorType`. For example, this `BackendError` type, which will be used in later examples: + +```swift +enum BackendError: ErrorType { + case Network(error: NSError) + case DataSerialization(reason: String) + case JSONSerialization(error: NSError) + case ObjectSerialization(reason: String) + case XMLSerialization(error: NSError) +} +``` + #### Creating a Custom Response Serializer Alamofire provides built-in response serialization for strings, JSON, and property lists, but others can be added in extensions on `Alamofire.Request`. @@ -687,26 +735,24 @@ For example, here's how a response handler using [Ono](https://github.com/mattt/ ```swift extension Request { - public static func XMLResponseSerializer() -> ResponseSerializer { + public static func XMLResponseSerializer() -> ResponseSerializer { return ResponseSerializer { request, response, data, error in - guard error == nil else { return .Failure(error!) } + guard error == nil else { return .Failure(.Network(error: error!)) } guard let validData = data else { - let failureReason = "Data could not be serialized. Input data was nil." - let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason) - return .Failure(error) + return .Failure(.DataSerialization(reason: "Data could not be serialized. Input data was nil.")) } do { let XML = try ONOXMLDocument(data: validData) return .Success(XML) } catch { - return .Failure(error as NSError) + return .Failure(.XMLSerialization(error: error as NSError)) } } } - public func responseXMLDocument(completionHandler: Response -> Void) -> Self { + public func responseXMLDocument(completionHandler: Response -> Void) -> Self { return response(responseSerializer: Request.XMLResponseSerializer(), completionHandler: completionHandler) } } @@ -722,9 +768,9 @@ public protocol ResponseObjectSerializable { } extension Request { - public func responseObject(completionHandler: Response -> Void) -> Self { - let responseSerializer = ResponseSerializer { request, response, data, error in - guard error == nil else { return .Failure(error!) } + public func responseObject(completionHandler: Response -> Void) -> Self { + let responseSerializer = ResponseSerializer { request, response, data, error in + guard error == nil else { return .Failure(.Network(error: error!)) } let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments) let result = JSONResponseSerializer.serializeResponse(request, response, data, error) @@ -737,12 +783,10 @@ extension Request { { return .Success(responseObject) } else { - let failureReason = "JSON could not be serialized into response object: \(value)" - let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason) - return .Failure(error) + return .Failure(.ObjectSerialization(reason: "JSON could not be serialized into response object: \(value)")) } case .Failure(let error): - return .Failure(error) + return .Failure(.JSONSerialization(error: error)) } } @@ -765,7 +809,7 @@ final class User: ResponseObjectSerializable { ```swift Alamofire.request(.GET, "https://example.com/users/mattt") - .responseObject { (response: Response) in + .responseObject { (response: Response) in debugPrint(response) } ``` @@ -777,10 +821,26 @@ public protocol ResponseCollectionSerializable { static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [Self] } +extension ResponseCollectionSerializable where Self: ResponseObjectSerializable { + static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [Self] { + var collection = [Self]() + + if let representation = representation as? [[String: AnyObject]] { + for itemRepresentation in representation { + if let item = Self(response: response, representation: itemRepresentation) { + collection.append(item) + } + } + } + + return collection + } +} + extension Alamofire.Request { - public func responseCollection(completionHandler: Response<[T], NSError> -> Void) -> Self { - let responseSerializer = ResponseSerializer<[T], NSError> { request, response, data, error in - guard error == nil else { return .Failure(error!) } + public func responseCollection(completionHandler: Response<[T], BackendError> -> Void) -> Self { + let responseSerializer = ResponseSerializer<[T], BackendError> { request, response, data, error in + guard error == nil else { return .Failure(.Network(error: error!)) } let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments) let result = JSONSerializer.serializeResponse(request, response, data, error) @@ -790,12 +850,10 @@ extension Alamofire.Request { if let response = response { return .Success(T.collection(response: response, representation: value)) } else { - let failureReason = "Response collection could not be serialized due to nil response" - let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason) - return .Failure(error) + return .Failure(. ObjectSerialization(reason: "Response collection could not be serialized due to nil response")) } case .Failure(let error): - return .Failure(error) + return .Failure(.JSONSerialization(error: error)) } } @@ -813,26 +871,12 @@ final class User: ResponseObjectSerializable, ResponseCollectionSerializable { self.username = response.URL!.lastPathComponent! self.name = representation.valueForKeyPath("name") as! String } - - static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [User] { - var users: [User] = [] - - if let representation = representation as? [[String: AnyObject]] { - for userRepresentation in representation { - if let user = User(response: response, representation: userRepresentation) { - users.append(user) - } - } - } - - return users - } } ``` ```swift Alamofire.request(.GET, "http://example.com/users") - .responseCollection { (response: Response<[User], NSError>) in + .responseCollection { (response: Response<[User], BackendError>) in debugPrint(response) } ``` @@ -912,7 +956,7 @@ enum Router: URLRequestConvertible { var URLRequest: NSMutableURLRequest { let result: (path: String, parameters: [String: AnyObject]) = { switch self { - case .Search(let query, let page) where page > 1: + case .Search(let query, let page) where page > 0: return ("/search", ["q": query, "offset": Router.perPage * page]) case .Search(let query, _): return ("/search", ["q": query]) @@ -997,6 +1041,74 @@ enum Router: URLRequestConvertible { Alamofire.request(Router.ReadUser("mattt")) // GET /users/mattt ``` +### SessionDelegate + +By default, an Alamofire `Manager` instance creates an internal `SessionDelegate` object to handle all the various types of delegate callbacks that are generated by the underlying `NSURLSession`. The implementations of each delegate method handle the most common use cases for these types of calls abstracting the complexity away from the top-level APIs. However, advanced users may find the need to override the default functionality for various reasons. + +#### Override Closures + +The first way to customize the `SessionDelegate` behavior is through the use of the override closures. Each closure gives you the ability to override the implementation of the matching `SessionDelegate` API, yet still use the default implementation for all other APIs. This makes it easy to customize subsets of the delegate functionality. Here are a few examples of some of the override closures available: + +```swift +/// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`. +public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? + +/// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`. +public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)? + +/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`. +public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? + +/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`. +public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)? +``` + +The following is a short example of how to use the `taskWillPerformHTTPRedirection` to avoid following redirects to any `apple.com` domains. + +```swift +let delegate: Alamofire.Manager.SessionDelegate = manager.delegate + +delegate.taskWillPerformHTTPRedirection = { session, task, response, request in + var finalRequest = request + + if let originalRequest = task.originalRequest where originalRequest.URLString.containsString("apple.com") { + finalRequest = originalRequest + } + + return finalRequest +} +``` + +#### Subclassing + +Another way to override the default implementation of the `SessionDelegate` is to subclass it. Subclassing allows you completely customize the behavior of the API or to create a proxy for the API and still use the default implementation. Creating a proxy allows you to log events, emit notifications, provide pre and post hook implementations, etc. Here's a quick example of subclassing the `SessionDelegate` and logging a message when a redirect occurs. + +```swift +class LoggingSessionDelegate: Manager.SessionDelegate { + override func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + willPerformHTTPRedirection response: NSHTTPURLResponse, + newRequest request: NSURLRequest, + completionHandler: NSURLRequest? -> Void) + { + print("URLSession will perform HTTP redirection to request: \(request)") + + super.URLSession( + session, + task: task, + willPerformHTTPRedirection: response, + newRequest: request, + completionHandler: completionHandler + ) + } +} +``` + +Generally, either the default implementation or the override closures should provide the necessary functionality required. Subclassing should only be used as a last resort. + +> It is important to keep in mind that the `subdelegates` are initialized and destroyed in the default implementation. Be careful when subclassing to not introduce memory leaks. + ### Security Using a secure HTTPS connection when communicating with servers and web services is an important step in securing sensitive data. By default, Alamofire will evaluate the certificate chain provided by the server using Apple's built in validation provided by the Security framework. While this guarantees the certificate chain is valid, it does not prevent man-in-the-middle (MITM) attacks or other potential vulnerabilities. In order to mitigate MITM attacks, applications dealing with sensitive customer data or financial information should use certificate or public key pinning provided by the `ServerTrustPolicy`. @@ -1075,7 +1187,7 @@ The `.PerformDefaultEvaluation`, `.PinCertificates` and `.PinPublicKeys` server #### Validating the Certificate Chain -Pinning certificates and public keys both have the option of validating the certificate chain using the `validateCertificateChain` parameter. By setting this value to `true`, the full certificate chain will be evaluated in addition to performing a byte equality check against the pinned certficates or public keys. A value of `false` will skip the certificate chain validation, but will still perform the byte equality check. +Pinning certificates and public keys both have the option of validating the certificate chain using the `validateCertificateChain` parameter. By setting this value to `true`, the full certificate chain will be evaluated in addition to performing a byte equality check against the pinned certificates or public keys. A value of `false` will skip the certificate chain validation, but will still perform the byte equality check. There are several cases where it may make sense to disable certificate chain validation. The most common use cases for disabling validation are self-signed and expired certificates. The evaluation would always fail in both of these cases, but the byte equality check will still ensure you are receiving the certificate you expect from the server. @@ -1114,19 +1226,41 @@ Whether you need to set the `NSExceptionRequiresForwardSecrecy` to `NO` depends > It is recommended to always use valid certificates in production environments. ---- +### Network Reachability -## Component Libraries +The `NetworkReachabilityManager` listens for reachability changes of hosts and addresses for both WWAN and WiFi network interfaces. -In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem. +```swift +let manager = NetworkReachabilityManager(host: "www.apple.com") -* [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache and a priority-based image downloading system. +manager?.listener = { status in + print("Network Status Changed: \(status)") +} + +manager?.startListening() +``` + +> Make sure to remember to retain the `manager` in the above example, or no status changes will be reported. + +There are some important things to remember when using network reachability to determine what to do next. + +* **Do NOT** use Reachability to determine if a network request should be sent. + * You should **ALWAYS** send it. +* When Reachability is restored, use the event to retry failed network requests. + * Even though the network requests may still fail, this is a good moment to retry them. +* The network reachability status can be useful for determining why a network request may have failed. + * If a network request fails, it is more useful to tell the user that the network request failed due to being offline rather than a more technical error, such as "request timed out." + +> It is recommended to check out [WWDC 2012 Session 706, "Networking Best Practices"](https://developer.apple.com/videos/play/wwdc2012-706/) for more info. + +--- ## Open Rdars The following rdars have some affect on the current implementation of Alamofire. * [rdar://21349340](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in test case +* [rdar://26761490](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage ## FAQ @@ -1144,6 +1278,20 @@ Alamofire is owned and maintained by the [Alamofire Software Foundation](http:// If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. +## Donations + +The [ASF](https://github.com/Alamofire/Foundation#members) is looking to raise money to officially register as a federal non-profit organization. Registering will allow us members to gain some legal protections and also allow us to put donations to use, tax free. Donating to the ASF will enable us to: + +* Pay our legal fees to register as a federal non-profit organization +* Pay our yearly legal fees to keep the non-profit in good status +* Pay for our mail servers to help us stay on top of all questions and security issues +* Potentially fund test servers to make it easier for us to test the edge cases +* Potentially fund developers to work on one of our projects full-time + +The community adoption of the ASF libraries has been amazing. We are greatly humbled by your enthusiam around the projects, and want to continue to do everything we can to move the needle forward. With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. If you use any of our libraries for work, see if your employers would be interested in donating. Our initial goal is to raise $1000 to get all our legal ducks in a row and kickstart this campaign. Any amount you can donate today to help us reach our goal would be greatly appreciated. + +Click here to lend your support to: Alamofire Software Foundation and make a donation at pledgie.com ! + ## License Alamofire is released under the MIT license. See LICENSE for details. diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift index b866f42264f..cb4b36afbd3 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift @@ -1,24 +1,26 @@ -// Alamofire.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Alamofire.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Download.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Download.swift index b9a043cb8e3..97b146fc016 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Download.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Download.swift @@ -1,24 +1,26 @@ -// Download.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Download.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -211,6 +213,8 @@ extension Request { totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + if let downloadTaskDidWriteData = downloadTaskDidWriteData { downloadTaskDidWriteData( session, diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Error.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Error.swift index 7a813f1b813..467d99c916c 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Error.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Error.swift @@ -1,24 +1,26 @@ -// Error.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Error.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -39,6 +41,15 @@ public struct Error { case PropertyListSerializationFailed = -6007 } + /// Custom keys contained within certain NSError `userInfo` dictionaries generated by Alamofire. + public struct UserInfoKeys { + /// The content type user info key for a `.ContentTypeValidationFailed` error stored as a `String` value. + public static let ContentType = "ContentType" + + /// The status code user info key for a `.StatusCodeValidationFailed` error stored as an `Int` value. + public static let StatusCode = "StatusCode" + } + /** Creates an `NSError` with the given error code and failure reason. @@ -47,6 +58,7 @@ public struct Error { - returns: An `NSError` with the given error code and failure reason. */ + @available(*, deprecated=3.4.0) public static func errorWithCode(code: Code, failureReason: String) -> NSError { return errorWithCode(code.rawValue, failureReason: failureReason) } @@ -59,8 +71,18 @@ public struct Error { - returns: An `NSError` with the given error code and failure reason. */ + @available(*, deprecated=3.4.0) public static func errorWithCode(code: Int, failureReason: String) -> NSError { let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] return NSError(domain: Domain, code: code, userInfo: userInfo) } + + static func error(domain domain: String = Error.Domain, code: Code, failureReason: String) -> NSError { + return error(domain: domain, code: code.rawValue, failureReason: failureReason) + } + + static func error(domain domain: String = Error.Domain, code: Int, failureReason: String) -> NSError { + let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] + return NSError(domain: domain, code: code, userInfo: userInfo) + } } diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift index d81c7380fa8..691d31f62f7 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift @@ -1,24 +1,26 @@ -// Manager.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Manager.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -56,17 +58,40 @@ public class Manager { // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 let userAgent: String = { if let info = NSBundle.mainBundle().infoDictionary { - let executable: AnyObject = info[kCFBundleExecutableKey as String] ?? "Unknown" - let bundle: AnyObject = info[kCFBundleIdentifierKey as String] ?? "Unknown" - let version: AnyObject = info[kCFBundleVersionKey as String] ?? "Unknown" - let os: AnyObject = NSProcessInfo.processInfo().operatingSystemVersionString ?? "Unknown" + let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown" + let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown" + let version = info[kCFBundleVersionKey as String] as? String ?? "Unknown" - var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString - let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString + let osNameVersion: String = { + let versionString: String - if CFStringTransform(mutableUserAgent, UnsafeMutablePointer(nil), transform, false) { - return mutableUserAgent as String - } + if #available(OSX 10.10, *) { + let version = NSProcessInfo.processInfo().operatingSystemVersion + versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" + } else { + versionString = "10.9" + } + + let osName: String = { + #if os(iOS) + return "iOS" + #elseif os(watchOS) + return "watchOS" + #elseif os(tvOS) + return "tvOS" + #elseif os(OSX) + return "OS X" + #elseif os(Linux) + return "Linux" + #else + return "Unknown" + #endif + }() + + return "\(osName) \(versionString)" + }() + + return "\(executable)/\(bundle) (\(version); \(osNameVersion))" } return "Alamofire" @@ -143,11 +168,11 @@ public class Manager { delegate: SessionDelegate, serverTrustPolicyManager: ServerTrustPolicyManager? = nil) { + guard delegate === session.delegate else { return nil } + self.delegate = delegate self.session = session - guard delegate === session.delegate else { return nil } - commonInit(serverTrustPolicyManager: serverTrustPolicyManager) } @@ -218,18 +243,18 @@ public class Manager { /** Responsible for handling all delegate callbacks for the underlying session. */ - public final class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate { + public class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate { private var subdelegates: [Int: Request.TaskDelegate] = [:] private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) - subscript(task: NSURLSessionTask) -> Request.TaskDelegate? { + /// Access the task delegate for the specified task in a thread-safe manner. + public subscript(task: NSURLSessionTask) -> Request.TaskDelegate? { get { var subdelegate: Request.TaskDelegate? dispatch_sync(subdelegateQueue) { subdelegate = self.subdelegates[task.taskIdentifier] } return subdelegate } - set { dispatch_barrier_async(subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue } } @@ -254,6 +279,9 @@ public class Manager { /// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`. public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? + /// Overrides all behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:` and requires the caller to call the `completionHandler`. + public var sessionDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)? + /// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`. public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)? @@ -281,6 +309,11 @@ public class Manager { didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) { + guard sessionDidReceiveChallengeWithCompletion == nil else { + sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler) + return + } + var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling var credential: NSURLCredential? @@ -321,11 +354,23 @@ public class Manager { /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`. public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? + /// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:` and + /// requires the caller to call the `completionHandler`. + public var taskWillPerformHTTPRedirectionWithCompletion: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest, NSURLRequest? -> Void) -> Void)? + /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`. public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? + /// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:` and + /// requires the caller to call the `completionHandler`. + public var taskDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)? + /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`. - public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream!)? + public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)? + + /// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:` and + /// requires the caller to call the `completionHandler`. + public var taskNeedNewBodyStreamWithCompletion: ((NSURLSession, NSURLSessionTask, NSInputStream? -> Void) -> Void)? /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`. public var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)? @@ -351,8 +396,13 @@ public class Manager { task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, - completionHandler: ((NSURLRequest?) -> Void)) + completionHandler: NSURLRequest? -> Void) { + guard taskWillPerformHTTPRedirectionWithCompletion == nil else { + taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler) + return + } + var redirectRequest: NSURLRequest? = request if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { @@ -374,10 +424,16 @@ public class Manager { session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, - completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) + completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) { + guard taskDidReceiveChallengeWithCompletion == nil else { + taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler) + return + } + if let taskDidReceiveChallenge = taskDidReceiveChallenge { - completionHandler(taskDidReceiveChallenge(session, task, challenge)) + let result = taskDidReceiveChallenge(session, task, challenge) + completionHandler(result.0, result.1) } else if let delegate = self[task] { delegate.URLSession( session, @@ -400,8 +456,13 @@ public class Manager { public func URLSession( session: NSURLSession, task: NSURLSessionTask, - needNewBodyStream completionHandler: ((NSInputStream?) -> Void)) + needNewBodyStream completionHandler: NSInputStream? -> Void) { + guard taskNeedNewBodyStreamWithCompletion == nil else { + taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler) + return + } + if let taskNeedNewBodyStream = taskNeedNewBodyStream { completionHandler(taskNeedNewBodyStream(session, task)) } else if let delegate = self[task] { @@ -452,6 +513,8 @@ public class Manager { delegate.URLSession(session, task: task, didCompleteWithError: error) } + NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidComplete, object: task) + self[task] = nil } @@ -462,6 +525,10 @@ public class Manager { /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`. public var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)? + /// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:` and + /// requires caller to call the `completionHandler`. + public var dataTaskDidReceiveResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSURLResponse, NSURLSessionResponseDisposition -> Void) -> Void)? + /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`. public var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)? @@ -469,7 +536,11 @@ public class Manager { public var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)? /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`. - public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse!)? + public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)? + + /// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:` and + /// requires caller to call the `completionHandler`. + public var dataTaskWillCacheResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse, NSCachedURLResponse? -> Void) -> Void)? // MARK: Delegate Methods @@ -487,8 +558,13 @@ public class Manager { session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, - completionHandler: ((NSURLSessionResponseDisposition) -> Void)) + completionHandler: NSURLSessionResponseDisposition -> Void) { + guard dataTaskDidReceiveResponseWithCompletion == nil else { + dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler) + return + } + var disposition: NSURLSessionResponseDisposition = .Allow if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { @@ -550,8 +626,13 @@ public class Manager { session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, - completionHandler: ((NSCachedURLResponse?) -> Void)) + completionHandler: NSCachedURLResponse? -> Void) { + guard dataTaskWillCacheResponseWithCompletion == nil else { + dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler) + return + } + if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) } else if let delegate = self[dataTask] as? Request.DataTaskDelegate { @@ -674,17 +755,21 @@ public class Manager { // MARK: - NSObject public override func respondsToSelector(selector: Selector) -> Bool { + #if !os(OSX) + if selector == #selector(NSURLSessionDelegate.URLSessionDidFinishEventsForBackgroundURLSession(_:)) { + return sessionDidFinishEventsForBackgroundURLSession != nil + } + #endif + switch selector { - case "URLSession:didBecomeInvalidWithError:": + case #selector(NSURLSessionDelegate.URLSession(_:didBecomeInvalidWithError:)): return sessionDidBecomeInvalidWithError != nil - case "URLSession:didReceiveChallenge:completionHandler:": - return sessionDidReceiveChallenge != nil - case "URLSessionDidFinishEventsForBackgroundURLSession:": - return sessionDidFinishEventsForBackgroundURLSession != nil - case "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:": - return taskWillPerformHTTPRedirection != nil - case "URLSession:dataTask:didReceiveResponse:completionHandler:": - return dataTaskDidReceiveResponse != nil + case #selector(NSURLSessionDelegate.URLSession(_:didReceiveChallenge:completionHandler:)): + return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil) + case #selector(NSURLSessionTaskDelegate.URLSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)): + return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil) + case #selector(NSURLSessionDataDelegate.URLSession(_:dataTask:didReceiveResponse:completionHandler:)): + return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil) default: return self.dynamicType.instancesRespondToSelector(selector) } diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift index 8c37f164e7e..b4087eca830 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift @@ -1,24 +1,26 @@ -// MultipartFormData.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// MultipartFormData.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -217,7 +219,7 @@ public class MultipartFormData { appendBodyPart(fileURL: fileURL, name: name, fileName: fileName, mimeType: mimeType) } else { let failureReason = "Failed to extract the fileName of the provided URL: \(fileURL)" - setBodyPartError(Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)) + setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason) } } @@ -245,8 +247,7 @@ public class MultipartFormData { guard fileURL.fileURL else { let failureReason = "The file URL does not point to a file URL: \(fileURL)" - let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) - setBodyPartError(error) + setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason) return } @@ -261,8 +262,7 @@ public class MultipartFormData { } guard isReachable else { - let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)") - setBodyPartError(error) + setBodyPartError(code: NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)") return } @@ -277,8 +277,7 @@ public class MultipartFormData { where NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) && !isDirectory else { let failureReason = "The file URL is a directory, not a file: \(fileURL)" - let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) - setBodyPartError(error) + setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason) return } @@ -301,8 +300,7 @@ public class MultipartFormData { guard let length = bodyContentLength else { let failureReason = "Could not fetch attributes from the file URL: \(fileURL)" - let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) - setBodyPartError(error) + setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason) return } @@ -312,8 +310,7 @@ public class MultipartFormData { guard let stream = NSInputStream(URL: fileURL) else { let failureReason = "Failed to create an input stream from the file URL: \(fileURL)" - let error = Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason) - setBodyPartError(error) + setBodyPartError(code: NSURLErrorCannotOpenFile, failureReason: failureReason) return } @@ -413,10 +410,10 @@ public class MultipartFormData { if let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path) { let failureReason = "A file already exists at the given file URL: \(fileURL)" - throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) + throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorBadURL, failureReason: failureReason) } else if !fileURL.fileURL { let failureReason = "The URL does not point to a valid file: \(fileURL)" - throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) + throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorBadURL, failureReason: failureReason) } let outputStream: NSOutputStream @@ -425,10 +422,9 @@ public class MultipartFormData { outputStream = possibleOutputStream } else { let failureReason = "Failed to create an output stream with the given URL: \(fileURL)" - throw Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason) + throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorCannotOpenFile, failureReason: failureReason) } - outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) outputStream.open() self.bodyParts.first?.hasInitialBoundary = true @@ -439,7 +435,6 @@ public class MultipartFormData { } outputStream.close() - outputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) } // MARK: - Private - Body Part Encoding @@ -476,7 +471,6 @@ public class MultipartFormData { private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) throws -> NSData { let inputStream = bodyPart.bodyStream - inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) inputStream.open() var error: NSError? @@ -495,7 +489,7 @@ public class MultipartFormData { encoded.appendBytes(buffer, length: bytesRead) } else if bytesRead < 0 { let failureReason = "Failed to read from input stream: \(inputStream)" - error = Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason) + error = Error.error(domain: NSURLErrorDomain, code: .InputStreamReadFailed, failureReason: failureReason) break } else { break @@ -503,7 +497,6 @@ public class MultipartFormData { } inputStream.close() - inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) if let error = error { throw error @@ -537,7 +530,6 @@ public class MultipartFormData { private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { let inputStream = bodyPart.bodyStream - inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) inputStream.open() while inputStream.hasBytesAvailable { @@ -556,14 +548,13 @@ public class MultipartFormData { try writeBuffer(&buffer, toOutputStream: outputStream) } else if bytesRead < 0 { let failureReason = "Failed to read from input stream: \(inputStream)" - throw Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason) + throw Error.error(domain: NSURLErrorDomain, code: .InputStreamReadFailed, failureReason: failureReason) } else { break } } inputStream.close() - inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) } private func writeFinalBoundaryDataForBodyPart( @@ -598,7 +589,7 @@ public class MultipartFormData { if bytesWritten < 0 { let failureReason = "Failed to write to output stream: \(outputStream)" - throw Error.errorWithCode(.OutputStreamWriteFailed, failureReason: failureReason) + throw Error.error(domain: NSURLErrorDomain, code: .OutputStreamWriteFailed, failureReason: failureReason) } bytesToWrite -= bytesWritten @@ -661,9 +652,8 @@ public class MultipartFormData { // MARK: - Private - Errors - private func setBodyPartError(error: NSError) { - if bodyPartError == nil { - bodyPartError = error - } + private func setBodyPartError(code code: Int, failureReason: String) { + guard bodyPartError == nil else { return } + bodyPartError = Error.error(domain: NSURLErrorDomain, code: code, failureReason: failureReason) } } diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/NetworkReachabilityManager.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/NetworkReachabilityManager.swift new file mode 100644 index 00000000000..1e5c7b030d3 --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/NetworkReachabilityManager.swift @@ -0,0 +1,244 @@ +// +// NetworkReachabilityManager.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#if !os(watchOS) + +import Foundation +import SystemConfiguration + +/** + The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and + WiFi network interfaces. + + Reachability can be used to determine background information about why a network operation failed, or to retry + network requests when a connection is established. It should not be used to prevent a user from initiating a network + request, as it's possible that an initial request may be required to establish reachability. +*/ +public class NetworkReachabilityManager { + /** + Defines the various states of network reachability. + + - Unknown: It is unknown whether the network is reachable. + - NotReachable: The network is not reachable. + - ReachableOnWWAN: The network is reachable over the WWAN connection. + - ReachableOnWiFi: The network is reachable over the WiFi connection. + */ + public enum NetworkReachabilityStatus { + case Unknown + case NotReachable + case Reachable(ConnectionType) + } + + /** + Defines the various connection types detected by reachability flags. + + - EthernetOrWiFi: The connection type is either over Ethernet or WiFi. + - WWAN: The connection type is a WWAN connection. + */ + public enum ConnectionType { + case EthernetOrWiFi + case WWAN + } + + /// A closure executed when the network reachability status changes. The closure takes a single argument: the + /// network reachability status. + public typealias Listener = NetworkReachabilityStatus -> Void + + // MARK: - Properties + + /// Whether the network is currently reachable. + public var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi } + + /// Whether the network is currently reachable over the WWAN interface. + public var isReachableOnWWAN: Bool { return networkReachabilityStatus == .Reachable(.WWAN) } + + /// Whether the network is currently reachable over Ethernet or WiFi interface. + public var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .Reachable(.EthernetOrWiFi) } + + /// The current network reachability status. + public var networkReachabilityStatus: NetworkReachabilityStatus { + guard let flags = self.flags else { return .Unknown } + return networkReachabilityStatusForFlags(flags) + } + + /// The dispatch queue to execute the `listener` closure on. + public var listenerQueue: dispatch_queue_t = dispatch_get_main_queue() + + /// A closure executed when the network reachability status changes. + public var listener: Listener? + + private var flags: SCNetworkReachabilityFlags? { + var flags = SCNetworkReachabilityFlags() + + if SCNetworkReachabilityGetFlags(reachability, &flags) { + return flags + } + + return nil + } + + private let reachability: SCNetworkReachability + private var previousFlags: SCNetworkReachabilityFlags + + // MARK: - Initialization + + /** + Creates a `NetworkReachabilityManager` instance with the specified host. + + - parameter host: The host used to evaluate network reachability. + + - returns: The new `NetworkReachabilityManager` instance. + */ + public convenience init?(host: String) { + guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil } + self.init(reachability: reachability) + } + + /** + Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0. + + Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing + status of the device, both IPv4 and IPv6. + + - returns: The new `NetworkReachabilityManager` instance. + */ + public convenience init?() { + var address = sockaddr_in() + address.sin_len = UInt8(sizeofValue(address)) + address.sin_family = sa_family_t(AF_INET) + + guard let reachability = withUnsafePointer(&address, { + SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) + }) else { return nil } + + self.init(reachability: reachability) + } + + private init(reachability: SCNetworkReachability) { + self.reachability = reachability + self.previousFlags = SCNetworkReachabilityFlags() + } + + deinit { + stopListening() + } + + // MARK: - Listening + + /** + Starts listening for changes in network reachability status. + + - returns: `true` if listening was started successfully, `false` otherwise. + */ + public func startListening() -> Bool { + var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) + context.info = UnsafeMutablePointer(Unmanaged.passUnretained(self).toOpaque()) + + let callbackEnabled = SCNetworkReachabilitySetCallback( + reachability, + { (_, flags, info) in + let reachability = Unmanaged.fromOpaque(COpaquePointer(info)).takeUnretainedValue() + reachability.notifyListener(flags) + }, + &context + ) + + let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue) + + dispatch_async(listenerQueue) { + self.previousFlags = SCNetworkReachabilityFlags() + self.notifyListener(self.flags ?? SCNetworkReachabilityFlags()) + } + + return callbackEnabled && queueEnabled + } + + /** + Stops listening for changes in network reachability status. + */ + public func stopListening() { + SCNetworkReachabilitySetCallback(reachability, nil, nil) + SCNetworkReachabilitySetDispatchQueue(reachability, nil) + } + + // MARK: - Internal - Listener Notification + + func notifyListener(flags: SCNetworkReachabilityFlags) { + guard previousFlags != flags else { return } + previousFlags = flags + + listener?(networkReachabilityStatusForFlags(flags)) + } + + // MARK: - Internal - Network Reachability Status + + func networkReachabilityStatusForFlags(flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus { + guard flags.contains(.Reachable) else { return .NotReachable } + + var networkStatus: NetworkReachabilityStatus = .NotReachable + + if !flags.contains(.ConnectionRequired) { networkStatus = .Reachable(.EthernetOrWiFi) } + + if flags.contains(.ConnectionOnDemand) || flags.contains(.ConnectionOnTraffic) { + if !flags.contains(.InterventionRequired) { networkStatus = .Reachable(.EthernetOrWiFi) } + } + + #if os(iOS) + if flags.contains(.IsWWAN) { networkStatus = .Reachable(.WWAN) } + #endif + + return networkStatus + } +} + +// MARK: - + +extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {} + +/** + Returns whether the two network reachability status values are equal. + + - parameter lhs: The left-hand side value to compare. + - parameter rhs: The right-hand side value to compare. + + - returns: `true` if the two values are equal, `false` otherwise. +*/ +public func ==( + lhs: NetworkReachabilityManager.NetworkReachabilityStatus, + rhs: NetworkReachabilityManager.NetworkReachabilityStatus) + -> Bool +{ + switch (lhs, rhs) { + case (.Unknown, .Unknown): + return true + case (.NotReachable, .NotReachable): + return true + case let (.Reachable(lhsConnectionType), .Reachable(rhsConnectionType)): + return lhsConnectionType == rhsConnectionType + default: + return false + } +} + +#endif diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Notifications.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Notifications.swift new file mode 100644 index 00000000000..cece87a170d --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Notifications.swift @@ -0,0 +1,47 @@ +// +// Notifications.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Contains all the `NSNotification` names posted by Alamofire with descriptions of each notification's payload. +public struct Notifications { + /// Used as a namespace for all `NSURLSessionTask` related notifications. + public struct Task { + /// Notification posted when an `NSURLSessionTask` is resumed. The notification `object` contains the resumed + /// `NSURLSessionTask`. + public static let DidResume = "com.alamofire.notifications.task.didResume" + + /// Notification posted when an `NSURLSessionTask` is suspended. The notification `object` contains the + /// suspended `NSURLSessionTask`. + public static let DidSuspend = "com.alamofire.notifications.task.didSuspend" + + /// Notification posted when an `NSURLSessionTask` is cancelled. The notification `object` contains the + /// cancelled `NSURLSessionTask`. + public static let DidCancel = "com.alamofire.notifications.task.didCancel" + + /// Notification posted when an `NSURLSessionTask` is completed. The notification `object` contains the + /// completed `NSURLSessionTask`. + public static let DidComplete = "com.alamofire.notifications.task.didComplete" + } +} diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift index d56d2d6c3a7..32e63d9b7be 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift @@ -1,24 +1,26 @@ -// ParameterEncoding.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// ParameterEncoding.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -69,8 +71,8 @@ public enum ParameterEncoding { /** Creates a URL request by encoding parameters and applying them onto an existing request. - - parameter URLRequest: The request to have parameters applied - - parameter parameters: The parameters to apply + - parameter URLRequest: The request to have parameters applied. + - parameter parameters: The parameters to apply. - returns: A tuple containing the constructed request and the error that occurred during parameter encoding, if any. @@ -82,9 +84,7 @@ public enum ParameterEncoding { { var mutableURLRequest = URLRequest.URLRequest - guard let parameters = parameters where !parameters.isEmpty else { - return (mutableURLRequest, nil) - } + guard let parameters = parameters else { return (mutableURLRequest, nil) } var encodingError: NSError? = nil @@ -118,7 +118,10 @@ public enum ParameterEncoding { } if let method = Method(rawValue: mutableURLRequest.HTTPMethod) where encodesParametersInURL(method) { - if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) { + if let + URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) + where !parameters.isEmpty + { let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) URLComponents.percentEncodedQuery = percentEncodedQuery mutableURLRequest.URL = URLComponents.URL @@ -141,7 +144,10 @@ public enum ParameterEncoding { let options = NSJSONWritingOptions() let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: options) - mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil { + mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + mutableURLRequest.HTTPBody = data } catch { encodingError = error as NSError @@ -153,7 +159,11 @@ public enum ParameterEncoding { format: format, options: options ) - mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") + + if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil { + mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") + } + mutableURLRequest.HTTPBody = data } catch { encodingError = error as NSError @@ -219,7 +229,7 @@ public enum ParameterEncoding { //========================================================================================================== // // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few - // hundred Chinense characters causes various malloc error crashes. To avoid this issue until iOS 8 is no + // hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more // info, please refer to: // @@ -236,7 +246,7 @@ public enum ParameterEncoding { while index != string.endIndex { let startIndex = index let endIndex = index.advancedBy(batchSize, limit: string.endIndex) - let range = Range(start: startIndex, end: endIndex) + let range = startIndex.. [String: String] { + guard let data = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding) else { return [:] } + + let credential = data.base64EncodedStringWithOptions([]) + + return ["Authorization": "Basic \(credential)"] + } + // MARK: - Progress /** @@ -149,17 +172,21 @@ public class Request { // MARK: - State /** - Suspends the request. + Resumes the request. */ - public func suspend() { - task.suspend() + public func resume() { + if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() } + + task.resume() + NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidResume, object: task) } /** - Resumes the request. + Suspends the request. */ - public func resume() { - task.resume() + public func suspend() { + task.suspend() + NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidSuspend, object: task) } /** @@ -176,6 +203,8 @@ public class Request { } else { task.cancel() } + + NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidCancel, object: task) } // MARK: - TaskDelegate @@ -195,6 +224,7 @@ public class Request { var data: NSData? { return nil } var error: NSError? + var initialResponseTime: CFAbsoluteTime? var credential: NSURLCredential? init(task: NSURLSessionTask) { @@ -272,7 +302,7 @@ public class Request { } } else { if challenge.previousFailureCount > 0 { - disposition = .CancelAuthenticationChallenge + disposition = .RejectProtectionSpace } else { credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace) @@ -381,6 +411,8 @@ public class Request { } func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + if let dataTaskDidReceiveData = dataTaskDidReceiveData { dataTaskDidReceiveData(session, dataTask, data) } else { @@ -470,7 +502,7 @@ extension Request: CustomDebugStringConvertible { let protectionSpace = NSURLProtectionSpace( host: host, port: URL.port?.integerValue ?? 0, - `protocol`: URL.scheme, + protocol: URL.scheme, realm: host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic ) @@ -496,33 +528,31 @@ extension Request: CustomDebugStringConvertible { } } - if let headerFields = request.allHTTPHeaderFields { - for (field, value) in headerFields { - switch field { - case "Cookie": - continue - default: - components.append("-H \"\(field): \(value)\"") - } + var headers: [NSObject: AnyObject] = [:] + + if let additionalHeaders = session.configuration.HTTPAdditionalHeaders { + for (field, value) in additionalHeaders where field != "Cookie" { + headers[field] = value } } - if let additionalHeaders = session.configuration.HTTPAdditionalHeaders { - for (field, value) in additionalHeaders { - switch field { - case "Cookie": - continue - default: - components.append("-H \"\(field): \(value)\"") - } + if let headerFields = request.allHTTPHeaderFields { + for (field, value) in headerFields where field != "Cookie" { + headers[field] = value } } + for (field, value) in headers { + components.append("-H \"\(field): \(value)\"") + } + if let HTTPBodyData = request.HTTPBody, HTTPBody = String(data: HTTPBodyData, encoding: NSUTF8StringEncoding) { - let escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\"", withString: "\\\"") + var escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\\\"", withString: "\\\\\"") + escapedBody = escapedBody.stringByReplacingOccurrencesOfString("\"", withString: "\\\"") + components.append("-d \"\(escapedBody)\"") } diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Response.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Response.swift index fa2fffb3dea..dd700bb1c82 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Response.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Response.swift @@ -1,24 +1,26 @@ -// Response.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Response.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -36,6 +38,9 @@ public struct Response { /// The result of response serialization. public let result: Result + /// The timeline of the complete lifecycle of the `Request`. + public let timeline: Timeline + /** Initializes the `Response` instance with the specified URL request, URL response, server data and response serialization result. @@ -44,14 +49,22 @@ public struct Response { - parameter response: The server's response to the URL request. - parameter data: The data returned by the server. - parameter result: The result of response serialization. - + - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. + - returns: the new `Response` instance. */ - public init(request: NSURLRequest?, response: NSHTTPURLResponse?, data: NSData?, result: Result) { + public init( + request: NSURLRequest?, + response: NSHTTPURLResponse?, + data: NSData?, + result: Result, + timeline: Timeline = Timeline()) + { self.request = request self.response = response self.data = data self.result = result + self.timeline = timeline } } @@ -77,6 +90,7 @@ extension Response: CustomDebugStringConvertible { output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") output.append("[Data]: \(data?.length ?? 0) bytes") output.append("[Result]: \(result.debugDescription)") + output.append("[Timeline]: \(timeline.debugDescription)") return output.joinWithSeparator("\n") } diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift index 4aaacf61e31..5b7b61f9002 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift @@ -1,24 +1,26 @@ -// ResponseSerialization.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// ResponseSerialization.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -29,10 +31,10 @@ import Foundation */ public protocol ResponseSerializerType { /// The type of serialized object to be created by this `ResponseSerializerType`. - typealias SerializedObject + associatedtype SerializedObject /// The type of error to be created by this `ResponseSerializer` if serialization fails. - typealias ErrorObject: ErrorType + associatedtype ErrorObject: ErrorType /** A closure used by response handlers that takes a request, response, data and error and returns a result. @@ -119,16 +121,25 @@ extension Request { self.delegate.error ) - dispatch_async(queue ?? dispatch_get_main_queue()) { - let response = Response( - request: self.request, - response: self.response, - data: self.delegate.data, - result: result - ) + let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent() + let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime - completionHandler(response) - } + let timeline = Timeline( + requestStartTime: self.startTime ?? CFAbsoluteTimeGetCurrent(), + initialResponseTime: initialResponseTime, + requestCompletedTime: requestCompletedTime, + serializationCompletedTime: CFAbsoluteTimeGetCurrent() + ) + + let response = Response( + request: self.request, + response: self.response, + data: self.delegate.data, + result: result, + timeline: timeline + ) + + dispatch_async(queue ?? dispatch_get_main_queue()) { completionHandler(response) } } return self @@ -152,7 +163,7 @@ extension Request { guard let validData = data else { let failureReason = "Data could not be serialized. Input data was nil." - let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason) + let error = Error.error(code: .DataSerializationFailed, failureReason: failureReason) return .Failure(error) } @@ -167,8 +178,12 @@ extension Request { - returns: The request. */ - public func responseData(completionHandler: Response -> Void) -> Self { - return response(responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler) + public func responseData( + queue queue: dispatch_queue_t? = nil, + completionHandler: Response -> Void) + -> Self + { + return response(queue: queue, responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler) } } @@ -186,7 +201,7 @@ extension Request { - returns: A string response serializer. */ public static func stringResponseSerializer( - var encoding encoding: NSStringEncoding? = nil) + encoding encoding: NSStringEncoding? = nil) -> ResponseSerializer { return ResponseSerializer { _, response, data, error in @@ -196,23 +211,25 @@ extension Request { guard let validData = data else { let failureReason = "String could not be serialized. Input data was nil." - let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason) + let error = Error.error(code: .StringSerializationFailed, failureReason: failureReason) return .Failure(error) } - - if let encodingName = response?.textEncodingName where encoding == nil { - encoding = CFStringConvertEncodingToNSStringEncoding( + + var convertedEncoding = encoding + + if let encodingName = response?.textEncodingName where convertedEncoding == nil { + convertedEncoding = CFStringConvertEncodingToNSStringEncoding( CFStringConvertIANACharSetNameToEncoding(encodingName) ) } - let actualEncoding = encoding ?? NSISOLatin1StringEncoding + let actualEncoding = convertedEncoding ?? NSISOLatin1StringEncoding if let string = String(data: validData, encoding: actualEncoding) { return .Success(string) } else { let failureReason = "String could not be serialized with encoding: \(actualEncoding)" - let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason) + let error = Error.error(code: .StringSerializationFailed, failureReason: failureReason) return .Failure(error) } } @@ -229,11 +246,13 @@ extension Request { - returns: The request. */ public func responseString( - encoding encoding: NSStringEncoding? = nil, + queue queue: dispatch_queue_t? = nil, + encoding: NSStringEncoding? = nil, completionHandler: Response -> Void) -> Self { return response( + queue: queue, responseSerializer: Request.stringResponseSerializer(encoding: encoding), completionHandler: completionHandler ) @@ -263,7 +282,7 @@ extension Request { guard let validData = data where validData.length > 0 else { let failureReason = "JSON could not be serialized. Input data was nil or zero length." - let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason) + let error = Error.error(code: .JSONSerializationFailed, failureReason: failureReason) return .Failure(error) } @@ -285,11 +304,13 @@ extension Request { - returns: The request. */ public func responseJSON( - options options: NSJSONReadingOptions = .AllowFragments, + queue queue: dispatch_queue_t? = nil, + options: NSJSONReadingOptions = .AllowFragments, completionHandler: Response -> Void) -> Self { return response( + queue: queue, responseSerializer: Request.JSONResponseSerializer(options: options), completionHandler: completionHandler ) @@ -319,7 +340,7 @@ extension Request { guard let validData = data where validData.length > 0 else { let failureReason = "Property list could not be serialized. Input data was nil or zero length." - let error = Error.errorWithCode(.PropertyListSerializationFailed, failureReason: failureReason) + let error = Error.error(code: .PropertyListSerializationFailed, failureReason: failureReason) return .Failure(error) } @@ -343,11 +364,13 @@ extension Request { - returns: The request. */ public func responsePropertyList( - options options: NSPropertyListReadOptions = NSPropertyListReadOptions(), + queue queue: dispatch_queue_t? = nil, + options: NSPropertyListReadOptions = NSPropertyListReadOptions(), completionHandler: Response -> Void) -> Self { return response( + queue: queue, responseSerializer: Request.propertyListResponseSerializer(options: options), completionHandler: completionHandler ) diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Result.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Result.swift index a8557cabb42..ed1df0fc845 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Result.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Result.swift @@ -1,24 +1,26 @@ -// Result.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Result.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift index 07cd848a606..44ba100be43 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift @@ -1,24 +1,26 @@ -// ServerTrustPolicy.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// ServerTrustPolicy.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift index bc9ee450c5a..07ebe3374ff 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift @@ -1,30 +1,32 @@ -// Stream.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Stream.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation #if !os(watchOS) -@available(iOS 9.0, OSX 10.11, *) +@available(iOS 9.0, OSX 10.11, tvOS 9.0, *) extension Manager { private enum Streamable { case Stream(String, Int) @@ -82,7 +84,7 @@ extension Manager { // MARK: - -@available(iOS 9.0, OSX 10.11, *) +@available(iOS 9.0, OSX 10.11, tvOS 9.0, *) extension Manager.SessionDelegate: NSURLSessionStreamDelegate { // MARK: Override Closures diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Timeline.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Timeline.swift new file mode 100644 index 00000000000..95936827285 --- /dev/null +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Timeline.swift @@ -0,0 +1,138 @@ +// +// Timeline.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Responsible for computing the timing metrics for the complete lifecycle of a `Request`. +public struct Timeline { + /// The time the request was initialized. + public let requestStartTime: CFAbsoluteTime + + /// The time the first bytes were received from or sent to the server. + public let initialResponseTime: CFAbsoluteTime + + /// The time when the request was completed. + public let requestCompletedTime: CFAbsoluteTime + + /// The time when the response serialization was completed. + public let serializationCompletedTime: CFAbsoluteTime + + /// The time interval in seconds from the time the request started to the initial response from the server. + public let latency: NSTimeInterval + + /// The time interval in seconds from the time the request started to the time the request completed. + public let requestDuration: NSTimeInterval + + /// The time interval in seconds from the time the request completed to the time response serialization completed. + public let serializationDuration: NSTimeInterval + + /// The time interval in seconds from the time the request started to the time response serialization completed. + public let totalDuration: NSTimeInterval + + /** + Creates a new `Timeline` instance with the specified request times. + + - parameter requestStartTime: The time the request was initialized. Defaults to `0.0`. + - parameter initialResponseTime: The time the first bytes were received from or sent to the server. + Defaults to `0.0`. + - parameter requestCompletedTime: The time when the request was completed. Defaults to `0.0`. + - parameter serializationCompletedTime: The time when the response serialization was completed. Defaults + to `0.0`. + + - returns: The new `Timeline` instance. + */ + public init( + requestStartTime: CFAbsoluteTime = 0.0, + initialResponseTime: CFAbsoluteTime = 0.0, + requestCompletedTime: CFAbsoluteTime = 0.0, + serializationCompletedTime: CFAbsoluteTime = 0.0) + { + self.requestStartTime = requestStartTime + self.initialResponseTime = initialResponseTime + self.requestCompletedTime = requestCompletedTime + self.serializationCompletedTime = serializationCompletedTime + + self.latency = initialResponseTime - requestStartTime + self.requestDuration = requestCompletedTime - requestStartTime + self.serializationDuration = serializationCompletedTime - requestCompletedTime + self.totalDuration = serializationCompletedTime - requestStartTime + } +} + +// MARK: - CustomStringConvertible + +extension Timeline: CustomStringConvertible { + /// The textual representation used when written to an output stream, which includes the latency, the request + /// duration and the total duration. + public var description: String { + let latency = String(format: "%.3f", self.latency) + let requestDuration = String(format: "%.3f", self.requestDuration) + let serializationDuration = String(format: "%.3f", self.serializationDuration) + let totalDuration = String(format: "%.3f", self.totalDuration) + + // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is + // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. + let timings = [ + "\"Latency\": " + latency + " secs", + "\"Request Duration\": " + requestDuration + " secs", + "\"Serialization Duration\": " + serializationDuration + " secs", + "\"Total Duration\": " + totalDuration + " secs" + ] + + return "Timeline: { " + timings.joinWithSeparator(", ") + " }" + } +} + +// MARK: - CustomDebugStringConvertible + +extension Timeline: CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, which includes the request start time, the + /// initial response time, the request completed time, the serialization completed time, the latency, the request + /// duration and the total duration. + public var debugDescription: String { + let requestStartTime = String(format: "%.3f", self.requestStartTime) + let initialResponseTime = String(format: "%.3f", self.initialResponseTime) + let requestCompletedTime = String(format: "%.3f", self.requestCompletedTime) + let serializationCompletedTime = String(format: "%.3f", self.serializationCompletedTime) + let latency = String(format: "%.3f", self.latency) + let requestDuration = String(format: "%.3f", self.requestDuration) + let serializationDuration = String(format: "%.3f", self.serializationDuration) + let totalDuration = String(format: "%.3f", self.totalDuration) + + // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is + // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. + let timings = [ + "\"Request Start Time\": " + requestStartTime, + "\"Initial Response Time\": " + initialResponseTime, + "\"Request Completed Time\": " + requestCompletedTime, + "\"Serialization Completed Time\": " + serializationCompletedTime, + "\"Latency\": " + latency + " secs", + "\"Request Duration\": " + requestDuration + " secs", + "\"Serialization Duration\": " + serializationDuration + " secs", + "\"Total Duration\": " + totalDuration + " secs" + ] + + return "Timeline: { " + timings.joinWithSeparator(", ") + " }" + } +} diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift index ee6b34ced5b..7b31ba53073 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift @@ -1,24 +1,26 @@ -// Upload.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Upload.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -359,6 +361,8 @@ extension Request { totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + if let taskDidSendBodyData = taskDidSendBodyData { taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) } else { diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift index 71d21e1afa6..e90db2d4a10 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift @@ -1,24 +1,26 @@ -// Validation.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Validation.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -80,7 +82,17 @@ extension Request { return .Success } else { let failureReason = "Response status code was unacceptable: \(response.statusCode)" - return .Failure(Error.errorWithCode(.StatusCodeValidationFailed, failureReason: failureReason)) + + let error = NSError( + domain: Error.Domain, + code: Error.Code.StatusCodeValidationFailed.rawValue, + userInfo: [ + NSLocalizedFailureReasonErrorKey: failureReason, + Error.UserInfoKeys.StatusCode: response.statusCode + ] + ) + + return .Failure(error) } } } @@ -149,18 +161,31 @@ extension Request { } } + let contentType: String let failureReason: String if let responseContentType = response.MIMEType { + contentType = responseContentType + failureReason = ( "Response content type \"\(responseContentType)\" does not match any acceptable " + "content types: \(acceptableContentTypes)" ) } else { + contentType = "" failureReason = "Response content type was missing and acceptable content type does not match \"*/*\"" } - return .Failure(Error.errorWithCode(.ContentTypeValidationFailed, failureReason: failureReason)) + let error = NSError( + domain: Error.Domain, + code: Error.Code.ContentTypeValidationFailed.rawValue, + userInfo: [ + NSLocalizedFailureReasonErrorKey: failureReason, + Error.UserInfoKeys.ContentType: contentType + ] + ) + + return .Failure(error) } } diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json index addbe0f7543..4cdc0899bd5 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json @@ -16,7 +16,7 @@ "source_files": "PetstoreClient/Classes/Swaggers/**/*.swift", "dependencies": { "Alamofire": [ - "~> 3.1.5" + "~> 3.4.1" ] } } diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Manifest.lock b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Manifest.lock index ac8d6671916..f5b98a5d811 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Manifest.lock +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Manifest.lock @@ -1,18 +1,18 @@ PODS: - - Alamofire (3.1.5) + - Alamofire (3.4.1) - PetstoreClient (0.0.1): - - Alamofire (~> 3.1.5) + - Alamofire (~> 3.4.1) DEPENDENCIES: - PetstoreClient (from `../`) EXTERNAL SOURCES: PetstoreClient: - :path: ../ + :path: "../" SPEC CHECKSUMS: - Alamofire: 5f730ba29fd113b7ddd71c1e65d0c630acf5d7b0 - PetstoreClient: 575f4a5776e6a693e70f9d14bae0aabd8c467111 + Alamofire: 01a82e2f6c0f860ade35534c8dd88be61bdef40c + PetstoreClient: 7489b461499be1b2c4e0ed6624ca76c8db506297 PODFILE CHECKSUM: 84472aca2a88b7f7ed9fcd63e9f5fdb5ad4aab94 diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj index 98d247e012c..1b141de2352 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj @@ -7,46 +7,49 @@ objects = { /* Begin PBXBuildFile section */ - 03F494989CC1A8857B68A317D5D6860F /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8AE82608C8C2A46981A07D7E422BEB45 /* Response.swift */; }; - 0681ADC8BAE2C3185F13487BAAB4D9DD /* Upload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 948996616B0A38BD6FE8C4CB309CC964 /* Upload.swift */; }; - 0BD8B4E55E72312366130E97A1204CD8 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 41EA265E42E2F53F87DD98BDA6BDEFD5 /* Foundation.framework */; }; + 095406039B4D371E48D08B38A2975AC8 /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D1F9022AC9979CD59E8F83962DAF51D /* Error.swift */; }; 121BA006C3D23D9290D868AA19E4BFBA /* Category.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4DF0604EDC1460935E6E445A47023A4 /* Category.swift */; }; + 16102E4E35FAA0FC4161282FECE56469 /* Timeline.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0DBA7F3642776C1964512C9A38829081 /* Timeline.swift */; }; 1ED3811BA132299733D3A71543A4339C /* Models.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F0266C5AE0B23A436291F6647902086 /* Models.swift */; }; 2737DA3907C231E7CCCBF6075FCE4AB3 /* UserAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 552D15E0340BF58CC1922B82E864AEC9 /* UserAPI.swift */; }; - 2C5450AC69398958CF6F7539EF7D99E5 /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 4FC4583A4BD15196E6859EA5E990AD3F /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 2D3405986FC586FA6C0A5E0B6BA7E64E /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 658CBED44D4009D80F990A188D7A8B3F /* Validation.swift */; }; + 34CCDCA848A701466256BC2927DA8856 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = F9278DA00F41E390EE68B6F3C8161C54 /* NetworkReachabilityManager.swift */; }; 37D0F7B54F7677AEB499F204040C6DA1 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 41EA265E42E2F53F87DD98BDA6BDEFD5 /* Foundation.framework */; }; 388FE86EB5084CB37EC19ED82DE8242C /* AlamofireImplementations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 92734297B64DFE0EB0EDE1EA821163DB /* AlamofireImplementations.swift */; }; 39EBC7781F42F6F790D3E54F3E8D8ED1 /* Tag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 211F73A46D90346F7FC6D0D29640EE4F /* Tag.swift */; }; 3CA0C61EB5AA01268C12B7E61FF59C56 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 41EA265E42E2F53F87DD98BDA6BDEFD5 /* Foundation.framework */; }; + 3EA8F215C9C1432D74E5CCA4834AA8C0 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2959D264574F227296E36F7CDF2E4F4F /* ResponseSerialization.swift */; }; + 4081EA628AF0B73AC51FFB9D7AB3B89E /* Manager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 101C763FD5409006D69EDB82815E4A61 /* Manager.swift */; }; 40AED0FDEFFB776F649058C34D72BB95 /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 706C7AFFE37BA158C3553250F4B5FAED /* Alamofire.framework */; }; 45961D28C6B8E4BAB87690F714B8727B /* PetstoreClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */; }; - 4DE5FCC41D100B113B6645EA64410F16 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5465E2051CE332BA7D4E0595F9B44718 /* ParameterEncoding.swift */; }; 562F951C949B9293B74C2E5D86BEF1BC /* StoreAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A3E5E3CD673B025FD8AC260E67AB47E /* StoreAPI.swift */; }; 59C731A013A3F62794AABFB1C1025B4F /* APIs.swift in Sources */ = {isa = PBXBuildFile; fileRef = D8072E1108951F272C003553FC8926C7 /* APIs.swift */; }; + 5BC19E6E0F199276003F0AF96838BCE5 /* Upload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 09DC3EB7B14F56C5823591E484CC06DC /* Upload.swift */; }; + 5CB05FBCB32D21E194B5ECF680CB6AE0 /* Download.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50BCAC7849E43619A0E6BA6D3291D195 /* Download.swift */; }; + 62E8346F03C03E7F4D631361F325689E /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = DDC2C7A48545D8C54D52554343225FB8 /* Response.swift */; }; + 7B48852C4D848FA2DA416A98F6425869 /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E07E98001DB6C163294A39CAB05963D /* ServerTrustPolicy.swift */; }; 7D0C7E08FEC92B9C59B3EAFB8D15026D /* APIHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = D2BAD338E56EF3CAA6E54490FE0C5DF9 /* APIHelper.swift */; }; - 80F496237530D382A045A29654D8C11C /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 52836A3E223CCB5C120D4BE7D37AC1BF /* ServerTrustPolicy.swift */; }; 816BE1BBC1F4E434D7BD3F793F38B347 /* Pods-SwaggerClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 82971968CBDAB224212EEB4607C9FB8D /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7835749D1C4FA403E4BB17A0C787EDCA /* Result.swift */; }; - 8399DBEE3E2D98EB1F466132E476F4D9 /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 10653C142FFDF1986227894BF0317944 /* MultipartFormData.swift */; }; 897283A0B7F5299913327CC8FD6CC997 /* Pods-SwaggerClientTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8EB11202167FCDDF1257AAAB1D1FB244 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7ED443D528393D61A04FBD88603DE5F3 /* Alamofire.swift */; }; 909E1A21FF97D3DFD0E2707B0E078686 /* PetAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 261F03A3C73374FD19333EEA59CCD59F /* PetAPI.swift */; }; + 91C09AC2A52ED69A27C8D923139A006F /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 41EA265E42E2F53F87DD98BDA6BDEFD5 /* Foundation.framework */; }; 93A9E4EBCD41B6C350DB55CB545D797E /* User.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B248364ABF60ACD7DB31A17DCFDFD0C /* User.swift */; }; - A2C172FE407C0BC3478ADCA91A6C9CEC /* Manager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5241F56B5C8C48BD734958D586267D1A /* Manager.swift */; }; - A3505FA2FB3067D53847AD288AC04F03 /* Download.swift in Sources */ = {isa = PBXBuildFile; fileRef = ADA14379DE2012C9EFB2B9C3A3A39AB4 /* Download.swift */; }; + 9469DF81ECB494E84675969B5E13374C /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = AE6827D6CBD3F8B59B79641ABF6ED159 /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; A871DC508D9A11F280135D7B56266E97 /* PetstoreClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - B0FB4B01682814B9E3D32F9DC4A5E762 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 23D4D8DBF3D77B1F970DB9DF6C963A84 /* Alamofire.swift */; }; - B6D2DC3E3DA44CD382B9B425F40E11C1 /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 8D1C843C58F0C2DFE4522F24897D8CCE /* Alamofire-dummy.m */; }; + AA314156AC500125F4078EE968DB14C6 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E393CF47FE31F265B29AA2D9B67C656 /* Result.swift */; }; + ADF19C953CE2A7D0B72EC93A81FCCC26 /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 9FD74E0A1B7122513F9BCD2B66B65219 /* Alamofire-dummy.m */; }; + AE4CF87C02C042DF13ED5B21C4FDC1E0 /* Stream.swift in Sources */ = {isa = PBXBuildFile; fileRef = F9039D48B1E893EF8AD87645A4FF820F /* Stream.swift */; }; + BE41196F6A3903E59C3306FE3F8B43FE /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79E32C97D15B18BFEB591B4A8B5C8477 /* Notifications.swift */; }; + C0DB70AB368765DC64BFB5FEA75E0696 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB714D2EF499EE0EF3E1957151533A5D /* ParameterEncoding.swift */; }; C546890220177F840E8AFC829D0E3FEB /* Pods-SwaggerClientTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */; }; - C75519F0450166A6F28126ECC7664E9C /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 779B19103BE8402A434ED95F67573911 /* Validation.swift */; }; + C7B6DD7C0456C50289A2C381DFE9FA3F /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B09F376C277F027BDCD54137D76C547 /* MultipartFormData.swift */; }; C8592AD030234E841A61CA09ED02059A /* Pods-SwaggerClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */; }; CA8020EE393C1F6085F284A7CAE3B9E3 /* Pet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 284B3DE9B793FCC633E971DB1798AFAF /* Pet.swift */; }; - D21B7325B3642887BFBE977E021F2D26 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5EBB70A7BA5F9037CD2DA409E148A73 /* ResponseSerialization.swift */; }; D228AFA3B6BFAE551ADA6A57A57F8DF9 /* Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5412898DEB10F1983487A10453C6B9CB /* Extensions.swift */; }; - D75CA395D510E08C404E55F5BDAE55CE /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 83957AB2EE778B52399CC4C903539BD0 /* Error.swift */; }; DAF614ED4A24537ACAF1F517EF31668E /* Order.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A545673F09F49CDD60A13B4B0AF1020 /* Order.swift */; }; + EFE92E8D3813DD26E78E93EEAF6D7E7E /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1E2A29BA50E80B66E36C94B60FAD8863 /* Request.swift */; }; F206C370F63155D3468E0C188498C5DC /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 41EA265E42E2F53F87DD98BDA6BDEFD5 /* Foundation.framework */; }; - FC14480CECE872865A9C6E584F886DA3 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA23887509C9FF173ECBE0A470EDD527 /* Request.swift */; }; - FEF0D7653948988B804226129471C1EC /* Stream.swift in Sources */ = {isa = PBXBuildFile; fileRef = C89117FC38D94C9DF36CA21E3C96EEB7 /* Stream.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -61,14 +64,14 @@ isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; - remoteGlobalIDString = 432ECC54282C84882B482CCB4CF227FC; + remoteGlobalIDString = 79C040AFDDCE1BCBF6D8B5EB0B85887F; remoteInfo = Alamofire; }; 9587C29FFB2EF204C279D7FF29DA45C2 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; - remoteGlobalIDString = 432ECC54282C84882B482CCB4CF227FC; + remoteGlobalIDString = 79C040AFDDCE1BCBF6D8B5EB0B85887F; remoteInfo = Alamofire; }; /* End PBXContainerItemProxy section */ @@ -76,15 +79,17 @@ /* Begin PBXFileReference section */ 00ACB4396DD1B4E4539E4E81C1D7A14E /* Pods-SwaggerClientTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = "Pods-SwaggerClientTests.modulemap"; sourceTree = ""; }; 02F28E719AA874BE9213D6CF8CE7E36B /* Pods-SwaggerClientTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClientTests-acknowledgements.plist"; sourceTree = ""; }; + 09DC3EB7B14F56C5823591E484CC06DC /* Upload.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Upload.swift; path = Source/Upload.swift; sourceTree = ""; }; 0A545673F09F49CDD60A13B4B0AF1020 /* Order.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Order.swift; sourceTree = ""; }; - 10653C142FFDF1986227894BF0317944 /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; + 0DBA7F3642776C1964512C9A38829081 /* Timeline.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeline.swift; path = Source/Timeline.swift; sourceTree = ""; }; + 101C763FD5409006D69EDB82815E4A61 /* Manager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Manager.swift; path = Source/Manager.swift; sourceTree = ""; }; 1A3E5E3CD673B025FD8AC260E67AB47E /* StoreAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = StoreAPI.swift; sourceTree = ""; }; + 1E2A29BA50E80B66E36C94B60FAD8863 /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; 211F73A46D90346F7FC6D0D29640EE4F /* Tag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Tag.swift; sourceTree = ""; }; - 21FA4AD1EF77337F9C8F2AD871ED371D /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = Alamofire.modulemap; sourceTree = ""; }; - 23D4D8DBF3D77B1F970DB9DF6C963A84 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; 261F03A3C73374FD19333EEA59CCD59F /* PetAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PetAPI.swift; sourceTree = ""; }; 284B3DE9B793FCC633E971DB1798AFAF /* Pet.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Pet.swift; sourceTree = ""; }; 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClient-dummy.m"; sourceTree = ""; }; + 2959D264574F227296E36F7CDF2E4F4F /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; 2FF17440CCD2E1A69791A4AA23325AD5 /* Pods-SwaggerClient-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClient-acknowledgements.markdown"; sourceTree = ""; }; 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-SwaggerClient-umbrella.h"; sourceTree = ""; }; 3F16B43ABD2C8CD4A311AA1AB3B6C02F /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; @@ -92,53 +97,54 @@ 43FC49AA70D3E2A84CAED9C37BE9C4B5 /* Pods-SwaggerClientTests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-frameworks.sh"; sourceTree = ""; }; 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "PetstoreClient-dummy.m"; sourceTree = ""; }; 49A9B3BBFEA1CFFC48229E438EA64F9E /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 4FC4583A4BD15196E6859EA5E990AD3F /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; - 5241F56B5C8C48BD734958D586267D1A /* Manager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Manager.swift; path = Source/Manager.swift; sourceTree = ""; }; - 52836A3E223CCB5C120D4BE7D37AC1BF /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; + 4E07E98001DB6C163294A39CAB05963D /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; + 4E393CF47FE31F265B29AA2D9B67C656 /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = ""; }; + 50BCAC7849E43619A0E6BA6D3291D195 /* Download.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Download.swift; path = Source/Download.swift; sourceTree = ""; }; + 5175E677ADC3F810A4FB10B104C4332B /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 5412898DEB10F1983487A10453C6B9CB /* Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Extensions.swift; sourceTree = ""; }; - 5465E2051CE332BA7D4E0595F9B44718 /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.debug.xcconfig"; sourceTree = ""; }; 552D15E0340BF58CC1922B82E864AEC9 /* UserAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = UserAPI.swift; sourceTree = ""; }; + 5B09F376C277F027BDCD54137D76C547 /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; 5B248364ABF60ACD7DB31A17DCFDFD0C /* User.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = User.swift; sourceTree = ""; }; - 5E53BF5A61CAF6972C5CDD2C3EE6C003 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 5C5763A83A1E028B6C4A073221CB764F /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = Alamofire.modulemap; sourceTree = ""; }; + 658CBED44D4009D80F990A188D7A8B3F /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClientTests-dummy.m"; sourceTree = ""; }; 6C0ACB269F0C836F1865A56C4AF7A07E /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 6D1F9022AC9979CD59E8F83962DAF51D /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = Source/Error.swift; sourceTree = ""; }; 706C7AFFE37BA158C3553250F4B5FAED /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 779B19103BE8402A434ED95F67573911 /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; - 7835749D1C4FA403E4BB17A0C787EDCA /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = ""; }; + 79E32C97D15B18BFEB591B4A8B5C8477 /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = ""; }; 7C8E63660D346FD8ED2A97242E74EA09 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 7D7AAA0E85E40ED735D6BCBF7A243C46 /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; - 83957AB2EE778B52399CC4C903539BD0 /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = Source/Error.swift; sourceTree = ""; }; + 7ED443D528393D61A04FBD88603DE5F3 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; 849FECBC6CC67F2B6800F982927E3A9E /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; 897F0C201C5E0C66A1F1E359AECF4C9C /* PetstoreClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = PetstoreClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 8AE82608C8C2A46981A07D7E422BEB45 /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; - 8D1C843C58F0C2DFE4522F24897D8CCE /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; 8F0266C5AE0B23A436291F6647902086 /* Models.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Models.swift; sourceTree = ""; }; + 8FFF564423DBE209836D47626963E9D4 /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; 92734297B64DFE0EB0EDE1EA821163DB /* AlamofireImplementations.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AlamofireImplementations.swift; sourceTree = ""; }; 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; - 948996616B0A38BD6FE8C4CB309CC964 /* Upload.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Upload.swift; path = Source/Upload.swift; sourceTree = ""; }; 969C2AF48F4307163B301A92E78AFCF2 /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = ""; }; 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-umbrella.h"; sourceTree = ""; }; - ADA14379DE2012C9EFB2B9C3A3A39AB4 /* Download.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Download.swift; path = Source/Download.swift; sourceTree = ""; }; + 9FD74E0A1B7122513F9BCD2B66B65219 /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; + A149BF2819128352A98494A4402603EE /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; + AB714D2EF499EE0EF3E1957151533A5D /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; + AE6827D6CBD3F8B59B79641ABF6ED159 /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; B3A144887C8B13FD888B76AB096B0CA1 /* PetstoreClient-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-prefix.pch"; sourceTree = ""; }; BCF2D4DFF08D2A18E8C8FE4C4B4633FB /* Pods-SwaggerClient-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-frameworks.sh"; sourceTree = ""; }; - C89117FC38D94C9DF36CA21E3C96EEB7 /* Stream.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Stream.swift; path = Source/Stream.swift; sourceTree = ""; }; D2841E5E2183846280B97F6E660DA26C /* Pods-SwaggerClient-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-resources.sh"; sourceTree = ""; }; D2BAD338E56EF3CAA6E54490FE0C5DF9 /* APIHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = APIHelper.swift; sourceTree = ""; }; D4DF0604EDC1460935E6E445A47023A4 /* Category.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Category.swift; sourceTree = ""; }; D8072E1108951F272C003553FC8926C7 /* APIs.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = APIs.swift; sourceTree = ""; }; DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = PetstoreClient.xcconfig; sourceTree = ""; }; + DDC2C7A48545D8C54D52554343225FB8 /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; DE164497A94DD3215ED4D1AE0D4703B1 /* Pods-SwaggerClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = "Pods-SwaggerClient.modulemap"; sourceTree = ""; }; E1E4BCB344D3C100253B24B79421F00A /* Pods-SwaggerClient-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClient-acknowledgements.plist"; sourceTree = ""; }; E3D1141B63DF38660CD6F3AC588A782B /* PetstoreClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = PetstoreClient.modulemap; sourceTree = ""; }; E4E6F4A58FE7868CA2177D3AC79AD2FA /* Pods-SwaggerClientTests-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-resources.sh"; sourceTree = ""; }; - E6D51E88CF06503F74AC8F5ECD5A209B /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; EA3FFA48FB4D08FC02C47F71C0089CD9 /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; F0D4E00A8974E74325E9E53D456F9AD4 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-SwaggerClientTests-umbrella.h"; sourceTree = ""; }; - F5EBB70A7BA5F9037CD2DA409E148A73 /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; - FA23887509C9FF173ECBE0A470EDD527 /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; + F9039D48B1E893EF8AD87645A4FF820F /* Stream.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Stream.swift; path = Source/Stream.swift; sourceTree = ""; }; + F9278DA00F41E390EE68B6F3C8161C54 /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = ""; }; FB170EFD14935F121CDE3211DB4C5CA3 /* Pods-SwaggerClientTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClientTests-acknowledgements.markdown"; sourceTree = ""; }; /* End PBXFileReference section */ @@ -151,11 +157,11 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - A5AE1D340C4A0691EC28EEA8241C9FCD /* Frameworks */ = { + B1729F851F648EC60EE93CDB3C8BAEAD /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 0BD8B4E55E72312366130E97A1204CD8 /* Foundation.framework in Frameworks */, + 91C09AC2A52ED69A27C8D923139A006F /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -179,28 +185,6 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 09192E6B9C45ACAB5568261F45FA3D88 /* Alamofire */ = { - isa = PBXGroup; - children = ( - 23D4D8DBF3D77B1F970DB9DF6C963A84 /* Alamofire.swift */, - ADA14379DE2012C9EFB2B9C3A3A39AB4 /* Download.swift */, - 83957AB2EE778B52399CC4C903539BD0 /* Error.swift */, - 5241F56B5C8C48BD734958D586267D1A /* Manager.swift */, - 10653C142FFDF1986227894BF0317944 /* MultipartFormData.swift */, - 5465E2051CE332BA7D4E0595F9B44718 /* ParameterEncoding.swift */, - FA23887509C9FF173ECBE0A470EDD527 /* Request.swift */, - 8AE82608C8C2A46981A07D7E422BEB45 /* Response.swift */, - F5EBB70A7BA5F9037CD2DA409E148A73 /* ResponseSerialization.swift */, - 7835749D1C4FA403E4BB17A0C787EDCA /* Result.swift */, - 52836A3E223CCB5C120D4BE7D37AC1BF /* ServerTrustPolicy.swift */, - C89117FC38D94C9DF36CA21E3C96EEB7 /* Stream.swift */, - 948996616B0A38BD6FE8C4CB309CC964 /* Upload.swift */, - 779B19103BE8402A434ED95F67573911 /* Validation.swift */, - 405A7C3030F6D3BDE3978D6D558FDF7F /* Support Files */, - ); - path = Alamofire; - sourceTree = ""; - }; 1322FED69118C64DAD026CAF7F4C38C6 /* Models */ = { isa = PBXGroup; children = ( @@ -213,14 +197,6 @@ path = Models; sourceTree = ""; }; - 20C396BA1B90EEE39D4B19FE012C4F6D /* Pods */ = { - isa = PBXGroup; - children = ( - 09192E6B9C45ACAB5568261F45FA3D88 /* Alamofire */, - ); - name = Pods; - sourceTree = ""; - }; 22F52349E1BE90FC6E064DAAC9EA9612 /* Development Pods */ = { isa = PBXGroup; children = ( @@ -237,18 +213,12 @@ name = iOS; sourceTree = ""; }; - 405A7C3030F6D3BDE3978D6D558FDF7F /* Support Files */ = { + 35F128EB69B6F7FB7DA93BBF6C130FAE /* Pods */ = { isa = PBXGroup; children = ( - 21FA4AD1EF77337F9C8F2AD871ED371D /* Alamofire.modulemap */, - 7D7AAA0E85E40ED735D6BCBF7A243C46 /* Alamofire.xcconfig */, - 8D1C843C58F0C2DFE4522F24897D8CCE /* Alamofire-dummy.m */, - E6D51E88CF06503F74AC8F5ECD5A209B /* Alamofire-prefix.pch */, - 4FC4583A4BD15196E6859EA5E990AD3F /* Alamofire-umbrella.h */, - 5E53BF5A61CAF6972C5CDD2C3EE6C003 /* Info.plist */, + 6E519FC8760483F5D136181B2EBCBDEB /* Alamofire */, ); - name = "Support Files"; - path = "../Target Support Files/Alamofire"; + name = Pods; sourceTree = ""; }; 59B91F212518421F271EBA85D5530651 /* Frameworks */ = { @@ -260,13 +230,52 @@ name = Frameworks; sourceTree = ""; }; + 68F6D4CBC8B6CDE1D634D9F379F37168 /* Support Files */ = { + isa = PBXGroup; + children = ( + 5C5763A83A1E028B6C4A073221CB764F /* Alamofire.modulemap */, + A149BF2819128352A98494A4402603EE /* Alamofire.xcconfig */, + 9FD74E0A1B7122513F9BCD2B66B65219 /* Alamofire-dummy.m */, + 8FFF564423DBE209836D47626963E9D4 /* Alamofire-prefix.pch */, + AE6827D6CBD3F8B59B79641ABF6ED159 /* Alamofire-umbrella.h */, + 5175E677ADC3F810A4FB10B104C4332B /* Info.plist */, + ); + name = "Support Files"; + path = "../Target Support Files/Alamofire"; + sourceTree = ""; + }; + 6E519FC8760483F5D136181B2EBCBDEB /* Alamofire */ = { + isa = PBXGroup; + children = ( + 7ED443D528393D61A04FBD88603DE5F3 /* Alamofire.swift */, + 50BCAC7849E43619A0E6BA6D3291D195 /* Download.swift */, + 6D1F9022AC9979CD59E8F83962DAF51D /* Error.swift */, + 101C763FD5409006D69EDB82815E4A61 /* Manager.swift */, + 5B09F376C277F027BDCD54137D76C547 /* MultipartFormData.swift */, + F9278DA00F41E390EE68B6F3C8161C54 /* NetworkReachabilityManager.swift */, + 79E32C97D15B18BFEB591B4A8B5C8477 /* Notifications.swift */, + AB714D2EF499EE0EF3E1957151533A5D /* ParameterEncoding.swift */, + 1E2A29BA50E80B66E36C94B60FAD8863 /* Request.swift */, + DDC2C7A48545D8C54D52554343225FB8 /* Response.swift */, + 2959D264574F227296E36F7CDF2E4F4F /* ResponseSerialization.swift */, + 4E393CF47FE31F265B29AA2D9B67C656 /* Result.swift */, + 4E07E98001DB6C163294A39CAB05963D /* ServerTrustPolicy.swift */, + F9039D48B1E893EF8AD87645A4FF820F /* Stream.swift */, + 0DBA7F3642776C1964512C9A38829081 /* Timeline.swift */, + 09DC3EB7B14F56C5823591E484CC06DC /* Upload.swift */, + 658CBED44D4009D80F990A188D7A8B3F /* Validation.swift */, + 68F6D4CBC8B6CDE1D634D9F379F37168 /* Support Files */, + ); + path = Alamofire; + sourceTree = ""; + }; 7DB346D0F39D3F0E887471402A8071AB = { isa = PBXGroup; children = ( 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */, 22F52349E1BE90FC6E064DAAC9EA9612 /* Development Pods */, 59B91F212518421F271EBA85D5530651 /* Frameworks */, - 20C396BA1B90EEE39D4B19FE012C4F6D /* Pods */, + 35F128EB69B6F7FB7DA93BBF6C130FAE /* Pods */, 9BBD96A0F02B8F92DD3659B2DCDF1A8C /* Products */, C1A60D10CED0E61146591438999C7502 /* Targets Support Files */, ); @@ -395,27 +404,27 @@ /* End PBXGroup section */ /* Begin PBXHeadersBuildPhase section */ - 5F7B61281F714E2A64A51E80A2C9C062 /* Headers */ = { + 6C794A7763C2F85750D66CDD002E271F /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - 2C5450AC69398958CF6F7539EF7D99E5 /* Alamofire-umbrella.h in Headers */, + A871DC508D9A11F280135D7B56266E97 /* PetstoreClient-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; - 6C794A7763C2F85750D66CDD002E271F /* Headers */ = { + 8EB9FB8BCBCBC01234ED5877A870758B /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - A871DC508D9A11F280135D7B56266E97 /* PetstoreClient-umbrella.h in Headers */, + 816BE1BBC1F4E434D7BD3F793F38B347 /* Pods-SwaggerClient-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; - 8EB9FB8BCBCBC01234ED5877A870758B /* Headers */ = { + EFDF3B631BBB965A372347705CA14854 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - 816BE1BBC1F4E434D7BD3F793F38B347 /* Pods-SwaggerClient-umbrella.h in Headers */, + 9469DF81ECB494E84675969B5E13374C /* Alamofire-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -449,23 +458,6 @@ productReference = 6C0ACB269F0C836F1865A56C4AF7A07E /* Pods_SwaggerClient.framework */; productType = "com.apple.product-type.framework"; }; - 432ECC54282C84882B482CCB4CF227FC /* Alamofire */ = { - isa = PBXNativeTarget; - buildConfigurationList = 8B2B2DA2F7F80D41B1FDB5FACFA4B3DE /* Build configuration list for PBXNativeTarget "Alamofire" */; - buildPhases = ( - EF659EFF40D426A3A32A82CDB98CC6EE /* Sources */, - A5AE1D340C4A0691EC28EEA8241C9FCD /* Frameworks */, - 5F7B61281F714E2A64A51E80A2C9C062 /* Headers */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = Alamofire; - productName = Alamofire; - productReference = 49A9B3BBFEA1CFFC48229E438EA64F9E /* Alamofire.framework */; - productType = "com.apple.product-type.framework"; - }; 462B200BD111D7F438E47B7C42B6772F /* Pods-SwaggerClientTests */ = { isa = PBXNativeTarget; buildConfigurationList = 245A935A321D16F418F4D34C5D17D2B6 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClientTests" */; @@ -501,6 +493,23 @@ productReference = 897F0C201C5E0C66A1F1E359AECF4C9C /* PetstoreClient.framework */; productType = "com.apple.product-type.framework"; }; + 79C040AFDDCE1BCBF6D8B5EB0B85887F /* Alamofire */ = { + isa = PBXNativeTarget; + buildConfigurationList = 3CFB42910790CF0BDBCCEBAACD6B9367 /* Build configuration list for PBXNativeTarget "Alamofire" */; + buildPhases = ( + 95CC2C7E06DC188A05DAAEE9CAA555A3 /* Sources */, + B1729F851F648EC60EE93CDB3C8BAEAD /* Frameworks */, + EFDF3B631BBB965A372347705CA14854 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Alamofire; + productName = Alamofire; + productReference = 49A9B3BBFEA1CFFC48229E438EA64F9E /* Alamofire.framework */; + productType = "com.apple.product-type.framework"; + }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ @@ -522,7 +531,7 @@ projectDirPath = ""; projectRoot = ""; targets = ( - 432ECC54282C84882B482CCB4CF227FC /* Alamofire */, + 79C040AFDDCE1BCBF6D8B5EB0B85887F /* Alamofire */, 757F9BBABE83623770250F65EAEE4FD6 /* PetstoreClient */, 01C67FBB627BDC9D36B9F648C0BF5228 /* Pods-SwaggerClient */, 462B200BD111D7F438E47B7C42B6772F /* Pods-SwaggerClientTests */, @@ -560,33 +569,36 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - C2AD20E62D6A15C7CE3E20F8A811548F /* Sources */ = { + 95CC2C7E06DC188A05DAAEE9CAA555A3 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - C8592AD030234E841A61CA09ED02059A /* Pods-SwaggerClient-dummy.m in Sources */, + ADF19C953CE2A7D0B72EC93A81FCCC26 /* Alamofire-dummy.m in Sources */, + 8EB11202167FCDDF1257AAAB1D1FB244 /* Alamofire.swift in Sources */, + 5CB05FBCB32D21E194B5ECF680CB6AE0 /* Download.swift in Sources */, + 095406039B4D371E48D08B38A2975AC8 /* Error.swift in Sources */, + 4081EA628AF0B73AC51FFB9D7AB3B89E /* Manager.swift in Sources */, + C7B6DD7C0456C50289A2C381DFE9FA3F /* MultipartFormData.swift in Sources */, + 34CCDCA848A701466256BC2927DA8856 /* NetworkReachabilityManager.swift in Sources */, + BE41196F6A3903E59C3306FE3F8B43FE /* Notifications.swift in Sources */, + C0DB70AB368765DC64BFB5FEA75E0696 /* ParameterEncoding.swift in Sources */, + EFE92E8D3813DD26E78E93EEAF6D7E7E /* Request.swift in Sources */, + 62E8346F03C03E7F4D631361F325689E /* Response.swift in Sources */, + 3EA8F215C9C1432D74E5CCA4834AA8C0 /* ResponseSerialization.swift in Sources */, + AA314156AC500125F4078EE968DB14C6 /* Result.swift in Sources */, + 7B48852C4D848FA2DA416A98F6425869 /* ServerTrustPolicy.swift in Sources */, + AE4CF87C02C042DF13ED5B21C4FDC1E0 /* Stream.swift in Sources */, + 16102E4E35FAA0FC4161282FECE56469 /* Timeline.swift in Sources */, + 5BC19E6E0F199276003F0AF96838BCE5 /* Upload.swift in Sources */, + 2D3405986FC586FA6C0A5E0B6BA7E64E /* Validation.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; - EF659EFF40D426A3A32A82CDB98CC6EE /* Sources */ = { + C2AD20E62D6A15C7CE3E20F8A811548F /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - B6D2DC3E3DA44CD382B9B425F40E11C1 /* Alamofire-dummy.m in Sources */, - B0FB4B01682814B9E3D32F9DC4A5E762 /* Alamofire.swift in Sources */, - A3505FA2FB3067D53847AD288AC04F03 /* Download.swift in Sources */, - D75CA395D510E08C404E55F5BDAE55CE /* Error.swift in Sources */, - A2C172FE407C0BC3478ADCA91A6C9CEC /* Manager.swift in Sources */, - 8399DBEE3E2D98EB1F466132E476F4D9 /* MultipartFormData.swift in Sources */, - 4DE5FCC41D100B113B6645EA64410F16 /* ParameterEncoding.swift in Sources */, - FC14480CECE872865A9C6E584F886DA3 /* Request.swift in Sources */, - 03F494989CC1A8857B68A317D5D6860F /* Response.swift in Sources */, - D21B7325B3642887BFBE977E021F2D26 /* ResponseSerialization.swift in Sources */, - 82971968CBDAB224212EEB4607C9FB8D /* Result.swift in Sources */, - 80F496237530D382A045A29654D8C11C /* ServerTrustPolicy.swift in Sources */, - FEF0D7653948988B804226129471C1EC /* Stream.swift in Sources */, - 0681ADC8BAE2C3185F13487BAAB4D9DD /* Upload.swift in Sources */, - C75519F0450166A6F28126ECC7664E9C /* Validation.swift in Sources */, + C8592AD030234E841A61CA09ED02059A /* Pods-SwaggerClient-dummy.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -596,13 +608,13 @@ 9D7C00D5DABDA9EE2ED06BE7F85DD5EA /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = Alamofire; - target = 432ECC54282C84882B482CCB4CF227FC /* Alamofire */; + target = 79C040AFDDCE1BCBF6D8B5EB0B85887F /* Alamofire */; targetProxy = 9587C29FFB2EF204C279D7FF29DA45C2 /* PBXContainerItemProxy */; }; A2B064722D89556FD34AF0A4A3EC3847 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = Alamofire; - target = 432ECC54282C84882B482CCB4CF227FC /* Alamofire */; + target = 79C040AFDDCE1BCBF6D8B5EB0B85887F /* Alamofire */; targetProxy = 815A2A76D6EC0B2933867EA1BA7E51D8 /* PBXContainerItemProxy */; }; A51999658423B0F25DD2B4FEECD542E3 /* PBXTargetDependency */ = { @@ -614,6 +626,35 @@ /* End PBXTargetDependency section */ /* Begin XCBuildConfiguration section */ + 32AD5F8918CA8B349E4671410FA624C9 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = A149BF2819128352A98494A4402603EE /* Alamofire.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; 51E864C21FD4E8BF48B7DE196DE05017 /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */; @@ -648,6 +689,36 @@ }; name = Debug; }; + 75218111E718FACE36F771E8ABECDB62 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = A149BF2819128352A98494A4402603EE /* Alamofire.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; 7C4A68800C97518F39692FF062F013EE /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */; @@ -785,35 +856,6 @@ }; name = Release; }; - 9B26D3A39011247999C097562A550399 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 7D7AAA0E85E40ED735D6BCBF7A243C46 /* Alamofire.xcconfig */; - buildSettings = { - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; - GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; - MTL_ENABLE_DEBUG_INFO = NO; - PRODUCT_NAME = Alamofire; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Release; - }; B316166B7E92675830371A4D5A9C5B6B /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */; @@ -844,36 +886,6 @@ }; name = Debug; }; - BE1BF3E5FC53BAFA505AB342C35E1F50 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 7D7AAA0E85E40ED735D6BCBF7A243C46 /* Alamofire.xcconfig */; - buildSettings = { - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = dwarf; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; - GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; - MTL_ENABLE_DEBUG_INFO = YES; - PRODUCT_NAME = Alamofire; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Debug; - }; F594C655D48020EC34B00AA63E001773 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { @@ -966,20 +978,20 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 75D763A79F74FE2B1D1C066F125F118E /* Build configuration list for PBXNativeTarget "PetstoreClient" */ = { + 3CFB42910790CF0BDBCCEBAACD6B9367 /* Build configuration list for PBXNativeTarget "Alamofire" */ = { isa = XCConfigurationList; buildConfigurations = ( - B316166B7E92675830371A4D5A9C5B6B /* Debug */, - 95F68EBF32996F2AC8422FE5C210682D /* Release */, + 75218111E718FACE36F771E8ABECDB62 /* Debug */, + 32AD5F8918CA8B349E4671410FA624C9 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 8B2B2DA2F7F80D41B1FDB5FACFA4B3DE /* Build configuration list for PBXNativeTarget "Alamofire" */ = { + 75D763A79F74FE2B1D1C066F125F118E /* Build configuration list for PBXNativeTarget "PetstoreClient" */ = { isa = XCConfigurationList; buildConfigurations = ( - BE1BF3E5FC53BAFA505AB342C35E1F50 /* Debug */, - 9B26D3A39011247999C097562A550399 /* Release */, + B316166B7E92675830371A4D5A9C5B6B /* Debug */, + 95F68EBF32996F2AC8422FE5C210682D /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Info.plist b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Info.plist index c1aea25c248..7694605fe7a 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Info.plist +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Alamofire/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 3.1.5 + 3.4.1 CFBundleSignature ???? CFBundleVersion diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.markdown b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.markdown index 3852291ae7d..938fc5f29a8 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.markdown +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.markdown @@ -3,7 +3,7 @@ This application makes use of the following third party libraries: ## Alamofire -Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.plist b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.plist index c188b147b3b..289edb2592c 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.plist +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.plist @@ -14,7 +14,7 @@ FooterText - Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) + Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient.podspec b/samples/client/petstore/swift/promisekit/PetstoreClient.podspec index b4eccbce888..25ab9199796 100644 --- a/samples/client/petstore/swift/promisekit/PetstoreClient.podspec +++ b/samples/client/petstore/swift/promisekit/PetstoreClient.podspec @@ -4,11 +4,11 @@ Pod::Spec.new do |s| s.osx.deployment_target = '10.9' s.version = '0.0.1' s.source = { :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' } - s.authors = + s.authors = '' s.license = 'Apache License, Version 2.0' s.homepage = 'https://github.com/swagger-api/swagger-codegen' s.summary = 'PetstoreClient' s.source_files = 'PetstoreClient/Classes/Swaggers/**/*.swift' s.dependency 'PromiseKit', '~> 3.1.1' - s.dependency 'Alamofire', '~> 3.1.5' + s.dependency 'Alamofire', '~> 3.4.1' end diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs.swift index 96eead0d8dd..ab0ea147e4f 100644 --- a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs.swift +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs.swift @@ -37,6 +37,9 @@ public class RequestBuilder { let method: String let URLString: String + /// Optional block to obtain a reference to the request's progress instance when available. + public var onProgressReady: ((NSProgress) -> ())? + required public init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool) { self.method = method self.URLString = URLString diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index 2faa0a6f24d..baa6d8aa72a 100644 --- a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -57,15 +57,22 @@ class AlamofireRequestBuilder: RequestBuilder { encodingMemoryThreshold: Manager.MultipartFormDataEncodingMemoryThreshold, encodingCompletion: { encodingResult in switch encodingResult { - case .Success(let upload, _, _): - self.processRequest(upload, managerId, completion) + case .Success(let uploadRequest, _, _): + if let onProgressReady = self.onProgressReady { + onProgressReady(uploadRequest.progress) + } + self.processRequest(uploadRequest, managerId, completion) case .Failure(let encodingError): completion(response: nil, error: encodingError) } } ) } else { - processRequest(manager.request(xMethod!, URLString, parameters: parameters, encoding: encoding), managerId, completion) + let request = manager.request(xMethod!, URLString, parameters: parameters, encoding: encoding) + if let onProgressReady = self.onProgressReady { + onProgressReady(request.progress) + } + processRequest(request, managerId, completion) } } @@ -75,30 +82,59 @@ class AlamofireRequestBuilder: RequestBuilder { request.authenticate(usingCredential: credential) } - request.validate().responseJSON(options: .AllowFragments) { response in + let cleanupRequest = { managerStore.removeValueForKey(managerId) + } - if response.result.isFailure { - completion(response: nil, error: response.result.error) - return - } + let validatedRequest = request.validate() - if () is T { - completion(response: Response(response: response.response!, body: () as! T), error: nil) - return - } - if let json: AnyObject = response.result.value { - let body = Decoders.decode(clazz: T.self, source: json) - completion(response: Response(response: response.response!, body: body), error: nil) - return - } else if "" is T { - // swagger-parser currently doesn't support void, which will be fixed in future swagger-parser release - // https://github.com/swagger-api/swagger-parser/pull/34 - completion(response: Response(response: response.response!, body: "" as! T), error: nil) - return - } + switch T.self { + case is NSData.Type: + validatedRequest.responseData(completionHandler: { (dataResponse) in + cleanupRequest() + + if (dataResponse.result.isFailure) { + completion( + response: nil, + error: dataResponse.result.error + ) + return + } - completion(response: nil, error: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) + completion( + response: Response( + response: dataResponse.response!, + body: dataResponse.data as! T + ), + error: nil + ) + }) + default: + validatedRequest.responseJSON(options: .AllowFragments) { response in + cleanupRequest() + + if response.result.isFailure { + completion(response: nil, error: response.result.error) + return + } + + if () is T { + completion(response: Response(response: response.response!, body: () as! T), error: nil) + return + } + if let json: AnyObject = response.result.value { + let body = Decoders.decode(clazz: T.self, source: json) + completion(response: Response(response: response.response!, body: body), error: nil) + return + } else if "" is T { + // swagger-parser currently doesn't support void, which will be fixed in future swagger-parser release + // https://github.com/swagger-api/swagger-parser/pull/34 + completion(response: Response(response: response.response!, body: "" as! T), error: nil) + return + } + + completion(response: nil, error: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) + } } } diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Extensions.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Extensions.swift index 2a032d561b1..976ff5a7c3b 100644 --- a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Extensions.swift +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Extensions.swift @@ -59,6 +59,11 @@ extension Dictionary: JSONEncodable { } } +extension NSData: JSONEncodable { + func encodeToJSON() -> AnyObject { + return self.base64EncodedStringWithOptions(NSDataBase64EncodingOptions()) + } +} private let dateFormatter: NSDateFormatter = { let fmt = NSDateFormatter() @@ -73,6 +78,12 @@ extension NSDate: JSONEncodable { } } +extension NSUUID: JSONEncodable { + func encodeToJSON() -> AnyObject { + return self.UUIDString + } +} + extension RequestBuilder { public func execute() -> Promise> { let deferred = Promise>.pendingPromise() diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models.swift index cad60a236a7..519aa5cc787 100644 --- a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models.swift +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models.swift @@ -62,9 +62,15 @@ class Decoders { if T.self is Int64.Type && source is NSNumber { return source.longLongValue as! T; } + if T.self is NSUUID.Type && source is String { + return NSUUID(UUIDString: source as! String) as! T + } if source is T { return source as! T } + if T.self is NSData.Type && source is String { + return NSData(base64EncodedString: source as! String, options: NSDataBase64DecodingOptions()) as! T + } let key = "\(T.self)" if let decoder = decoders[key] { diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/LICENSE b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/LICENSE index bf300e4482e..4cfbf72a4d8 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/LICENSE +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/README.md b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/README.md index bcc0ff4bd05..56a6771636c 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/README.md +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/README.md @@ -1,7 +1,7 @@ ![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/assets/alamofire.png) [![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg)](https://travis-ci.org/Alamofire/Alamofire) -[![Cocoapods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.svg) +[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.svg) [![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) [![Platform](https://img.shields.io/cocoapods/p/Alamofire.svg?style=flat)](http://cocoadocs.org/docsets/Alamofire) [![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat)](http://twitter.com/AlamofireSF) @@ -22,10 +22,17 @@ Alamofire is an HTTP networking library written in Swift. - [x] Comprehensive Unit Test Coverage - [x] [Complete Documentation](http://cocoadocs.org/docsets/Alamofire) +## Component Libraries + +In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem. + +* [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache and a priority-based image downloading system. +* [AlamofireNetworkActivityIndicator](https://github.com/Alamofire/AlamofireNetworkActivityIndicator) - Controls the visibility of the network activity indicator on iOS using Alamofire. It contains configurable delay timers to help mitigate flicker and can support `NSURLSession` instances not managed by Alamofire. + ## Requirements - iOS 8.0+ / Mac OS X 10.9+ / tvOS 9.0+ / watchOS 2.0+ -- Xcode 7.2+ +- Xcode 7.3+ ## Migration Guides @@ -60,10 +67,12 @@ To integrate Alamofire into your Xcode project using CocoaPods, specify it in yo ```ruby source 'https://github.com/CocoaPods/Specs.git' -platform :ios, '8.0' +platform :ios, '9.0' use_frameworks! -pod 'Alamofire', '~> 3.0' +target '' do + pod 'Alamofire', '~> 3.4' +end ``` Then, run the following command: @@ -86,7 +95,7 @@ $ brew install carthage To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: ```ogdl -github "Alamofire/Alamofire" ~> 3.0 +github "Alamofire/Alamofire" ~> 3.4 ``` Run `carthage update` to build the framework and drag the built `Alamofire.framework` into your Xcode project. @@ -161,6 +170,38 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) > Rather than blocking execution to wait for a response from the server, a [callback](http://en.wikipedia.org/wiki/Callback_%28computer_programming%29) is specified to handle the response once it's received. The result of a request is only available inside the scope of a response handler. Any execution contingent on the response or data received from the server must be done within a handler. +### Validation + +By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling `validate` before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type. + +#### Manual Validation + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .validate(statusCode: 200..<300) + .validate(contentType: ["application/json"]) + .response { response in + print(response) + } +``` + +#### Automatic Validation + +Automatically validates status code within `200...299` range, and that the `Content-Type` header of the response matches the `Accept` header of the request, if one is provided. + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .validate() + .responseJSON { response in + switch response.result { + case .Success: + print("Validation Successful") + case .Failure(let error): + print(error) + } + } +``` + ### Response Serialization **Built-in Response Methods** @@ -175,6 +216,7 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) ```swift Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .validate() .response { request, response, data, error in print(request) print(response) @@ -183,12 +225,13 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) } ``` -> The `response` serializer does NOT evaluate any of the response data. It merely forwards on all the information directly from the URL session delegate. We strongly encourage you to leverage the other responser serializers taking advantage of `Response` and `Result` types. +> The `response` serializer does NOT evaluate any of the response data. It merely forwards on all the information directly from the URL session delegate. We strongly encourage you to leverage the other response serializers taking advantage of `Response` and `Result` types. #### Response Data Handler ```swift Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .validate() .responseData { response in print(response.request) print(response.response) @@ -200,6 +243,7 @@ Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) ```swift Alamofire.request(.GET, "https://httpbin.org/get") + .validate() .responseString { response in print("Success: \(response.result.isSuccess)") print("Response String: \(response.result.value)") @@ -210,6 +254,7 @@ Alamofire.request(.GET, "https://httpbin.org/get") ```swift Alamofire.request(.GET, "https://httpbin.org/get") + .validate() .responseJSON { response in debugPrint(response) } @@ -221,6 +266,7 @@ Response handlers can even be chained: ```swift Alamofire.request(.GET, "https://httpbin.org/get") + .validate() .responseString { response in print("Response String: \(response.result.value)") } @@ -332,7 +378,7 @@ Adding a custom HTTP header to a `Request` is supported directly in the global ` ```swift let headers = [ "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", - "Content-Type": "application/x-www-form-urlencoded" + "Accept": "application/json" ] Alamofire.request(.GET, "https://httpbin.org/get", headers: headers) @@ -374,6 +420,7 @@ Alamofire.upload(.POST, "https://httpbin.org/post", file: fileURL) print("Total bytes written on main queue: \(totalBytesWritten)") } } + .validate() .responseJSON { response in debugPrint(response) } @@ -540,38 +587,25 @@ Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)") } ``` -### Validation - -By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling `validate` before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type. - -#### Manual Validation - -```swift -Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) - .validate(statusCode: 200..<300) - .validate(contentType: ["application/json"]) - .response { response in - print(response) - } -``` - -#### Automatic Validation +### Timeline -Automatically validates status code within `200...299` range, and that the `Content-Type` header of the response matches the `Accept` header of the request, if one is provided. +Alamofire collects timings throughout the lifecycle of a `Request` and creates a `Timeline` object exposed as a property on a `Response`. ```swift Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) .validate() .responseJSON { response in - switch response.result { - case .Success: - print("Validation Successful") - case .Failure(let error): - print(error) - } + print(response.timeline) } ``` +The above reports the following `Timeline` info: + +- `Latency`: 0.428 seconds +- `Request Duration`: 0.428 seconds +- `Serialization Duration`: 0.001 seconds +- `Total Duration`: 0.429 seconds + ### Printable ```swift @@ -679,6 +713,20 @@ Requests can be suspended, resumed, and cancelled: ### Response Serialization +#### Handling Errors + +Before implementing custom response serializers or object serialization methods, it's important to be prepared to handle any errors that may occur. Alamofire recommends handling these through the use of either your own `NSError` creation methods, or a simple `enum` that conforms to `ErrorType`. For example, this `BackendError` type, which will be used in later examples: + +```swift +enum BackendError: ErrorType { + case Network(error: NSError) + case DataSerialization(reason: String) + case JSONSerialization(error: NSError) + case ObjectSerialization(reason: String) + case XMLSerialization(error: NSError) +} +``` + #### Creating a Custom Response Serializer Alamofire provides built-in response serialization for strings, JSON, and property lists, but others can be added in extensions on `Alamofire.Request`. @@ -687,26 +735,24 @@ For example, here's how a response handler using [Ono](https://github.com/mattt/ ```swift extension Request { - public static func XMLResponseSerializer() -> ResponseSerializer { + public static func XMLResponseSerializer() -> ResponseSerializer { return ResponseSerializer { request, response, data, error in - guard error == nil else { return .Failure(error!) } + guard error == nil else { return .Failure(.Network(error: error!)) } guard let validData = data else { - let failureReason = "Data could not be serialized. Input data was nil." - let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason) - return .Failure(error) + return .Failure(.DataSerialization(reason: "Data could not be serialized. Input data was nil.")) } do { let XML = try ONOXMLDocument(data: validData) return .Success(XML) } catch { - return .Failure(error as NSError) + return .Failure(.XMLSerialization(error: error as NSError)) } } } - public func responseXMLDocument(completionHandler: Response -> Void) -> Self { + public func responseXMLDocument(completionHandler: Response -> Void) -> Self { return response(responseSerializer: Request.XMLResponseSerializer(), completionHandler: completionHandler) } } @@ -722,9 +768,9 @@ public protocol ResponseObjectSerializable { } extension Request { - public func responseObject(completionHandler: Response -> Void) -> Self { - let responseSerializer = ResponseSerializer { request, response, data, error in - guard error == nil else { return .Failure(error!) } + public func responseObject(completionHandler: Response -> Void) -> Self { + let responseSerializer = ResponseSerializer { request, response, data, error in + guard error == nil else { return .Failure(.Network(error: error!)) } let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments) let result = JSONResponseSerializer.serializeResponse(request, response, data, error) @@ -737,12 +783,10 @@ extension Request { { return .Success(responseObject) } else { - let failureReason = "JSON could not be serialized into response object: \(value)" - let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason) - return .Failure(error) + return .Failure(.ObjectSerialization(reason: "JSON could not be serialized into response object: \(value)")) } case .Failure(let error): - return .Failure(error) + return .Failure(.JSONSerialization(error: error)) } } @@ -765,7 +809,7 @@ final class User: ResponseObjectSerializable { ```swift Alamofire.request(.GET, "https://example.com/users/mattt") - .responseObject { (response: Response) in + .responseObject { (response: Response) in debugPrint(response) } ``` @@ -777,10 +821,26 @@ public protocol ResponseCollectionSerializable { static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [Self] } +extension ResponseCollectionSerializable where Self: ResponseObjectSerializable { + static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [Self] { + var collection = [Self]() + + if let representation = representation as? [[String: AnyObject]] { + for itemRepresentation in representation { + if let item = Self(response: response, representation: itemRepresentation) { + collection.append(item) + } + } + } + + return collection + } +} + extension Alamofire.Request { - public func responseCollection(completionHandler: Response<[T], NSError> -> Void) -> Self { - let responseSerializer = ResponseSerializer<[T], NSError> { request, response, data, error in - guard error == nil else { return .Failure(error!) } + public func responseCollection(completionHandler: Response<[T], BackendError> -> Void) -> Self { + let responseSerializer = ResponseSerializer<[T], BackendError> { request, response, data, error in + guard error == nil else { return .Failure(.Network(error: error!)) } let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments) let result = JSONSerializer.serializeResponse(request, response, data, error) @@ -790,12 +850,10 @@ extension Alamofire.Request { if let response = response { return .Success(T.collection(response: response, representation: value)) } else { - let failureReason = "Response collection could not be serialized due to nil response" - let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason) - return .Failure(error) + return .Failure(. ObjectSerialization(reason: "Response collection could not be serialized due to nil response")) } case .Failure(let error): - return .Failure(error) + return .Failure(.JSONSerialization(error: error)) } } @@ -813,26 +871,12 @@ final class User: ResponseObjectSerializable, ResponseCollectionSerializable { self.username = response.URL!.lastPathComponent! self.name = representation.valueForKeyPath("name") as! String } - - static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [User] { - var users: [User] = [] - - if let representation = representation as? [[String: AnyObject]] { - for userRepresentation in representation { - if let user = User(response: response, representation: userRepresentation) { - users.append(user) - } - } - } - - return users - } } ``` ```swift Alamofire.request(.GET, "http://example.com/users") - .responseCollection { (response: Response<[User], NSError>) in + .responseCollection { (response: Response<[User], BackendError>) in debugPrint(response) } ``` @@ -912,7 +956,7 @@ enum Router: URLRequestConvertible { var URLRequest: NSMutableURLRequest { let result: (path: String, parameters: [String: AnyObject]) = { switch self { - case .Search(let query, let page) where page > 1: + case .Search(let query, let page) where page > 0: return ("/search", ["q": query, "offset": Router.perPage * page]) case .Search(let query, _): return ("/search", ["q": query]) @@ -997,6 +1041,74 @@ enum Router: URLRequestConvertible { Alamofire.request(Router.ReadUser("mattt")) // GET /users/mattt ``` +### SessionDelegate + +By default, an Alamofire `Manager` instance creates an internal `SessionDelegate` object to handle all the various types of delegate callbacks that are generated by the underlying `NSURLSession`. The implementations of each delegate method handle the most common use cases for these types of calls abstracting the complexity away from the top-level APIs. However, advanced users may find the need to override the default functionality for various reasons. + +#### Override Closures + +The first way to customize the `SessionDelegate` behavior is through the use of the override closures. Each closure gives you the ability to override the implementation of the matching `SessionDelegate` API, yet still use the default implementation for all other APIs. This makes it easy to customize subsets of the delegate functionality. Here are a few examples of some of the override closures available: + +```swift +/// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`. +public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? + +/// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`. +public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)? + +/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`. +public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? + +/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`. +public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)? +``` + +The following is a short example of how to use the `taskWillPerformHTTPRedirection` to avoid following redirects to any `apple.com` domains. + +```swift +let delegate: Alamofire.Manager.SessionDelegate = manager.delegate + +delegate.taskWillPerformHTTPRedirection = { session, task, response, request in + var finalRequest = request + + if let originalRequest = task.originalRequest where originalRequest.URLString.containsString("apple.com") { + finalRequest = originalRequest + } + + return finalRequest +} +``` + +#### Subclassing + +Another way to override the default implementation of the `SessionDelegate` is to subclass it. Subclassing allows you completely customize the behavior of the API or to create a proxy for the API and still use the default implementation. Creating a proxy allows you to log events, emit notifications, provide pre and post hook implementations, etc. Here's a quick example of subclassing the `SessionDelegate` and logging a message when a redirect occurs. + +```swift +class LoggingSessionDelegate: Manager.SessionDelegate { + override func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + willPerformHTTPRedirection response: NSHTTPURLResponse, + newRequest request: NSURLRequest, + completionHandler: NSURLRequest? -> Void) + { + print("URLSession will perform HTTP redirection to request: \(request)") + + super.URLSession( + session, + task: task, + willPerformHTTPRedirection: response, + newRequest: request, + completionHandler: completionHandler + ) + } +} +``` + +Generally, either the default implementation or the override closures should provide the necessary functionality required. Subclassing should only be used as a last resort. + +> It is important to keep in mind that the `subdelegates` are initialized and destroyed in the default implementation. Be careful when subclassing to not introduce memory leaks. + ### Security Using a secure HTTPS connection when communicating with servers and web services is an important step in securing sensitive data. By default, Alamofire will evaluate the certificate chain provided by the server using Apple's built in validation provided by the Security framework. While this guarantees the certificate chain is valid, it does not prevent man-in-the-middle (MITM) attacks or other potential vulnerabilities. In order to mitigate MITM attacks, applications dealing with sensitive customer data or financial information should use certificate or public key pinning provided by the `ServerTrustPolicy`. @@ -1075,7 +1187,7 @@ The `.PerformDefaultEvaluation`, `.PinCertificates` and `.PinPublicKeys` server #### Validating the Certificate Chain -Pinning certificates and public keys both have the option of validating the certificate chain using the `validateCertificateChain` parameter. By setting this value to `true`, the full certificate chain will be evaluated in addition to performing a byte equality check against the pinned certficates or public keys. A value of `false` will skip the certificate chain validation, but will still perform the byte equality check. +Pinning certificates and public keys both have the option of validating the certificate chain using the `validateCertificateChain` parameter. By setting this value to `true`, the full certificate chain will be evaluated in addition to performing a byte equality check against the pinned certificates or public keys. A value of `false` will skip the certificate chain validation, but will still perform the byte equality check. There are several cases where it may make sense to disable certificate chain validation. The most common use cases for disabling validation are self-signed and expired certificates. The evaluation would always fail in both of these cases, but the byte equality check will still ensure you are receiving the certificate you expect from the server. @@ -1114,19 +1226,41 @@ Whether you need to set the `NSExceptionRequiresForwardSecrecy` to `NO` depends > It is recommended to always use valid certificates in production environments. ---- +### Network Reachability -## Component Libraries +The `NetworkReachabilityManager` listens for reachability changes of hosts and addresses for both WWAN and WiFi network interfaces. -In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem. +```swift +let manager = NetworkReachabilityManager(host: "www.apple.com") -* [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache and a priority-based image downloading system. +manager?.listener = { status in + print("Network Status Changed: \(status)") +} + +manager?.startListening() +``` + +> Make sure to remember to retain the `manager` in the above example, or no status changes will be reported. + +There are some important things to remember when using network reachability to determine what to do next. + +* **Do NOT** use Reachability to determine if a network request should be sent. + * You should **ALWAYS** send it. +* When Reachability is restored, use the event to retry failed network requests. + * Even though the network requests may still fail, this is a good moment to retry them. +* The network reachability status can be useful for determining why a network request may have failed. + * If a network request fails, it is more useful to tell the user that the network request failed due to being offline rather than a more technical error, such as "request timed out." + +> It is recommended to check out [WWDC 2012 Session 706, "Networking Best Practices"](https://developer.apple.com/videos/play/wwdc2012-706/) for more info. + +--- ## Open Rdars The following rdars have some affect on the current implementation of Alamofire. * [rdar://21349340](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in test case +* [rdar://26761490](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage ## FAQ @@ -1144,6 +1278,20 @@ Alamofire is owned and maintained by the [Alamofire Software Foundation](http:// If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. +## Donations + +The [ASF](https://github.com/Alamofire/Foundation#members) is looking to raise money to officially register as a federal non-profit organization. Registering will allow us members to gain some legal protections and also allow us to put donations to use, tax free. Donating to the ASF will enable us to: + +* Pay our legal fees to register as a federal non-profit organization +* Pay our yearly legal fees to keep the non-profit in good status +* Pay for our mail servers to help us stay on top of all questions and security issues +* Potentially fund test servers to make it easier for us to test the edge cases +* Potentially fund developers to work on one of our projects full-time + +The community adoption of the ASF libraries has been amazing. We are greatly humbled by your enthusiam around the projects, and want to continue to do everything we can to move the needle forward. With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. If you use any of our libraries for work, see if your employers would be interested in donating. Our initial goal is to raise $1000 to get all our legal ducks in a row and kickstart this campaign. Any amount you can donate today to help us reach our goal would be greatly appreciated. + +Click here to lend your support to: Alamofire Software Foundation and make a donation at pledgie.com ! + ## License Alamofire is released under the MIT license. See LICENSE for details. diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift index b866f42264f..cb4b36afbd3 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift @@ -1,24 +1,26 @@ -// Alamofire.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Alamofire.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Download.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Download.swift index b9a043cb8e3..97b146fc016 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Download.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Download.swift @@ -1,24 +1,26 @@ -// Download.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Download.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -211,6 +213,8 @@ extension Request { totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + if let downloadTaskDidWriteData = downloadTaskDidWriteData { downloadTaskDidWriteData( session, diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Error.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Error.swift index 7a813f1b813..467d99c916c 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Error.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Error.swift @@ -1,24 +1,26 @@ -// Error.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Error.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -39,6 +41,15 @@ public struct Error { case PropertyListSerializationFailed = -6007 } + /// Custom keys contained within certain NSError `userInfo` dictionaries generated by Alamofire. + public struct UserInfoKeys { + /// The content type user info key for a `.ContentTypeValidationFailed` error stored as a `String` value. + public static let ContentType = "ContentType" + + /// The status code user info key for a `.StatusCodeValidationFailed` error stored as an `Int` value. + public static let StatusCode = "StatusCode" + } + /** Creates an `NSError` with the given error code and failure reason. @@ -47,6 +58,7 @@ public struct Error { - returns: An `NSError` with the given error code and failure reason. */ + @available(*, deprecated=3.4.0) public static func errorWithCode(code: Code, failureReason: String) -> NSError { return errorWithCode(code.rawValue, failureReason: failureReason) } @@ -59,8 +71,18 @@ public struct Error { - returns: An `NSError` with the given error code and failure reason. */ + @available(*, deprecated=3.4.0) public static func errorWithCode(code: Int, failureReason: String) -> NSError { let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] return NSError(domain: Domain, code: code, userInfo: userInfo) } + + static func error(domain domain: String = Error.Domain, code: Code, failureReason: String) -> NSError { + return error(domain: domain, code: code.rawValue, failureReason: failureReason) + } + + static func error(domain domain: String = Error.Domain, code: Int, failureReason: String) -> NSError { + let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] + return NSError(domain: domain, code: code, userInfo: userInfo) + } } diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift index d81c7380fa8..691d31f62f7 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift @@ -1,24 +1,26 @@ -// Manager.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Manager.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -56,17 +58,40 @@ public class Manager { // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 let userAgent: String = { if let info = NSBundle.mainBundle().infoDictionary { - let executable: AnyObject = info[kCFBundleExecutableKey as String] ?? "Unknown" - let bundle: AnyObject = info[kCFBundleIdentifierKey as String] ?? "Unknown" - let version: AnyObject = info[kCFBundleVersionKey as String] ?? "Unknown" - let os: AnyObject = NSProcessInfo.processInfo().operatingSystemVersionString ?? "Unknown" + let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown" + let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown" + let version = info[kCFBundleVersionKey as String] as? String ?? "Unknown" - var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString - let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString + let osNameVersion: String = { + let versionString: String - if CFStringTransform(mutableUserAgent, UnsafeMutablePointer(nil), transform, false) { - return mutableUserAgent as String - } + if #available(OSX 10.10, *) { + let version = NSProcessInfo.processInfo().operatingSystemVersion + versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" + } else { + versionString = "10.9" + } + + let osName: String = { + #if os(iOS) + return "iOS" + #elseif os(watchOS) + return "watchOS" + #elseif os(tvOS) + return "tvOS" + #elseif os(OSX) + return "OS X" + #elseif os(Linux) + return "Linux" + #else + return "Unknown" + #endif + }() + + return "\(osName) \(versionString)" + }() + + return "\(executable)/\(bundle) (\(version); \(osNameVersion))" } return "Alamofire" @@ -143,11 +168,11 @@ public class Manager { delegate: SessionDelegate, serverTrustPolicyManager: ServerTrustPolicyManager? = nil) { + guard delegate === session.delegate else { return nil } + self.delegate = delegate self.session = session - guard delegate === session.delegate else { return nil } - commonInit(serverTrustPolicyManager: serverTrustPolicyManager) } @@ -218,18 +243,18 @@ public class Manager { /** Responsible for handling all delegate callbacks for the underlying session. */ - public final class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate { + public class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate { private var subdelegates: [Int: Request.TaskDelegate] = [:] private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) - subscript(task: NSURLSessionTask) -> Request.TaskDelegate? { + /// Access the task delegate for the specified task in a thread-safe manner. + public subscript(task: NSURLSessionTask) -> Request.TaskDelegate? { get { var subdelegate: Request.TaskDelegate? dispatch_sync(subdelegateQueue) { subdelegate = self.subdelegates[task.taskIdentifier] } return subdelegate } - set { dispatch_barrier_async(subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue } } @@ -254,6 +279,9 @@ public class Manager { /// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`. public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? + /// Overrides all behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:` and requires the caller to call the `completionHandler`. + public var sessionDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)? + /// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`. public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)? @@ -281,6 +309,11 @@ public class Manager { didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) { + guard sessionDidReceiveChallengeWithCompletion == nil else { + sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler) + return + } + var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling var credential: NSURLCredential? @@ -321,11 +354,23 @@ public class Manager { /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`. public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? + /// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:` and + /// requires the caller to call the `completionHandler`. + public var taskWillPerformHTTPRedirectionWithCompletion: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest, NSURLRequest? -> Void) -> Void)? + /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`. public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? + /// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:` and + /// requires the caller to call the `completionHandler`. + public var taskDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)? + /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`. - public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream!)? + public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)? + + /// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:` and + /// requires the caller to call the `completionHandler`. + public var taskNeedNewBodyStreamWithCompletion: ((NSURLSession, NSURLSessionTask, NSInputStream? -> Void) -> Void)? /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`. public var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)? @@ -351,8 +396,13 @@ public class Manager { task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, - completionHandler: ((NSURLRequest?) -> Void)) + completionHandler: NSURLRequest? -> Void) { + guard taskWillPerformHTTPRedirectionWithCompletion == nil else { + taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler) + return + } + var redirectRequest: NSURLRequest? = request if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { @@ -374,10 +424,16 @@ public class Manager { session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, - completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) + completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) { + guard taskDidReceiveChallengeWithCompletion == nil else { + taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler) + return + } + if let taskDidReceiveChallenge = taskDidReceiveChallenge { - completionHandler(taskDidReceiveChallenge(session, task, challenge)) + let result = taskDidReceiveChallenge(session, task, challenge) + completionHandler(result.0, result.1) } else if let delegate = self[task] { delegate.URLSession( session, @@ -400,8 +456,13 @@ public class Manager { public func URLSession( session: NSURLSession, task: NSURLSessionTask, - needNewBodyStream completionHandler: ((NSInputStream?) -> Void)) + needNewBodyStream completionHandler: NSInputStream? -> Void) { + guard taskNeedNewBodyStreamWithCompletion == nil else { + taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler) + return + } + if let taskNeedNewBodyStream = taskNeedNewBodyStream { completionHandler(taskNeedNewBodyStream(session, task)) } else if let delegate = self[task] { @@ -452,6 +513,8 @@ public class Manager { delegate.URLSession(session, task: task, didCompleteWithError: error) } + NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidComplete, object: task) + self[task] = nil } @@ -462,6 +525,10 @@ public class Manager { /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`. public var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)? + /// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:` and + /// requires caller to call the `completionHandler`. + public var dataTaskDidReceiveResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSURLResponse, NSURLSessionResponseDisposition -> Void) -> Void)? + /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`. public var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)? @@ -469,7 +536,11 @@ public class Manager { public var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)? /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`. - public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse!)? + public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)? + + /// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:` and + /// requires caller to call the `completionHandler`. + public var dataTaskWillCacheResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse, NSCachedURLResponse? -> Void) -> Void)? // MARK: Delegate Methods @@ -487,8 +558,13 @@ public class Manager { session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, - completionHandler: ((NSURLSessionResponseDisposition) -> Void)) + completionHandler: NSURLSessionResponseDisposition -> Void) { + guard dataTaskDidReceiveResponseWithCompletion == nil else { + dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler) + return + } + var disposition: NSURLSessionResponseDisposition = .Allow if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { @@ -550,8 +626,13 @@ public class Manager { session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, - completionHandler: ((NSCachedURLResponse?) -> Void)) + completionHandler: NSCachedURLResponse? -> Void) { + guard dataTaskWillCacheResponseWithCompletion == nil else { + dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler) + return + } + if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) } else if let delegate = self[dataTask] as? Request.DataTaskDelegate { @@ -674,17 +755,21 @@ public class Manager { // MARK: - NSObject public override func respondsToSelector(selector: Selector) -> Bool { + #if !os(OSX) + if selector == #selector(NSURLSessionDelegate.URLSessionDidFinishEventsForBackgroundURLSession(_:)) { + return sessionDidFinishEventsForBackgroundURLSession != nil + } + #endif + switch selector { - case "URLSession:didBecomeInvalidWithError:": + case #selector(NSURLSessionDelegate.URLSession(_:didBecomeInvalidWithError:)): return sessionDidBecomeInvalidWithError != nil - case "URLSession:didReceiveChallenge:completionHandler:": - return sessionDidReceiveChallenge != nil - case "URLSessionDidFinishEventsForBackgroundURLSession:": - return sessionDidFinishEventsForBackgroundURLSession != nil - case "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:": - return taskWillPerformHTTPRedirection != nil - case "URLSession:dataTask:didReceiveResponse:completionHandler:": - return dataTaskDidReceiveResponse != nil + case #selector(NSURLSessionDelegate.URLSession(_:didReceiveChallenge:completionHandler:)): + return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil) + case #selector(NSURLSessionTaskDelegate.URLSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)): + return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil) + case #selector(NSURLSessionDataDelegate.URLSession(_:dataTask:didReceiveResponse:completionHandler:)): + return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil) default: return self.dynamicType.instancesRespondToSelector(selector) } diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift index 8c37f164e7e..b4087eca830 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift @@ -1,24 +1,26 @@ -// MultipartFormData.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// MultipartFormData.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -217,7 +219,7 @@ public class MultipartFormData { appendBodyPart(fileURL: fileURL, name: name, fileName: fileName, mimeType: mimeType) } else { let failureReason = "Failed to extract the fileName of the provided URL: \(fileURL)" - setBodyPartError(Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)) + setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason) } } @@ -245,8 +247,7 @@ public class MultipartFormData { guard fileURL.fileURL else { let failureReason = "The file URL does not point to a file URL: \(fileURL)" - let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) - setBodyPartError(error) + setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason) return } @@ -261,8 +262,7 @@ public class MultipartFormData { } guard isReachable else { - let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)") - setBodyPartError(error) + setBodyPartError(code: NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)") return } @@ -277,8 +277,7 @@ public class MultipartFormData { where NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) && !isDirectory else { let failureReason = "The file URL is a directory, not a file: \(fileURL)" - let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) - setBodyPartError(error) + setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason) return } @@ -301,8 +300,7 @@ public class MultipartFormData { guard let length = bodyContentLength else { let failureReason = "Could not fetch attributes from the file URL: \(fileURL)" - let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) - setBodyPartError(error) + setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason) return } @@ -312,8 +310,7 @@ public class MultipartFormData { guard let stream = NSInputStream(URL: fileURL) else { let failureReason = "Failed to create an input stream from the file URL: \(fileURL)" - let error = Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason) - setBodyPartError(error) + setBodyPartError(code: NSURLErrorCannotOpenFile, failureReason: failureReason) return } @@ -413,10 +410,10 @@ public class MultipartFormData { if let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path) { let failureReason = "A file already exists at the given file URL: \(fileURL)" - throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) + throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorBadURL, failureReason: failureReason) } else if !fileURL.fileURL { let failureReason = "The URL does not point to a valid file: \(fileURL)" - throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) + throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorBadURL, failureReason: failureReason) } let outputStream: NSOutputStream @@ -425,10 +422,9 @@ public class MultipartFormData { outputStream = possibleOutputStream } else { let failureReason = "Failed to create an output stream with the given URL: \(fileURL)" - throw Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason) + throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorCannotOpenFile, failureReason: failureReason) } - outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) outputStream.open() self.bodyParts.first?.hasInitialBoundary = true @@ -439,7 +435,6 @@ public class MultipartFormData { } outputStream.close() - outputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) } // MARK: - Private - Body Part Encoding @@ -476,7 +471,6 @@ public class MultipartFormData { private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) throws -> NSData { let inputStream = bodyPart.bodyStream - inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) inputStream.open() var error: NSError? @@ -495,7 +489,7 @@ public class MultipartFormData { encoded.appendBytes(buffer, length: bytesRead) } else if bytesRead < 0 { let failureReason = "Failed to read from input stream: \(inputStream)" - error = Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason) + error = Error.error(domain: NSURLErrorDomain, code: .InputStreamReadFailed, failureReason: failureReason) break } else { break @@ -503,7 +497,6 @@ public class MultipartFormData { } inputStream.close() - inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) if let error = error { throw error @@ -537,7 +530,6 @@ public class MultipartFormData { private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { let inputStream = bodyPart.bodyStream - inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) inputStream.open() while inputStream.hasBytesAvailable { @@ -556,14 +548,13 @@ public class MultipartFormData { try writeBuffer(&buffer, toOutputStream: outputStream) } else if bytesRead < 0 { let failureReason = "Failed to read from input stream: \(inputStream)" - throw Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason) + throw Error.error(domain: NSURLErrorDomain, code: .InputStreamReadFailed, failureReason: failureReason) } else { break } } inputStream.close() - inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) } private func writeFinalBoundaryDataForBodyPart( @@ -598,7 +589,7 @@ public class MultipartFormData { if bytesWritten < 0 { let failureReason = "Failed to write to output stream: \(outputStream)" - throw Error.errorWithCode(.OutputStreamWriteFailed, failureReason: failureReason) + throw Error.error(domain: NSURLErrorDomain, code: .OutputStreamWriteFailed, failureReason: failureReason) } bytesToWrite -= bytesWritten @@ -661,9 +652,8 @@ public class MultipartFormData { // MARK: - Private - Errors - private func setBodyPartError(error: NSError) { - if bodyPartError == nil { - bodyPartError = error - } + private func setBodyPartError(code code: Int, failureReason: String) { + guard bodyPartError == nil else { return } + bodyPartError = Error.error(domain: NSURLErrorDomain, code: code, failureReason: failureReason) } } diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/NetworkReachabilityManager.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/NetworkReachabilityManager.swift new file mode 100644 index 00000000000..1e5c7b030d3 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/NetworkReachabilityManager.swift @@ -0,0 +1,244 @@ +// +// NetworkReachabilityManager.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#if !os(watchOS) + +import Foundation +import SystemConfiguration + +/** + The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and + WiFi network interfaces. + + Reachability can be used to determine background information about why a network operation failed, or to retry + network requests when a connection is established. It should not be used to prevent a user from initiating a network + request, as it's possible that an initial request may be required to establish reachability. +*/ +public class NetworkReachabilityManager { + /** + Defines the various states of network reachability. + + - Unknown: It is unknown whether the network is reachable. + - NotReachable: The network is not reachable. + - ReachableOnWWAN: The network is reachable over the WWAN connection. + - ReachableOnWiFi: The network is reachable over the WiFi connection. + */ + public enum NetworkReachabilityStatus { + case Unknown + case NotReachable + case Reachable(ConnectionType) + } + + /** + Defines the various connection types detected by reachability flags. + + - EthernetOrWiFi: The connection type is either over Ethernet or WiFi. + - WWAN: The connection type is a WWAN connection. + */ + public enum ConnectionType { + case EthernetOrWiFi + case WWAN + } + + /// A closure executed when the network reachability status changes. The closure takes a single argument: the + /// network reachability status. + public typealias Listener = NetworkReachabilityStatus -> Void + + // MARK: - Properties + + /// Whether the network is currently reachable. + public var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi } + + /// Whether the network is currently reachable over the WWAN interface. + public var isReachableOnWWAN: Bool { return networkReachabilityStatus == .Reachable(.WWAN) } + + /// Whether the network is currently reachable over Ethernet or WiFi interface. + public var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .Reachable(.EthernetOrWiFi) } + + /// The current network reachability status. + public var networkReachabilityStatus: NetworkReachabilityStatus { + guard let flags = self.flags else { return .Unknown } + return networkReachabilityStatusForFlags(flags) + } + + /// The dispatch queue to execute the `listener` closure on. + public var listenerQueue: dispatch_queue_t = dispatch_get_main_queue() + + /// A closure executed when the network reachability status changes. + public var listener: Listener? + + private var flags: SCNetworkReachabilityFlags? { + var flags = SCNetworkReachabilityFlags() + + if SCNetworkReachabilityGetFlags(reachability, &flags) { + return flags + } + + return nil + } + + private let reachability: SCNetworkReachability + private var previousFlags: SCNetworkReachabilityFlags + + // MARK: - Initialization + + /** + Creates a `NetworkReachabilityManager` instance with the specified host. + + - parameter host: The host used to evaluate network reachability. + + - returns: The new `NetworkReachabilityManager` instance. + */ + public convenience init?(host: String) { + guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil } + self.init(reachability: reachability) + } + + /** + Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0. + + Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing + status of the device, both IPv4 and IPv6. + + - returns: The new `NetworkReachabilityManager` instance. + */ + public convenience init?() { + var address = sockaddr_in() + address.sin_len = UInt8(sizeofValue(address)) + address.sin_family = sa_family_t(AF_INET) + + guard let reachability = withUnsafePointer(&address, { + SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) + }) else { return nil } + + self.init(reachability: reachability) + } + + private init(reachability: SCNetworkReachability) { + self.reachability = reachability + self.previousFlags = SCNetworkReachabilityFlags() + } + + deinit { + stopListening() + } + + // MARK: - Listening + + /** + Starts listening for changes in network reachability status. + + - returns: `true` if listening was started successfully, `false` otherwise. + */ + public func startListening() -> Bool { + var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) + context.info = UnsafeMutablePointer(Unmanaged.passUnretained(self).toOpaque()) + + let callbackEnabled = SCNetworkReachabilitySetCallback( + reachability, + { (_, flags, info) in + let reachability = Unmanaged.fromOpaque(COpaquePointer(info)).takeUnretainedValue() + reachability.notifyListener(flags) + }, + &context + ) + + let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue) + + dispatch_async(listenerQueue) { + self.previousFlags = SCNetworkReachabilityFlags() + self.notifyListener(self.flags ?? SCNetworkReachabilityFlags()) + } + + return callbackEnabled && queueEnabled + } + + /** + Stops listening for changes in network reachability status. + */ + public func stopListening() { + SCNetworkReachabilitySetCallback(reachability, nil, nil) + SCNetworkReachabilitySetDispatchQueue(reachability, nil) + } + + // MARK: - Internal - Listener Notification + + func notifyListener(flags: SCNetworkReachabilityFlags) { + guard previousFlags != flags else { return } + previousFlags = flags + + listener?(networkReachabilityStatusForFlags(flags)) + } + + // MARK: - Internal - Network Reachability Status + + func networkReachabilityStatusForFlags(flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus { + guard flags.contains(.Reachable) else { return .NotReachable } + + var networkStatus: NetworkReachabilityStatus = .NotReachable + + if !flags.contains(.ConnectionRequired) { networkStatus = .Reachable(.EthernetOrWiFi) } + + if flags.contains(.ConnectionOnDemand) || flags.contains(.ConnectionOnTraffic) { + if !flags.contains(.InterventionRequired) { networkStatus = .Reachable(.EthernetOrWiFi) } + } + + #if os(iOS) + if flags.contains(.IsWWAN) { networkStatus = .Reachable(.WWAN) } + #endif + + return networkStatus + } +} + +// MARK: - + +extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {} + +/** + Returns whether the two network reachability status values are equal. + + - parameter lhs: The left-hand side value to compare. + - parameter rhs: The right-hand side value to compare. + + - returns: `true` if the two values are equal, `false` otherwise. +*/ +public func ==( + lhs: NetworkReachabilityManager.NetworkReachabilityStatus, + rhs: NetworkReachabilityManager.NetworkReachabilityStatus) + -> Bool +{ + switch (lhs, rhs) { + case (.Unknown, .Unknown): + return true + case (.NotReachable, .NotReachable): + return true + case let (.Reachable(lhsConnectionType), .Reachable(rhsConnectionType)): + return lhsConnectionType == rhsConnectionType + default: + return false + } +} + +#endif diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Notifications.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Notifications.swift new file mode 100644 index 00000000000..cece87a170d --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Notifications.swift @@ -0,0 +1,47 @@ +// +// Notifications.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Contains all the `NSNotification` names posted by Alamofire with descriptions of each notification's payload. +public struct Notifications { + /// Used as a namespace for all `NSURLSessionTask` related notifications. + public struct Task { + /// Notification posted when an `NSURLSessionTask` is resumed. The notification `object` contains the resumed + /// `NSURLSessionTask`. + public static let DidResume = "com.alamofire.notifications.task.didResume" + + /// Notification posted when an `NSURLSessionTask` is suspended. The notification `object` contains the + /// suspended `NSURLSessionTask`. + public static let DidSuspend = "com.alamofire.notifications.task.didSuspend" + + /// Notification posted when an `NSURLSessionTask` is cancelled. The notification `object` contains the + /// cancelled `NSURLSessionTask`. + public static let DidCancel = "com.alamofire.notifications.task.didCancel" + + /// Notification posted when an `NSURLSessionTask` is completed. The notification `object` contains the + /// completed `NSURLSessionTask`. + public static let DidComplete = "com.alamofire.notifications.task.didComplete" + } +} diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift index d56d2d6c3a7..32e63d9b7be 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift @@ -1,24 +1,26 @@ -// ParameterEncoding.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// ParameterEncoding.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -69,8 +71,8 @@ public enum ParameterEncoding { /** Creates a URL request by encoding parameters and applying them onto an existing request. - - parameter URLRequest: The request to have parameters applied - - parameter parameters: The parameters to apply + - parameter URLRequest: The request to have parameters applied. + - parameter parameters: The parameters to apply. - returns: A tuple containing the constructed request and the error that occurred during parameter encoding, if any. @@ -82,9 +84,7 @@ public enum ParameterEncoding { { var mutableURLRequest = URLRequest.URLRequest - guard let parameters = parameters where !parameters.isEmpty else { - return (mutableURLRequest, nil) - } + guard let parameters = parameters else { return (mutableURLRequest, nil) } var encodingError: NSError? = nil @@ -118,7 +118,10 @@ public enum ParameterEncoding { } if let method = Method(rawValue: mutableURLRequest.HTTPMethod) where encodesParametersInURL(method) { - if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) { + if let + URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) + where !parameters.isEmpty + { let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) URLComponents.percentEncodedQuery = percentEncodedQuery mutableURLRequest.URL = URLComponents.URL @@ -141,7 +144,10 @@ public enum ParameterEncoding { let options = NSJSONWritingOptions() let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: options) - mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil { + mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + mutableURLRequest.HTTPBody = data } catch { encodingError = error as NSError @@ -153,7 +159,11 @@ public enum ParameterEncoding { format: format, options: options ) - mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") + + if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil { + mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") + } + mutableURLRequest.HTTPBody = data } catch { encodingError = error as NSError @@ -219,7 +229,7 @@ public enum ParameterEncoding { //========================================================================================================== // // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few - // hundred Chinense characters causes various malloc error crashes. To avoid this issue until iOS 8 is no + // hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more // info, please refer to: // @@ -236,7 +246,7 @@ public enum ParameterEncoding { while index != string.endIndex { let startIndex = index let endIndex = index.advancedBy(batchSize, limit: string.endIndex) - let range = Range(start: startIndex, end: endIndex) + let range = startIndex.. [String: String] { + guard let data = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding) else { return [:] } + + let credential = data.base64EncodedStringWithOptions([]) + + return ["Authorization": "Basic \(credential)"] + } + // MARK: - Progress /** @@ -149,17 +172,21 @@ public class Request { // MARK: - State /** - Suspends the request. + Resumes the request. */ - public func suspend() { - task.suspend() + public func resume() { + if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() } + + task.resume() + NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidResume, object: task) } /** - Resumes the request. + Suspends the request. */ - public func resume() { - task.resume() + public func suspend() { + task.suspend() + NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidSuspend, object: task) } /** @@ -176,6 +203,8 @@ public class Request { } else { task.cancel() } + + NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidCancel, object: task) } // MARK: - TaskDelegate @@ -195,6 +224,7 @@ public class Request { var data: NSData? { return nil } var error: NSError? + var initialResponseTime: CFAbsoluteTime? var credential: NSURLCredential? init(task: NSURLSessionTask) { @@ -272,7 +302,7 @@ public class Request { } } else { if challenge.previousFailureCount > 0 { - disposition = .CancelAuthenticationChallenge + disposition = .RejectProtectionSpace } else { credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace) @@ -381,6 +411,8 @@ public class Request { } func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + if let dataTaskDidReceiveData = dataTaskDidReceiveData { dataTaskDidReceiveData(session, dataTask, data) } else { @@ -470,7 +502,7 @@ extension Request: CustomDebugStringConvertible { let protectionSpace = NSURLProtectionSpace( host: host, port: URL.port?.integerValue ?? 0, - `protocol`: URL.scheme, + protocol: URL.scheme, realm: host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic ) @@ -496,33 +528,31 @@ extension Request: CustomDebugStringConvertible { } } - if let headerFields = request.allHTTPHeaderFields { - for (field, value) in headerFields { - switch field { - case "Cookie": - continue - default: - components.append("-H \"\(field): \(value)\"") - } + var headers: [NSObject: AnyObject] = [:] + + if let additionalHeaders = session.configuration.HTTPAdditionalHeaders { + for (field, value) in additionalHeaders where field != "Cookie" { + headers[field] = value } } - if let additionalHeaders = session.configuration.HTTPAdditionalHeaders { - for (field, value) in additionalHeaders { - switch field { - case "Cookie": - continue - default: - components.append("-H \"\(field): \(value)\"") - } + if let headerFields = request.allHTTPHeaderFields { + for (field, value) in headerFields where field != "Cookie" { + headers[field] = value } } + for (field, value) in headers { + components.append("-H \"\(field): \(value)\"") + } + if let HTTPBodyData = request.HTTPBody, HTTPBody = String(data: HTTPBodyData, encoding: NSUTF8StringEncoding) { - let escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\"", withString: "\\\"") + var escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\\\"", withString: "\\\\\"") + escapedBody = escapedBody.stringByReplacingOccurrencesOfString("\"", withString: "\\\"") + components.append("-d \"\(escapedBody)\"") } diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Response.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Response.swift index fa2fffb3dea..dd700bb1c82 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Response.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Response.swift @@ -1,24 +1,26 @@ -// Response.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Response.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -36,6 +38,9 @@ public struct Response { /// The result of response serialization. public let result: Result + /// The timeline of the complete lifecycle of the `Request`. + public let timeline: Timeline + /** Initializes the `Response` instance with the specified URL request, URL response, server data and response serialization result. @@ -44,14 +49,22 @@ public struct Response { - parameter response: The server's response to the URL request. - parameter data: The data returned by the server. - parameter result: The result of response serialization. - + - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. + - returns: the new `Response` instance. */ - public init(request: NSURLRequest?, response: NSHTTPURLResponse?, data: NSData?, result: Result) { + public init( + request: NSURLRequest?, + response: NSHTTPURLResponse?, + data: NSData?, + result: Result, + timeline: Timeline = Timeline()) + { self.request = request self.response = response self.data = data self.result = result + self.timeline = timeline } } @@ -77,6 +90,7 @@ extension Response: CustomDebugStringConvertible { output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") output.append("[Data]: \(data?.length ?? 0) bytes") output.append("[Result]: \(result.debugDescription)") + output.append("[Timeline]: \(timeline.debugDescription)") return output.joinWithSeparator("\n") } diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift index 4aaacf61e31..5b7b61f9002 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift @@ -1,24 +1,26 @@ -// ResponseSerialization.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// ResponseSerialization.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -29,10 +31,10 @@ import Foundation */ public protocol ResponseSerializerType { /// The type of serialized object to be created by this `ResponseSerializerType`. - typealias SerializedObject + associatedtype SerializedObject /// The type of error to be created by this `ResponseSerializer` if serialization fails. - typealias ErrorObject: ErrorType + associatedtype ErrorObject: ErrorType /** A closure used by response handlers that takes a request, response, data and error and returns a result. @@ -119,16 +121,25 @@ extension Request { self.delegate.error ) - dispatch_async(queue ?? dispatch_get_main_queue()) { - let response = Response( - request: self.request, - response: self.response, - data: self.delegate.data, - result: result - ) + let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent() + let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime - completionHandler(response) - } + let timeline = Timeline( + requestStartTime: self.startTime ?? CFAbsoluteTimeGetCurrent(), + initialResponseTime: initialResponseTime, + requestCompletedTime: requestCompletedTime, + serializationCompletedTime: CFAbsoluteTimeGetCurrent() + ) + + let response = Response( + request: self.request, + response: self.response, + data: self.delegate.data, + result: result, + timeline: timeline + ) + + dispatch_async(queue ?? dispatch_get_main_queue()) { completionHandler(response) } } return self @@ -152,7 +163,7 @@ extension Request { guard let validData = data else { let failureReason = "Data could not be serialized. Input data was nil." - let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason) + let error = Error.error(code: .DataSerializationFailed, failureReason: failureReason) return .Failure(error) } @@ -167,8 +178,12 @@ extension Request { - returns: The request. */ - public func responseData(completionHandler: Response -> Void) -> Self { - return response(responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler) + public func responseData( + queue queue: dispatch_queue_t? = nil, + completionHandler: Response -> Void) + -> Self + { + return response(queue: queue, responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler) } } @@ -186,7 +201,7 @@ extension Request { - returns: A string response serializer. */ public static func stringResponseSerializer( - var encoding encoding: NSStringEncoding? = nil) + encoding encoding: NSStringEncoding? = nil) -> ResponseSerializer { return ResponseSerializer { _, response, data, error in @@ -196,23 +211,25 @@ extension Request { guard let validData = data else { let failureReason = "String could not be serialized. Input data was nil." - let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason) + let error = Error.error(code: .StringSerializationFailed, failureReason: failureReason) return .Failure(error) } - - if let encodingName = response?.textEncodingName where encoding == nil { - encoding = CFStringConvertEncodingToNSStringEncoding( + + var convertedEncoding = encoding + + if let encodingName = response?.textEncodingName where convertedEncoding == nil { + convertedEncoding = CFStringConvertEncodingToNSStringEncoding( CFStringConvertIANACharSetNameToEncoding(encodingName) ) } - let actualEncoding = encoding ?? NSISOLatin1StringEncoding + let actualEncoding = convertedEncoding ?? NSISOLatin1StringEncoding if let string = String(data: validData, encoding: actualEncoding) { return .Success(string) } else { let failureReason = "String could not be serialized with encoding: \(actualEncoding)" - let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason) + let error = Error.error(code: .StringSerializationFailed, failureReason: failureReason) return .Failure(error) } } @@ -229,11 +246,13 @@ extension Request { - returns: The request. */ public func responseString( - encoding encoding: NSStringEncoding? = nil, + queue queue: dispatch_queue_t? = nil, + encoding: NSStringEncoding? = nil, completionHandler: Response -> Void) -> Self { return response( + queue: queue, responseSerializer: Request.stringResponseSerializer(encoding: encoding), completionHandler: completionHandler ) @@ -263,7 +282,7 @@ extension Request { guard let validData = data where validData.length > 0 else { let failureReason = "JSON could not be serialized. Input data was nil or zero length." - let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason) + let error = Error.error(code: .JSONSerializationFailed, failureReason: failureReason) return .Failure(error) } @@ -285,11 +304,13 @@ extension Request { - returns: The request. */ public func responseJSON( - options options: NSJSONReadingOptions = .AllowFragments, + queue queue: dispatch_queue_t? = nil, + options: NSJSONReadingOptions = .AllowFragments, completionHandler: Response -> Void) -> Self { return response( + queue: queue, responseSerializer: Request.JSONResponseSerializer(options: options), completionHandler: completionHandler ) @@ -319,7 +340,7 @@ extension Request { guard let validData = data where validData.length > 0 else { let failureReason = "Property list could not be serialized. Input data was nil or zero length." - let error = Error.errorWithCode(.PropertyListSerializationFailed, failureReason: failureReason) + let error = Error.error(code: .PropertyListSerializationFailed, failureReason: failureReason) return .Failure(error) } @@ -343,11 +364,13 @@ extension Request { - returns: The request. */ public func responsePropertyList( - options options: NSPropertyListReadOptions = NSPropertyListReadOptions(), + queue queue: dispatch_queue_t? = nil, + options: NSPropertyListReadOptions = NSPropertyListReadOptions(), completionHandler: Response -> Void) -> Self { return response( + queue: queue, responseSerializer: Request.propertyListResponseSerializer(options: options), completionHandler: completionHandler ) diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Result.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Result.swift index a8557cabb42..ed1df0fc845 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Result.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Result.swift @@ -1,24 +1,26 @@ -// Result.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Result.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift index 07cd848a606..44ba100be43 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift @@ -1,24 +1,26 @@ -// ServerTrustPolicy.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// ServerTrustPolicy.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift index bc9ee450c5a..07ebe3374ff 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift @@ -1,30 +1,32 @@ -// Stream.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Stream.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation #if !os(watchOS) -@available(iOS 9.0, OSX 10.11, *) +@available(iOS 9.0, OSX 10.11, tvOS 9.0, *) extension Manager { private enum Streamable { case Stream(String, Int) @@ -82,7 +84,7 @@ extension Manager { // MARK: - -@available(iOS 9.0, OSX 10.11, *) +@available(iOS 9.0, OSX 10.11, tvOS 9.0, *) extension Manager.SessionDelegate: NSURLSessionStreamDelegate { // MARK: Override Closures diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Timeline.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Timeline.swift new file mode 100644 index 00000000000..95936827285 --- /dev/null +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Timeline.swift @@ -0,0 +1,138 @@ +// +// Timeline.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Responsible for computing the timing metrics for the complete lifecycle of a `Request`. +public struct Timeline { + /// The time the request was initialized. + public let requestStartTime: CFAbsoluteTime + + /// The time the first bytes were received from or sent to the server. + public let initialResponseTime: CFAbsoluteTime + + /// The time when the request was completed. + public let requestCompletedTime: CFAbsoluteTime + + /// The time when the response serialization was completed. + public let serializationCompletedTime: CFAbsoluteTime + + /// The time interval in seconds from the time the request started to the initial response from the server. + public let latency: NSTimeInterval + + /// The time interval in seconds from the time the request started to the time the request completed. + public let requestDuration: NSTimeInterval + + /// The time interval in seconds from the time the request completed to the time response serialization completed. + public let serializationDuration: NSTimeInterval + + /// The time interval in seconds from the time the request started to the time response serialization completed. + public let totalDuration: NSTimeInterval + + /** + Creates a new `Timeline` instance with the specified request times. + + - parameter requestStartTime: The time the request was initialized. Defaults to `0.0`. + - parameter initialResponseTime: The time the first bytes were received from or sent to the server. + Defaults to `0.0`. + - parameter requestCompletedTime: The time when the request was completed. Defaults to `0.0`. + - parameter serializationCompletedTime: The time when the response serialization was completed. Defaults + to `0.0`. + + - returns: The new `Timeline` instance. + */ + public init( + requestStartTime: CFAbsoluteTime = 0.0, + initialResponseTime: CFAbsoluteTime = 0.0, + requestCompletedTime: CFAbsoluteTime = 0.0, + serializationCompletedTime: CFAbsoluteTime = 0.0) + { + self.requestStartTime = requestStartTime + self.initialResponseTime = initialResponseTime + self.requestCompletedTime = requestCompletedTime + self.serializationCompletedTime = serializationCompletedTime + + self.latency = initialResponseTime - requestStartTime + self.requestDuration = requestCompletedTime - requestStartTime + self.serializationDuration = serializationCompletedTime - requestCompletedTime + self.totalDuration = serializationCompletedTime - requestStartTime + } +} + +// MARK: - CustomStringConvertible + +extension Timeline: CustomStringConvertible { + /// The textual representation used when written to an output stream, which includes the latency, the request + /// duration and the total duration. + public var description: String { + let latency = String(format: "%.3f", self.latency) + let requestDuration = String(format: "%.3f", self.requestDuration) + let serializationDuration = String(format: "%.3f", self.serializationDuration) + let totalDuration = String(format: "%.3f", self.totalDuration) + + // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is + // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. + let timings = [ + "\"Latency\": " + latency + " secs", + "\"Request Duration\": " + requestDuration + " secs", + "\"Serialization Duration\": " + serializationDuration + " secs", + "\"Total Duration\": " + totalDuration + " secs" + ] + + return "Timeline: { " + timings.joinWithSeparator(", ") + " }" + } +} + +// MARK: - CustomDebugStringConvertible + +extension Timeline: CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, which includes the request start time, the + /// initial response time, the request completed time, the serialization completed time, the latency, the request + /// duration and the total duration. + public var debugDescription: String { + let requestStartTime = String(format: "%.3f", self.requestStartTime) + let initialResponseTime = String(format: "%.3f", self.initialResponseTime) + let requestCompletedTime = String(format: "%.3f", self.requestCompletedTime) + let serializationCompletedTime = String(format: "%.3f", self.serializationCompletedTime) + let latency = String(format: "%.3f", self.latency) + let requestDuration = String(format: "%.3f", self.requestDuration) + let serializationDuration = String(format: "%.3f", self.serializationDuration) + let totalDuration = String(format: "%.3f", self.totalDuration) + + // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is + // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. + let timings = [ + "\"Request Start Time\": " + requestStartTime, + "\"Initial Response Time\": " + initialResponseTime, + "\"Request Completed Time\": " + requestCompletedTime, + "\"Serialization Completed Time\": " + serializationCompletedTime, + "\"Latency\": " + latency + " secs", + "\"Request Duration\": " + requestDuration + " secs", + "\"Serialization Duration\": " + serializationDuration + " secs", + "\"Total Duration\": " + totalDuration + " secs" + ] + + return "Timeline: { " + timings.joinWithSeparator(", ") + " }" + } +} diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift index ee6b34ced5b..7b31ba53073 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift @@ -1,24 +1,26 @@ -// Upload.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Upload.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -359,6 +361,8 @@ extension Request { totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + if let taskDidSendBodyData = taskDidSendBodyData { taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) } else { diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift index 71d21e1afa6..e90db2d4a10 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift @@ -1,24 +1,26 @@ -// Validation.swift // -// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// Validation.swift // -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. import Foundation @@ -80,7 +82,17 @@ extension Request { return .Success } else { let failureReason = "Response status code was unacceptable: \(response.statusCode)" - return .Failure(Error.errorWithCode(.StatusCodeValidationFailed, failureReason: failureReason)) + + let error = NSError( + domain: Error.Domain, + code: Error.Code.StatusCodeValidationFailed.rawValue, + userInfo: [ + NSLocalizedFailureReasonErrorKey: failureReason, + Error.UserInfoKeys.StatusCode: response.statusCode + ] + ) + + return .Failure(error) } } } @@ -149,18 +161,31 @@ extension Request { } } + let contentType: String let failureReason: String if let responseContentType = response.MIMEType { + contentType = responseContentType + failureReason = ( "Response content type \"\(responseContentType)\" does not match any acceptable " + "content types: \(acceptableContentTypes)" ) } else { + contentType = "" failureReason = "Response content type was missing and acceptable content type does not match \"*/*\"" } - return .Failure(Error.errorWithCode(.ContentTypeValidationFailed, failureReason: failureReason)) + let error = NSError( + domain: Error.Domain, + code: Error.Code.ContentTypeValidationFailed.rawValue, + userInfo: [ + NSLocalizedFailureReasonErrorKey: failureReason, + Error.UserInfoKeys.ContentType: contentType + ] + ) + + return .Failure(error) } } diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json index 99bf5ef601f..0920f1985e9 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json @@ -9,8 +9,8 @@ "git": "git@github.com:swagger-api/swagger-mustache.git", "tag": "v1.0.0" }, + "authors": "", "license": "Apache License, Version 2.0", - "authors": "Apache License, Version 2.0", "homepage": "https://github.com/swagger-api/swagger-codegen", "summary": "PetstoreClient", "source_files": "PetstoreClient/Classes/Swaggers/**/*.swift", @@ -19,7 +19,7 @@ "~> 3.1.1" ], "Alamofire": [ - "~> 3.1.5" + "~> 3.4.1" ] } } diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Manifest.lock b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Manifest.lock index 201c7e37514..0686012e4a0 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Manifest.lock +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Manifest.lock @@ -1,14 +1,14 @@ PODS: - - Alamofire (3.1.5) - - OMGHTTPURLRQ (3.1.1): - - OMGHTTPURLRQ/RQ (= 3.1.1) - - OMGHTTPURLRQ/FormURLEncode (3.1.1) - - OMGHTTPURLRQ/RQ (3.1.1): + - Alamofire (3.4.1) + - OMGHTTPURLRQ (3.1.3): + - OMGHTTPURLRQ/RQ (= 3.1.3) + - OMGHTTPURLRQ/FormURLEncode (3.1.3) + - OMGHTTPURLRQ/RQ (3.1.3): - OMGHTTPURLRQ/FormURLEncode - OMGHTTPURLRQ/UserAgent - - OMGHTTPURLRQ/UserAgent (3.1.1) + - OMGHTTPURLRQ/UserAgent (3.1.3) - PetstoreClient (0.0.1): - - Alamofire (~> 3.1.5) + - Alamofire (~> 3.4.1) - PromiseKit (~> 3.1.1) - PromiseKit (3.1.1): - PromiseKit/Foundation (= 3.1.1) @@ -31,11 +31,11 @@ EXTERNAL SOURCES: :path: "../" SPEC CHECKSUMS: - Alamofire: 5f730ba29fd113b7ddd71c1e65d0c630acf5d7b0 - OMGHTTPURLRQ: 633f98ee745aeda02345935a52eec1784cddb589 - PetstoreClient: efd495da2b7a6f3e798752702d59f96e306dbace + Alamofire: 01a82e2f6c0f860ade35534c8dd88be61bdef40c + OMGHTTPURLRQ: a547be1b9721ddfbf9d08aab56ab72dc4c1cc417 + PetstoreClient: 24135348a992f2cbd76bc324719173b52e864cdc PromiseKit: 4e8127c22a9b29d1b44958ab2ec762ea6115cbfb PODFILE CHECKSUM: 84472aca2a88b7f7ed9fcd63e9f5fdb5ad4aab94 -COCOAPODS: 1.0.0 +COCOAPODS: 1.0.1 diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/README.markdown b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/README.markdown index ff905517872..1cd71258ad3 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/README.markdown +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/README.markdown @@ -39,7 +39,7 @@ NSData *data2 = UIImagePNGRepresentation(image2); [multipartFormData addFile:data2 parameterName:@"file2" filename:@"myimage2.png" contentType:@"image/png"]; // SUPER Ideally you would not want to re-encode the JPEG as the process -// is lossy. If you image comes from the AssetLibrary you *CAN* get the +// is lossy. If your image comes from the AssetLibrary you *CAN* get the // original `NSData`. See stackoverflow.com. UIImage *image3 = [UIImage imageNamed:@"image3"]; NSData *data3 = UIImageJPEGRepresentation(image3); @@ -97,7 +97,7 @@ your API keys that registering at https://dev.twitter.com will provide you. ```objc -NSMutableURLRequest *rq = [TDOAuth URLRequestForPath:@"/oauth/request_token" POSTParameters:@{@"x_auth_mode" : @"reverse_auth"} host:@"api.twitter.com"consumerKey:APIKey consumerSecret:APISecret accessToken:nil tokenSecret:nil]; +NSMutableURLRequest *rq = [TDOAuth URLRequestForPath:@"/oauth/request_token" POSTParameters:@{@"x_auth_mode" : @"reverse_auth"} host:@"api.twitter.com" consumerKey:APIKey consumerSecret:APISecret accessToken:nil tokenSecret:nil]; [rq addValue:OMGUserAgent() forHTTPHeaderField:@"User-Agent"]; [NSURLConnection sendAsynchronousRequest:rq queue:nil completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { @@ -142,4 +142,4 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -``` \ No newline at end of file +``` diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGHTTPURLRQ.m b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGHTTPURLRQ.m index 0854acd0eb7..321ee61eb2e 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGHTTPURLRQ.m +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGHTTPURLRQ.m @@ -47,7 +47,6 @@ - (void)add:(NSData *)payload :(NSString *)name :(NSString *)filename :(NSString [body appendData:[ln1 dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[ln2 dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:payload]; - [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; } - (void)addFile:(NSData *)payload parameterName:(NSString *)name filename:(NSString *)filename contentType:(NSString *)contentType @@ -71,8 +70,8 @@ - (void)addParameters:(NSDictionary *)parameters { @implementation OMGHTTPURLRQ + (NSMutableURLRequest *)GET:(NSString *)urlString :(NSDictionary *)params error:(NSError **)error { - id queryString = OMGFormURLEncode(params); - if (queryString) urlString = [urlString stringByAppendingFormat:@"?%@", queryString]; + NSString *queryString = OMGFormURLEncode(params); + if (queryString.length) urlString = [urlString stringByAppendingFormat:@"?%@", queryString]; id url = [NSURL URLWithString:urlString]; if (!url) { diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj index b435c9a1477..1b6f460f95d 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj @@ -7,105 +7,108 @@ objects = { /* Begin PBXBuildFile section */ - 01BD61BBC475EB3369237B84FE24D3EE /* UIViewController+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 0BA017E288BB42E06EBEE9C6E6993EAF /* UIViewController+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 0268F9278E32ACC1F996F4E2E45622B5 /* UIActionSheet+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 6846D22C9F0CCBC48DF833E309A8E84F /* UIActionSheet+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 03F494989CC1A8857B68A317D5D6860F /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DF5FC3AF99846209C5FCE55A2E12D9A /* Response.swift */; }; + 01BD61BBC475EB3369237B84FE24D3EE /* UIViewController+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 7B892AF5EA37A5C7962FEA3E294B2526 /* UIViewController+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0268F9278E32ACC1F996F4E2E45622B5 /* UIActionSheet+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 590BCD68D24A72708312E57A91360AC7 /* UIActionSheet+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; 066335E8B1AEEB4CF633B2ED738D6223 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 79E01B70640812E104A60E8F985F7E9D /* Foundation.framework */; }; - 0681ADC8BAE2C3185F13487BAAB4D9DD /* Upload.swift in Sources */ = {isa = PBXBuildFile; fileRef = CCE38472832BBCC541E646DA6C18EF9C /* Upload.swift */; }; - 06F7C0C55DF4C09C015159F6B0802EB1 /* join.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84319E048FE6DD89B905FA3A81005C5F /* join.swift */; }; - 0B34EB4425C08BB021C2D09F75C9C146 /* OMGHTTPURLRQ.h in Headers */ = {isa = PBXBuildFile; fileRef = 450166FEA2155A5821D97744A0127DF8 /* OMGHTTPURLRQ.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 0BD8B4E55E72312366130E97A1204CD8 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 79E01B70640812E104A60E8F985F7E9D /* Foundation.framework */; }; - 0BDA43D8F48C8B0D504C440046FAF681 /* Umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 0A8906F6D6920DF197965D1740A7E283 /* Umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 0D240D796AAD10F0119A1D7AC2570AAA /* NSObject+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6EB54C331FED437583A5F01EB2757D1 /* NSObject+Promise.swift */; }; - 11C221075C5B20BDEEB3DDF8EAC99E63 /* NSNotificationCenter+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 4798BAC01B0E3F07E3BBBB07BA57F2D7 /* NSNotificationCenter+AnyPromise.m */; }; - 11EA8D6B0352FD31F520F983CFB9D993 /* UIAlertView+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = F075F63EFE77F7B59FF77CBA95B9AADF /* UIAlertView+AnyPromise.m */; }; - 12348513CB81BD05B497C210905CDF65 /* UIAlertView+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 92D340D66F03F31237B70F23FE9B00D0 /* UIAlertView+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 124EFF5E3C46EC88F47C52479FA6ACAF /* CALayer+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 04A22F2595054D39018E03961CA7283A /* CALayer+AnyPromise.m */; }; + 06F7C0C55DF4C09C015159F6B0802EB1 /* join.swift in Sources */ = {isa = PBXBuildFile; fileRef = BED547C24FF8AE5F91ED94E3BC8052C8 /* join.swift */; }; + 095406039B4D371E48D08B38A2975AC8 /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7390892336E4D605CF390FFA4B55EF0A /* Error.swift */; }; + 0B34EB4425C08BB021C2D09F75C9C146 /* OMGHTTPURLRQ.h in Headers */ = {isa = PBXBuildFile; fileRef = 859DDC0FFB13DB9C838BA38D0641A1BA /* OMGHTTPURLRQ.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0BDA43D8F48C8B0D504C440046FAF681 /* Umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = B0B08C036B6283A3D528F1FBBEEF40EC /* Umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0D240D796AAD10F0119A1D7AC2570AAA /* NSObject+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6650152803DA41F52DA6A26B5DF713D7 /* NSObject+Promise.swift */; }; + 11C221075C5B20BDEEB3DDF8EAC99E63 /* NSNotificationCenter+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = DCBC249F9443D7D79A42B5C4BAC874C8 /* NSNotificationCenter+AnyPromise.m */; }; + 11EA8D6B0352FD31F520F983CFB9D993 /* UIAlertView+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 9FB7C011EC5C968D7A91E71A028913B7 /* UIAlertView+AnyPromise.m */; }; + 12348513CB81BD05B497C210905CDF65 /* UIAlertView+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 4E19A7D44620C4AED963248648938767 /* UIAlertView+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 124EFF5E3C46EC88F47C52479FA6ACAF /* CALayer+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = DD83C2B5FF3BF5AB85E18B1BB6293857 /* CALayer+AnyPromise.m */; }; 15ECEBA1EFBD023AEA47F36524270D2C /* Models.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F0266C5AE0B23A436291F6647902086 /* Models.swift */; }; - 18FAC6B4FD3B44CB353C7A6027286100 /* NSURLConnection+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = BAE48ACA10E8895BB8BF5CE8C0846B4B /* NSURLConnection+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 1AC7E88F0EC64D1D4E83CE7767BFD2B7 /* afterlife.swift in Sources */ = {isa = PBXBuildFile; fileRef = C476B916B763E55E4161F0B30760C4E8 /* afterlife.swift */; }; + 16102E4E35FAA0FC4161282FECE56469 /* Timeline.swift in Sources */ = {isa = PBXBuildFile; fileRef = 47B728204DA3D60FAB04A757D3B09D2E /* Timeline.swift */; }; + 18FAC6B4FD3B44CB353C7A6027286100 /* NSURLConnection+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = E0B0C8D6D1D56B95983D680363E6F785 /* NSURLConnection+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 1AC7E88F0EC64D1D4E83CE7767BFD2B7 /* afterlife.swift in Sources */ = {isa = PBXBuildFile; fileRef = 178262A3EEE3B9A6F7B9B2B4ED5AA150 /* afterlife.swift */; }; 1CB5E10963E95432A9674D1FF2B48FA1 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 79E01B70640812E104A60E8F985F7E9D /* Foundation.framework */; }; 1CDA074C6DC95876D85E13ECF882B93A /* Pet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 284B3DE9B793FCC633E971DB1798AFAF /* Pet.swift */; }; - 1E1010EA437F154A554D04F7F3A894EC /* Promise+Properties.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7E0DBDE561A6C2E7AC7A24160F8A5F28 /* Promise+Properties.swift */; }; + 1E1010EA437F154A554D04F7F3A894EC /* Promise+Properties.swift in Sources */ = {isa = PBXBuildFile; fileRef = B225BF6ADAA247F1300081D25732B5B4 /* Promise+Properties.swift */; }; 25FBB92AFB8F5A777CE8E40EC3B9DACA /* PetstoreClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */; }; 2B38BB4603B4286FF8D7A780372E947F /* PetAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 261F03A3C73374FD19333EEA59CCD59F /* PetAPI.swift */; }; - 2C5450AC69398958CF6F7539EF7D99E5 /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 30CE7341A995EF6812D71771E74CF7F7 /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 2D3405986FC586FA6C0A5E0B6BA7E64E /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0435721889B71489503A007D233559DF /* Validation.swift */; }; 2D9379807BA243E1CE457D1BE963DA09 /* UserAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 552D15E0340BF58CC1922B82E864AEC9 /* UserAPI.swift */; }; - 3860D960E37C1257BDA54626CA592E86 /* AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 1F19945EE403F7B29D8B1939EA6D579A /* AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 387C7387FDC662D23D743879B6143D59 /* UIActionSheet+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD570E28B63274E742E7D1FBBD55BB41 /* UIActionSheet+Promise.swift */; }; - 3A8D316D4266A3309D0A98ED74F8A13A /* OMGUserAgent.h in Headers */ = {isa = PBXBuildFile; fileRef = 87BC7910B8D7D31310A07C32438A8C67 /* OMGUserAgent.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 34CCDCA848A701466256BC2927DA8856 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = FFB0686D05BA9C4D5A69D6058C029FF2 /* NetworkReachabilityManager.swift */; }; + 3860D960E37C1257BDA54626CA592E86 /* AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = D475FE9899956F5D2196D1C19DFC1F28 /* AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 387C7387FDC662D23D743879B6143D59 /* UIActionSheet+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = DDDBF73F440D96AB666A6418AEEF2946 /* UIActionSheet+Promise.swift */; }; + 3A8D316D4266A3309D0A98ED74F8A13A /* OMGUserAgent.h in Headers */ = {isa = PBXBuildFile; fileRef = 4FF818D195F8814F5F8878A2FD02AF1D /* OMGUserAgent.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3EA8F215C9C1432D74E5CCA4834AA8C0 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA62734652B80C3897AA655226B3BCF3 /* ResponseSerialization.swift */; }; + 4081EA628AF0B73AC51FFB9D7AB3B89E /* Manager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1AA002805CE140B0968FC965A53F0A4C /* Manager.swift */; }; 443361437B359830308B93A7B98BE039 /* StoreAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A3E5E3CD673B025FD8AC260E67AB47E /* StoreAPI.swift */; }; 46F838880F41F56ABD91796FC956B4BF /* APIHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = D2BAD338E56EF3CAA6E54490FE0C5DF9 /* APIHelper.swift */; }; - 48CB8E7E16443CA771E4DCFB3E0709A2 /* OMGHTTPURLRQ.m in Sources */ = {isa = PBXBuildFile; fileRef = 9D579267FC1F163C8F04B444DAEFED0D /* OMGHTTPURLRQ.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; - 4C22563311AC2B52651A6525A979E076 /* UIView+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 2F0F4EDC2236E1C270DC2014181D6506 /* UIView+AnyPromise.m */; }; - 4DE5FCC41D100B113B6645EA64410F16 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1FBD351D007CF4095C98C9DFD9D83D61 /* ParameterEncoding.swift */; }; + 48CB8E7E16443CA771E4DCFB3E0709A2 /* OMGHTTPURLRQ.m in Sources */ = {isa = PBXBuildFile; fileRef = 3EEC1FB4B45C5C247D2D0FB33D4F5A1D /* OMGHTTPURLRQ.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + 4C22563311AC2B52651A6525A979E076 /* UIView+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = EA13BF2FADA101A1AB34BF5EC8C7BA85 /* UIView+AnyPromise.m */; }; 516D41E4D035A817CC5116C11302E408 /* AlamofireImplementations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 92734297B64DFE0EB0EDE1EA821163DB /* AlamofireImplementations.swift */; }; - 5192A7466019F9B3D7F1E987124E96BC /* OMGHTTPURLRQ-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F7EBDD2EEED520E06ACB3538B3832049 /* OMGHTTPURLRQ-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 5480169E42C456C49BE59E273D7E0115 /* OMGFormURLEncode.h in Headers */ = {isa = PBXBuildFile; fileRef = 51ADA0B6B6B00CB0E818AA8CBC311677 /* OMGFormURLEncode.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 5D7EAE5725A7E750B51FD27AECB5F0FD /* join.m in Sources */ = {isa = PBXBuildFile; fileRef = 6AD59903FAA8315AD0036AC459FFB97F /* join.m */; }; + 5192A7466019F9B3D7F1E987124E96BC /* OMGHTTPURLRQ-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 3029ADF04ADC2B8F3A7264A416D70B56 /* OMGHTTPURLRQ-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5480169E42C456C49BE59E273D7E0115 /* OMGFormURLEncode.h in Headers */ = {isa = PBXBuildFile; fileRef = 3B1578E353CE37C4C4201EC9101DE67F /* OMGFormURLEncode.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5BC19E6E0F199276003F0AF96838BCE5 /* Upload.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9E0C3DC76C639C91EF9B920C8E3D60F /* Upload.swift */; }; + 5CB05FBCB32D21E194B5ECF680CB6AE0 /* Download.swift in Sources */ = {isa = PBXBuildFile; fileRef = 770621722C3B98D9380F76F3310EAA7F /* Download.swift */; }; + 5D7EAE5725A7E750B51FD27AECB5F0FD /* join.m in Sources */ = {isa = PBXBuildFile; fileRef = E3B8EDBFFE2A701981A073412ECCF6AD /* join.m */; }; 5EE5E1CA27F3CB04A5DCF5BB90B76000 /* Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5412898DEB10F1983487A10453C6B9CB /* Extensions.swift */; }; - 5FFED823C0BDD412FA41B01EA47394D1 /* hang.m in Sources */ = {isa = PBXBuildFile; fileRef = F4B6A98D6DAF474045210F5A74FF1C3C /* hang.m */; }; - 60EBBACB76CD5879FB7B9B3E0AA5E2C1 /* UIViewController+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = AA24C5EC82CF437D8D1FFFAB68975408 /* UIViewController+AnyPromise.m */; }; + 5FFED823C0BDD412FA41B01EA47394D1 /* hang.m in Sources */ = {isa = PBXBuildFile; fileRef = 955F5499BB7496155FBF443B524F1D50 /* hang.m */; }; + 60EBBACB76CD5879FB7B9B3E0AA5E2C1 /* UIViewController+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 53F1201EF49979297542207D6EB6EC55 /* UIViewController+AnyPromise.m */; }; + 62E8346F03C03E7F4D631361F325689E /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74E1D5C24530737CDD54FA854E37B371 /* Response.swift */; }; 656BED6137A9FFA3B2DF03861F525022 /* PetstoreClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 6A128FE350973D8A693E3F063C5E4A49 /* dispatch_promise.m in Sources */ = {isa = PBXBuildFile; fileRef = A92242715FB4C0608F8DCEBF8F3791E2 /* dispatch_promise.m */; }; + 6A128FE350973D8A693E3F063C5E4A49 /* dispatch_promise.m in Sources */ = {isa = PBXBuildFile; fileRef = 7356B0365E4182E6E6D55124C678B591 /* dispatch_promise.m */; }; 6B0A17CD24331793D2504E0FBBAF5EB2 /* Tag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 211F73A46D90346F7FC6D0D29640EE4F /* Tag.swift */; }; - 6CB84A616D7B4D189A4E94BD37621575 /* OMGUserAgent.m in Sources */ = {isa = PBXBuildFile; fileRef = E11BFB27B43B742CB5D6086C4233A909 /* OMGUserAgent.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; - 6F63943B0E954F701F32BC7A1F4C2FEC /* OMGFormURLEncode.m in Sources */ = {isa = PBXBuildFile; fileRef = 25614E715DDC170DAFB0DF50C5503E33 /* OMGFormURLEncode.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; - 73FA79FDB37E5C458B996012BFB0CF04 /* PMKAlertController.swift in Sources */ = {isa = PBXBuildFile; fileRef = C731FBFCC690050C6C08E5AC9D9DC724 /* PMKAlertController.swift */; }; + 6CB84A616D7B4D189A4E94BD37621575 /* OMGUserAgent.m in Sources */ = {isa = PBXBuildFile; fileRef = 937CB6976C5F585A76A9383107F5AF73 /* OMGUserAgent.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + 6F63943B0E954F701F32BC7A1F4C2FEC /* OMGFormURLEncode.m in Sources */ = {isa = PBXBuildFile; fileRef = 56CDA7C9327CF6F3DFC66FC128D7365B /* OMGFormURLEncode.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + 73FA79FDB37E5C458B996012BFB0CF04 /* PMKAlertController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0608A7843513940A299A88D778388F9D /* PMKAlertController.swift */; }; + 7B48852C4D848FA2DA416A98F6425869 /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D1D96AB285E285A3CC15FAD1CD875B2 /* ServerTrustPolicy.swift */; }; 7D7A40DBAC93241786E8C553921E8C86 /* OMGHTTPURLRQ.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3530BF15E14D1F6D7134EE67377D5C8C /* OMGHTTPURLRQ.framework */; }; - 80F496237530D382A045A29654D8C11C /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 400A6910E83F606BCD67DC11FA706697 /* ServerTrustPolicy.swift */; }; - 81A2DB65C0742D785DE7C2609CC14140 /* NSURLSession+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 535DF88FC12304114DEF55E4003421B2 /* NSURLSession+Promise.swift */; }; + 81A2DB65C0742D785DE7C2609CC14140 /* NSURLSession+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5A5AEB5CADDFFFC419A0D8D6FD914800 /* NSURLSession+Promise.swift */; }; 825D1C93689636D09044C5077E5D905F /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 355303D423040E9AB8E2164D8C903B23 /* UIKit.framework */; }; - 82971968CBDAB224212EEB4607C9FB8D /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 53F8B2513042BD6DB957E8063EF895BD /* Result.swift */; }; - 8399DBEE3E2D98EB1F466132E476F4D9 /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5F14E17B4D6BDF8BD3E384BE6528F744 /* MultipartFormData.swift */; }; - 857E5961D9F6E23BD86DEB613A1499C7 /* NSError+Cancellation.h in Headers */ = {isa = PBXBuildFile; fileRef = 045C1F608ADE57757E6732D721779F22 /* NSError+Cancellation.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 88B3F911629C08DEEB226F3B294AAB36 /* NSNotificationCenter+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = B93FB4BB16CFB41DCA35A8CFAD7A7FEF /* NSNotificationCenter+Promise.swift */; }; + 857E5961D9F6E23BD86DEB613A1499C7 /* NSError+Cancellation.h in Headers */ = {isa = PBXBuildFile; fileRef = 2E9E05F82273A09FD6E5CA99FD3A74D9 /* NSError+Cancellation.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 88B3F911629C08DEEB226F3B294AAB36 /* NSNotificationCenter+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 786AAA1F62613C489FD473D4CE16127A /* NSNotificationCenter+Promise.swift */; }; 897283A0B7F5299913327CC8FD6CC997 /* Pods-SwaggerClientTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 8C4A96A3E69C772990E3E922D0FD1BC4 /* UIView+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = BCDD82DB3E6D43BA9769FCA9B744CB5E /* UIView+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 8D3A68D3CBD8A1D89099F704A04A04FC /* PromiseKit-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 9042667D08D783E45394FE8B97EE6468 /* PromiseKit-dummy.m */; }; - 8E3861989641484EE3095722EC08B5A9 /* NSURLConnection+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = A7F0DAACAC89A93B940BBE54E6A87E9F /* NSURLConnection+AnyPromise.m */; }; - 909B0A29022956D90C32C4AA319F75D1 /* AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 1B7E90A568681E000EF3CB0917584F3C /* AnyPromise.m */; }; - 97D71F12142A541BEEF425805D51379E /* race.swift in Sources */ = {isa = PBXBuildFile; fileRef = 980FD13F87B44BFD90F8AC129BEB2E61 /* race.swift */; }; + 8C4A96A3E69C772990E3E922D0FD1BC4 /* UIView+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 13DB7D7990FD3354E34510894CC30CD1 /* UIView+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8D3A68D3CBD8A1D89099F704A04A04FC /* PromiseKit-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = B09DEE52CBDEC1EA108DD327EF036F4A /* PromiseKit-dummy.m */; }; + 8E3861989641484EE3095722EC08B5A9 /* NSURLConnection+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = D9A940E08D42AC7D07C6B74D3310C69A /* NSURLConnection+AnyPromise.m */; }; + 8EB11202167FCDDF1257AAAB1D1FB244 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = FDA7C65B58A0E739E615FA7A750AA0AD /* Alamofire.swift */; }; + 909B0A29022956D90C32C4AA319F75D1 /* AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = EC8150042B23FCA7DF9979098694EC0B /* AnyPromise.m */; }; + 91C09AC2A52ED69A27C8D923139A006F /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 79E01B70640812E104A60E8F985F7E9D /* Foundation.framework */; }; + 9469DF81ECB494E84675969B5E13374C /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 791F2A99A7894F88F8BBAE2F6C627522 /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 97D71F12142A541BEEF425805D51379E /* race.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EC07412ABFB8D5A06E7B38380FFD9C4 /* race.swift */; }; 9876AE0817723FB5E93A94B1E1906901 /* Pods-SwaggerClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */; }; 9CFBA896DF45B68C788F80013AC3FDBB /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A1D1571AB15108DF6F9C4FE2064E3C43 /* Alamofire.framework */; }; - A2C172FE407C0BC3478ADCA91A6C9CEC /* Manager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2D51C929AC51E34493AA757180C09C3B /* Manager.swift */; }; - A3505FA2FB3067D53847AD288AC04F03 /* Download.swift in Sources */ = {isa = PBXBuildFile; fileRef = A04177B09D9596450D827FE49A36C4C4 /* Download.swift */; }; A4BA36ADDDFBCF208CC58E552C0AC85C /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 79E01B70640812E104A60E8F985F7E9D /* Foundation.framework */; }; - ADEEE5F368B5D707D03E78FD75C59048 /* Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3D23C407A7CDBFD244D6115899F9D45D /* Promise.swift */; }; - B0FB4B01682814B9E3D32F9DC4A5E762 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8B476A57549D7994745E17A6DE5BE745 /* Alamofire.swift */; }; - B6D2DC3E3DA44CD382B9B425F40E11C1 /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 139346EB669CBE2DE8FE506E14A2BA9C /* Alamofire-dummy.m */; }; + AA314156AC500125F4078EE968DB14C6 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1F60254382C7024DDFD16533FB81750A /* Result.swift */; }; + ADEEE5F368B5D707D03E78FD75C59048 /* Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = DDB573F3C977C55072704AA24EC06164 /* Promise.swift */; }; + ADF19C953CE2A7D0B72EC93A81FCCC26 /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = F0962CCF21BDD2EB5751C14F9322AFC9 /* Alamofire-dummy.m */; }; + AE4CF87C02C042DF13ED5B21C4FDC1E0 /* Stream.swift in Sources */ = {isa = PBXBuildFile; fileRef = BCC88BB5150F5865EE3017D1B9AB4CF5 /* Stream.swift */; }; + BE41196F6A3903E59C3306FE3F8B43FE /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9519BB8B059D8A17CE43587EB6EFA61D /* Notifications.swift */; }; + C0DB70AB368765DC64BFB5FEA75E0696 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = E4B2CF9B72BC56E74E6B0037BDE92031 /* ParameterEncoding.swift */; }; C141DD535C090B58DD95D53988AAA42B /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 79E01B70640812E104A60E8F985F7E9D /* Foundation.framework */; }; C546890220177F840E8AFC829D0E3FEB /* Pods-SwaggerClientTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */; }; - C75519F0450166A6F28126ECC7664E9C /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA1AD92813B887E2D017D051B8C0E3D2 /* Validation.swift */; }; - C86881D2285095255829A578F0A85300 /* after.m in Sources */ = {isa = PBXBuildFile; fileRef = B868468092D7B2489B889A50981C9247 /* after.m */; }; - C86CE0A47FAD4C9B2929A335D62A179E /* UIViewController+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6D459D0AB2361B48F81C4D14C6D0DAA /* UIViewController+Promise.swift */; }; - CAF12A3EDA2376FFEAD4A12E413C1AAD /* UIActionSheet+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 9774D31336C85248A115B569E7D95283 /* UIActionSheet+AnyPromise.m */; }; - CB2A58CBAB5A2E63D0CB70F2697CAE87 /* when.m in Sources */ = {isa = PBXBuildFile; fileRef = 143BC30E5DDAF52A3D9578F507EC6A41 /* when.m */; }; + C7B6DD7C0456C50289A2C381DFE9FA3F /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA79CBD1DDA33C45473F8807605719BC /* MultipartFormData.swift */; }; + C86881D2285095255829A578F0A85300 /* after.m in Sources */ = {isa = PBXBuildFile; fileRef = 4765491FCD8E096D84D4E57E005B8B49 /* after.m */; }; + C86CE0A47FAD4C9B2929A335D62A179E /* UIViewController+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7C40ADE30634419CED97EC829EE5D2C /* UIViewController+Promise.swift */; }; + CAF12A3EDA2376FFEAD4A12E413C1AAD /* UIActionSheet+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = CABB6C822D84DC5F0596B6D7B60CC5AA /* UIActionSheet+AnyPromise.m */; }; + CB2A58CBAB5A2E63D0CB70F2697CAE87 /* when.m in Sources */ = {isa = PBXBuildFile; fileRef = 9C307C0A58A490D3080DB4C1E745C973 /* when.m */; }; CD97970D21D3CB8C459FAFEF11EE60F3 /* Category.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4DF0604EDC1460935E6E445A47023A4 /* Category.swift */; }; - CE225CF07E6E385F014883D607AFA44D /* URLDataPromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7CE161ED0CF68954A63F30528ACAD9B /* URLDataPromise.swift */; }; - CE89E5C528D52BBCBCD23309603BA6D1 /* CALayer+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 27E0FE41D771BE8BE3F0D4F1DAD0B179 /* CALayer+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; - D1735D6C4D574339EB49024228448459 /* UIView+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3CDA0958D6247505ECD9098D662EA74 /* UIView+Promise.swift */; }; - D21B7325B3642887BFBE977E021F2D26 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD558DDCDDA1B46951548B02C34277EF /* ResponseSerialization.swift */; }; - D358A828E68E152D06FC8E35533BF00B /* OMGHTTPURLRQ-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 0F36B65CF990C57DC527824ED0BA1915 /* OMGHTTPURLRQ-dummy.m */; }; + CE225CF07E6E385F014883D607AFA44D /* URLDataPromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0E339112CF5C9275CFBEB94C29AD250B /* URLDataPromise.swift */; }; + CE89E5C528D52BBCBCD23309603BA6D1 /* CALayer+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = E48946E76C93EE81F20C76C0EE272B8E /* CALayer+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D1735D6C4D574339EB49024228448459 /* UIView+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5E69FDAAF09817F0BA67D7C575BAFF48 /* UIView+Promise.swift */; }; + D358A828E68E152D06FC8E35533BF00B /* OMGHTTPURLRQ-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 8F88352C39FB2D4A0D36696674E7C05D /* OMGHTTPURLRQ-dummy.m */; }; D546A4DBA3F7750F45A6F63B994C081C /* User.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B248364ABF60ACD7DB31A17DCFDFD0C /* User.swift */; }; - D75CA395D510E08C404E55F5BDAE55CE /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A9CB35983E4859DFFBAD8840196A094 /* Error.swift */; }; - D93596046CD3B301F4EC99A7A118C82C /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 558DFECE2C740177CA6357DA71A1DFBB /* Error.swift */; }; + D93596046CD3B301F4EC99A7A118C82C /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = DFFF6310B8F8C445362FF33E936F85CA /* Error.swift */; }; D97B0097ACB39F4E308E996F4F2AC836 /* Pods-SwaggerClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - DBD1F4247E1C591AE4EE5531599AB170 /* NSNotificationCenter+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 3616971BAEF40302B7F2F8B1007C0B2B /* NSNotificationCenter+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + DBD1F4247E1C591AE4EE5531599AB170 /* NSNotificationCenter+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = EFC77A5BCF407679FAB606F03E631A11 /* NSNotificationCenter+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; E2B0094FAAEA55C55AD141136F650E35 /* Order.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A545673F09F49CDD60A13B4B0AF1020 /* Order.swift */; }; EA35E77B4F31DC3E1D224458E0BC959D /* APIs.swift in Sources */ = {isa = PBXBuildFile; fileRef = D8072E1108951F272C003553FC8926C7 /* APIs.swift */; }; - EA67B414E392EFD2B14742F55A595596 /* after.swift in Sources */ = {isa = PBXBuildFile; fileRef = 275DA9A664C70DD40A4059090D1A00D4 /* after.swift */; }; - EB3C88CDAF122BA763FEF85758370C7C /* UIAlertView+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA854180C132DB5511D64C82535C5FDE /* UIAlertView+Promise.swift */; }; - EB9A1F33DB49ADA09F6E7F19A2C30357 /* NSURLConnection+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 412985229DA7A4DF9E129B7E8F0C09BB /* NSURLConnection+Promise.swift */; }; - ED30A8B82BA1D53CBC370B1DC18DA1EB /* when.swift in Sources */ = {isa = PBXBuildFile; fileRef = 16730DAF3E51C161D8247E473F069E71 /* when.swift */; }; + EA67B414E392EFD2B14742F55A595596 /* after.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3E49ED544745AD479AFA0B6766F441CE /* after.swift */; }; + EB3C88CDAF122BA763FEF85758370C7C /* UIAlertView+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E29EB54AEC61300AD412C40991FFED5 /* UIAlertView+Promise.swift */; }; + EB9A1F33DB49ADA09F6E7F19A2C30357 /* NSURLConnection+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9066E09FAD7A3236DAD81317C1E48214 /* NSURLConnection+Promise.swift */; }; + ED30A8B82BA1D53CBC370B1DC18DA1EB /* when.swift in Sources */ = {isa = PBXBuildFile; fileRef = DEFA2BBF978F33CA2112DC5D6209A3EF /* when.swift */; }; + EFE92E8D3813DD26E78E93EEAF6D7E7E /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D3192434754120C2AAF44818AEE054B /* Request.swift */; }; F206C370F63155D3468E0C188498C5DC /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 79E01B70640812E104A60E8F985F7E9D /* Foundation.framework */; }; - F4582E8DC1C9F362ADA4BAE9CEF8B681 /* dispatch_promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 392FA21A33296B88F790D62A4FAA4E4E /* dispatch_promise.swift */; }; - F700EAA9F9F6C1F99C83B45D05C5AD14 /* PromiseKit.h in Headers */ = {isa = PBXBuildFile; fileRef = 3BFFA6FD621E9ED341AA89AEAC1604D7 /* PromiseKit.h */; settings = {ATTRIBUTES = (Public, ); }; }; - F7161E50F083B2267363F243C4E4B78F /* AnyPromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5973BC143AE488C12FFB1E83E71F0C45 /* AnyPromise.swift */; }; - F898D4270885EF1114608E76B0C09E21 /* State.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8DC63EB77B3791891517B98CAA115DE8 /* State.swift */; }; + F4582E8DC1C9F362ADA4BAE9CEF8B681 /* dispatch_promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 85FD17541BFB4152FD5F2CA46F9E3ACC /* dispatch_promise.swift */; }; + F700EAA9F9F6C1F99C83B45D05C5AD14 /* PromiseKit.h in Headers */ = {isa = PBXBuildFile; fileRef = 1AAED38B682D186542DC2B8D273486F4 /* PromiseKit.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F7161E50F083B2267363F243C4E4B78F /* AnyPromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1FB5ABB73E12675999DE989CC2478A7A /* AnyPromise.swift */; }; + F898D4270885EF1114608E76B0C09E21 /* State.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3BEE20F7C5242E616D2D97B5FBE31323 /* State.swift */; }; FB0B33F03AC2BC8A7FC7FD912C12CC22 /* PromiseKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A112EF8BB3933C1C1E42F11B3DD3B02A /* PromiseKit.framework */; }; - FC14480CECE872865A9C6E584F886DA3 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 133C5287CFDCB3B67578A7B1221E132C /* Request.swift */; }; - FEF0D7653948988B804226129471C1EC /* Stream.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A8F373B23E0F7FB68B0BA71D92D1C60 /* Stream.swift */; }; FFA95B8BEE43D793FF453E49099AC52E /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0B92202857E3535647B0785253083518 /* QuartzCore.framework */; }; /* End PBXBuildFile section */ @@ -114,7 +117,7 @@ isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; - remoteGlobalIDString = 432ECC54282C84882B482CCB4CF227FC; + remoteGlobalIDString = 79C040AFDDCE1BCBF6D8B5EB0B85887F; remoteInfo = Alamofire; }; 6795BDA8BF074DFC4E5D1758C8F88C2A /* PBXContainerItemProxy */ = { @@ -142,7 +145,7 @@ isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; - remoteGlobalIDString = 432ECC54282C84882B482CCB4CF227FC; + remoteGlobalIDString = 79C040AFDDCE1BCBF6D8B5EB0B85887F; remoteInfo = Alamofire; }; ABF692D458113B268763EDC4670EAF7A /* PBXContainerItemProxy */ = { @@ -164,138 +167,141 @@ /* Begin PBXFileReference section */ 00ACB4396DD1B4E4539E4E81C1D7A14E /* Pods-SwaggerClientTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = "Pods-SwaggerClientTests.modulemap"; sourceTree = ""; }; 02F28E719AA874BE9213D6CF8CE7E36B /* Pods-SwaggerClientTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClientTests-acknowledgements.plist"; sourceTree = ""; }; - 045C1F608ADE57757E6732D721779F22 /* NSError+Cancellation.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSError+Cancellation.h"; path = "Sources/NSError+Cancellation.h"; sourceTree = ""; }; - 04A22F2595054D39018E03961CA7283A /* CALayer+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "CALayer+AnyPromise.m"; path = "Categories/QuartzCore/CALayer+AnyPromise.m"; sourceTree = ""; }; + 0435721889B71489503A007D233559DF /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; + 0608A7843513940A299A88D778388F9D /* PMKAlertController.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PMKAlertController.swift; path = Categories/UIKit/PMKAlertController.swift; sourceTree = ""; }; 0A545673F09F49CDD60A13B4B0AF1020 /* Order.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Order.swift; sourceTree = ""; }; - 0A8906F6D6920DF197965D1740A7E283 /* Umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Umbrella.h; path = Sources/Umbrella.h; sourceTree = ""; }; 0B92202857E3535647B0785253083518 /* QuartzCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QuartzCore.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.3.sdk/System/Library/Frameworks/QuartzCore.framework; sourceTree = DEVELOPER_DIR; }; - 0BA017E288BB42E06EBEE9C6E6993EAF /* UIViewController+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIViewController+AnyPromise.h"; path = "Categories/UIKit/UIViewController+AnyPromise.h"; sourceTree = ""; }; 0C552CDBDD89D489D23D5D4E28356F84 /* PromiseKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = PromiseKit.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 0F36B65CF990C57DC527824ED0BA1915 /* OMGHTTPURLRQ-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "OMGHTTPURLRQ-dummy.m"; sourceTree = ""; }; - 122D5005A81832479161CD1D223C573A /* PromiseKit-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PromiseKit-prefix.pch"; sourceTree = ""; }; - 133C5287CFDCB3B67578A7B1221E132C /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; - 139346EB669CBE2DE8FE506E14A2BA9C /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; - 141F0B43C42CE92856BBA8F8D98481DB /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; - 143BC30E5DDAF52A3D9578F507EC6A41 /* when.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = when.m; path = Sources/when.m; sourceTree = ""; }; - 16730DAF3E51C161D8247E473F069E71 /* when.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = when.swift; path = Sources/when.swift; sourceTree = ""; }; - 16D7C901D915C251DEBA27AC1EF57E34 /* OMGHTTPURLRQ.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = OMGHTTPURLRQ.xcconfig; sourceTree = ""; }; + 0E339112CF5C9275CFBEB94C29AD250B /* URLDataPromise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = URLDataPromise.swift; path = Sources/URLDataPromise.swift; sourceTree = ""; }; + 10A634092EE6D018EB00C75E9864A6A2 /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; + 11683764D40FE241FCEEB379EE92E817 /* PromiseKit-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PromiseKit-prefix.pch"; sourceTree = ""; }; + 13DB7D7990FD3354E34510894CC30CD1 /* UIView+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIView+AnyPromise.h"; path = "Categories/UIKit/UIView+AnyPromise.h"; sourceTree = ""; }; + 178262A3EEE3B9A6F7B9B2B4ED5AA150 /* afterlife.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = afterlife.swift; path = Categories/Foundation/afterlife.swift; sourceTree = ""; }; 1A3E5E3CD673B025FD8AC260E67AB47E /* StoreAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = StoreAPI.swift; sourceTree = ""; }; - 1B7E90A568681E000EF3CB0917584F3C /* AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AnyPromise.m; path = Sources/AnyPromise.m; sourceTree = ""; }; - 1F19945EE403F7B29D8B1939EA6D579A /* AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AnyPromise.h; path = Sources/AnyPromise.h; sourceTree = ""; }; - 1FBD351D007CF4095C98C9DFD9D83D61 /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; + 1AA002805CE140B0968FC965A53F0A4C /* Manager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Manager.swift; path = Source/Manager.swift; sourceTree = ""; }; + 1AAED38B682D186542DC2B8D273486F4 /* PromiseKit.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PromiseKit.h; path = Sources/PromiseKit.h; sourceTree = ""; }; + 1F60254382C7024DDFD16533FB81750A /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = ""; }; + 1FB5ABB73E12675999DE989CC2478A7A /* AnyPromise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnyPromise.swift; path = Sources/AnyPromise.swift; sourceTree = ""; }; 211F73A46D90346F7FC6D0D29640EE4F /* Tag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Tag.swift; sourceTree = ""; }; - 24C79ED4B5226F263307B22E96E88F9F /* OMGHTTPURLRQ.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = OMGHTTPURLRQ.modulemap; sourceTree = ""; }; - 25614E715DDC170DAFB0DF50C5503E33 /* OMGFormURLEncode.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OMGFormURLEncode.m; path = Sources/OMGFormURLEncode.m; sourceTree = ""; }; 261F03A3C73374FD19333EEA59CCD59F /* PetAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PetAPI.swift; sourceTree = ""; }; - 275DA9A664C70DD40A4059090D1A00D4 /* after.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = after.swift; path = Sources/after.swift; sourceTree = ""; }; - 27E0FE41D771BE8BE3F0D4F1DAD0B179 /* CALayer+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "CALayer+AnyPromise.h"; path = "Categories/QuartzCore/CALayer+AnyPromise.h"; sourceTree = ""; }; 284B3DE9B793FCC633E971DB1798AFAF /* Pet.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Pet.swift; sourceTree = ""; }; 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClient-dummy.m"; sourceTree = ""; }; - 2D51C929AC51E34493AA757180C09C3B /* Manager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Manager.swift; path = Source/Manager.swift; sourceTree = ""; }; - 2F0F4EDC2236E1C270DC2014181D6506 /* UIView+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIView+AnyPromise.m"; path = "Categories/UIKit/UIView+AnyPromise.m"; sourceTree = ""; }; + 2E750A27FAB06DE866BC27CC8FA07806 /* PromiseKit.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = PromiseKit.xcconfig; sourceTree = ""; }; + 2E9E05F82273A09FD6E5CA99FD3A74D9 /* NSError+Cancellation.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSError+Cancellation.h"; path = "Sources/NSError+Cancellation.h"; sourceTree = ""; }; 2FF17440CCD2E1A69791A4AA23325AD5 /* Pods-SwaggerClient-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClient-acknowledgements.markdown"; sourceTree = ""; }; - 30CE7341A995EF6812D71771E74CF7F7 /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; + 3029ADF04ADC2B8F3A7264A416D70B56 /* OMGHTTPURLRQ-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "OMGHTTPURLRQ-umbrella.h"; sourceTree = ""; }; 3530BF15E14D1F6D7134EE67377D5C8C /* OMGHTTPURLRQ.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = OMGHTTPURLRQ.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 355303D423040E9AB8E2164D8C903B23 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.3.sdk/System/Library/Frameworks/UIKit.framework; sourceTree = DEVELOPER_DIR; }; - 3616971BAEF40302B7F2F8B1007C0B2B /* NSNotificationCenter+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSNotificationCenter+AnyPromise.h"; path = "Categories/Foundation/NSNotificationCenter+AnyPromise.h"; sourceTree = ""; }; - 392FA21A33296B88F790D62A4FAA4E4E /* dispatch_promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = dispatch_promise.swift; path = Sources/dispatch_promise.swift; sourceTree = ""; }; - 3950B63B8EB1B9CD8FC31CDA8CC2E7C7 /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; - 3BFFA6FD621E9ED341AA89AEAC1604D7 /* PromiseKit.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PromiseKit.h; path = Sources/PromiseKit.h; sourceTree = ""; }; - 3CE589B7B1FE57084403D25DC49528B5 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 3D23C407A7CDBFD244D6115899F9D45D /* Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Promise.swift; path = Sources/Promise.swift; sourceTree = ""; }; + 3B1578E353CE37C4C4201EC9101DE67F /* OMGFormURLEncode.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OMGFormURLEncode.h; path = Sources/OMGFormURLEncode.h; sourceTree = ""; }; + 3BEE20F7C5242E616D2D97B5FBE31323 /* State.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = State.swift; path = Sources/State.swift; sourceTree = ""; }; + 3E49ED544745AD479AFA0B6766F441CE /* after.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = after.swift; path = Sources/after.swift; sourceTree = ""; }; + 3EC07412ABFB8D5A06E7B38380FFD9C4 /* race.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = race.swift; path = Sources/race.swift; sourceTree = ""; }; 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-SwaggerClient-umbrella.h"; sourceTree = ""; }; + 3EEC1FB4B45C5C247D2D0FB33D4F5A1D /* OMGHTTPURLRQ.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OMGHTTPURLRQ.m; path = Sources/OMGHTTPURLRQ.m; sourceTree = ""; }; 3F16B43ABD2C8CD4A311AA1AB3B6C02F /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 400A6910E83F606BCD67DC11FA706697 /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; - 412985229DA7A4DF9E129B7E8F0C09BB /* NSURLConnection+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSURLConnection+Promise.swift"; path = "Categories/Foundation/NSURLConnection+Promise.swift"; sourceTree = ""; }; 43FC49AA70D3E2A84CAED9C37BE9C4B5 /* Pods-SwaggerClientTests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-frameworks.sh"; sourceTree = ""; }; - 450166FEA2155A5821D97744A0127DF8 /* OMGHTTPURLRQ.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OMGHTTPURLRQ.h; path = Sources/OMGHTTPURLRQ.h; sourceTree = ""; }; + 467F288FF1A023115720F192FD4D9297 /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = Alamofire.modulemap; sourceTree = ""; }; 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "PetstoreClient-dummy.m"; sourceTree = ""; }; - 4798BAC01B0E3F07E3BBBB07BA57F2D7 /* NSNotificationCenter+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSNotificationCenter+AnyPromise.m"; path = "Categories/Foundation/NSNotificationCenter+AnyPromise.m"; sourceTree = ""; }; - 51ADA0B6B6B00CB0E818AA8CBC311677 /* OMGFormURLEncode.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OMGFormURLEncode.h; path = Sources/OMGFormURLEncode.h; sourceTree = ""; }; - 535DF88FC12304114DEF55E4003421B2 /* NSURLSession+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSURLSession+Promise.swift"; path = "Categories/Foundation/NSURLSession+Promise.swift"; sourceTree = ""; }; - 53F8B2513042BD6DB957E8063EF895BD /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = ""; }; + 4765491FCD8E096D84D4E57E005B8B49 /* after.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = after.m; path = Sources/after.m; sourceTree = ""; }; + 47B728204DA3D60FAB04A757D3B09D2E /* Timeline.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeline.swift; path = Source/Timeline.swift; sourceTree = ""; }; + 4E19A7D44620C4AED963248648938767 /* UIAlertView+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIAlertView+AnyPromise.h"; path = "Categories/UIKit/UIAlertView+AnyPromise.h"; sourceTree = ""; }; + 4FF818D195F8814F5F8878A2FD02AF1D /* OMGUserAgent.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OMGUserAgent.h; path = Sources/OMGUserAgent.h; sourceTree = ""; }; + 53F1201EF49979297542207D6EB6EC55 /* UIViewController+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIViewController+AnyPromise.m"; path = "Categories/UIKit/UIViewController+AnyPromise.m"; sourceTree = ""; }; 5412898DEB10F1983487A10453C6B9CB /* Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Extensions.swift; sourceTree = ""; }; 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.debug.xcconfig"; sourceTree = ""; }; 552D15E0340BF58CC1922B82E864AEC9 /* UserAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = UserAPI.swift; sourceTree = ""; }; - 558DFECE2C740177CA6357DA71A1DFBB /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = Sources/Error.swift; sourceTree = ""; }; - 5973BC143AE488C12FFB1E83E71F0C45 /* AnyPromise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnyPromise.swift; path = Sources/AnyPromise.swift; sourceTree = ""; }; + 56CDA7C9327CF6F3DFC66FC128D7365B /* OMGFormURLEncode.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OMGFormURLEncode.m; path = Sources/OMGFormURLEncode.m; sourceTree = ""; }; + 590BCD68D24A72708312E57A91360AC7 /* UIActionSheet+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIActionSheet+AnyPromise.h"; path = "Categories/UIKit/UIActionSheet+AnyPromise.h"; sourceTree = ""; }; + 5A5AEB5CADDFFFC419A0D8D6FD914800 /* NSURLSession+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSURLSession+Promise.swift"; path = "Categories/Foundation/NSURLSession+Promise.swift"; sourceTree = ""; }; 5B248364ABF60ACD7DB31A17DCFDFD0C /* User.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = User.swift; sourceTree = ""; }; - 5DF5FC3AF99846209C5FCE55A2E12D9A /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; - 5F14E17B4D6BDF8BD3E384BE6528F744 /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; - 6846D22C9F0CCBC48DF833E309A8E84F /* UIActionSheet+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIActionSheet+AnyPromise.h"; path = "Categories/UIKit/UIActionSheet+AnyPromise.h"; sourceTree = ""; }; + 5E69FDAAF09817F0BA67D7C575BAFF48 /* UIView+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIView+Promise.swift"; path = "Categories/UIKit/UIView+Promise.swift"; sourceTree = ""; }; + 6650152803DA41F52DA6A26B5DF713D7 /* NSObject+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSObject+Promise.swift"; path = "Categories/Foundation/NSObject+Promise.swift"; sourceTree = ""; }; 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClientTests-dummy.m"; sourceTree = ""; }; - 6AD59903FAA8315AD0036AC459FFB97F /* join.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = join.m; path = Sources/join.m; sourceTree = ""; }; - 792D14AC86CD98AA9C31373287E0F353 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 705D1370384B46A3E5A39B39E7B4D181 /* OMGHTTPURLRQ-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "OMGHTTPURLRQ-prefix.pch"; sourceTree = ""; }; + 7356B0365E4182E6E6D55124C678B591 /* dispatch_promise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = dispatch_promise.m; path = Sources/dispatch_promise.m; sourceTree = ""; }; + 7390892336E4D605CF390FFA4B55EF0A /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = Source/Error.swift; sourceTree = ""; }; + 74E1D5C24530737CDD54FA854E37B371 /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; + 770621722C3B98D9380F76F3310EAA7F /* Download.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Download.swift; path = Source/Download.swift; sourceTree = ""; }; + 786AAA1F62613C489FD473D4CE16127A /* NSNotificationCenter+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSNotificationCenter+Promise.swift"; path = "Categories/Foundation/NSNotificationCenter+Promise.swift"; sourceTree = ""; }; + 791F2A99A7894F88F8BBAE2F6C627522 /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; 79E01B70640812E104A60E8F985F7E9D /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.3.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + 7B892AF5EA37A5C7962FEA3E294B2526 /* UIViewController+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIViewController+AnyPromise.h"; path = "Categories/UIKit/UIViewController+AnyPromise.h"; sourceTree = ""; }; 7C8E63660D346FD8ED2A97242E74EA09 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 7E0DBDE561A6C2E7AC7A24160F8A5F28 /* Promise+Properties.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Properties.swift"; path = "Sources/Promise+Properties.swift"; sourceTree = ""; }; - 84319E048FE6DD89B905FA3A81005C5F /* join.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = join.swift; path = Sources/join.swift; sourceTree = ""; }; + 7D3192434754120C2AAF44818AEE054B /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; + 835E52C658674D7A44ED95B966432726 /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; 849FECBC6CC67F2B6800F982927E3A9E /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; + 859DDC0FFB13DB9C838BA38D0641A1BA /* OMGHTTPURLRQ.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OMGHTTPURLRQ.h; path = Sources/OMGHTTPURLRQ.h; sourceTree = ""; }; + 85FD17541BFB4152FD5F2CA46F9E3ACC /* dispatch_promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = dispatch_promise.swift; path = Sources/dispatch_promise.swift; sourceTree = ""; }; 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; - 8749F40CC17CE0C26C36B0F431A9C8F0 /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = Alamofire.modulemap; sourceTree = ""; }; - 87BC7910B8D7D31310A07C32438A8C67 /* OMGUserAgent.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OMGUserAgent.h; path = Sources/OMGUserAgent.h; sourceTree = ""; }; - 8A8F373B23E0F7FB68B0BA71D92D1C60 /* Stream.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Stream.swift; path = Source/Stream.swift; sourceTree = ""; }; - 8A9CB35983E4859DFFBAD8840196A094 /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = Source/Error.swift; sourceTree = ""; }; - 8B476A57549D7994745E17A6DE5BE745 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; - 8DC63EB77B3791891517B98CAA115DE8 /* State.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = State.swift; path = Sources/State.swift; sourceTree = ""; }; + 8D1D96AB285E285A3CC15FAD1CD875B2 /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; + 8E29EB54AEC61300AD412C40991FFED5 /* UIAlertView+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIAlertView+Promise.swift"; path = "Categories/UIKit/UIAlertView+Promise.swift"; sourceTree = ""; }; 8F0266C5AE0B23A436291F6647902086 /* Models.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Models.swift; sourceTree = ""; }; - 9042667D08D783E45394FE8B97EE6468 /* PromiseKit-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "PromiseKit-dummy.m"; sourceTree = ""; }; + 8F8078A9DEC41CD886A8676D889912A4 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 8F88352C39FB2D4A0D36696674E7C05D /* OMGHTTPURLRQ-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "OMGHTTPURLRQ-dummy.m"; sourceTree = ""; }; + 9066E09FAD7A3236DAD81317C1E48214 /* NSURLConnection+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSURLConnection+Promise.swift"; path = "Categories/Foundation/NSURLConnection+Promise.swift"; sourceTree = ""; }; 92734297B64DFE0EB0EDE1EA821163DB /* AlamofireImplementations.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AlamofireImplementations.swift; sourceTree = ""; }; - 92D340D66F03F31237B70F23FE9B00D0 /* UIAlertView+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIAlertView+AnyPromise.h"; path = "Categories/UIKit/UIAlertView+AnyPromise.h"; sourceTree = ""; }; + 937CB6976C5F585A76A9383107F5AF73 /* OMGUserAgent.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OMGUserAgent.m; path = Sources/OMGUserAgent.m; sourceTree = ""; }; 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + 94F9363EEBC7855FA6B9A6B7485D5170 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 9519BB8B059D8A17CE43587EB6EFA61D /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = ""; }; + 955F5499BB7496155FBF443B524F1D50 /* hang.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = hang.m; path = Sources/hang.m; sourceTree = ""; }; 969C2AF48F4307163B301A92E78AFCF2 /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = ""; }; - 9774D31336C85248A115B569E7D95283 /* UIActionSheet+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIActionSheet+AnyPromise.m"; path = "Categories/UIKit/UIActionSheet+AnyPromise.m"; sourceTree = ""; }; 97FF5C0140A433518CF653B6A520F27A /* OMGHTTPURLRQ.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = OMGHTTPURLRQ.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 980FD13F87B44BFD90F8AC129BEB2E61 /* race.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = race.swift; path = Sources/race.swift; sourceTree = ""; }; - 9D579267FC1F163C8F04B444DAEFED0D /* OMGHTTPURLRQ.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OMGHTTPURLRQ.m; path = Sources/OMGHTTPURLRQ.m; sourceTree = ""; }; + 9C307C0A58A490D3080DB4C1E745C973 /* when.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = when.m; path = Sources/when.m; sourceTree = ""; }; 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-umbrella.h"; sourceTree = ""; }; - A04177B09D9596450D827FE49A36C4C4 /* Download.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Download.swift; path = Source/Download.swift; sourceTree = ""; }; + 9FB7C011EC5C968D7A91E71A028913B7 /* UIAlertView+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIAlertView+AnyPromise.m"; path = "Categories/UIKit/UIAlertView+AnyPromise.m"; sourceTree = ""; }; A112EF8BB3933C1C1E42F11B3DD3B02A /* PromiseKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = PromiseKit.framework; sourceTree = BUILT_PRODUCTS_DIR; }; A1D1571AB15108DF6F9C4FE2064E3C43 /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - A7F0DAACAC89A93B940BBE54E6A87E9F /* NSURLConnection+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSURLConnection+AnyPromise.m"; path = "Categories/Foundation/NSURLConnection+AnyPromise.m"; sourceTree = ""; }; - A92242715FB4C0608F8DCEBF8F3791E2 /* dispatch_promise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = dispatch_promise.m; path = Sources/dispatch_promise.m; sourceTree = ""; }; - AA24C5EC82CF437D8D1FFFAB68975408 /* UIViewController+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIViewController+AnyPromise.m"; path = "Categories/UIKit/UIViewController+AnyPromise.m"; sourceTree = ""; }; - AB4DA378490493502B34B20D4B12325B /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + A9E0C3DC76C639C91EF9B920C8E3D60F /* Upload.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Upload.swift; path = Source/Upload.swift; sourceTree = ""; }; + B09DEE52CBDEC1EA108DD327EF036F4A /* PromiseKit-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "PromiseKit-dummy.m"; sourceTree = ""; }; + B0B08C036B6283A3D528F1FBBEEF40EC /* Umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Umbrella.h; path = Sources/Umbrella.h; sourceTree = ""; }; + B225BF6ADAA247F1300081D25732B5B4 /* Promise+Properties.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Properties.swift"; path = "Sources/Promise+Properties.swift"; sourceTree = ""; }; + B349821C1F2B2C5F593BC228C462C99D /* OMGHTTPURLRQ.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = OMGHTTPURLRQ.modulemap; sourceTree = ""; }; B3A144887C8B13FD888B76AB096B0CA1 /* PetstoreClient-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-prefix.pch"; sourceTree = ""; }; - B868468092D7B2489B889A50981C9247 /* after.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = after.m; path = Sources/after.m; sourceTree = ""; }; - B93FB4BB16CFB41DCA35A8CFAD7A7FEF /* NSNotificationCenter+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSNotificationCenter+Promise.swift"; path = "Categories/Foundation/NSNotificationCenter+Promise.swift"; sourceTree = ""; }; - B9E21DC1171D712B2D2307EE5034D99E /* OMGHTTPURLRQ-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "OMGHTTPURLRQ-prefix.pch"; sourceTree = ""; }; - BAE48ACA10E8895BB8BF5CE8C0846B4B /* NSURLConnection+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSURLConnection+AnyPromise.h"; path = "Categories/Foundation/NSURLConnection+AnyPromise.h"; sourceTree = ""; }; - BCDD82DB3E6D43BA9769FCA9B744CB5E /* UIView+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIView+AnyPromise.h"; path = "Categories/UIKit/UIView+AnyPromise.h"; sourceTree = ""; }; + B7C40ADE30634419CED97EC829EE5D2C /* UIViewController+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIViewController+Promise.swift"; path = "Categories/UIKit/UIViewController+Promise.swift"; sourceTree = ""; }; + BCC88BB5150F5865EE3017D1B9AB4CF5 /* Stream.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Stream.swift; path = Source/Stream.swift; sourceTree = ""; }; BCF2D4DFF08D2A18E8C8FE4C4B4633FB /* Pods-SwaggerClient-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-frameworks.sh"; sourceTree = ""; }; - C476B916B763E55E4161F0B30760C4E8 /* afterlife.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = afterlife.swift; path = Categories/Foundation/afterlife.swift; sourceTree = ""; }; - C731FBFCC690050C6C08E5AC9D9DC724 /* PMKAlertController.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PMKAlertController.swift; path = Categories/UIKit/PMKAlertController.swift; sourceTree = ""; }; - CA1AD92813B887E2D017D051B8C0E3D2 /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; - CA854180C132DB5511D64C82535C5FDE /* UIAlertView+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIAlertView+Promise.swift"; path = "Categories/UIKit/UIAlertView+Promise.swift"; sourceTree = ""; }; - CC49FF2A84C0E0E9349747D94036B728 /* PromiseKit.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = PromiseKit.xcconfig; sourceTree = ""; }; - CCE38472832BBCC541E646DA6C18EF9C /* Upload.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Upload.swift; path = Source/Upload.swift; sourceTree = ""; }; - CDC4DD7DB9F4C34A288BECA73BC13B57 /* PromiseKit.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = PromiseKit.modulemap; sourceTree = ""; }; + BDEAF9E48610133B23BB992381D0E22B /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + BED547C24FF8AE5F91ED94E3BC8052C8 /* join.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = join.swift; path = Sources/join.swift; sourceTree = ""; }; + CA79CBD1DDA33C45473F8807605719BC /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; + CABB6C822D84DC5F0596B6D7B60CC5AA /* UIActionSheet+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIActionSheet+AnyPromise.m"; path = "Categories/UIKit/UIActionSheet+AnyPromise.m"; sourceTree = ""; }; CF8754792D6C49D6F5C8859350F48B35 /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; D2841E5E2183846280B97F6E660DA26C /* Pods-SwaggerClient-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-resources.sh"; sourceTree = ""; }; D2BAD338E56EF3CAA6E54490FE0C5DF9 /* APIHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = APIHelper.swift; sourceTree = ""; }; + D3A577E7C7DF4A2157D9001CA0D40A72 /* PromiseKit.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = PromiseKit.modulemap; sourceTree = ""; }; + D475FE9899956F5D2196D1C19DFC1F28 /* AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AnyPromise.h; path = Sources/AnyPromise.h; sourceTree = ""; }; D4DF0604EDC1460935E6E445A47023A4 /* Category.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Category.swift; sourceTree = ""; }; - D6D459D0AB2361B48F81C4D14C6D0DAA /* UIViewController+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIViewController+Promise.swift"; path = "Categories/UIKit/UIViewController+Promise.swift"; sourceTree = ""; }; - D6EB54C331FED437583A5F01EB2757D1 /* NSObject+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSObject+Promise.swift"; path = "Categories/Foundation/NSObject+Promise.swift"; sourceTree = ""; }; D8072E1108951F272C003553FC8926C7 /* APIs.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = APIs.swift; sourceTree = ""; }; + D9A940E08D42AC7D07C6B74D3310C69A /* NSURLConnection+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSURLConnection+AnyPromise.m"; path = "Categories/Foundation/NSURLConnection+AnyPromise.m"; sourceTree = ""; }; + DA62734652B80C3897AA655226B3BCF3 /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = PetstoreClient.xcconfig; sourceTree = ""; }; + DCBC249F9443D7D79A42B5C4BAC874C8 /* NSNotificationCenter+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSNotificationCenter+AnyPromise.m"; path = "Categories/Foundation/NSNotificationCenter+AnyPromise.m"; sourceTree = ""; }; + DD83C2B5FF3BF5AB85E18B1BB6293857 /* CALayer+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "CALayer+AnyPromise.m"; path = "Categories/QuartzCore/CALayer+AnyPromise.m"; sourceTree = ""; }; + DDB573F3C977C55072704AA24EC06164 /* Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Promise.swift; path = Sources/Promise.swift; sourceTree = ""; }; + DDDBF73F440D96AB666A6418AEEF2946 /* UIActionSheet+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIActionSheet+Promise.swift"; path = "Categories/UIKit/UIActionSheet+Promise.swift"; sourceTree = ""; }; DE164497A94DD3215ED4D1AE0D4703B1 /* Pods-SwaggerClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = "Pods-SwaggerClient.modulemap"; sourceTree = ""; }; - E11BFB27B43B742CB5D6086C4233A909 /* OMGUserAgent.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OMGUserAgent.m; path = Sources/OMGUserAgent.m; sourceTree = ""; }; + DEFA2BBF978F33CA2112DC5D6209A3EF /* when.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = when.swift; path = Sources/when.swift; sourceTree = ""; }; + DFFF6310B8F8C445362FF33E936F85CA /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = Sources/Error.swift; sourceTree = ""; }; + E0B0C8D6D1D56B95983D680363E6F785 /* NSURLConnection+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSURLConnection+AnyPromise.h"; path = "Categories/Foundation/NSURLConnection+AnyPromise.h"; sourceTree = ""; }; E1E4BCB344D3C100253B24B79421F00A /* Pods-SwaggerClient-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClient-acknowledgements.plist"; sourceTree = ""; }; - E3CDA0958D6247505ECD9098D662EA74 /* UIView+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIView+Promise.swift"; path = "Categories/UIKit/UIView+Promise.swift"; sourceTree = ""; }; + E3B8EDBFFE2A701981A073412ECCF6AD /* join.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = join.m; path = Sources/join.m; sourceTree = ""; }; E3D1141B63DF38660CD6F3AC588A782B /* PetstoreClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = PetstoreClient.modulemap; sourceTree = ""; }; + E48946E76C93EE81F20C76C0EE272B8E /* CALayer+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "CALayer+AnyPromise.h"; path = "Categories/QuartzCore/CALayer+AnyPromise.h"; sourceTree = ""; }; + E4B2CF9B72BC56E74E6B0037BDE92031 /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; E4E6F4A58FE7868CA2177D3AC79AD2FA /* Pods-SwaggerClientTests-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-resources.sh"; sourceTree = ""; }; - E7CE161ED0CF68954A63F30528ACAD9B /* URLDataPromise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = URLDataPromise.swift; path = Sources/URLDataPromise.swift; sourceTree = ""; }; - F075F63EFE77F7B59FF77CBA95B9AADF /* UIAlertView+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIAlertView+AnyPromise.m"; path = "Categories/UIKit/UIAlertView+AnyPromise.m"; sourceTree = ""; }; + E6EC6723A17EAD72862789D6748FAA26 /* OMGHTTPURLRQ.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = OMGHTTPURLRQ.xcconfig; sourceTree = ""; }; + EA13BF2FADA101A1AB34BF5EC8C7BA85 /* UIView+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIView+AnyPromise.m"; path = "Categories/UIKit/UIView+AnyPromise.m"; sourceTree = ""; }; + EC8150042B23FCA7DF9979098694EC0B /* AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AnyPromise.m; path = Sources/AnyPromise.m; sourceTree = ""; }; + EFC77A5BCF407679FAB606F03E631A11 /* NSNotificationCenter+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSNotificationCenter+AnyPromise.h"; path = "Categories/Foundation/NSNotificationCenter+AnyPromise.h"; sourceTree = ""; }; + F0962CCF21BDD2EB5751C14F9322AFC9 /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; F0D4E00A8974E74325E9E53D456F9AD4 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-SwaggerClientTests-umbrella.h"; sourceTree = ""; }; F2BEA8A3A2770EF455BB2ECCDA8CE0AD /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - F4B6A98D6DAF474045210F5A74FF1C3C /* hang.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = hang.m; path = Sources/hang.m; sourceTree = ""; }; - F7EBDD2EEED520E06ACB3538B3832049 /* OMGHTTPURLRQ-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "OMGHTTPURLRQ-umbrella.h"; sourceTree = ""; }; FB170EFD14935F121CDE3211DB4C5CA3 /* Pods-SwaggerClientTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClientTests-acknowledgements.markdown"; sourceTree = ""; }; - FD558DDCDDA1B46951548B02C34277EF /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; - FD570E28B63274E742E7D1FBBD55BB41 /* UIActionSheet+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIActionSheet+Promise.swift"; path = "Categories/UIKit/UIActionSheet+Promise.swift"; sourceTree = ""; }; + FDA7C65B58A0E739E615FA7A750AA0AD /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; FE74210E04DEED84E2357049E4589759 /* PetstoreClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = PetstoreClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; FEEC58138887E454A6CBD0A7BFF2910A /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + FFB0686D05BA9C4D5A69D6058C029FF2 /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -315,11 +321,11 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - A5AE1D340C4A0691EC28EEA8241C9FCD /* Frameworks */ = { + B1729F851F648EC60EE93CDB3C8BAEAD /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 0BD8B4E55E72312366130E97A1204CD8 /* Foundation.framework in Frameworks */, + 91C09AC2A52ED69A27C8D923139A006F /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -355,6 +361,15 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 00ED77B3FFE891B16DC5B4DD2FCC0408 /* UserAgent */ = { + isa = PBXGroup; + children = ( + 4FF818D195F8814F5F8878A2FD02AF1D /* OMGUserAgent.h */, + 937CB6976C5F585A76A9383107F5AF73 /* OMGUserAgent.m */, + ); + name = UserAgent; + sourceTree = ""; + }; 01A9CB10E1E9A90B6A796034AF093E8C /* Products */ = { isa = PBXGroup; children = ( @@ -368,15 +383,6 @@ name = Products; sourceTree = ""; }; - 07467E828160702D1DB7EC2F492C337C /* UserAgent */ = { - isa = PBXGroup; - children = ( - 87BC7910B8D7D31310A07C32438A8C67 /* OMGUserAgent.h */, - E11BFB27B43B742CB5D6086C4233A909 /* OMGUserAgent.m */, - ); - name = UserAgent; - sourceTree = ""; - }; 1322FED69118C64DAD026CAF7F4C38C6 /* Models */ = { isa = PBXGroup; children = ( @@ -389,18 +395,25 @@ path = Models; sourceTree = ""; }; - 1D2330E920AD5F6E4655BE449D006A77 /* Support Files */ = { + 188F1582EFF9CD3E8AB3A7470820B51F /* PromiseKit */ = { isa = PBXGroup; children = ( - AB4DA378490493502B34B20D4B12325B /* Info.plist */, - 24C79ED4B5226F263307B22E96E88F9F /* OMGHTTPURLRQ.modulemap */, - 16D7C901D915C251DEBA27AC1EF57E34 /* OMGHTTPURLRQ.xcconfig */, - 0F36B65CF990C57DC527824ED0BA1915 /* OMGHTTPURLRQ-dummy.m */, - B9E21DC1171D712B2D2307EE5034D99E /* OMGHTTPURLRQ-prefix.pch */, - F7EBDD2EEED520E06ACB3538B3832049 /* OMGHTTPURLRQ-umbrella.h */, + 72B5E9FE2F2C23CD28C86A837D09964A /* CorePromise */, + 79A7166061336F6A7FF214DB285A9584 /* Foundation */, + 2115C8F445286DAD6754A21C2ABE2E78 /* QuartzCore */, + 977CD7DB18C38452FB8DCFCEC690CBDE /* Support Files */, + 933F0A2EBD44D53190D1E9FAF3F54AFB /* UIKit */, ); - name = "Support Files"; - path = "../Target Support Files/OMGHTTPURLRQ"; + path = PromiseKit; + sourceTree = ""; + }; + 2115C8F445286DAD6754A21C2ABE2E78 /* QuartzCore */ = { + isa = PBXGroup; + children = ( + E48946E76C93EE81F20C76C0EE272B8E /* CALayer+AnyPromise.h */, + DD83C2B5FF3BF5AB85E18B1BB6293857 /* CALayer+AnyPromise.m */, + ); + name = QuartzCore; sourceTree = ""; }; 22F52349E1BE90FC6E064DAAC9EA9612 /* Development Pods */ = { @@ -411,65 +424,120 @@ name = "Development Pods"; sourceTree = ""; }; - 76DC20E0A9F8CDC0E47176B58A9C5BD5 /* Foundation */ = { + 27098387544928716460DD8F5024EE8A /* Pods */ = { isa = PBXGroup; children = ( - C476B916B763E55E4161F0B30760C4E8 /* afterlife.swift */, - 3616971BAEF40302B7F2F8B1007C0B2B /* NSNotificationCenter+AnyPromise.h */, - 4798BAC01B0E3F07E3BBBB07BA57F2D7 /* NSNotificationCenter+AnyPromise.m */, - B93FB4BB16CFB41DCA35A8CFAD7A7FEF /* NSNotificationCenter+Promise.swift */, - D6EB54C331FED437583A5F01EB2757D1 /* NSObject+Promise.swift */, - BAE48ACA10E8895BB8BF5CE8C0846B4B /* NSURLConnection+AnyPromise.h */, - A7F0DAACAC89A93B940BBE54E6A87E9F /* NSURLConnection+AnyPromise.m */, - 412985229DA7A4DF9E129B7E8F0C09BB /* NSURLConnection+Promise.swift */, - 535DF88FC12304114DEF55E4003421B2 /* NSURLSession+Promise.swift */, + 41488276780D879BE61AA0617BDC29A0 /* Alamofire */, + 6C55196C7E1A0F95D0BEFD790EA1450C /* OMGHTTPURLRQ */, + 188F1582EFF9CD3E8AB3A7470820B51F /* PromiseKit */, ); - name = Foundation; + name = Pods; sourceTree = ""; }; - 7DB346D0F39D3F0E887471402A8071AB = { + 41488276780D879BE61AA0617BDC29A0 /* Alamofire */ = { isa = PBXGroup; children = ( - 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */, - 22F52349E1BE90FC6E064DAAC9EA9612 /* Development Pods */, - E85F5154C248966A1EC7B7B6EACB20CF /* Frameworks */, - CF22FA3EE19C3EC42FEBA1247EB70D85 /* Pods */, - 01A9CB10E1E9A90B6A796034AF093E8C /* Products */, - C1A60D10CED0E61146591438999C7502 /* Targets Support Files */, + FDA7C65B58A0E739E615FA7A750AA0AD /* Alamofire.swift */, + 770621722C3B98D9380F76F3310EAA7F /* Download.swift */, + 7390892336E4D605CF390FFA4B55EF0A /* Error.swift */, + 1AA002805CE140B0968FC965A53F0A4C /* Manager.swift */, + CA79CBD1DDA33C45473F8807605719BC /* MultipartFormData.swift */, + FFB0686D05BA9C4D5A69D6058C029FF2 /* NetworkReachabilityManager.swift */, + 9519BB8B059D8A17CE43587EB6EFA61D /* Notifications.swift */, + E4B2CF9B72BC56E74E6B0037BDE92031 /* ParameterEncoding.swift */, + 7D3192434754120C2AAF44818AEE054B /* Request.swift */, + 74E1D5C24530737CDD54FA854E37B371 /* Response.swift */, + DA62734652B80C3897AA655226B3BCF3 /* ResponseSerialization.swift */, + 1F60254382C7024DDFD16533FB81750A /* Result.swift */, + 8D1D96AB285E285A3CC15FAD1CD875B2 /* ServerTrustPolicy.swift */, + BCC88BB5150F5865EE3017D1B9AB4CF5 /* Stream.swift */, + 47B728204DA3D60FAB04A757D3B09D2E /* Timeline.swift */, + A9E0C3DC76C639C91EF9B920C8E3D60F /* Upload.swift */, + 0435721889B71489503A007D233559DF /* Validation.swift */, + DFFDACE0170FB00C7ECFDA52A87A7665 /* Support Files */, ); + path = Alamofire; sourceTree = ""; }; - 7DFF028D9F7D443B2361EBEDACC99624 /* OMGHTTPURLRQ */ = { + 45199ED47CEA398ADDDFDE8F9D0A591D /* Support Files */ = { isa = PBXGroup; children = ( - 8FCF5C41226503429E7875DF4CA4D36E /* FormURLEncode */, - A00A425F2E132E8FF4DE929E7DF9CC1E /* RQ */, - 1D2330E920AD5F6E4655BE449D006A77 /* Support Files */, - 07467E828160702D1DB7EC2F492C337C /* UserAgent */, + 8F8078A9DEC41CD886A8676D889912A4 /* Info.plist */, + B349821C1F2B2C5F593BC228C462C99D /* OMGHTTPURLRQ.modulemap */, + E6EC6723A17EAD72862789D6748FAA26 /* OMGHTTPURLRQ.xcconfig */, + 8F88352C39FB2D4A0D36696674E7C05D /* OMGHTTPURLRQ-dummy.m */, + 705D1370384B46A3E5A39B39E7B4D181 /* OMGHTTPURLRQ-prefix.pch */, + 3029ADF04ADC2B8F3A7264A416D70B56 /* OMGHTTPURLRQ-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/OMGHTTPURLRQ"; + sourceTree = ""; + }; + 6C55196C7E1A0F95D0BEFD790EA1450C /* OMGHTTPURLRQ */ = { + isa = PBXGroup; + children = ( + B00B1E51F2524127FFF78DB52869057E /* FormURLEncode */, + 9466970616DD9491B9B80845EBAF6997 /* RQ */, + 45199ED47CEA398ADDDFDE8F9D0A591D /* Support Files */, + 00ED77B3FFE891B16DC5B4DD2FCC0408 /* UserAgent */, ); path = OMGHTTPURLRQ; sourceTree = ""; }; - 81B1E3A8E00502B38EACDE3617A7A73B /* Support Files */ = { + 72B5E9FE2F2C23CD28C86A837D09964A /* CorePromise */ = { isa = PBXGroup; children = ( - 792D14AC86CD98AA9C31373287E0F353 /* Info.plist */, - CDC4DD7DB9F4C34A288BECA73BC13B57 /* PromiseKit.modulemap */, - CC49FF2A84C0E0E9349747D94036B728 /* PromiseKit.xcconfig */, - 9042667D08D783E45394FE8B97EE6468 /* PromiseKit-dummy.m */, - 122D5005A81832479161CD1D223C573A /* PromiseKit-prefix.pch */, + 4765491FCD8E096D84D4E57E005B8B49 /* after.m */, + 3E49ED544745AD479AFA0B6766F441CE /* after.swift */, + D475FE9899956F5D2196D1C19DFC1F28 /* AnyPromise.h */, + EC8150042B23FCA7DF9979098694EC0B /* AnyPromise.m */, + 1FB5ABB73E12675999DE989CC2478A7A /* AnyPromise.swift */, + 7356B0365E4182E6E6D55124C678B591 /* dispatch_promise.m */, + 85FD17541BFB4152FD5F2CA46F9E3ACC /* dispatch_promise.swift */, + DFFF6310B8F8C445362FF33E936F85CA /* Error.swift */, + 955F5499BB7496155FBF443B524F1D50 /* hang.m */, + E3B8EDBFFE2A701981A073412ECCF6AD /* join.m */, + BED547C24FF8AE5F91ED94E3BC8052C8 /* join.swift */, + 2E9E05F82273A09FD6E5CA99FD3A74D9 /* NSError+Cancellation.h */, + DDB573F3C977C55072704AA24EC06164 /* Promise.swift */, + B225BF6ADAA247F1300081D25732B5B4 /* Promise+Properties.swift */, + 1AAED38B682D186542DC2B8D273486F4 /* PromiseKit.h */, + 3EC07412ABFB8D5A06E7B38380FFD9C4 /* race.swift */, + 3BEE20F7C5242E616D2D97B5FBE31323 /* State.swift */, + B0B08C036B6283A3D528F1FBBEEF40EC /* Umbrella.h */, + 0E339112CF5C9275CFBEB94C29AD250B /* URLDataPromise.swift */, + 9C307C0A58A490D3080DB4C1E745C973 /* when.m */, + DEFA2BBF978F33CA2112DC5D6209A3EF /* when.swift */, ); - name = "Support Files"; - path = "../Target Support Files/PromiseKit"; + name = CorePromise; sourceTree = ""; }; - 83C3888E1F7B1FC86D9CBF3B74DC2896 /* QuartzCore */ = { + 79A7166061336F6A7FF214DB285A9584 /* Foundation */ = { isa = PBXGroup; children = ( - 27E0FE41D771BE8BE3F0D4F1DAD0B179 /* CALayer+AnyPromise.h */, - 04A22F2595054D39018E03961CA7283A /* CALayer+AnyPromise.m */, + 178262A3EEE3B9A6F7B9B2B4ED5AA150 /* afterlife.swift */, + EFC77A5BCF407679FAB606F03E631A11 /* NSNotificationCenter+AnyPromise.h */, + DCBC249F9443D7D79A42B5C4BAC874C8 /* NSNotificationCenter+AnyPromise.m */, + 786AAA1F62613C489FD473D4CE16127A /* NSNotificationCenter+Promise.swift */, + 6650152803DA41F52DA6A26B5DF713D7 /* NSObject+Promise.swift */, + E0B0C8D6D1D56B95983D680363E6F785 /* NSURLConnection+AnyPromise.h */, + D9A940E08D42AC7D07C6B74D3310C69A /* NSURLConnection+AnyPromise.m */, + 9066E09FAD7A3236DAD81317C1E48214 /* NSURLConnection+Promise.swift */, + 5A5AEB5CADDFFFC419A0D8D6FD914800 /* NSURLSession+Promise.swift */, + ); + name = Foundation; + sourceTree = ""; + }; + 7DB346D0F39D3F0E887471402A8071AB = { + isa = PBXGroup; + children = ( + 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */, + 22F52349E1BE90FC6E064DAAC9EA9612 /* Development Pods */, + E85F5154C248966A1EC7B7B6EACB20CF /* Frameworks */, + 27098387544928716460DD8F5024EE8A /* Pods */, + 01A9CB10E1E9A90B6A796034AF093E8C /* Products */, + C1A60D10CED0E61146591438999C7502 /* Targets Support Files */, ); - name = QuartzCore; sourceTree = ""; }; 88CE2B3F08C34DDB098AD8A5DCC1DF1E /* Pods-SwaggerClient */ = { @@ -490,26 +558,6 @@ path = "Target Support Files/Pods-SwaggerClient"; sourceTree = ""; }; - 8EA2A359F1831ACBB15BAAEA04D6FB95 /* UIKit */ = { - isa = PBXGroup; - children = ( - C731FBFCC690050C6C08E5AC9D9DC724 /* PMKAlertController.swift */, - 6846D22C9F0CCBC48DF833E309A8E84F /* UIActionSheet+AnyPromise.h */, - 9774D31336C85248A115B569E7D95283 /* UIActionSheet+AnyPromise.m */, - FD570E28B63274E742E7D1FBBD55BB41 /* UIActionSheet+Promise.swift */, - 92D340D66F03F31237B70F23FE9B00D0 /* UIAlertView+AnyPromise.h */, - F075F63EFE77F7B59FF77CBA95B9AADF /* UIAlertView+AnyPromise.m */, - CA854180C132DB5511D64C82535C5FDE /* UIAlertView+Promise.swift */, - BCDD82DB3E6D43BA9769FCA9B744CB5E /* UIView+AnyPromise.h */, - 2F0F4EDC2236E1C270DC2014181D6506 /* UIView+AnyPromise.m */, - E3CDA0958D6247505ECD9098D662EA74 /* UIView+Promise.swift */, - 0BA017E288BB42E06EBEE9C6E6993EAF /* UIViewController+AnyPromise.h */, - AA24C5EC82CF437D8D1FFFAB68975408 /* UIViewController+AnyPromise.m */, - D6D459D0AB2361B48F81C4D14C6D0DAA /* UIViewController+Promise.swift */, - ); - name = UIKit; - sourceTree = ""; - }; 8F6D133867EE63820DFB7E83F4C51252 /* Support Files */ = { isa = PBXGroup; children = ( @@ -524,66 +572,63 @@ path = "SwaggerClientTests/Pods/Target Support Files/PetstoreClient"; sourceTree = ""; }; - 8FCF5C41226503429E7875DF4CA4D36E /* FormURLEncode */ = { + 933F0A2EBD44D53190D1E9FAF3F54AFB /* UIKit */ = { isa = PBXGroup; children = ( - 51ADA0B6B6B00CB0E818AA8CBC311677 /* OMGFormURLEncode.h */, - 25614E715DDC170DAFB0DF50C5503E33 /* OMGFormURLEncode.m */, + 0608A7843513940A299A88D778388F9D /* PMKAlertController.swift */, + 590BCD68D24A72708312E57A91360AC7 /* UIActionSheet+AnyPromise.h */, + CABB6C822D84DC5F0596B6D7B60CC5AA /* UIActionSheet+AnyPromise.m */, + DDDBF73F440D96AB666A6418AEEF2946 /* UIActionSheet+Promise.swift */, + 4E19A7D44620C4AED963248648938767 /* UIAlertView+AnyPromise.h */, + 9FB7C011EC5C968D7A91E71A028913B7 /* UIAlertView+AnyPromise.m */, + 8E29EB54AEC61300AD412C40991FFED5 /* UIAlertView+Promise.swift */, + 13DB7D7990FD3354E34510894CC30CD1 /* UIView+AnyPromise.h */, + EA13BF2FADA101A1AB34BF5EC8C7BA85 /* UIView+AnyPromise.m */, + 5E69FDAAF09817F0BA67D7C575BAFF48 /* UIView+Promise.swift */, + 7B892AF5EA37A5C7962FEA3E294B2526 /* UIViewController+AnyPromise.h */, + 53F1201EF49979297542207D6EB6EC55 /* UIViewController+AnyPromise.m */, + B7C40ADE30634419CED97EC829EE5D2C /* UIViewController+Promise.swift */, ); - name = FormURLEncode; + name = UIKit; sourceTree = ""; }; - 99640BFBD45FFAD70A89B868F85EFA36 /* Alamofire */ = { + 9466970616DD9491B9B80845EBAF6997 /* RQ */ = { isa = PBXGroup; children = ( - 8B476A57549D7994745E17A6DE5BE745 /* Alamofire.swift */, - A04177B09D9596450D827FE49A36C4C4 /* Download.swift */, - 8A9CB35983E4859DFFBAD8840196A094 /* Error.swift */, - 2D51C929AC51E34493AA757180C09C3B /* Manager.swift */, - 5F14E17B4D6BDF8BD3E384BE6528F744 /* MultipartFormData.swift */, - 1FBD351D007CF4095C98C9DFD9D83D61 /* ParameterEncoding.swift */, - 133C5287CFDCB3B67578A7B1221E132C /* Request.swift */, - 5DF5FC3AF99846209C5FCE55A2E12D9A /* Response.swift */, - FD558DDCDDA1B46951548B02C34277EF /* ResponseSerialization.swift */, - 53F8B2513042BD6DB957E8063EF895BD /* Result.swift */, - 400A6910E83F606BCD67DC11FA706697 /* ServerTrustPolicy.swift */, - 8A8F373B23E0F7FB68B0BA71D92D1C60 /* Stream.swift */, - CCE38472832BBCC541E646DA6C18EF9C /* Upload.swift */, - CA1AD92813B887E2D017D051B8C0E3D2 /* Validation.swift */, - 9E101A4CE6D982647EED5C067C563BED /* Support Files */, + 859DDC0FFB13DB9C838BA38D0641A1BA /* OMGHTTPURLRQ.h */, + 3EEC1FB4B45C5C247D2D0FB33D4F5A1D /* OMGHTTPURLRQ.m */, ); - path = Alamofire; + name = RQ; sourceTree = ""; }; - 9E101A4CE6D982647EED5C067C563BED /* Support Files */ = { + 977CD7DB18C38452FB8DCFCEC690CBDE /* Support Files */ = { isa = PBXGroup; children = ( - 8749F40CC17CE0C26C36B0F431A9C8F0 /* Alamofire.modulemap */, - 141F0B43C42CE92856BBA8F8D98481DB /* Alamofire.xcconfig */, - 139346EB669CBE2DE8FE506E14A2BA9C /* Alamofire-dummy.m */, - 3950B63B8EB1B9CD8FC31CDA8CC2E7C7 /* Alamofire-prefix.pch */, - 30CE7341A995EF6812D71771E74CF7F7 /* Alamofire-umbrella.h */, - 3CE589B7B1FE57084403D25DC49528B5 /* Info.plist */, + 94F9363EEBC7855FA6B9A6B7485D5170 /* Info.plist */, + D3A577E7C7DF4A2157D9001CA0D40A72 /* PromiseKit.modulemap */, + 2E750A27FAB06DE866BC27CC8FA07806 /* PromiseKit.xcconfig */, + B09DEE52CBDEC1EA108DD327EF036F4A /* PromiseKit-dummy.m */, + 11683764D40FE241FCEEB379EE92E817 /* PromiseKit-prefix.pch */, ); name = "Support Files"; - path = "../Target Support Files/Alamofire"; + path = "../Target Support Files/PromiseKit"; sourceTree = ""; }; - A00A425F2E132E8FF4DE929E7DF9CC1E /* RQ */ = { + AD94092456F8ABCB18F74CAC75AD85DE /* Classes */ = { isa = PBXGroup; children = ( - 450166FEA2155A5821D97744A0127DF8 /* OMGHTTPURLRQ.h */, - 9D579267FC1F163C8F04B444DAEFED0D /* OMGHTTPURLRQ.m */, + F64549CFCC17C7AC6479508BE180B18D /* Swaggers */, ); - name = RQ; + path = Classes; sourceTree = ""; }; - AD94092456F8ABCB18F74CAC75AD85DE /* Classes */ = { + B00B1E51F2524127FFF78DB52869057E /* FormURLEncode */ = { isa = PBXGroup; children = ( - F64549CFCC17C7AC6479508BE180B18D /* Swaggers */, + 3B1578E353CE37C4C4201EC9101DE67F /* OMGFormURLEncode.h */, + 56CDA7C9327CF6F3DFC66FC128D7365B /* OMGFormURLEncode.m */, ); - path = Classes; + name = FormURLEncode; sourceTree = ""; }; B4A5C9FBC309EB945E2E089539878931 /* iOS */ = { @@ -596,34 +641,6 @@ name = iOS; sourceTree = ""; }; - BEACE1971060500B96701CBC3F667BAE /* CorePromise */ = { - isa = PBXGroup; - children = ( - B868468092D7B2489B889A50981C9247 /* after.m */, - 275DA9A664C70DD40A4059090D1A00D4 /* after.swift */, - 1F19945EE403F7B29D8B1939EA6D579A /* AnyPromise.h */, - 1B7E90A568681E000EF3CB0917584F3C /* AnyPromise.m */, - 5973BC143AE488C12FFB1E83E71F0C45 /* AnyPromise.swift */, - A92242715FB4C0608F8DCEBF8F3791E2 /* dispatch_promise.m */, - 392FA21A33296B88F790D62A4FAA4E4E /* dispatch_promise.swift */, - 558DFECE2C740177CA6357DA71A1DFBB /* Error.swift */, - F4B6A98D6DAF474045210F5A74FF1C3C /* hang.m */, - 6AD59903FAA8315AD0036AC459FFB97F /* join.m */, - 84319E048FE6DD89B905FA3A81005C5F /* join.swift */, - 045C1F608ADE57757E6732D721779F22 /* NSError+Cancellation.h */, - 3D23C407A7CDBFD244D6115899F9D45D /* Promise.swift */, - 7E0DBDE561A6C2E7AC7A24160F8A5F28 /* Promise+Properties.swift */, - 3BFFA6FD621E9ED341AA89AEAC1604D7 /* PromiseKit.h */, - 980FD13F87B44BFD90F8AC129BEB2E61 /* race.swift */, - 8DC63EB77B3791891517B98CAA115DE8 /* State.swift */, - 0A8906F6D6920DF197965D1740A7E283 /* Umbrella.h */, - E7CE161ED0CF68954A63F30528ACAD9B /* URLDataPromise.swift */, - 143BC30E5DDAF52A3D9578F507EC6A41 /* when.m */, - 16730DAF3E51C161D8247E473F069E71 /* when.swift */, - ); - name = CorePromise; - sourceTree = ""; - }; C1A60D10CED0E61146591438999C7502 /* Targets Support Files */ = { isa = PBXGroup; children = ( @@ -633,16 +650,6 @@ name = "Targets Support Files"; sourceTree = ""; }; - CF22FA3EE19C3EC42FEBA1247EB70D85 /* Pods */ = { - isa = PBXGroup; - children = ( - 99640BFBD45FFAD70A89B868F85EFA36 /* Alamofire */, - 7DFF028D9F7D443B2361EBEDACC99624 /* OMGHTTPURLRQ */, - D9FC474F1DB94FC75B3AAC120F0D4AB7 /* PromiseKit */, - ); - name = Pods; - sourceTree = ""; - }; D6D0CD30E3EAF2ED10AE0CBC07506C5A /* Pods-SwaggerClientTests */ = { isa = PBXGroup; children = ( @@ -661,16 +668,18 @@ path = "Target Support Files/Pods-SwaggerClientTests"; sourceTree = ""; }; - D9FC474F1DB94FC75B3AAC120F0D4AB7 /* PromiseKit */ = { + DFFDACE0170FB00C7ECFDA52A87A7665 /* Support Files */ = { isa = PBXGroup; children = ( - BEACE1971060500B96701CBC3F667BAE /* CorePromise */, - 76DC20E0A9F8CDC0E47176B58A9C5BD5 /* Foundation */, - 83C3888E1F7B1FC86D9CBF3B74DC2896 /* QuartzCore */, - 81B1E3A8E00502B38EACDE3617A7A73B /* Support Files */, - 8EA2A359F1831ACBB15BAAEA04D6FB95 /* UIKit */, + 467F288FF1A023115720F192FD4D9297 /* Alamofire.modulemap */, + 10A634092EE6D018EB00C75E9864A6A2 /* Alamofire.xcconfig */, + F0962CCF21BDD2EB5751C14F9322AFC9 /* Alamofire-dummy.m */, + 835E52C658674D7A44ED95B966432726 /* Alamofire-prefix.pch */, + 791F2A99A7894F88F8BBAE2F6C627522 /* Alamofire-umbrella.h */, + BDEAF9E48610133B23BB992381D0E22B /* Info.plist */, ); - path = PromiseKit; + name = "Support Files"; + path = "../Target Support Files/Alamofire"; sourceTree = ""; }; E73D9BF152C59F341559DE62A3143721 /* PetstoreClient */ = { @@ -763,22 +772,22 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - 5F7B61281F714E2A64A51E80A2C9C062 /* Headers */ = { + 8EC2461DE4442A7991319873E6012164 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - 2C5450AC69398958CF6F7539EF7D99E5 /* Alamofire-umbrella.h in Headers */, + 5480169E42C456C49BE59E273D7E0115 /* OMGFormURLEncode.h in Headers */, + 5192A7466019F9B3D7F1E987124E96BC /* OMGHTTPURLRQ-umbrella.h in Headers */, + 0B34EB4425C08BB021C2D09F75C9C146 /* OMGHTTPURLRQ.h in Headers */, + 3A8D316D4266A3309D0A98ED74F8A13A /* OMGUserAgent.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; - 8EC2461DE4442A7991319873E6012164 /* Headers */ = { + EFDF3B631BBB965A372347705CA14854 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - 5480169E42C456C49BE59E273D7E0115 /* OMGFormURLEncode.h in Headers */, - 5192A7466019F9B3D7F1E987124E96BC /* OMGHTTPURLRQ-umbrella.h in Headers */, - 0B34EB4425C08BB021C2D09F75C9C146 /* OMGHTTPURLRQ.h in Headers */, - 3A8D316D4266A3309D0A98ED74F8A13A /* OMGUserAgent.h in Headers */, + 9469DF81ECB494E84675969B5E13374C /* Alamofire-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -868,38 +877,38 @@ productReference = FE74210E04DEED84E2357049E4589759 /* PetstoreClient.framework */; productType = "com.apple.product-type.framework"; }; - 432ECC54282C84882B482CCB4CF227FC /* Alamofire */ = { + 462B200BD111D7F438E47B7C42B6772F /* Pods-SwaggerClientTests */ = { isa = PBXNativeTarget; - buildConfigurationList = 8B2B2DA2F7F80D41B1FDB5FACFA4B3DE /* Build configuration list for PBXNativeTarget "Alamofire" */; + buildConfigurationList = 245A935A321D16F418F4D34C5D17D2B6 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClientTests" */; buildPhases = ( - EF659EFF40D426A3A32A82CDB98CC6EE /* Sources */, - A5AE1D340C4A0691EC28EEA8241C9FCD /* Frameworks */, - 5F7B61281F714E2A64A51E80A2C9C062 /* Headers */, + 0529825EC79AED06C77091DC0F061854 /* Sources */, + FE8FC779CF4B0CFCC594E81C0FF86C7E /* Frameworks */, + FF84DA06E91FBBAA756A7832375803CE /* Headers */, ); buildRules = ( ); dependencies = ( ); - name = Alamofire; - productName = Alamofire; - productReference = F2BEA8A3A2770EF455BB2ECCDA8CE0AD /* Alamofire.framework */; + name = "Pods-SwaggerClientTests"; + productName = "Pods-SwaggerClientTests"; + productReference = FEEC58138887E454A6CBD0A7BFF2910A /* Pods_SwaggerClientTests.framework */; productType = "com.apple.product-type.framework"; }; - 462B200BD111D7F438E47B7C42B6772F /* Pods-SwaggerClientTests */ = { + 79C040AFDDCE1BCBF6D8B5EB0B85887F /* Alamofire */ = { isa = PBXNativeTarget; - buildConfigurationList = 245A935A321D16F418F4D34C5D17D2B6 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClientTests" */; + buildConfigurationList = 3CFB42910790CF0BDBCCEBAACD6B9367 /* Build configuration list for PBXNativeTarget "Alamofire" */; buildPhases = ( - 0529825EC79AED06C77091DC0F061854 /* Sources */, - FE8FC779CF4B0CFCC594E81C0FF86C7E /* Frameworks */, - FF84DA06E91FBBAA756A7832375803CE /* Headers */, + 95CC2C7E06DC188A05DAAEE9CAA555A3 /* Sources */, + B1729F851F648EC60EE93CDB3C8BAEAD /* Frameworks */, + EFDF3B631BBB965A372347705CA14854 /* Headers */, ); buildRules = ( ); dependencies = ( ); - name = "Pods-SwaggerClientTests"; - productName = "Pods-SwaggerClientTests"; - productReference = FEEC58138887E454A6CBD0A7BFF2910A /* Pods_SwaggerClientTests.framework */; + name = Alamofire; + productName = Alamofire; + productReference = F2BEA8A3A2770EF455BB2ECCDA8CE0AD /* Alamofire.framework */; productType = "com.apple.product-type.framework"; }; /* End PBXNativeTarget section */ @@ -923,7 +932,7 @@ projectDirPath = ""; projectRoot = ""; targets = ( - 432ECC54282C84882B482CCB4CF227FC /* Alamofire */, + 79C040AFDDCE1BCBF6D8B5EB0B85887F /* Alamofire */, 190ACD3A51BC90B85EADB13E9CDD207B /* OMGHTTPURLRQ */, 2FD913B4E24277823983BABFDB071664 /* PetstoreClient */, 1EABA30CF432461C9C71EFB7319C5EC0 /* Pods-SwaggerClient */, @@ -1024,25 +1033,28 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - EF659EFF40D426A3A32A82CDB98CC6EE /* Sources */ = { + 95CC2C7E06DC188A05DAAEE9CAA555A3 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - B6D2DC3E3DA44CD382B9B425F40E11C1 /* Alamofire-dummy.m in Sources */, - B0FB4B01682814B9E3D32F9DC4A5E762 /* Alamofire.swift in Sources */, - A3505FA2FB3067D53847AD288AC04F03 /* Download.swift in Sources */, - D75CA395D510E08C404E55F5BDAE55CE /* Error.swift in Sources */, - A2C172FE407C0BC3478ADCA91A6C9CEC /* Manager.swift in Sources */, - 8399DBEE3E2D98EB1F466132E476F4D9 /* MultipartFormData.swift in Sources */, - 4DE5FCC41D100B113B6645EA64410F16 /* ParameterEncoding.swift in Sources */, - FC14480CECE872865A9C6E584F886DA3 /* Request.swift in Sources */, - 03F494989CC1A8857B68A317D5D6860F /* Response.swift in Sources */, - D21B7325B3642887BFBE977E021F2D26 /* ResponseSerialization.swift in Sources */, - 82971968CBDAB224212EEB4607C9FB8D /* Result.swift in Sources */, - 80F496237530D382A045A29654D8C11C /* ServerTrustPolicy.swift in Sources */, - FEF0D7653948988B804226129471C1EC /* Stream.swift in Sources */, - 0681ADC8BAE2C3185F13487BAAB4D9DD /* Upload.swift in Sources */, - C75519F0450166A6F28126ECC7664E9C /* Validation.swift in Sources */, + ADF19C953CE2A7D0B72EC93A81FCCC26 /* Alamofire-dummy.m in Sources */, + 8EB11202167FCDDF1257AAAB1D1FB244 /* Alamofire.swift in Sources */, + 5CB05FBCB32D21E194B5ECF680CB6AE0 /* Download.swift in Sources */, + 095406039B4D371E48D08B38A2975AC8 /* Error.swift in Sources */, + 4081EA628AF0B73AC51FFB9D7AB3B89E /* Manager.swift in Sources */, + C7B6DD7C0456C50289A2C381DFE9FA3F /* MultipartFormData.swift in Sources */, + 34CCDCA848A701466256BC2927DA8856 /* NetworkReachabilityManager.swift in Sources */, + BE41196F6A3903E59C3306FE3F8B43FE /* Notifications.swift in Sources */, + C0DB70AB368765DC64BFB5FEA75E0696 /* ParameterEncoding.swift in Sources */, + EFE92E8D3813DD26E78E93EEAF6D7E7E /* Request.swift in Sources */, + 62E8346F03C03E7F4D631361F325689E /* Response.swift in Sources */, + 3EA8F215C9C1432D74E5CCA4834AA8C0 /* ResponseSerialization.swift in Sources */, + AA314156AC500125F4078EE968DB14C6 /* Result.swift in Sources */, + 7B48852C4D848FA2DA416A98F6425869 /* ServerTrustPolicy.swift in Sources */, + AE4CF87C02C042DF13ED5B21C4FDC1E0 /* Stream.swift in Sources */, + 16102E4E35FAA0FC4161282FECE56469 /* Timeline.swift in Sources */, + 5BC19E6E0F199276003F0AF96838BCE5 /* Upload.swift in Sources */, + 2D3405986FC586FA6C0A5E0B6BA7E64E /* Validation.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -1082,13 +1094,13 @@ FC9E3FF49D9B636B2925749B2D51A5D3 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = Alamofire; - target = 432ECC54282C84882B482CCB4CF227FC /* Alamofire */; + target = 79C040AFDDCE1BCBF6D8B5EB0B85887F /* Alamofire */; targetProxy = 4BED27A854EA6600536518D29BBB3670 /* PBXContainerItemProxy */; }; FFAF754843564CB3D6F424CE47B71A27 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = Alamofire; - target = 432ECC54282C84882B482CCB4CF227FC /* Alamofire */; + target = 79C040AFDDCE1BCBF6D8B5EB0B85887F /* Alamofire */; targetProxy = 8E08EC4F5A85093B738D80C4F04BA3F1 /* PBXContainerItemProxy */; }; /* End PBXTargetDependency section */ @@ -1157,9 +1169,38 @@ }; name = Debug; }; + 32AD5F8918CA8B349E4671410FA624C9 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 10A634092EE6D018EB00C75E9864A6A2 /* Alamofire.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; 6D58F928D13C57FA81A386B6364889AA /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = CC49FF2A84C0E0E9349747D94036B728 /* PromiseKit.xcconfig */; + baseConfigurationReference = 2E750A27FAB06DE866BC27CC8FA07806 /* PromiseKit.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; CURRENT_PROJECT_VERSION = 1; @@ -1186,6 +1227,36 @@ }; name = Release; }; + 75218111E718FACE36F771E8ABECDB62 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 10A634092EE6D018EB00C75E9864A6A2 /* Alamofire.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; 7EA02FDF9D26C9AD275654E73F406F04 /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 969C2AF48F4307163B301A92E78AFCF2 /* Pods-SwaggerClientTests.debug.xcconfig */; @@ -1290,38 +1361,9 @@ }; name = Debug; }; - 9B26D3A39011247999C097562A550399 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 141F0B43C42CE92856BBA8F8D98481DB /* Alamofire.xcconfig */; - buildSettings = { - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; - GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; - MTL_ENABLE_DEBUG_INFO = NO; - PRODUCT_NAME = Alamofire; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Release; - }; A1075551063662DDB4B1D70BD9D48C6E /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 16D7C901D915C251DEBA27AC1EF57E34 /* OMGHTTPURLRQ.xcconfig */; + baseConfigurationReference = E6EC6723A17EAD72862789D6748FAA26 /* OMGHTTPURLRQ.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; CURRENT_PROJECT_VERSION = 1; @@ -1384,7 +1426,7 @@ }; AF5D8A65BDA6B725A14D20EC25949CE0 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = CC49FF2A84C0E0E9349747D94036B728 /* PromiseKit.xcconfig */; + baseConfigurationReference = 2E750A27FAB06DE866BC27CC8FA07806 /* PromiseKit.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; CURRENT_PROJECT_VERSION = 1; @@ -1412,36 +1454,6 @@ }; name = Debug; }; - BE1BF3E5FC53BAFA505AB342C35E1F50 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 141F0B43C42CE92856BBA8F8D98481DB /* Alamofire.xcconfig */; - buildSettings = { - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = dwarf; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_NO_COMMON_BLOCKS = YES; - GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; - MTL_ENABLE_DEBUG_INFO = YES; - PRODUCT_NAME = Alamofire; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Debug; - }; F594C655D48020EC34B00AA63E001773 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { @@ -1482,7 +1494,7 @@ }; F81B9CD48A7BB5944F3E7D734DA19714 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 16D7C901D915C251DEBA27AC1EF57E34 /* OMGHTTPURLRQ.xcconfig */; + baseConfigurationReference = E6EC6723A17EAD72862789D6748FAA26 /* OMGHTTPURLRQ.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; CURRENT_PROJECT_VERSION = 1; @@ -1572,20 +1584,20 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 620A8F6BEDF449F55F08EDB4CDBF60A2 /* Build configuration list for PBXNativeTarget "OMGHTTPURLRQ" */ = { + 3CFB42910790CF0BDBCCEBAACD6B9367 /* Build configuration list for PBXNativeTarget "Alamofire" */ = { isa = XCConfigurationList; buildConfigurations = ( - F81B9CD48A7BB5944F3E7D734DA19714 /* Debug */, - A1075551063662DDB4B1D70BD9D48C6E /* Release */, + 75218111E718FACE36F771E8ABECDB62 /* Debug */, + 32AD5F8918CA8B349E4671410FA624C9 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 8B2B2DA2F7F80D41B1FDB5FACFA4B3DE /* Build configuration list for PBXNativeTarget "Alamofire" */ = { + 620A8F6BEDF449F55F08EDB4CDBF60A2 /* Build configuration list for PBXNativeTarget "OMGHTTPURLRQ" */ = { isa = XCConfigurationList; buildConfigurations = ( - BE1BF3E5FC53BAFA505AB342C35E1F50 /* Debug */, - 9B26D3A39011247999C097562A550399 /* Release */, + F81B9CD48A7BB5944F3E7D734DA19714 /* Debug */, + A1075551063662DDB4B1D70BD9D48C6E /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Info.plist b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Info.plist index c1aea25c248..7694605fe7a 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Info.plist +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Alamofire/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 3.1.5 + 3.4.1 CFBundleSignature ???? CFBundleVersion diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/Info.plist b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/Info.plist index 793d31a9fdd..8b511bb3946 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/Info.plist +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/OMGHTTPURLRQ/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 3.1.1 + 3.1.3 CFBundleSignature ???? CFBundleVersion diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.markdown b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.markdown index 876c8ce5ee8..e6778cdc3f6 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.markdown +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.markdown @@ -3,7 +3,7 @@ This application makes use of the following third party libraries: ## Alamofire -Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -26,7 +26,7 @@ THE SOFTWARE. ## OMGHTTPURLRQ -See README.markdown for full license text. +https://github.com/mxcl/OMGHTTPURLRQ/blob/master/README.markdown ## PetstoreClient diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.plist b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.plist index 49af015bfaf..dfbd5e635c9 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.plist +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.plist @@ -14,7 +14,7 @@ FooterText - Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) + Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -41,7 +41,7 @@ THE SOFTWARE. FooterText - See README.markdown for full license text. + https://github.com/mxcl/OMGHTTPURLRQ/blob/master/README.markdown Title OMGHTTPURLRQ Type diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh index e768f92993e..0a1561528cb 100755 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh @@ -48,8 +48,8 @@ EOM ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ;; *.xib) - echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT}" - ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ;; *.framework) echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh index e768f92993e..0a1561528cb 100755 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh @@ -48,8 +48,8 @@ EOM ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ;; *.xib) - echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT}" - ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ;; *.framework) echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index 3d557a9280f..0eec9dcf8c6 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -143,12 +143,12 @@ isa = PBXNativeTarget; buildConfigurationList = 6D4EFBAE1C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClient" */; buildPhases = ( - 1F03F780DC2D9727E5E64BA9 /* 📦 Check Pods Manifest.lock */, + 1F03F780DC2D9727E5E64BA9 /* [CP] Check Pods Manifest.lock */, 6D4EFB8D1C692C6300B96B06 /* Sources */, 6D4EFB8E1C692C6300B96B06 /* Frameworks */, 6D4EFB8F1C692C6300B96B06 /* Resources */, - 4485A75250058E2D5BBDF63F /* 📦 Embed Pods Frameworks */, - 808CE4A0CE801CAC5ABF5B08 /* 📦 Copy Pods Resources */, + 4485A75250058E2D5BBDF63F /* [CP] Embed Pods Frameworks */, + 808CE4A0CE801CAC5ABF5B08 /* [CP] Copy Pods Resources */, ); buildRules = ( ); @@ -163,12 +163,12 @@ isa = PBXNativeTarget; buildConfigurationList = 6D4EFBB11C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */; buildPhases = ( - 79FE27B09B2DD354C831BD49 /* 📦 Check Pods Manifest.lock */, + 79FE27B09B2DD354C831BD49 /* [CP] Check Pods Manifest.lock */, 6D4EFBA11C692C6300B96B06 /* Sources */, 6D4EFBA21C692C6300B96B06 /* Frameworks */, 6D4EFBA31C692C6300B96B06 /* Resources */, - 796EAD48F1BCCDAA291CD963 /* 📦 Embed Pods Frameworks */, - 1652CB1A246A4689869E442D /* 📦 Copy Pods Resources */, + 796EAD48F1BCCDAA291CD963 /* [CP] Embed Pods Frameworks */, + 1652CB1A246A4689869E442D /* [CP] Copy Pods Resources */, ); buildRules = ( ); @@ -239,14 +239,14 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ - 1652CB1A246A4689869E442D /* 📦 Copy Pods Resources */ = { + 1652CB1A246A4689869E442D /* [CP] Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Copy Pods Resources"; + name = "[CP] Copy Pods Resources"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -254,14 +254,14 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh\"\n"; showEnvVarsInLog = 0; }; - 1F03F780DC2D9727E5E64BA9 /* 📦 Check Pods Manifest.lock */ = { + 1F03F780DC2D9727E5E64BA9 /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Check Pods Manifest.lock"; + name = "[CP] Check Pods Manifest.lock"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -269,14 +269,14 @@ shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; showEnvVarsInLog = 0; }; - 4485A75250058E2D5BBDF63F /* 📦 Embed Pods Frameworks */ = { + 4485A75250058E2D5BBDF63F /* [CP] Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Embed Pods Frameworks"; + name = "[CP] Embed Pods Frameworks"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -284,14 +284,14 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; - 796EAD48F1BCCDAA291CD963 /* 📦 Embed Pods Frameworks */ = { + 796EAD48F1BCCDAA291CD963 /* [CP] Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Embed Pods Frameworks"; + name = "[CP] Embed Pods Frameworks"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -299,14 +299,14 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; - 79FE27B09B2DD354C831BD49 /* 📦 Check Pods Manifest.lock */ = { + 79FE27B09B2DD354C831BD49 /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Check Pods Manifest.lock"; + name = "[CP] Check Pods Manifest.lock"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -314,14 +314,14 @@ shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; showEnvVarsInLog = 0; }; - 808CE4A0CE801CAC5ABF5B08 /* 📦 Copy Pods Resources */ = { + 808CE4A0CE801CAC5ABF5B08 /* [CP] Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Copy Pods Resources"; + name = "[CP] Copy Pods Resources"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; From 75cd4bf4373d4fcb0d9a427bbd811227719c0f0a Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 31 Jul 2016 10:07:04 +0800 Subject: [PATCH 173/470] add shippable badge, update travis badge --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 97b1fa3bf5d..75c01efc103 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,10 @@ # Swagger Code Generator -[![Build Status](https://travis-ci.org/swagger-api/swagger-codegen.svg)](https://travis-ci.org/swagger-api/swagger-codegen) +[![Build Status](https://img.shields.io/travis/swagger-api/swagger-codegen.svg?label=Petstore%20Integration%20Test)](https://travis-ci.org/swagger-api/swagger-codegen) +[![Run Status](https://img.shields.io/shippable/5782588a3be4f4faa56c5bea.svg?label=Mustache%20Template%20Test)](https://app.shippable.com/projects/5782588a3be4f4faa56c5bea) +[![Windows Test](https://ci.appveyor.com/api/projects/status/github/swagger-api/swagger-codegen?branch=master&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/swagger-codegen-wh2wu) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/io.swagger/swagger-codegen-project/badge.svg?style=plastic)](https://maven-badges.herokuapp.com/maven-central/io.swagger/swagger-codegen-project) [![PR Stats](http://issuestats.com/github/swagger-api/swagger-codegen/badge/pr)](http://issuestats.com/github/swagger-api/swagger-codegen) [![Issue Stats](http://issuestats.com/github/swagger-api/swagger-codegen/badge/issue)](http://issuestats.com/github/swagger-api/swagger-codegen) -[![Windows Test](https://ci.appveyor.com/api/projects/status/github/swagger-api/swagger-codegen?branch=master&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/swagger-codegen-wh2wu) :star::star::star: If you would like to contribute, please refer to [guidelines](https://github.com/swagger-api/swagger-codegen/blob/master/CONTRIBUTING.md) and a list of [open tasks](https://github.com/swagger-api/swagger-codegen/issues?q=is%3Aopen+is%3Aissue+label%3A%22Need+community+contribution%22).:star::star::star: From c91b004b0b1db27db76ebf912e3d8ef371fc7c1d Mon Sep 17 00:00:00 2001 From: Peter Szanto Date: Sun, 31 Jul 2016 04:16:22 +0200 Subject: [PATCH 174/470] fixing bug of rendering an extra spaces into @FeignClient annotation properties --- .../JavaSpring/libraries/spring-cloud/apiClient.mustache | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/apiClient.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/apiClient.mustache index 57d227f6bbb..52fedbea776 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/apiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/apiClient.mustache @@ -3,6 +3,8 @@ package {{package}}; import org.springframework.cloud.netflix.feign.FeignClient; import {{configPackage}}.ClientConfiguration; -@FeignClient(name="${ {{{title}}}.name:{{{title}}}}", url="${ {{{title}}}.url:{{{basePath}}}}", configuration = ClientConfiguration.class) +{{=<% %>=}} +@FeignClient(name="${<%title%>.name:<%title%>}", url="${<%title%>.url:<%basePath%>}", configuration = ClientConfiguration.class) +<%={{ }}=%> public interface {{classname}}Client extends {{classname}} { } \ No newline at end of file From 3d7ff26c67eeffa73ce134a3e318a1966e341c1e Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 31 Jul 2016 22:37:06 +0800 Subject: [PATCH 175/470] [C#] Add C# Petstore test to AppVeyor (#3489) * update appveyor.yml to test c# petstore client * update csproj file * add docker version test * add docker version * add docker * add cpuid.ps1 * comment out cpuid * use start process * remove mvn test * remove comments related to docker * fix appveyor to run local petstore, shippable caching turned on * add comments to ci config * remove cpuid.ps1 * update C# petstore sample --- appveyor.yml | 11 +++- .../main/resources/csharp/gitignore.mustache | 52 +++++++++---------- .../petstore/csharp/SwaggerClient/.gitignore | 52 +++++++++---------- .../csharp/SwaggerClient/IO.Swagger.sln | 10 ++-- .../petstore/csharp/SwaggerClient/README.md | 2 +- .../IO.Swagger.Test/IO.Swagger.Test.csproj | 12 ++--- .../src/IO.Swagger/IO.Swagger.csproj | 2 +- shippable.yml | 8 +-- 8 files changed, 80 insertions(+), 69 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index 2b31bd9f70a..5710fa5bc3a 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,7 +1,9 @@ # for CI with appveyor.yml # Ref: http://www.yegor256.com/2015/01/10/windows-appveyor-maven.html -version: '{build}' +version: '{branch}-{build}' os: Windows Server 2012 +hosts: + petstore.swagger.io: 127.0.0.1 install: - ps: | Add-Type -AssemblyName System.IO.Compression.FileSystem @@ -15,9 +17,16 @@ install: - cmd: SET PATH=C:\maven\apache-maven-3.2.5\bin;%JAVA_HOME%\bin;%PATH% - cmd: SET MAVEN_OPTS=-XX:MaxPermSize=2g -Xmx4g - cmd: SET JAVA_OPTS=-XX:MaxPermSize=2g -Xmx4g + - git clone https://github.com/wing328/swagger-samples + - ps: Start-Process -FilePath 'C:\maven\apache-maven-3.2.5\bin\mvn' -ArgumentList 'jetty:run' -WorkingDirectory "$env:appveyor_build_folder\swagger-samples\java\java-jersey-jaxrs" build_script: + - nuget restore samples\client\petstore\csharp\SwaggerClient\IO.Swagger.sln + - msbuild samples\client\petstore\csharp\SwaggerClient\IO.Swagger.sln /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" - mvn clean install --batch-mode test_script: + # test c# API client + - nunit-console samples\client\petstore\csharp\SwaggerClient\src\IO.Swagger.Test\bin\Debug\IO.Swagger.Test.dll --result=myresults.xml;format=AppVeyor + # generate all petstore clients - .\bin\windows\run-all-petstore.cmd cache: - C:\maven\ diff --git a/modules/swagger-codegen/src/main/resources/csharp/gitignore.mustache b/modules/swagger-codegen/src/main/resources/csharp/gitignore.mustache index 56fef626922..d3f4f7b6f55 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/gitignore.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/gitignore.mustache @@ -147,39 +147,39 @@ UpgradeLog*.htm *.swp *.swo - # svn - .svn +# svn +.svn - # SQL Server files - **/App_Data/*.mdf - **/App_Data/*.ldf - **/App_Data/*.sdf +# SQL Server files +**/App_Data/*.mdf +**/App_Data/*.ldf +**/App_Data/*.sdf - #LightSwitch generated files - GeneratedArtifacts/ - _Pvt_Extensions/ - ModelManifest.xml +#LightSwitch generated files +GeneratedArtifacts/ +_Pvt_Extensions/ +ModelManifest.xml - # ========================= - # Windows detritus - # ========================= +# ========================= +# Windows detritus +# ========================= - # Windows image file caches - Thumbs.db - ehthumbs.db +# Windows image file caches +Thumbs.db +ehthumbs.db - # Folder config file - Desktop.ini +# Folder config file +Desktop.ini - # Recycle Bin used on file shares - $RECYCLE.BIN/ +# Recycle Bin used on file shares +$RECYCLE.BIN/ - # Mac desktop service store files - .DS_Store +# Mac desktop service store files +.DS_Store - # SASS Compiler cache - .sass-cache +# SASS Compiler cache +.sass-cache - # Visual Studio 2014 CTP - **/*.sln.ide +# Visual Studio 2014 CTP +**/*.sln.ide diff --git a/samples/client/petstore/csharp/SwaggerClient/.gitignore b/samples/client/petstore/csharp/SwaggerClient/.gitignore index 56fef626922..d3f4f7b6f55 100644 --- a/samples/client/petstore/csharp/SwaggerClient/.gitignore +++ b/samples/client/petstore/csharp/SwaggerClient/.gitignore @@ -147,39 +147,39 @@ UpgradeLog*.htm *.swp *.swo - # svn - .svn +# svn +.svn - # SQL Server files - **/App_Data/*.mdf - **/App_Data/*.ldf - **/App_Data/*.sdf +# SQL Server files +**/App_Data/*.mdf +**/App_Data/*.ldf +**/App_Data/*.sdf - #LightSwitch generated files - GeneratedArtifacts/ - _Pvt_Extensions/ - ModelManifest.xml +#LightSwitch generated files +GeneratedArtifacts/ +_Pvt_Extensions/ +ModelManifest.xml - # ========================= - # Windows detritus - # ========================= +# ========================= +# Windows detritus +# ========================= - # Windows image file caches - Thumbs.db - ehthumbs.db +# Windows image file caches +Thumbs.db +ehthumbs.db - # Folder config file - Desktop.ini +# Folder config file +Desktop.ini - # Recycle Bin used on file shares - $RECYCLE.BIN/ +# Recycle Bin used on file shares +$RECYCLE.BIN/ - # Mac desktop service store files - .DS_Store +# Mac desktop service store files +.DS_Store - # SASS Compiler cache - .sass-cache +# SASS Compiler cache +.sass-cache - # Visual Studio 2014 CTP - **/*.sln.ide +# Visual Studio 2014 CTP +**/*.sln.ide diff --git a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln index 28a3d31c548..9dc6bc62fa2 100644 --- a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln +++ b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln @@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 VisualStudioVersion = 12.0.0.0 MinimumVisualStudioVersion = 10.0.0.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{C95ADC68-F3D8-41D1-BA8A-6C0754E6BB54}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{F616AC0A-13D9-4D7E-ACE1-93E41B628F88}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger.Test", "src\IO.Swagger.Test\IO.Swagger.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" EndProject @@ -12,10 +12,10 @@ Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution -{C95ADC68-F3D8-41D1-BA8A-6C0754E6BB54}.Debug|Any CPU.ActiveCfg = Debug|Any CPU -{C95ADC68-F3D8-41D1-BA8A-6C0754E6BB54}.Debug|Any CPU.Build.0 = Debug|Any CPU -{C95ADC68-F3D8-41D1-BA8A-6C0754E6BB54}.Release|Any CPU.ActiveCfg = Release|Any CPU -{C95ADC68-F3D8-41D1-BA8A-6C0754E6BB54}.Release|Any CPU.Build.0 = Release|Any CPU +{F616AC0A-13D9-4D7E-ACE1-93E41B628F88}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{F616AC0A-13D9-4D7E-ACE1-93E41B628F88}.Debug|Any CPU.Build.0 = Debug|Any CPU +{F616AC0A-13D9-4D7E-ACE1-93E41B628F88}.Release|Any CPU.ActiveCfg = Release|Any CPU +{F616AC0A-13D9-4D7E-ACE1-93E41B628F88}.Release|Any CPU.Build.0 = Release|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/samples/client/petstore/csharp/SwaggerClient/README.md b/samples/client/petstore/csharp/SwaggerClient/README.md index d890bfa20f0..94f420f1cba 100644 --- a/samples/client/petstore/csharp/SwaggerClient/README.md +++ b/samples/client/petstore/csharp/SwaggerClient/README.md @@ -6,7 +6,7 @@ This C# SDK is automatically generated by the [Swagger Codegen](https://github.c - API version: 1.0.0 - SDK version: 1.0.0 -- Build date: 2016-07-26T14:25:16.509+08:00 +- Build date: 2016-07-31T22:04:18.446+08:00 - Build package: class io.swagger.codegen.languages.CSharpClientCodegen ## Frameworks supported diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj index 5660f132a37..c92b1ab1663 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj @@ -2,7 +2,7 @@ + samples/server/petstore/java-inflector samples/server/petstore/jaxrs/jersey1 samples/server/petstore/jaxrs/jersey2 samples/server/petstore/jaxrs-resteasy/default diff --git a/samples/server/petstore/java-inflector/.swagger-codegen-ignore b/samples/server/petstore/java-inflector/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/java-inflector/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/java-inflector/LICENSE b/samples/server/petstore/java-inflector/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/server/petstore/java-inflector/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/handler/StringUtil.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/handler/StringUtil.java new file mode 100644 index 00000000000..16c10060121 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/handler/StringUtil.java @@ -0,0 +1,42 @@ +package io.swagger.handler; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+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(); + } +} diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..572c1ba2d26 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java @@ -0,0 +1,97 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +public class AdditionalPropertiesClass { + private Map mapProperty = new HashMap(); + + private Map> mapOfMapProperty = new HashMap>(); + + /** + **/ + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("map_property") + public Map getMapProperty() { + return mapProperty; + } + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + /** + **/ + public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("map_of_map_property") + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; + return Objects.equals(mapProperty, additionalPropertiesClass.mapProperty) && + Objects.equals(mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); + } + + @Override + public int hashCode() { + return Objects.hash(mapProperty, mapOfMapProperty); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Animal.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Animal.java new file mode 100644 index 00000000000..d385d3d355b --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Animal.java @@ -0,0 +1,94 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +public class Animal { + private String className = null; + + private String color = "red"; + + /** + **/ + public Animal className(String className) { + this.className = className; + return this; + } + + + @ApiModelProperty(example = "null", required = true, value = "") + @JsonProperty("className") + public String getClassName() { + return className; + } + public void setClassName(String className) { + this.className = className; + } + + /** + **/ + public Animal color(String color) { + this.color = color; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("color") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Animal animal = (Animal) o; + return Objects.equals(className, animal.className) && + Objects.equals(color, animal.color); + } + + @Override + public int hashCode() { + return Objects.hash(className, color); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Animal {\n"); + + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/AnimalFarm.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/AnimalFarm.java new file mode 100644 index 00000000000..4ae707c1a77 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/AnimalFarm.java @@ -0,0 +1,52 @@ +package io.swagger.model; + +import java.util.Objects; +import io.swagger.model.Animal; +import java.util.ArrayList; +import java.util.List; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +public class AnimalFarm extends ArrayList { + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AnimalFarm animalFarm = (AnimalFarm) o; + return true; + } + + @Override + public int hashCode() { + return Objects.hash(); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 00000000000..8db5e4343e9 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,76 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +public class ArrayOfArrayOfNumberOnly { + private List> arrayArrayNumber = new ArrayList>(); + + /** + **/ + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("ArrayArrayNumber") + public List> getArrayArrayNumber() { + return arrayArrayNumber; + } + public void setArrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly = (ArrayOfArrayOfNumberOnly) o; + return Objects.equals(arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayArrayNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfArrayOfNumberOnly {\n"); + + sb.append(" arrayArrayNumber: ").append(toIndentedString(arrayArrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java new file mode 100644 index 00000000000..232e4786b13 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java @@ -0,0 +1,76 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +public class ArrayOfNumberOnly { + private List arrayNumber = new ArrayList(); + + /** + **/ + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("ArrayNumber") + public List getArrayNumber() { + return arrayNumber; + } + public void setArrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfNumberOnly arrayOfNumberOnly = (ArrayOfNumberOnly) o; + return Objects.equals(arrayNumber, arrayOfNumberOnly.arrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfNumberOnly {\n"); + + sb.append(" arrayNumber: ").append(toIndentedString(arrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ArrayTest.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ArrayTest.java new file mode 100644 index 00000000000..4a0e569dbc7 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ArrayTest.java @@ -0,0 +1,118 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.ReadOnlyFirst; +import java.util.ArrayList; +import java.util.List; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +public class ArrayTest { + private List arrayOfString = new ArrayList(); + + private List> arrayArrayOfInteger = new ArrayList>(); + + private List> arrayArrayOfModel = new ArrayList>(); + + /** + **/ + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("array_of_string") + public List getArrayOfString() { + return arrayOfString; + } + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + /** + **/ + public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("array_array_of_integer") + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + /** + **/ + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("array_array_of_model") + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayTest arrayTest = (ArrayTest) o; + return Objects.equals(arrayOfString, arrayTest.arrayOfString) && + Objects.equals(arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(arrayArrayOfModel, arrayTest.arrayArrayOfModel); + } + + @Override + public int hashCode() { + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Cat.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Cat.java new file mode 100644 index 00000000000..0977daffdfd --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Cat.java @@ -0,0 +1,74 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Animal; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +public class Cat extends Animal { + private Boolean declawed = null; + + /** + **/ + public Cat declawed(Boolean declawed) { + this.declawed = declawed; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("declawed") + public Boolean getDeclawed() { + return declawed; + } + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Cat cat = (Cat) o; + return Objects.equals(declawed, cat.declawed); + } + + @Override + public int hashCode() { + return Objects.hash(declawed); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Cat {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Category.java new file mode 100644 index 00000000000..2437d48f9e2 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Category.java @@ -0,0 +1,94 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +public class Category { + private Long id = null; + + private String name = null; + + /** + **/ + public Category id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + public Category name(String name) { + this.name = name; + return this; + } + + + @ApiModelProperty(example = "null", 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(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Client.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Client.java new file mode 100644 index 00000000000..9e71d506697 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Client.java @@ -0,0 +1,73 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +public class Client { + private String client = null; + + /** + **/ + public Client client(String client) { + this.client = client; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("client") + public String getClient() { + return client; + } + public void setClient(String client) { + this.client = client; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Client client = (Client) o; + return Objects.equals(client, client.client); + } + + @Override + public int hashCode() { + return Objects.hash(client); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Client {\n"); + + sb.append(" client: ").append(toIndentedString(client)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Dog.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Dog.java new file mode 100644 index 00000000000..9adc4bdcfc0 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Dog.java @@ -0,0 +1,74 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Animal; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +public class Dog extends Animal { + private String breed = null; + + /** + **/ + public Dog breed(String breed) { + this.breed = breed; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("breed") + public String getBreed() { + return breed; + } + public void setBreed(String breed) { + this.breed = breed; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Dog dog = (Dog) o; + return Objects.equals(breed, dog.breed); + } + + @Override + public int hashCode() { + return Objects.hash(breed); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Dog {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumArrays.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumArrays.java new file mode 100644 index 00000000000..bc44bd58575 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumArrays.java @@ -0,0 +1,137 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.ArrayList; +import java.util.List; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +public class EnumArrays { + /** + * Gets or Sets justSymbol + */ + public enum JustSymbolEnum { + GREATER_THAN_OR_EQUAL_TO(">="), + + DOLLAR("$"); + + private String value; + + JustSymbolEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + private JustSymbolEnum justSymbol = null; + + /** + * Gets or Sets arrayEnum + */ + public enum ArrayEnumEnum { + FISH("fish"), + + CRAB("crab"); + + private String value; + + ArrayEnumEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + private List arrayEnum = new ArrayList(); + + /** + **/ + public EnumArrays justSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("just_symbol") + public JustSymbolEnum getJustSymbol() { + return justSymbol; + } + public void setJustSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + } + + /** + **/ + public EnumArrays arrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("array_enum") + public List getArrayEnum() { + return arrayEnum; + } + public void setArrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumArrays enumArrays = (EnumArrays) o; + return Objects.equals(justSymbol, enumArrays.justSymbol) && + Objects.equals(arrayEnum, enumArrays.arrayEnum); + } + + @Override + public int hashCode() { + return Objects.hash(justSymbol, arrayEnum); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumArrays {\n"); + + sb.append(" justSymbol: ").append(toIndentedString(justSymbol)).append("\n"); + sb.append(" arrayEnum: ").append(toIndentedString(arrayEnum)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumClass.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumClass.java new file mode 100644 index 00000000000..2eb1a992f3e --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumClass.java @@ -0,0 +1,31 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonValue; + + + +/** + * Gets or Sets EnumClass + */ +public enum EnumClass { + + _ABC("_abc"), + + _EFG("-efg"), + + _XYZ_("(xyz)"); + + private String value; + + EnumClass(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } +} + + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumTest.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumTest.java new file mode 100644 index 00000000000..3b9e69a43c9 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumTest.java @@ -0,0 +1,176 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +public class EnumTest { + /** + * Gets or Sets enumString + */ + public enum EnumStringEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + EnumStringEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + private EnumStringEnum enumString = null; + + /** + * Gets or Sets enumInteger + */ + public enum EnumIntegerEnum { + NUMBER_1(1), + + NUMBER_MINUS_1(-1); + + private Integer value; + + EnumIntegerEnum(Integer value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + private EnumIntegerEnum enumInteger = null; + + /** + * Gets or Sets enumNumber + */ + public enum EnumNumberEnum { + NUMBER_1_DOT_1(1.1), + + NUMBER_MINUS_1_DOT_2(-1.2); + + private Double value; + + EnumNumberEnum(Double value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + private EnumNumberEnum enumNumber = null; + + /** + **/ + public EnumTest enumString(EnumStringEnum enumString) { + this.enumString = enumString; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("enum_string") + public EnumStringEnum getEnumString() { + return enumString; + } + public void setEnumString(EnumStringEnum enumString) { + this.enumString = enumString; + } + + /** + **/ + public EnumTest enumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("enum_integer") + public EnumIntegerEnum getEnumInteger() { + return enumInteger; + } + public void setEnumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + } + + /** + **/ + public EnumTest enumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("enum_number") + public EnumNumberEnum getEnumNumber() { + return enumNumber; + } + public void setEnumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumTest enumTest = (EnumTest) o; + return Objects.equals(enumString, enumTest.enumString) && + Objects.equals(enumInteger, enumTest.enumInteger) && + Objects.equals(enumNumber, enumTest.enumNumber); + } + + @Override + public int hashCode() { + return Objects.hash(enumString, enumInteger, enumNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/FormatTest.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/FormatTest.java new file mode 100644 index 00000000000..1d7dd3ec37e --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/FormatTest.java @@ -0,0 +1,337 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.Date; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +public class FormatTest { + private Integer integer = null; + + private Integer int32 = null; + + private Long int64 = null; + + private BigDecimal number = null; + + private Float _float = null; + + private Double _double = null; + + private String string = null; + + private byte[] _byte = null; + + private byte[] binary = null; + + private Date date = null; + + private Date dateTime = null; + + private String uuid = null; + + private String password = null; + + /** + * minimum: 10.0 + * maximum: 100.0 + **/ + public FormatTest integer(Integer integer) { + this.integer = integer; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("integer") + public Integer getInteger() { + return integer; + } + public void setInteger(Integer integer) { + this.integer = integer; + } + + /** + * minimum: 20.0 + * maximum: 200.0 + **/ + public FormatTest int32(Integer int32) { + this.int32 = int32; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("int32") + public Integer getInt32() { + return int32; + } + public void setInt32(Integer int32) { + this.int32 = int32; + } + + /** + **/ + public FormatTest int64(Long int64) { + this.int64 = int64; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("int64") + public Long getInt64() { + return int64; + } + public void setInt64(Long int64) { + this.int64 = int64; + } + + /** + * minimum: 32.1 + * maximum: 543.2 + **/ + public FormatTest number(BigDecimal number) { + this.number = number; + return this; + } + + + @ApiModelProperty(example = "null", required = true, value = "") + @JsonProperty("number") + public BigDecimal getNumber() { + return number; + } + public void setNumber(BigDecimal number) { + this.number = number; + } + + /** + * minimum: 54.3 + * maximum: 987.6 + **/ + public FormatTest _float(Float _float) { + this._float = _float; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("float") + public Float getFloat() { + return _float; + } + public void setFloat(Float _float) { + this._float = _float; + } + + /** + * minimum: 67.8 + * maximum: 123.4 + **/ + public FormatTest _double(Double _double) { + this._double = _double; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("double") + public Double getDouble() { + return _double; + } + public void setDouble(Double _double) { + this._double = _double; + } + + /** + **/ + public FormatTest string(String string) { + this.string = string; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("string") + public String getString() { + return string; + } + public void setString(String string) { + this.string = string; + } + + /** + **/ + public FormatTest _byte(byte[] _byte) { + this._byte = _byte; + return this; + } + + + @ApiModelProperty(example = "null", required = true, value = "") + @JsonProperty("byte") + public byte[] getByte() { + return _byte; + } + public void setByte(byte[] _byte) { + this._byte = _byte; + } + + /** + **/ + public FormatTest binary(byte[] binary) { + this.binary = binary; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("binary") + public byte[] getBinary() { + return binary; + } + public void setBinary(byte[] binary) { + this.binary = binary; + } + + /** + **/ + public FormatTest date(Date date) { + this.date = date; + return this; + } + + + @ApiModelProperty(example = "null", required = true, value = "") + @JsonProperty("date") + public Date getDate() { + return date; + } + public void setDate(Date date) { + this.date = date; + } + + /** + **/ + public FormatTest dateTime(Date dateTime) { + this.dateTime = dateTime; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("dateTime") + public Date getDateTime() { + return dateTime; + } + public void setDateTime(Date dateTime) { + this.dateTime = dateTime; + } + + /** + **/ + public FormatTest uuid(String uuid) { + this.uuid = uuid; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("uuid") + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + + /** + **/ + public FormatTest password(String password) { + this.password = password; + return this; + } + + + @ApiModelProperty(example = "null", required = true, value = "") + @JsonProperty("password") + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + FormatTest formatTest = (FormatTest) o; + return Objects.equals(integer, formatTest.integer) && + Objects.equals(int32, formatTest.int32) && + Objects.equals(int64, formatTest.int64) && + Objects.equals(number, formatTest.number) && + Objects.equals(_float, formatTest._float) && + Objects.equals(_double, formatTest._double) && + Objects.equals(string, formatTest.string) && + Objects.equals(_byte, formatTest._byte) && + Objects.equals(binary, formatTest.binary) && + Objects.equals(date, formatTest.date) && + Objects.equals(dateTime, formatTest.dateTime) && + Objects.equals(uuid, formatTest.uuid) && + Objects.equals(password, formatTest.password); + } + + @Override + public int hashCode() { + return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, uuid, password); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FormatTest {\n"); + + sb.append(" integer: ").append(toIndentedString(integer)).append("\n"); + sb.append(" int32: ").append(toIndentedString(int32)).append("\n"); + sb.append(" int64: ").append(toIndentedString(int64)).append("\n"); + sb.append(" number: ").append(toIndentedString(number)).append("\n"); + sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); + sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); + sb.append(" string: ").append(toIndentedString(string)).append("\n"); + sb.append(" _byte: ").append(toIndentedString(_byte)).append("\n"); + sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); + sb.append(" date: ").append(toIndentedString(date)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/HasOnlyReadOnly.java new file mode 100644 index 00000000000..a780629909f --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/HasOnlyReadOnly.java @@ -0,0 +1,94 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +public class HasOnlyReadOnly { + private String bar = null; + + private String foo = null; + + /** + **/ + public HasOnlyReadOnly bar(String bar) { + this.bar = bar; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("bar") + public String getBar() { + return bar; + } + public void setBar(String bar) { + this.bar = bar; + } + + /** + **/ + public HasOnlyReadOnly foo(String foo) { + this.foo = foo; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("foo") + public String getFoo() { + return foo; + } + public void setFoo(String foo) { + this.foo = foo; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HasOnlyReadOnly hasOnlyReadOnly = (HasOnlyReadOnly) o; + return Objects.equals(bar, hasOnlyReadOnly.bar) && + Objects.equals(foo, hasOnlyReadOnly.foo); + } + + @Override + public int hashCode() { + return Objects.hash(bar, foo); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HasOnlyReadOnly {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" foo: ").append(toIndentedString(foo)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/MapTest.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/MapTest.java new file mode 100644 index 00000000000..033494b6b91 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/MapTest.java @@ -0,0 +1,118 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +public class MapTest { + private Map> mapMapOfString = new HashMap>(); + + /** + * Gets or Sets inner + */ + public enum InnerEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + InnerEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + private Map mapOfEnumString = new HashMap(); + + /** + **/ + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("map_map_of_string") + public Map> getMapMapOfString() { + return mapMapOfString; + } + public void setMapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + } + + /** + **/ + public MapTest mapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("map_of_enum_string") + public Map getMapOfEnumString() { + return mapOfEnumString; + } + public void setMapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MapTest mapTest = (MapTest) o; + return Objects.equals(mapMapOfString, mapTest.mapMapOfString) && + Objects.equals(mapOfEnumString, mapTest.mapOfEnumString); + } + + @Override + public int hashCode() { + return Objects.hash(mapMapOfString, mapOfEnumString); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MapTest {\n"); + + sb.append(" mapMapOfString: ").append(toIndentedString(mapMapOfString)).append("\n"); + sb.append(" mapOfEnumString: ").append(toIndentedString(mapOfEnumString)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..d10d2b2881a --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,120 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Animal; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +public class MixedPropertiesAndAdditionalPropertiesClass { + private String uuid = null; + + private Date dateTime = null; + + private Map map = new HashMap(); + + /** + **/ + public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { + this.uuid = uuid; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("uuid") + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + + /** + **/ + public MixedPropertiesAndAdditionalPropertiesClass dateTime(Date dateTime) { + this.dateTime = dateTime; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("dateTime") + public Date getDateTime() { + return dateTime; + } + public void setDateTime(Date dateTime) { + this.dateTime = dateTime; + } + + /** + **/ + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + this.map = map; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("map") + public Map getMap() { + return map; + } + public void setMap(Map map) { + this.map = map; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; + return Objects.equals(uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(map, mixedPropertiesAndAdditionalPropertiesClass.map); + } + + @Override + public int hashCode() { + return Objects.hash(uuid, dateTime, map); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Model200Response.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Model200Response.java new file mode 100644 index 00000000000..079077e8c4e --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Model200Response.java @@ -0,0 +1,97 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + +/** + * Model for testing model name starting with number + **/ + +@ApiModel(description = "Model for testing model name starting with number") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +public class Model200Response { + private Integer name = null; + + private String PropertyClass = null; + + /** + **/ + public Model200Response name(Integer name) { + this.name = name; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("name") + public Integer getName() { + return name; + } + public void setName(Integer name) { + this.name = name; + } + + /** + **/ + public Model200Response PropertyClass(String PropertyClass) { + this.PropertyClass = PropertyClass; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("class") + public String getPropertyClass() { + return PropertyClass; + } + public void setPropertyClass(String PropertyClass) { + this.PropertyClass = PropertyClass; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Model200Response _200Response = (Model200Response) o; + return Objects.equals(name, _200Response.name) && + Objects.equals(PropertyClass, _200Response.PropertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(name, PropertyClass); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" PropertyClass: ").append(toIndentedString(PropertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ModelApiResponse.java new file mode 100644 index 00000000000..85e9ec6a465 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -0,0 +1,115 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +public class ModelApiResponse { + private Integer code = null; + + private String type = null; + + private String message = null; + + /** + **/ + public ModelApiResponse code(Integer code) { + this.code = code; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("code") + public Integer getCode() { + return code; + } + public void setCode(Integer code) { + this.code = code; + } + + /** + **/ + public ModelApiResponse type(String type) { + this.type = type; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("type") + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + + /** + **/ + public ModelApiResponse message(String message) { + this.message = message; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("message") + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(code, _apiResponse.code) && + Objects.equals(type, _apiResponse.type) && + Objects.equals(message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ModelReturn.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ModelReturn.java new file mode 100644 index 00000000000..b27b0095f9a --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ModelReturn.java @@ -0,0 +1,76 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + +/** + * Model for testing reserved words + **/ + +@ApiModel(description = "Model for testing reserved words") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +public class ModelReturn { + private Integer _return = null; + + /** + **/ + public ModelReturn _return(Integer _return) { + this._return = _return; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("return") + public Integer getReturn() { + return _return; + } + public void setReturn(Integer _return) { + this._return = _return; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelReturn _return = (ModelReturn) o; + return Objects.equals(_return, _return._return); + } + + @Override + public int hashCode() { + return Objects.hash(_return); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelReturn {\n"); + + sb.append(" _return: ").append(toIndentedString(_return)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Name.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Name.java new file mode 100644 index 00000000000..83664f19a0b --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Name.java @@ -0,0 +1,139 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + +/** + * Model for testing model name same as property name + **/ + +@ApiModel(description = "Model for testing model name same as property name") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +public class Name { + private Integer name = null; + + private Integer snakeCase = null; + + private String property = null; + + private Integer _123Number = null; + + /** + **/ + public Name name(Integer name) { + this.name = name; + return this; + } + + + @ApiModelProperty(example = "null", required = true, value = "") + @JsonProperty("name") + public Integer getName() { + return name; + } + public void setName(Integer name) { + this.name = name; + } + + /** + **/ + public Name snakeCase(Integer snakeCase) { + this.snakeCase = snakeCase; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("snake_case") + public Integer getSnakeCase() { + return snakeCase; + } + public void setSnakeCase(Integer snakeCase) { + this.snakeCase = snakeCase; + } + + /** + **/ + public Name property(String property) { + this.property = property; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("property") + public String getProperty() { + return property; + } + public void setProperty(String property) { + this.property = property; + } + + /** + **/ + public Name _123Number(Integer _123Number) { + this._123Number = _123Number; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("123Number") + public Integer get123Number() { + return _123Number; + } + public void set123Number(Integer _123Number) { + this._123Number = _123Number; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Name name = (Name) o; + return Objects.equals(name, name.name) && + Objects.equals(snakeCase, name.snakeCase) && + Objects.equals(property, name.property) && + Objects.equals(_123Number, name._123Number); + } + + @Override + public int hashCode() { + return Objects.hash(name, snakeCase, property, _123Number); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Name {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); + sb.append(" property: ").append(toIndentedString(property)).append("\n"); + sb.append(" _123Number: ").append(toIndentedString(_123Number)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/NumberOnly.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/NumberOnly.java new file mode 100644 index 00000000000..8bfcfec586b --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/NumberOnly.java @@ -0,0 +1,74 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +public class NumberOnly { + private BigDecimal justNumber = null; + + /** + **/ + public NumberOnly justNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("JustNumber") + public BigDecimal getJustNumber() { + return justNumber; + } + public void setJustNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NumberOnly numberOnly = (NumberOnly) o; + return Objects.equals(justNumber, numberOnly.justNumber); + } + + @Override + public int hashCode() { + return Objects.hash(justNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NumberOnly {\n"); + + sb.append(" justNumber: ").append(toIndentedString(justNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Order.java new file mode 100644 index 00000000000..4b88e8761c8 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Order.java @@ -0,0 +1,203 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.Date; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +public class Order { + private Long id = null; + + private Long petId = null; + + private Integer quantity = null; + + private Date shipDate = null; + + /** + * Order Status + */ + public enum StatusEnum { + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + private StatusEnum status = null; + + private Boolean complete = false; + + /** + **/ + public Order id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + public Order petId(Long petId) { + this.petId = petId; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("petId") + public Long getPetId() { + return petId; + } + public void setPetId(Long petId) { + this.petId = petId; + } + + /** + **/ + public Order quantity(Integer quantity) { + this.quantity = quantity; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("quantity") + public Integer getQuantity() { + return quantity; + } + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + /** + **/ + public Order shipDate(Date shipDate) { + this.shipDate = shipDate; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("shipDate") + public Date getShipDate() { + return shipDate; + } + public void setShipDate(Date shipDate) { + this.shipDate = shipDate; + } + + /** + * Order Status + **/ + public Order status(StatusEnum status) { + this.status = status; + return this; + } + + + @ApiModelProperty(example = "null", value = "Order Status") + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + /** + **/ + public Order complete(Boolean complete) { + this.complete = complete; + return this; + } + + + @ApiModelProperty(example = "null", 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(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Pet.java new file mode 100644 index 00000000000..a5056440398 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Pet.java @@ -0,0 +1,206 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Category; +import io.swagger.model.Tag; +import java.util.ArrayList; +import java.util.List; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+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(); + + /** + * pet status in the store + */ + public enum StatusEnum { + AVAILABLE("available"), + + PENDING("pending"), + + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + private StatusEnum status = null; + + /** + **/ + public Pet id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + public Pet category(Category category) { + this.category = category; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("category") + public Category getCategory() { + return category; + } + public void setCategory(Category category) { + this.category = category; + } + + /** + **/ + public Pet name(String name) { + this.name = name; + return this; + } + + + @ApiModelProperty(example = "doggie", required = true, value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + /** + **/ + public Pet photoUrls(List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + + @ApiModelProperty(example = "null", required = true, value = "") + @JsonProperty("photoUrls") + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + /** + **/ + public Pet tags(List tags) { + this.tags = tags; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("tags") + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + + /** + * pet status in the store + **/ + public Pet status(StatusEnum status) { + this.status = status; + return this; + } + + + @ApiModelProperty(example = "null", 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(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..1005fa50379 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ReadOnlyFirst.java @@ -0,0 +1,94 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +public class ReadOnlyFirst { + private String bar = null; + + private String baz = null; + + /** + **/ + public ReadOnlyFirst bar(String bar) { + this.bar = bar; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("bar") + public String getBar() { + return bar; + } + public void setBar(String bar) { + this.bar = bar; + } + + /** + **/ + public ReadOnlyFirst baz(String baz) { + this.baz = baz; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("baz") + public String getBaz() { + return baz; + } + public void setBaz(String baz) { + this.baz = baz; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; + return Objects.equals(bar, readOnlyFirst.bar) && + Objects.equals(baz, readOnlyFirst.baz); + } + + @Override + public int hashCode() { + return Objects.hash(bar, baz); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/SpecialModelName.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/SpecialModelName.java new file mode 100644 index 00000000000..90b0e254401 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/SpecialModelName.java @@ -0,0 +1,73 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +public class SpecialModelName { + private Long specialPropertyName = null; + + /** + **/ + public SpecialModelName specialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("$special[property.name]") + public Long getSpecialPropertyName() { + return specialPropertyName; + } + public void setSpecialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SpecialModelName specialModelName = (SpecialModelName) o; + return Objects.equals(specialPropertyName, specialModelName.specialPropertyName); + } + + @Override + public int hashCode() { + return Objects.hash(specialPropertyName); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SpecialModelName {\n"); + + sb.append(" specialPropertyName: ").append(toIndentedString(specialPropertyName)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Tag.java new file mode 100644 index 00000000000..b71a54c270d --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Tag.java @@ -0,0 +1,94 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +public class Tag { + private Long id = null; + + private String name = null; + + /** + **/ + public Tag id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + public Tag name(String name) { + this.name = name; + return this; + } + + + @ApiModelProperty(example = "null", 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(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/User.java new file mode 100644 index 00000000000..0d7a6d1710a --- /dev/null +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/User.java @@ -0,0 +1,221 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+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; + + /** + **/ + public User id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + public User username(String username) { + this.username = username; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("username") + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + + /** + **/ + public User firstName(String firstName) { + this.firstName = firstName; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("firstName") + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + /** + **/ + public User lastName(String lastName) { + this.lastName = lastName; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("lastName") + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } + + /** + **/ + public User email(String email) { + this.email = email; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("email") + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + + /** + **/ + public User password(String password) { + this.password = password; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("password") + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + + /** + **/ + public User phone(String phone) { + this.phone = phone; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("phone") + public String getPhone() { + return phone; + } + public void setPhone(String phone) { + this.phone = phone; + } + + /** + * User Status + **/ + public User userStatus(Integer userStatus) { + this.userStatus = userStatus; + return this; + } + + + @ApiModelProperty(example = "null", 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(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/FakeController.java b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/FakeController.java new file mode 100644 index 00000000000..1dfe454d271 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/FakeController.java @@ -0,0 +1,44 @@ +package io.swagger.handler; + +import io.swagger.inflector.models.RequestContext; +import io.swagger.inflector.models.ResponseContext; +import javax.ws.rs.core.Response.Status; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import java.io.File; +import java.util.List; + +import io.swagger.model.*; + +import io.swagger.model.Client; +import java.util.Date; +import java.math.BigDecimal; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +public class FakeController { + /** + * Uncomment and implement as you see fit. These operations will map + * Direclty to operation calls from the routing logic. Because the inflector + * Code allows you to implement logic incrementally, they are disabled. + **/ + + /* + public ResponseContext testClientModel(RequestContext request , Client body) { + return new ResponseContext().status(Status.INTERNAL_SERVER_ERROR).entity( "Not implemented" ); + } + */ + + /* + public ResponseContext testEndpointParameters(RequestContext request , BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, Date date, Date dateTime, String password) { + return new ResponseContext().status(Status.INTERNAL_SERVER_ERROR).entity( "Not implemented" ); + } + */ + + /* + public ResponseContext testEnumParameters(RequestContext request , List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) { + return new ResponseContext().status(Status.INTERNAL_SERVER_ERROR).entity( "Not implemented" ); + } + */ + +} + diff --git a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/PetController.java b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/PetController.java index e05a1ffc1f2..96d204a5063 100644 --- a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/PetController.java +++ b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/PetController.java @@ -11,10 +11,10 @@ import io.swagger.model.*; import io.swagger.model.Pet; -import io.swagger.model.ApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-04-15T17:48:04.458+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") public class PetController { /** * Uncomment and implement as you see fit. These operations will map diff --git a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/StoreController.java b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/StoreController.java index cf96ddf68fd..69eeded6cf5 100644 --- a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/StoreController.java +++ b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/StoreController.java @@ -13,7 +13,7 @@ import java.util.Map; import io.swagger.model.Order; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-04-15T17:48:04.458+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") public class StoreController { /** * Uncomment and implement as you see fit. These operations will map diff --git a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/UserController.java b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/UserController.java index 4d99da8b342..0f25bf720bc 100644 --- a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/UserController.java +++ b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/UserController.java @@ -13,7 +13,7 @@ import io.swagger.model.User; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-04-15T17:48:04.458+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") public class UserController { /** * Uncomment and implement as you see fit. These operations will map diff --git a/samples/server/petstore/java-inflector/src/main/swagger/swagger.yaml b/samples/server/petstore/java-inflector/src/main/swagger/swagger.yaml index 0917da7891b..118ca53356a 100644 --- a/samples/server/petstore/java-inflector/src/main/swagger/swagger.yaml +++ b/samples/server/petstore/java-inflector/src/main/swagger/swagger.yaml @@ -1,10 +1,9 @@ --- swagger: "2.0" info: - description: "This is a sample server Petstore server. You can find out more about\ - \ Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).\ - \ For this sample, you can use the api key `special-key` to test the authorization\ - \ filters." + description: "This spec is mainly for testing Petstore server and contains fake\ + \ endpoints, models. Please do not use this for any other purpose. Special characters:\ + \ \" \\" version: "1.0.0" title: "Swagger Petstore" termsOfService: "http://swagger.io/terms/" @@ -31,6 +30,221 @@ tags: schemes: - "http" paths: + /fake: + get: + tags: + - "fake" + summary: "To test enum parameters" + operationId: "testEnumParameters" + consumes: + - "application/json" + produces: + - "application/json" + parameters: + - name: "enum_form_string_array" + in: "formData" + description: "Form parameter enum test (string array)" + required: false + type: "array" + - name: "enum_form_string" + in: "formData" + description: "Form parameter enum test (string)" + required: false + type: "string" + default: "-efg" + enum: + - "_abc" + - "-efg" + - "(xyz)" + - name: "enum_header_string_array" + in: "header" + description: "Header parameter enum test (string array)" + required: false + type: "array" + - name: "enum_header_string" + in: "header" + description: "Header parameter enum test (string)" + required: false + type: "string" + default: "-efg" + enum: + - "_abc" + - "-efg" + - "(xyz)" + - name: "enum_query_string_array" + in: "query" + description: "Query parameter enum test (string array)" + required: false + type: "array" + items: + type: "string" + default: "$" + enum: + - ">" + - "$" + - name: "enum_query_string" + in: "query" + description: "Query parameter enum test (string)" + required: false + type: "string" + default: "-efg" + enum: + - "_abc" + - "-efg" + - "(xyz)" + - name: "enum_query_integer" + in: "query" + description: "Query parameter enum test (double)" + required: false + type: "number" + format: "int32" + enum: + - null + - null + - name: "enum_query_double" + in: "formData" + description: "Query parameter enum test (double)" + required: false + type: "number" + format: "double" + enum: + - null + - null + responses: + 400: + description: "Invalid request" + 404: + description: "Not found" + x-contentType: "application/json" + x-accepts: "application/json" + post: + tags: + - "fake" + summary: "Fake endpoint for testing various parameters\n假端點\n偽のエンドポイント\n가짜 엔\ + 드 포인트\n" + description: "Fake endpoint for testing various parameters\n假端點\n偽のエンドポイント\n\ + 가짜 엔드 포인트\n" + operationId: "testEndpointParameters" + consumes: + - "application/xml; charset=utf-8" + - "application/json; charset=utf-8" + produces: + - "application/xml; charset=utf-8" + - "application/json; charset=utf-8" + parameters: + - name: "integer" + in: "formData" + description: "None" + required: false + type: "integer" + maximum: 100.0 + minimum: 10.0 + - name: "int32" + in: "formData" + description: "None" + required: false + type: "integer" + maximum: 200.0 + minimum: 20.0 + format: "int32" + - name: "int64" + in: "formData" + description: "None" + required: false + type: "integer" + format: "int64" + - name: "number" + in: "formData" + description: "None" + required: true + type: "number" + maximum: 543.2 + minimum: 32.1 + - name: "float" + in: "formData" + description: "None" + required: false + type: "number" + maximum: 987.6 + format: "float" + - name: "double" + in: "formData" + description: "None" + required: true + type: "number" + maximum: 123.4 + minimum: 67.8 + format: "double" + - name: "string" + in: "formData" + description: "None" + required: true + type: "string" + pattern: "/[a-z]/i" + - name: "byte" + in: "formData" + description: "None" + required: true + type: "string" + format: "byte" + - name: "binary" + in: "formData" + description: "None" + required: false + type: "string" + format: "binary" + - name: "date" + in: "formData" + description: "None" + required: false + type: "string" + format: "date" + - name: "dateTime" + in: "formData" + description: "None" + required: false + type: "string" + format: "date-time" + - name: "password" + in: "formData" + description: "None" + required: false + type: "string" + maxLength: 64 + minLength: 10 + format: "password" + responses: + 400: + description: "Invalid username supplied" + 404: + description: "User not found" + security: + - http_basic_test: [] + x-contentType: "application/xml; charset=utf-8" + x-accepts: "application/xml; charset=utf-8,application/json; charset=utf-8" + patch: + tags: + - "fake" + summary: "To test \"client\" model" + operationId: "testClientModel" + consumes: + - "application/json" + produces: + - "application/json" + parameters: + - in: "body" + name: "body" + description: "client model" + required: true + schema: + $ref: "#/definitions/Client" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Client" + x-contentType: "application/json" + x-accepts: "application/json" /pet: post: tags: @@ -618,6 +832,8 @@ securityDefinitions: scopes: write:pets: "modify pets in your account" read:pets: "read your pets" + http_basic_test: + type: "basic" definitions: Order: type: "object" @@ -662,6 +878,7 @@ definitions: id: type: "integer" format: "int64" + x-is-unique: true username: type: "string" firstName: @@ -699,6 +916,7 @@ definitions: id: type: "integer" format: "int64" + x-is-unique: true category: $ref: "#/definitions/Category" name: @@ -737,6 +955,288 @@ definitions: type: "string" message: type: "string" + $special[model.name]: + properties: + $special[property.name]: + type: "integer" + format: "int64" + xml: + name: "$special[model.name]" + Return: + properties: + return: + type: "integer" + format: "int32" + description: "Model for testing reserved words" + xml: + name: "Return" + Name: + required: + - "name" + properties: + name: + type: "integer" + format: "int32" + snake_case: + type: "integer" + format: "int32" + readOnly: true + property: + type: "string" + 123Number: + type: "integer" + readOnly: true + description: "Model for testing model name same as property name" + xml: + name: "Name" + 200_response: + properties: + name: + type: "integer" + format: "int32" + class: + type: "string" + description: "Model for testing model name starting with number" + xml: + name: "Name" + Dog: + allOf: + - $ref: "#/definitions/Animal" + - type: "object" + properties: + breed: + type: "string" + Cat: + allOf: + - $ref: "#/definitions/Animal" + - type: "object" + properties: + declawed: + type: "boolean" + Animal: + type: "object" + required: + - "className" + discriminator: "className" + properties: + className: + type: "string" + color: + type: "string" + default: "red" + AnimalFarm: + type: "array" + items: + $ref: "#/definitions/Animal" + format_test: + type: "object" + required: + - "byte" + - "date" + - "number" + - "password" + properties: + integer: + type: "integer" + minimum: 10.0 + maximum: 100.0 + int32: + type: "integer" + format: "int32" + minimum: 20.0 + maximum: 200.0 + int64: + type: "integer" + format: "int64" + number: + type: "number" + minimum: 32.1 + maximum: 543.2 + float: + type: "number" + format: "float" + minimum: 54.3 + maximum: 987.6 + double: + type: "number" + format: "double" + minimum: 67.8 + maximum: 123.4 + string: + type: "string" + pattern: "/[a-z]/i" + byte: + type: "string" + format: "byte" + binary: + type: "string" + format: "binary" + date: + type: "string" + format: "date" + dateTime: + type: "string" + format: "date-time" + uuid: + type: "string" + format: "uuid" + password: + type: "string" + format: "password" + minLength: 10 + maxLength: 64 + EnumClass: + type: "string" + enum: + - "_abc" + - "-efg" + - "(xyz)" + default: "-efg" + Enum_Test: + type: "object" + properties: + enum_string: + type: "string" + enum: + - "UPPER" + - "lower" + enum_integer: + type: "integer" + format: "int32" + enum: + - 1 + - -1 + enum_number: + type: "number" + format: "double" + enum: + - 1.1 + - -1.2 + AdditionalPropertiesClass: + type: "object" + properties: + map_property: + type: "object" + additionalProperties: + type: "string" + map_of_map_property: + type: "object" + additionalProperties: + type: "object" + additionalProperties: + type: "string" + MixedPropertiesAndAdditionalPropertiesClass: + type: "object" + properties: + uuid: + type: "string" + format: "uuid" + dateTime: + type: "string" + format: "date-time" + map: + type: "object" + additionalProperties: + $ref: "#/definitions/Animal" + List: + type: "object" + properties: + 123-list: + type: "string" + Client: + type: "object" + properties: + client: + type: "string" + ReadOnlyFirst: + type: "object" + properties: + bar: + type: "string" + readOnly: true + baz: + type: "string" + hasOnlyReadOnly: + type: "object" + properties: + bar: + type: "string" + readOnly: true + foo: + type: "string" + readOnly: true + MapTest: + type: "object" + properties: + map_map_of_string: + type: "object" + additionalProperties: + type: "object" + additionalProperties: + type: "string" + map_of_enum_string: + type: "object" + additionalProperties: + type: "string" + enum: + - "UPPER" + - "lower" + ArrayTest: + type: "object" + properties: + array_of_string: + type: "array" + items: + type: "string" + array_array_of_integer: + type: "array" + items: + type: "array" + items: + type: "integer" + format: "int64" + array_array_of_model: + type: "array" + items: + type: "array" + items: + $ref: "#/definitions/ReadOnlyFirst" + NumberOnly: + type: "object" + properties: + JustNumber: + type: "number" + ArrayOfNumberOnly: + type: "object" + properties: + ArrayNumber: + type: "array" + items: + type: "number" + ArrayOfArrayOfNumberOnly: + type: "object" + properties: + ArrayArrayNumber: + type: "array" + items: + type: "array" + items: + type: "number" + EnumArrays: + type: "object" + properties: + just_symbol: + type: "string" + enum: + - ">=" + - "$" + array_enum: + type: "array" + items: + type: "string" + enum: + - "fish" + - "crab" externalDocs: description: "Find out more about Swagger" url: "http://swagger.io" From 8536d7991ccbaddd511971c6c76d3ad48b2a10bd Mon Sep 17 00:00:00 2001 From: Mike Solomon Date: Fri, 19 Aug 2016 10:11:31 +0300 Subject: [PATCH 263/470] Uses this.{{name}} to scope instance Otherwise, if {{classVarName}} is the same as a class member name, the function will not work. --- .../swagger-codegen/src/main/resources/android/model.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/android/model.mustache b/modules/swagger-codegen/src/main/resources/android/model.mustache index df99de87403..701af6de43b 100644 --- a/modules/swagger-codegen/src/main/resources/android/model.mustache +++ b/modules/swagger-codegen/src/main/resources/android/model.mustache @@ -47,7 +47,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { return false; } {{classname}} {{classVarName}} = ({{classname}}) o;{{#hasVars}} - return {{#vars}}({{name}} == null ? {{classVarName}}.{{name}} == null : {{name}}.equals({{classVarName}}.{{name}})){{#hasMore}} && + return {{#vars}}(this.{{name}} == null ? {{classVarName}}.{{name}} == null : this.{{name}}.equals({{classVarName}}.{{name}})){{#hasMore}} && {{/hasMore}}{{^hasMore}};{{/hasMore}}{{/vars}}{{/hasVars}}{{^hasVars}} return true;{{/hasVars}} } From 64e03422c0c5e2b8183b173ea2fbed3704b81dc5 Mon Sep 17 00:00:00 2001 From: Kevin Chabreck Date: Fri, 19 Aug 2016 05:29:36 -0400 Subject: [PATCH 264/470] [Spring Boot] use port defined in spec file for server.port value (#3605) * uncommented server.port property in application.mustache template and set it to serverPort value parsed from spec file * update Petstore sample for Spring MVC and Boot --- .../resources/JavaSpring/application.mustache | 2 +- .../src/main/java/io/swagger/api/PetApi.java | 4 ++-- .../configuration/ClientConfiguration.java | 18 +++++++++--------- .../main/java/io/swagger/model/Category.java | 1 + .../io/swagger/model/ModelApiResponse.java | 1 + .../src/main/java/io/swagger/model/Order.java | 1 + .../src/main/java/io/swagger/model/Pet.java | 1 + .../src/main/java/io/swagger/model/Tag.java | 1 + .../src/main/java/io/swagger/model/User.java | 1 + .../src/main/java/io/swagger/api/PetApi.java | 4 ++-- .../main/java/io/swagger/model/Category.java | 1 + .../io/swagger/model/ModelApiResponse.java | 1 + .../src/main/java/io/swagger/model/Order.java | 1 + .../src/main/java/io/swagger/model/Pet.java | 1 + .../src/main/java/io/swagger/model/Tag.java | 1 + .../src/main/java/io/swagger/model/User.java | 1 + .../src/main/java/io/swagger/api/FakeApi.java | 6 ++++-- .../src/main/java/io/swagger/api/PetApi.java | 2 +- .../src/main/java/io/swagger/api/FakeApi.java | 6 ++++-- .../java/io/swagger/api/FakeApiController.java | 2 +- .../src/main/java/io/swagger/api/PetApi.java | 2 +- .../java/io/swagger/api/PetApiController.java | 2 +- .../src/main/java/io/swagger/api/FakeApi.java | 6 ++++-- .../java/io/swagger/api/FakeApiController.java | 2 +- .../src/main/java/io/swagger/api/PetApi.java | 2 +- .../java/io/swagger/api/PetApiController.java | 2 +- .../src/main/resources/application.properties | 2 +- 27 files changed, 46 insertions(+), 28 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/application.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/application.mustache index a4695deef76..b6923a2f77c 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/application.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/application.mustache @@ -1,3 +1,3 @@ springfox.documentation.swagger.v2.path=/api-docs server.contextPath={{^contextPath}}/{{/contextPath}}{{#contextPath}}{{contextPath}}{{/contextPath}} -#server.port=8090 \ No newline at end of file +server.port={{serverPort}} \ No newline at end of file diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java index 10adf8fbe89..1583f14bb47 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import java.io.File; import io.swagger.model.ModelApiResponse; +import java.io.File; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; @@ -73,7 +73,7 @@ ResponseEntity deletePet( produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true) @RequestParam(value = "status", required = true) List status + ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status ); diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/configuration/ClientConfiguration.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/configuration/ClientConfiguration.java index 9e68822a61e..b0816e2d6e9 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/configuration/ClientConfiguration.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/configuration/ClientConfiguration.java @@ -22,15 +22,6 @@ @EnableConfigurationProperties public class ClientConfiguration { - @Value("${ swaggerPetstore.security.apiKey.key:}") - private String apiKeyKey; - - @Bean - @ConditionalOnProperty(name = "swaggerPetstore.security.apiKey.key") - public ApiKeyRequestInterceptor apiKeyRequestInterceptor() { - return new ApiKeyRequestInterceptor("header", "api_key", this.apiKeyKey); - } - @Bean @ConditionalOnProperty("swaggerPetstore.security.petstoreAuth.client-id") public OAuth2FeignRequestInterceptor petstoreAuthRequestInterceptor() { @@ -46,4 +37,13 @@ public ImplicitResourceDetails petstoreAuthResourceDetails() { return details; } + @Value("${ swaggerPetstore.security.apiKey.key:}") + private String apiKeyKey; + + @Bean + @ConditionalOnProperty(name = "swaggerPetstore.security.apiKey.key") + public ApiKeyRequestInterceptor apiKeyRequestInterceptor() { + return new ApiKeyRequestInterceptor("header", "api_key", this.apiKeyKey); + } + } \ No newline at end of file diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Category.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Category.java index 8a3eaeedec1..5039fd77a60 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Category.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Category.java @@ -2,6 +2,7 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/ModelApiResponse.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/ModelApiResponse.java index 5937dc35c99..512dcd5f43b 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/ModelApiResponse.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/ModelApiResponse.java @@ -2,6 +2,7 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Order.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Order.java index c3eda741375..0cd70bfd939 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Order.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Order.java @@ -2,6 +2,7 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Pet.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Pet.java index 4717e8b65de..3592e1240dc 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Pet.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Pet.java @@ -2,6 +2,7 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Tag.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Tag.java index 545f4a91613..9ebfa434af2 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Tag.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Tag.java @@ -2,6 +2,7 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/User.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/User.java index fb15300d2bd..24abc50388a 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/User.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/User.java @@ -2,6 +2,7 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/PetApi.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/PetApi.java index 9f9b20c3120..c1c238e5f2e 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/PetApi.java +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/PetApi.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import java.io.File; import io.swagger.model.ModelApiResponse; +import java.io.File; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; @@ -76,7 +76,7 @@ ResponseEntity deletePet( produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true) @RequestParam(value = "status", required = true) List status + ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Category.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Category.java index 8a3eaeedec1..5039fd77a60 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Category.java +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Category.java @@ -2,6 +2,7 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/ModelApiResponse.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/ModelApiResponse.java index 5937dc35c99..512dcd5f43b 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/ModelApiResponse.java +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/ModelApiResponse.java @@ -2,6 +2,7 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Order.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Order.java index c3eda741375..0cd70bfd939 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Order.java +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Order.java @@ -2,6 +2,7 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Pet.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Pet.java index 4717e8b65de..3592e1240dc 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Pet.java +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Pet.java @@ -2,6 +2,7 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Tag.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Tag.java index 545f4a91613..9ebfa434af2 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Tag.java +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Tag.java @@ -2,6 +2,7 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/User.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/User.java index fb15300d2bd..24abc50388a 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/User.java +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/User.java @@ -2,6 +2,7 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApi.java index 7686a19ee28..5f272c67e8c 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApi.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Client; -import java.time.LocalDate; import java.time.OffsetDateTime; +import java.time.LocalDate; import java.math.BigDecimal; import io.swagger.annotations.*; @@ -41,7 +41,9 @@ default CompletableFuture> testClientModel( } - @ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", notes = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", response = Void.class, tags={ "fake", }) + @ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", notes = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", response = Void.class, authorizations = { + @Authorization(value = "http_basic_test") + }, tags={ "fake", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), @ApiResponse(code = 404, message = "User not found", response = Void.class) }) diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java index dca1545a5ef..8b23618a5a3 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import java.io.File; import io.swagger.model.ModelApiResponse; +import java.io.File; import io.swagger.annotations.*; import org.springframework.http.HttpStatus; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApi.java index a9de451f4bf..f15fbe3b4ff 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApi.java @@ -2,8 +2,8 @@ import io.swagger.model.Client; import org.joda.time.LocalDate; -import org.joda.time.DateTime; import java.math.BigDecimal; +import org.joda.time.DateTime; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; @@ -36,7 +36,9 @@ ResponseEntity testClientModel( ); - @ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", notes = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", response = Void.class, tags={ "fake", }) + @ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", notes = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", response = Void.class, authorizations = { + @Authorization(value = "http_basic_test") + }, tags={ "fake", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), @ApiResponse(code = 404, message = "User not found", response = Void.class) }) diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApiController.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApiController.java index 95b2a742008..888a50ef542 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApiController.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApiController.java @@ -2,8 +2,8 @@ import io.swagger.model.Client; import org.joda.time.LocalDate; -import org.joda.time.DateTime; import java.math.BigDecimal; +import org.joda.time.DateTime; import io.swagger.annotations.*; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java index 9b937019b32..ea0122441c1 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import java.io.File; import io.swagger.model.ModelApiResponse; +import java.io.File; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApiController.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApiController.java index af909d49ab8..8b95d74de51 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApiController.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApiController.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import java.io.File; import io.swagger.model.ModelApiResponse; +import java.io.File; import io.swagger.annotations.*; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApi.java index a9de451f4bf..f15fbe3b4ff 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApi.java @@ -2,8 +2,8 @@ import io.swagger.model.Client; import org.joda.time.LocalDate; -import org.joda.time.DateTime; import java.math.BigDecimal; +import org.joda.time.DateTime; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; @@ -36,7 +36,9 @@ ResponseEntity testClientModel( ); - @ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", notes = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", response = Void.class, tags={ "fake", }) + @ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", notes = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", response = Void.class, authorizations = { + @Authorization(value = "http_basic_test") + }, tags={ "fake", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), @ApiResponse(code = 404, message = "User not found", response = Void.class) }) diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApiController.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApiController.java index 95b2a742008..888a50ef542 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApiController.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApiController.java @@ -2,8 +2,8 @@ import io.swagger.model.Client; import org.joda.time.LocalDate; -import org.joda.time.DateTime; import java.math.BigDecimal; +import org.joda.time.DateTime; import io.swagger.annotations.*; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java index 9b937019b32..ea0122441c1 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import java.io.File; import io.swagger.model.ModelApiResponse; +import java.io.File; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java index af909d49ab8..8b95d74de51 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import java.io.File; import io.swagger.model.ModelApiResponse; +import java.io.File; import io.swagger.annotations.*; diff --git a/samples/server/petstore/springboot/src/main/resources/application.properties b/samples/server/petstore/springboot/src/main/resources/application.properties index 22fb546ba98..eb4cac4bec6 100644 --- a/samples/server/petstore/springboot/src/main/resources/application.properties +++ b/samples/server/petstore/springboot/src/main/resources/application.properties @@ -1,3 +1,3 @@ springfox.documentation.swagger.v2.path=/api-docs server.contextPath=/v2 -#server.port=8090 \ No newline at end of file +server.port=8080 \ No newline at end of file From 4e20bd9bab43ce21f21954a45402ca49df5a2a64 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sat, 20 Aug 2016 17:54:45 +0800 Subject: [PATCH 265/470] [Java][Spring][Inflector][Jax-RS] To fix various enum issues (#3615) * fix spring enum deserialization issue * fix enum class for spring * update java inflector to fix enum tostring * fix jaxrs jersey1 enum toString * fix jaxrs jersey patch issue --- bin/jaxrs-jersey1-petstore-server.sh | 2 +- .../AbstractJavaJAXRSServerCodegen.java | 2 + .../languages/JavaInflectorServerCodegen.java | 2 + .../codegen/languages/SpringCodegen.java | 15 +- .../JavaInflector/enumClass.mustache | 11 + .../JavaInflector/enumOuterClass.mustache | 15 + .../resources/JavaJaxRS/enumClass.mustache | 11 + .../JavaJaxRS/enumOuterClass.mustache | 15 + .../JavaJaxRS/libraries/jersey1/api.mustache | 1 + .../resources/JavaSpring/enumClass.mustache | 11 + .../JavaSpring/enumOuterClass.mustache | 15 + .../src/main/java/io/swagger/api/PetApi.java | 2 +- .../configuration/ClientConfiguration.java | 18 +- .../main/java/io/swagger/model/Category.java | 2 + .../io/swagger/model/ModelApiResponse.java | 3 + .../src/main/java/io/swagger/model/Order.java | 17 + .../src/main/java/io/swagger/model/Pet.java | 17 + .../src/main/java/io/swagger/model/Tag.java | 2 + .../src/main/java/io/swagger/model/User.java | 8 + .../src/main/java/io/swagger/api/PetApi.java | 2 +- .../main/java/io/swagger/model/Category.java | 2 + .../io/swagger/model/ModelApiResponse.java | 3 + .../src/main/java/io/swagger/model/Order.java | 17 + .../src/main/java/io/swagger/model/Pet.java | 17 + .../src/main/java/io/swagger/model/Tag.java | 2 + .../src/main/java/io/swagger/model/User.java | 8 + .../java/io/swagger/handler/StringUtil.java | 2 +- .../model/AdditionalPropertiesClass.java | 4 +- .../src/gen/java/io/swagger/model/Animal.java | 4 +- .../gen/java/io/swagger/model/AnimalFarm.java | 2 +- .../model/ArrayOfArrayOfNumberOnly.java | 3 +- .../io/swagger/model/ArrayOfNumberOnly.java | 3 +- .../gen/java/io/swagger/model/ArrayTest.java | 5 +- .../src/gen/java/io/swagger/model/Cat.java | 3 +- .../gen/java/io/swagger/model/Category.java | 4 +- .../src/gen/java/io/swagger/model/Client.java | 3 +- .../src/gen/java/io/swagger/model/Dog.java | 3 +- .../gen/java/io/swagger/model/EnumArrays.java | 26 +- .../gen/java/io/swagger/model/EnumClass.java | 13 + .../gen/java/io/swagger/model/EnumTest.java | 38 +- .../gen/java/io/swagger/model/FormatTest.java | 15 +- .../io/swagger/model/HasOnlyReadOnly.java | 4 +- .../gen/java/io/swagger/model/MapTest.java | 15 +- ...ropertiesAndAdditionalPropertiesClass.java | 5 +- .../io/swagger/model/Model200Response.java | 4 +- .../io/swagger/model/ModelApiResponse.java | 5 +- .../java/io/swagger/model/ModelReturn.java | 3 +- .../src/gen/java/io/swagger/model/Name.java | 6 +- .../gen/java/io/swagger/model/NumberOnly.java | 3 +- .../src/gen/java/io/swagger/model/Order.java | 19 +- .../src/gen/java/io/swagger/model/Pet.java | 19 +- .../java/io/swagger/model/ReadOnlyFirst.java | 4 +- .../io/swagger/model/SpecialModelName.java | 3 +- .../src/gen/java/io/swagger/model/Tag.java | 4 +- .../src/gen/java/io/swagger/model/User.java | 10 +- .../io/swagger/handler/FakeController.java | 2 +- .../io/swagger/handler/PetController.java | 2 +- .../io/swagger/handler/StoreController.java | 2 +- .../io/swagger/handler/UserController.java | 2 +- .../gen/java/io/swagger/api/PetApi.java | 2 +- .../src/gen/java/io/swagger/api/FakeApi.java | 98 +++++ .../java/io/swagger/api/FakeApiService.java | 31 ++ .../src/gen/java/io/swagger/api/PetApi.java | 7 +- .../src/gen/java/io/swagger/api/StoreApi.java | 1 + .../src/gen/java/io/swagger/api/UserApi.java | 1 + .../model/AdditionalPropertiesClass.java | 113 ++++++ .../src/gen/java/io/swagger/model/Animal.java | 100 +++++ .../gen/java/io/swagger/model/AnimalFarm.java | 53 +++ .../model/ArrayOfArrayOfNumberOnly.java | 85 ++++ .../io/swagger/model/ArrayOfNumberOnly.java | 85 ++++ .../gen/java/io/swagger/model/ArrayTest.java | 141 +++++++ .../src/gen/java/io/swagger/model/Cat.java | 79 ++++ .../gen/java/io/swagger/model/Category.java | 35 +- .../src/gen/java/io/swagger/model/Client.java | 77 ++++ .../src/gen/java/io/swagger/model/Dog.java | 79 ++++ .../gen/java/io/swagger/model/EnumArrays.java | 170 ++++++++ .../gen/java/io/swagger/model/EnumClass.java | 44 +++ .../gen/java/io/swagger/model/EnumTest.java | 217 +++++++++++ .../gen/java/io/swagger/model/FormatTest.java | 365 ++++++++++++++++++ .../io/swagger/model/HasOnlyReadOnly.java | 82 ++++ .../gen/java/io/swagger/model/MapTest.java | 145 +++++++ ...ropertiesAndAdditionalPropertiesClass.java | 133 +++++++ .../io/swagger/model/Model200Response.java | 104 +++++ .../io/swagger/model/ModelApiResponse.java | 48 ++- .../java/io/swagger/model/ModelReturn.java | 81 ++++ .../src/gen/java/io/swagger/model/Name.java | 132 +++++++ .../gen/java/io/swagger/model/NumberOnly.java | 78 ++++ .../src/gen/java/io/swagger/model/Order.java | 105 +++-- .../src/gen/java/io/swagger/model/Pet.java | 115 ++++-- .../java/io/swagger/model/ReadOnlyFirst.java | 91 +++++ .../io/swagger/model/SpecialModelName.java | 77 ++++ .../src/gen/java/io/swagger/model/Tag.java | 35 +- .../src/gen/java/io/swagger/model/User.java | 114 +++--- .../main/java/io/swagger/api/Bootstrap.java | 2 +- .../api/factories/FakeApiServiceFactory.java | 13 + .../swagger/api/impl/FakeApiServiceImpl.java | 43 +++ .../src/main/java/io/swagger/api/FakeApi.java | 2 +- .../src/main/java/io/swagger/api/PetApi.java | 2 +- .../model/AdditionalPropertiesClass.java | 2 + .../main/java/io/swagger/model/Animal.java | 2 + .../model/ArrayOfArrayOfNumberOnly.java | 1 + .../io/swagger/model/ArrayOfNumberOnly.java | 1 + .../main/java/io/swagger/model/ArrayTest.java | 3 + .../src/main/java/io/swagger/model/Cat.java | 1 + .../main/java/io/swagger/model/Category.java | 2 + .../main/java/io/swagger/model/Client.java | 1 + .../src/main/java/io/swagger/model/Dog.java | 1 + .../java/io/swagger/model/EnumArrays.java | 24 ++ .../main/java/io/swagger/model/EnumClass.java | 13 + .../main/java/io/swagger/model/EnumTest.java | 36 ++ .../java/io/swagger/model/FormatTest.java | 13 + .../io/swagger/model/HasOnlyReadOnly.java | 2 + .../main/java/io/swagger/model/MapTest.java | 13 + ...ropertiesAndAdditionalPropertiesClass.java | 3 + .../io/swagger/model/Model200Response.java | 2 + .../io/swagger/model/ModelApiResponse.java | 3 + .../java/io/swagger/model/ModelReturn.java | 1 + .../src/main/java/io/swagger/model/Name.java | 4 + .../java/io/swagger/model/NumberOnly.java | 1 + .../src/main/java/io/swagger/model/Order.java | 17 + .../src/main/java/io/swagger/model/Pet.java | 17 + .../java/io/swagger/model/ReadOnlyFirst.java | 2 + .../io/swagger/model/SpecialModelName.java | 1 + .../src/main/java/io/swagger/model/Tag.java | 2 + .../src/main/java/io/swagger/model/User.java | 8 + .../src/main/java/io/swagger/api/FakeApi.java | 2 +- .../io/swagger/api/FakeApiController.java | 2 +- .../src/main/java/io/swagger/api/PetApi.java | 2 +- .../java/io/swagger/api/PetApiController.java | 2 +- .../model/AdditionalPropertiesClass.java | 2 + .../main/java/io/swagger/model/Animal.java | 2 + .../model/ArrayOfArrayOfNumberOnly.java | 1 + .../io/swagger/model/ArrayOfNumberOnly.java | 1 + .../main/java/io/swagger/model/ArrayTest.java | 3 + .../src/main/java/io/swagger/model/Cat.java | 1 + .../main/java/io/swagger/model/Category.java | 2 + .../main/java/io/swagger/model/Client.java | 1 + .../src/main/java/io/swagger/model/Dog.java | 1 + .../java/io/swagger/model/EnumArrays.java | 24 ++ .../main/java/io/swagger/model/EnumClass.java | 13 + .../main/java/io/swagger/model/EnumTest.java | 36 ++ .../java/io/swagger/model/FormatTest.java | 13 + .../io/swagger/model/HasOnlyReadOnly.java | 2 + .../main/java/io/swagger/model/MapTest.java | 13 + ...ropertiesAndAdditionalPropertiesClass.java | 3 + .../io/swagger/model/Model200Response.java | 2 + .../io/swagger/model/ModelApiResponse.java | 3 + .../java/io/swagger/model/ModelReturn.java | 1 + .../src/main/java/io/swagger/model/Name.java | 4 + .../java/io/swagger/model/NumberOnly.java | 1 + .../src/main/java/io/swagger/model/Order.java | 17 + .../src/main/java/io/swagger/model/Pet.java | 17 + .../java/io/swagger/model/ReadOnlyFirst.java | 2 + .../io/swagger/model/SpecialModelName.java | 1 + .../src/main/java/io/swagger/model/Tag.java | 2 + .../src/main/java/io/swagger/model/User.java | 8 + .../src/main/java/io/swagger/api/FakeApi.java | 2 +- .../io/swagger/api/FakeApiController.java | 2 +- .../src/main/java/io/swagger/api/PetApi.java | 2 +- .../java/io/swagger/api/PetApiController.java | 2 +- .../model/AdditionalPropertiesClass.java | 2 + .../main/java/io/swagger/model/Animal.java | 2 + .../model/ArrayOfArrayOfNumberOnly.java | 1 + .../io/swagger/model/ArrayOfNumberOnly.java | 1 + .../main/java/io/swagger/model/ArrayTest.java | 3 + .../src/main/java/io/swagger/model/Cat.java | 1 + .../main/java/io/swagger/model/Category.java | 2 + .../main/java/io/swagger/model/Client.java | 1 + .../src/main/java/io/swagger/model/Dog.java | 1 + .../java/io/swagger/model/EnumArrays.java | 24 ++ .../main/java/io/swagger/model/EnumClass.java | 13 + .../main/java/io/swagger/model/EnumTest.java | 36 ++ .../java/io/swagger/model/FormatTest.java | 13 + .../io/swagger/model/HasOnlyReadOnly.java | 2 + .../main/java/io/swagger/model/MapTest.java | 13 + ...ropertiesAndAdditionalPropertiesClass.java | 3 + .../io/swagger/model/Model200Response.java | 2 + .../io/swagger/model/ModelApiResponse.java | 3 + .../java/io/swagger/model/ModelReturn.java | 1 + .../src/main/java/io/swagger/model/Name.java | 4 + .../java/io/swagger/model/NumberOnly.java | 1 + .../src/main/java/io/swagger/model/Order.java | 17 + .../src/main/java/io/swagger/model/Pet.java | 17 + .../java/io/swagger/model/ReadOnlyFirst.java | 2 + .../io/swagger/model/SpecialModelName.java | 1 + .../src/main/java/io/swagger/model/Tag.java | 2 + .../src/main/java/io/swagger/model/User.java | 8 + 187 files changed, 3960 insertions(+), 229 deletions(-) create mode 100644 samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApi.java create mode 100644 samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApiService.java create mode 100644 samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java create mode 100644 samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Animal.java create mode 100644 samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/AnimalFarm.java create mode 100644 samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java create mode 100644 samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java create mode 100644 samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayTest.java create mode 100644 samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Cat.java create mode 100644 samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Client.java create mode 100644 samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Dog.java create mode 100644 samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumArrays.java create mode 100644 samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumClass.java create mode 100644 samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumTest.java create mode 100644 samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/FormatTest.java create mode 100644 samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/HasOnlyReadOnly.java create mode 100644 samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/MapTest.java create mode 100644 samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java create mode 100644 samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Model200Response.java create mode 100644 samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelReturn.java create mode 100644 samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Name.java create mode 100644 samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/NumberOnly.java create mode 100644 samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ReadOnlyFirst.java create mode 100644 samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/SpecialModelName.java create mode 100644 samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/factories/FakeApiServiceFactory.java create mode 100644 samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java diff --git a/bin/jaxrs-jersey1-petstore-server.sh b/bin/jaxrs-jersey1-petstore-server.sh index 914900a1e7e..28547f26aa8 100755 --- a/bin/jaxrs-jersey1-petstore-server.sh +++ b/bin/jaxrs-jersey1-petstore-server.sh @@ -26,7 +26,7 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1 -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l jaxrs -o samples/server/petstore/jaxrs/jersey1 -DhideGenerationTimestamp=true --library=jersey1 --artifact-id=swagger-jaxrs-jersey1-server" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1 -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l jaxrs -o samples/server/petstore/jaxrs/jersey1 -DhideGenerationTimestamp=true --library=jersey1 --artifact-id=swagger-jaxrs-jersey1-server" echo "Removing files and folders under samples/server/petstore/jaxrs/jersey1/src/main" rm -rf samples/server/petstore/jaxrs/jersey1/src/main diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java index d1458514256..9ed96485119 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java @@ -33,6 +33,8 @@ public AbstractJavaJAXRSServerCodegen() modelPackage = "io.swagger.model"; additionalProperties.put("title", title); + // java inflector uses the jackson lib + additionalProperties.put("jackson", "true"); cliOptions.add(new CliOption(CodegenConstants.IMPL_FOLDER, CodegenConstants.IMPL_FOLDER_DESC)); cliOptions.add(new CliOption("title", "a title describing the application")); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java index e82c2893d59..1c856c95382 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java @@ -39,6 +39,8 @@ public JavaInflectorServerCodegen() { modelPackage = System.getProperty("swagger.codegen.inflector.modelpackage", "io.swagger.model"); additionalProperties.put("title", title); + // java inflector uses the jackson lib + additionalProperties.put("jackson", "true"); } @Override diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java index a564a499137..5cf8b65c5ff 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java @@ -4,7 +4,6 @@ import io.swagger.models.Operation; import io.swagger.models.Path; import io.swagger.models.Swagger; -import org.apache.commons.lang3.BooleanUtils; import java.io.File; import java.util.*; @@ -42,6 +41,9 @@ public SpringCodegen() { additionalProperties.put(CONFIG_PACKAGE, configPackage); additionalProperties.put(BASE_PACKAGE, basePackage); + // spring uses the jackson lib + additionalProperties.put("jackson", "true"); + cliOptions.add(new CliOption(TITLE, "server title name or client service name")); cliOptions.add(new CliOption(CONFIG_PACKAGE, "configuration package for generated code")); cliOptions.add(new CliOption(BASE_PACKAGE, "base package for generated code")); @@ -352,17 +354,22 @@ public void setSingleContentTypes(boolean singleContentTypes) { public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { super.postProcessModelProperty(model, property); - if("null".equals(property.example)) { + if ("null".equals(property.example)) { property.example = null; } //Add imports for Jackson - if(!BooleanUtils.toBoolean(model.isEnum)) { + if (!Boolean.TRUE.equals(model.isEnum)) { model.imports.add("JsonProperty"); - if(BooleanUtils.toBoolean(model.hasEnums)) { + if (Boolean.TRUE.equals(model.hasEnums)) { model.imports.add("JsonValue"); } + } else { // enum class + //Needed imports for Jackson's JsonCreator + if (additionalProperties.containsKey("jackson")) { + model.imports.add("JsonCreator"); + } } } diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/enumClass.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/enumClass.mustache index 398dae3e77f..c5c3143cb94 100644 --- a/modules/swagger-codegen/src/main/resources/JavaInflector/enumClass.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/enumClass.mustache @@ -27,7 +27,18 @@ } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue(String text) { + for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/enumOuterClass.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/enumOuterClass.mustache index 679ffbacb50..76c2cbf5a76 100644 --- a/modules/swagger-codegen/src/main/resources/JavaInflector/enumOuterClass.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/enumOuterClass.mustache @@ -1,3 +1,7 @@ +{{#jackson}} +import com.fasterxml.jackson.annotation.JsonCreator; +{{/jackson}} + /** * {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} */ @@ -21,7 +25,18 @@ public enum {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue(String text) { + for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/enumClass.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/enumClass.mustache index 398dae3e77f..c5c3143cb94 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/enumClass.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/enumClass.mustache @@ -27,7 +27,18 @@ } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue(String text) { + for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/enumOuterClass.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/enumOuterClass.mustache index 679ffbacb50..76c2cbf5a76 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/enumOuterClass.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/enumOuterClass.mustache @@ -1,3 +1,7 @@ +{{#jackson}} +import com.fasterxml.jackson.annotation.JsonCreator; +{{/jackson}} + /** * {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} */ @@ -21,7 +25,18 @@ public enum {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue(String text) { + for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/api.mustache index 15442ad4748..59074d1af13 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/api.mustache @@ -5,6 +5,7 @@ import {{package}}.{{classname}}Service; import {{package}}.factories.{{classname}}ServiceFactory; import io.swagger.annotations.ApiParam; +import io.swagger.jaxrs.*; import com.sun.jersey.multipart.FormDataParam; diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/enumClass.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/enumClass.mustache index 398dae3e77f..c5c3143cb94 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/enumClass.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/enumClass.mustache @@ -27,7 +27,18 @@ } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue(String text) { + for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/enumOuterClass.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/enumOuterClass.mustache index 679ffbacb50..76c2cbf5a76 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/enumOuterClass.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/enumOuterClass.mustache @@ -1,3 +1,7 @@ +{{#jackson}} +import com.fasterxml.jackson.annotation.JsonCreator; +{{/jackson}} + /** * {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} */ @@ -21,7 +25,18 @@ public enum {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue(String text) { + for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java index 1583f14bb47..5dbd5284d25 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/configuration/ClientConfiguration.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/configuration/ClientConfiguration.java index b0816e2d6e9..9e68822a61e 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/configuration/ClientConfiguration.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/configuration/ClientConfiguration.java @@ -22,6 +22,15 @@ @EnableConfigurationProperties public class ClientConfiguration { + @Value("${ swaggerPetstore.security.apiKey.key:}") + private String apiKeyKey; + + @Bean + @ConditionalOnProperty(name = "swaggerPetstore.security.apiKey.key") + public ApiKeyRequestInterceptor apiKeyRequestInterceptor() { + return new ApiKeyRequestInterceptor("header", "api_key", this.apiKeyKey); + } + @Bean @ConditionalOnProperty("swaggerPetstore.security.petstoreAuth.client-id") public OAuth2FeignRequestInterceptor petstoreAuthRequestInterceptor() { @@ -37,13 +46,4 @@ public ImplicitResourceDetails petstoreAuthResourceDetails() { return details; } - @Value("${ swaggerPetstore.security.apiKey.key:}") - private String apiKeyKey; - - @Bean - @ConditionalOnProperty(name = "swaggerPetstore.security.apiKey.key") - public ApiKeyRequestInterceptor apiKeyRequestInterceptor() { - return new ApiKeyRequestInterceptor("header", "api_key", this.apiKeyKey); - } - } \ No newline at end of file diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Category.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Category.java index 5039fd77a60..502d1c42bda 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Category.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Category.java @@ -14,8 +14,10 @@ */ public class Category { + @JsonProperty("id") private Long id = null; + @JsonProperty("name") private String name = null; public Category id(Long id) { diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/ModelApiResponse.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/ModelApiResponse.java index 512dcd5f43b..a8375a0abba 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/ModelApiResponse.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/ModelApiResponse.java @@ -14,10 +14,13 @@ */ public class ModelApiResponse { + @JsonProperty("code") private Integer code = null; + @JsonProperty("type") private String type = null; + @JsonProperty("message") private String message = null; public ModelApiResponse code(Integer code) { diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Order.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Order.java index 0cd70bfd939..09fe1ee39c3 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Order.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Order.java @@ -16,12 +16,16 @@ */ public class Order { + @JsonProperty("id") private Long id = null; + @JsonProperty("petId") private Long petId = null; + @JsonProperty("quantity") private Integer quantity = null; + @JsonProperty("shipDate") private DateTime shipDate = null; /** @@ -41,13 +45,26 @@ public enum StatusEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("status") private StatusEnum status = null; + @JsonProperty("complete") private Boolean complete = false; public Order id(Long id) { diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Pet.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Pet.java index 3592e1240dc..9189a91034b 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Pet.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Pet.java @@ -19,14 +19,19 @@ */ public class Pet { + @JsonProperty("id") private Long id = null; + @JsonProperty("category") private Category category = null; + @JsonProperty("name") private String name = null; + @JsonProperty("photoUrls") private List photoUrls = new ArrayList(); + @JsonProperty("tags") private List tags = new ArrayList(); /** @@ -46,11 +51,23 @@ public enum StatusEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("status") private StatusEnum status = null; public Pet id(Long id) { diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Tag.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Tag.java index 9ebfa434af2..e75d10df70e 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Tag.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Tag.java @@ -14,8 +14,10 @@ */ public class Tag { + @JsonProperty("id") private Long id = null; + @JsonProperty("name") private String name = null; public Tag id(Long id) { diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/User.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/User.java index 24abc50388a..11a1a82a5cd 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/User.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/User.java @@ -14,20 +14,28 @@ */ public class User { + @JsonProperty("id") private Long id = null; + @JsonProperty("username") private String username = null; + @JsonProperty("firstName") private String firstName = null; + @JsonProperty("lastName") private String lastName = null; + @JsonProperty("email") private String email = null; + @JsonProperty("password") private String password = null; + @JsonProperty("phone") private String phone = null; + @JsonProperty("userStatus") private Integer userStatus = null; public User id(Long id) { diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/PetApi.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/PetApi.java index c1c238e5f2e..6acd0c19d80 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/PetApi.java +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/PetApi.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Category.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Category.java index 5039fd77a60..502d1c42bda 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Category.java +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Category.java @@ -14,8 +14,10 @@ */ public class Category { + @JsonProperty("id") private Long id = null; + @JsonProperty("name") private String name = null; public Category id(Long id) { diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/ModelApiResponse.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/ModelApiResponse.java index 512dcd5f43b..a8375a0abba 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/ModelApiResponse.java +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/ModelApiResponse.java @@ -14,10 +14,13 @@ */ public class ModelApiResponse { + @JsonProperty("code") private Integer code = null; + @JsonProperty("type") private String type = null; + @JsonProperty("message") private String message = null; public ModelApiResponse code(Integer code) { diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Order.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Order.java index 0cd70bfd939..09fe1ee39c3 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Order.java +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Order.java @@ -16,12 +16,16 @@ */ public class Order { + @JsonProperty("id") private Long id = null; + @JsonProperty("petId") private Long petId = null; + @JsonProperty("quantity") private Integer quantity = null; + @JsonProperty("shipDate") private DateTime shipDate = null; /** @@ -41,13 +45,26 @@ public enum StatusEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("status") private StatusEnum status = null; + @JsonProperty("complete") private Boolean complete = false; public Order id(Long id) { diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Pet.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Pet.java index 3592e1240dc..9189a91034b 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Pet.java +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Pet.java @@ -19,14 +19,19 @@ */ public class Pet { + @JsonProperty("id") private Long id = null; + @JsonProperty("category") private Category category = null; + @JsonProperty("name") private String name = null; + @JsonProperty("photoUrls") private List photoUrls = new ArrayList(); + @JsonProperty("tags") private List tags = new ArrayList(); /** @@ -46,11 +51,23 @@ public enum StatusEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("status") private StatusEnum status = null; public Pet id(Long id) { diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Tag.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Tag.java index 9ebfa434af2..e75d10df70e 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Tag.java +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Tag.java @@ -14,8 +14,10 @@ */ public class Tag { + @JsonProperty("id") private Long id = null; + @JsonProperty("name") private String name = null; public Tag id(Long id) { diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/User.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/User.java index 24abc50388a..11a1a82a5cd 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/User.java +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/User.java @@ -14,20 +14,28 @@ */ public class User { + @JsonProperty("id") private Long id = null; + @JsonProperty("username") private String username = null; + @JsonProperty("firstName") private String firstName = null; + @JsonProperty("lastName") private String lastName = null; + @JsonProperty("email") private String email = null; + @JsonProperty("password") private String password = null; + @JsonProperty("phone") private String phone = null; + @JsonProperty("userStatus") private Integer userStatus = null; public User id(Long id) { diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/handler/StringUtil.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/handler/StringUtil.java index 16c10060121..337a801a13d 100644 --- a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/handler/StringUtil.java +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/handler/StringUtil.java @@ -1,6 +1,6 @@ package io.swagger.handler; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java index 572c1ba2d26..9755503f600 100644 --- a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java @@ -13,10 +13,12 @@ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class AdditionalPropertiesClass { + @JsonProperty("map_property") private Map mapProperty = new HashMap(); + @JsonProperty("map_of_map_property") private Map> mapOfMapProperty = new HashMap>(); /** diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Animal.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Animal.java index d385d3d355b..87ebd2daa69 100644 --- a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Animal.java +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Animal.java @@ -10,10 +10,12 @@ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class Animal { + @JsonProperty("className") private String className = null; + @JsonProperty("color") private String color = "red"; /** diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/AnimalFarm.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/AnimalFarm.java index 4ae707c1a77..dfe4c29628d 100644 --- a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/AnimalFarm.java +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/AnimalFarm.java @@ -9,7 +9,7 @@ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class AnimalFarm extends ArrayList { @Override diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java index 8db5e4343e9..37b5df65826 100644 --- a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java @@ -13,8 +13,9 @@ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class ArrayOfArrayOfNumberOnly { + @JsonProperty("ArrayArrayNumber") private List> arrayArrayNumber = new ArrayList>(); /** diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java index 232e4786b13..706d077179c 100644 --- a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java @@ -13,8 +13,9 @@ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class ArrayOfNumberOnly { + @JsonProperty("ArrayNumber") private List arrayNumber = new ArrayList(); /** diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ArrayTest.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ArrayTest.java index 4a0e569dbc7..423f536df40 100644 --- a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ArrayTest.java +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ArrayTest.java @@ -13,12 +13,15 @@ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class ArrayTest { + @JsonProperty("array_of_string") private List arrayOfString = new ArrayList(); + @JsonProperty("array_array_of_integer") private List> arrayArrayOfInteger = new ArrayList>(); + @JsonProperty("array_array_of_model") private List> arrayArrayOfModel = new ArrayList>(); /** diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Cat.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Cat.java index 0977daffdfd..865008e47c8 100644 --- a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Cat.java +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Cat.java @@ -11,8 +11,9 @@ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class Cat extends Animal { + @JsonProperty("declawed") private Boolean declawed = null; /** diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Category.java index 2437d48f9e2..ff244e9e5ae 100644 --- a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Category.java @@ -10,10 +10,12 @@ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class Category { + @JsonProperty("id") private Long id = null; + @JsonProperty("name") private String name = null; /** diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Client.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Client.java index 9e71d506697..0f4b7b6bd0b 100644 --- a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Client.java +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Client.java @@ -10,8 +10,9 @@ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class Client { + @JsonProperty("client") private String client = null; /** diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Dog.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Dog.java index 9adc4bdcfc0..ddc5b138ec5 100644 --- a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Dog.java +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Dog.java @@ -11,8 +11,9 @@ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class Dog extends Animal { + @JsonProperty("breed") private String breed = null; /** diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumArrays.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumArrays.java index bc44bd58575..1e0dc66db47 100644 --- a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumArrays.java +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumArrays.java @@ -13,7 +13,7 @@ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class EnumArrays { /** * Gets or Sets justSymbol @@ -30,11 +30,23 @@ public enum JustSymbolEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static JustSymbolEnum fromValue(String text) { + for (JustSymbolEnum b : JustSymbolEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("just_symbol") private JustSymbolEnum justSymbol = null; /** @@ -52,11 +64,23 @@ public enum ArrayEnumEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static ArrayEnumEnum fromValue(String text) { + for (ArrayEnumEnum b : ArrayEnumEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("array_enum") private List arrayEnum = new ArrayList(); /** diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumClass.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumClass.java index 2eb1a992f3e..ec7f34e4229 100644 --- a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumClass.java +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumClass.java @@ -5,6 +5,8 @@ +import com.fasterxml.jackson.annotation.JsonCreator; + /** * Gets or Sets EnumClass */ @@ -23,9 +25,20 @@ public enum EnumClass { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static EnumClass fromValue(String text) { + for (EnumClass b : EnumClass.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumTest.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumTest.java index 3b9e69a43c9..02fa4fc2283 100644 --- a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumTest.java +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumTest.java @@ -11,7 +11,7 @@ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class EnumTest { /** * Gets or Sets enumString @@ -28,11 +28,23 @@ public enum EnumStringEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static EnumStringEnum fromValue(String text) { + for (EnumStringEnum b : EnumStringEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("enum_string") private EnumStringEnum enumString = null; /** @@ -50,11 +62,23 @@ public enum EnumIntegerEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static EnumIntegerEnum fromValue(String text) { + for (EnumIntegerEnum b : EnumIntegerEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("enum_integer") private EnumIntegerEnum enumInteger = null; /** @@ -72,11 +96,23 @@ public enum EnumNumberEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static EnumNumberEnum fromValue(String text) { + for (EnumNumberEnum b : EnumNumberEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("enum_number") private EnumNumberEnum enumNumber = null; /** diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/FormatTest.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/FormatTest.java index 1d7dd3ec37e..7535534538c 100644 --- a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/FormatTest.java +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/FormatTest.java @@ -12,32 +12,45 @@ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class FormatTest { + @JsonProperty("integer") private Integer integer = null; + @JsonProperty("int32") private Integer int32 = null; + @JsonProperty("int64") private Long int64 = null; + @JsonProperty("number") private BigDecimal number = null; + @JsonProperty("float") private Float _float = null; + @JsonProperty("double") private Double _double = null; + @JsonProperty("string") private String string = null; + @JsonProperty("byte") private byte[] _byte = null; + @JsonProperty("binary") private byte[] binary = null; + @JsonProperty("date") private Date date = null; + @JsonProperty("dateTime") private Date dateTime = null; + @JsonProperty("uuid") private String uuid = null; + @JsonProperty("password") private String password = null; /** diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/HasOnlyReadOnly.java index a780629909f..990188118de 100644 --- a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/HasOnlyReadOnly.java @@ -10,10 +10,12 @@ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class HasOnlyReadOnly { + @JsonProperty("bar") private String bar = null; + @JsonProperty("foo") private String foo = null; /** diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/MapTest.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/MapTest.java index 033494b6b91..e3e1a7b8753 100644 --- a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/MapTest.java +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/MapTest.java @@ -14,8 +14,9 @@ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class MapTest { + @JsonProperty("map_map_of_string") private Map> mapMapOfString = new HashMap>(); /** @@ -33,11 +34,23 @@ public enum InnerEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static InnerEnum fromValue(String text) { + for (InnerEnum b : InnerEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("map_of_enum_string") private Map mapOfEnumString = new HashMap(); /** diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java index d10d2b2881a..ab28e910981 100644 --- a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -15,12 +15,15 @@ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class MixedPropertiesAndAdditionalPropertiesClass { + @JsonProperty("uuid") private String uuid = null; + @JsonProperty("dateTime") private Date dateTime = null; + @JsonProperty("map") private Map map = new HashMap(); /** diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Model200Response.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Model200Response.java index 079077e8c4e..b669912e402 100644 --- a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Model200Response.java +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Model200Response.java @@ -13,10 +13,12 @@ **/ @ApiModel(description = "Model for testing model name starting with number") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class Model200Response { + @JsonProperty("name") private Integer name = null; + @JsonProperty("class") private String PropertyClass = null; /** diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ModelApiResponse.java index 85e9ec6a465..d2cf14c4833 100644 --- a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -10,12 +10,15 @@ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class ModelApiResponse { + @JsonProperty("code") private Integer code = null; + @JsonProperty("type") private String type = null; + @JsonProperty("message") private String message = null; /** diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ModelReturn.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ModelReturn.java index b27b0095f9a..b240e33ad2f 100644 --- a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ModelReturn.java +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ModelReturn.java @@ -13,8 +13,9 @@ **/ @ApiModel(description = "Model for testing reserved words") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class ModelReturn { + @JsonProperty("return") private Integer _return = null; /** diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Name.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Name.java index 83664f19a0b..2c1e02dbf3e 100644 --- a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Name.java +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Name.java @@ -13,14 +13,18 @@ **/ @ApiModel(description = "Model for testing model name same as property name") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class Name { + @JsonProperty("name") private Integer name = null; + @JsonProperty("snake_case") private Integer snakeCase = null; + @JsonProperty("property") private String property = null; + @JsonProperty("123Number") private Integer _123Number = null; /** diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/NumberOnly.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/NumberOnly.java index 8bfcfec586b..33566fcb99c 100644 --- a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/NumberOnly.java +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/NumberOnly.java @@ -11,8 +11,9 @@ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class NumberOnly { + @JsonProperty("JustNumber") private BigDecimal justNumber = null; /** diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Order.java index 4b88e8761c8..55d84c48fff 100644 --- a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Order.java @@ -12,14 +12,18 @@ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class Order { + @JsonProperty("id") private Long id = null; + @JsonProperty("petId") private Long petId = null; + @JsonProperty("quantity") private Integer quantity = null; + @JsonProperty("shipDate") private Date shipDate = null; /** @@ -39,13 +43,26 @@ public enum StatusEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("status") private StatusEnum status = null; + @JsonProperty("complete") private Boolean complete = false; /** diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Pet.java index a5056440398..c1b1942400b 100644 --- a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Pet.java @@ -15,16 +15,21 @@ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class Pet { + @JsonProperty("id") private Long id = null; + @JsonProperty("category") private Category category = null; + @JsonProperty("name") private String name = null; + @JsonProperty("photoUrls") private List photoUrls = new ArrayList(); + @JsonProperty("tags") private List tags = new ArrayList(); /** @@ -44,11 +49,23 @@ public enum StatusEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("status") private StatusEnum status = null; /** diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ReadOnlyFirst.java index 1005fa50379..8dc882acafc 100644 --- a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ReadOnlyFirst.java +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/ReadOnlyFirst.java @@ -10,10 +10,12 @@ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class ReadOnlyFirst { + @JsonProperty("bar") private String bar = null; + @JsonProperty("baz") private String baz = null; /** diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/SpecialModelName.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/SpecialModelName.java index 90b0e254401..5503a673041 100644 --- a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/SpecialModelName.java +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/SpecialModelName.java @@ -10,8 +10,9 @@ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class SpecialModelName { + @JsonProperty("$special[property.name]") private Long specialPropertyName = null; /** diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Tag.java index b71a54c270d..26fa90e969e 100644 --- a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Tag.java @@ -10,10 +10,12 @@ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class Tag { + @JsonProperty("id") private Long id = null; + @JsonProperty("name") private String name = null; /** diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/User.java index 0d7a6d1710a..f6e1584d8b0 100644 --- a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/User.java @@ -10,22 +10,30 @@ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class User { + @JsonProperty("id") private Long id = null; + @JsonProperty("username") private String username = null; + @JsonProperty("firstName") private String firstName = null; + @JsonProperty("lastName") private String lastName = null; + @JsonProperty("email") private String email = null; + @JsonProperty("password") private String password = null; + @JsonProperty("phone") private String phone = null; + @JsonProperty("userStatus") private Integer userStatus = null; /** diff --git a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/FakeController.java b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/FakeController.java index 1dfe454d271..e4c99b9eaec 100644 --- a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/FakeController.java +++ b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/FakeController.java @@ -14,7 +14,7 @@ import java.util.Date; import java.math.BigDecimal; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class FakeController { /** * Uncomment and implement as you see fit. These operations will map diff --git a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/PetController.java b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/PetController.java index 96d204a5063..df14543085c 100644 --- a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/PetController.java +++ b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/PetController.java @@ -14,7 +14,7 @@ import java.io.File; import io.swagger.model.ModelApiResponse; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class PetController { /** * Uncomment and implement as you see fit. These operations will map diff --git a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/StoreController.java b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/StoreController.java index 69eeded6cf5..c67931a8461 100644 --- a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/StoreController.java +++ b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/StoreController.java @@ -13,7 +13,7 @@ import java.util.Map; import io.swagger.model.Order; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class StoreController { /** * Uncomment and implement as you see fit. These operations will map diff --git a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/UserController.java b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/UserController.java index 0f25bf720bc..cdb18da0b06 100644 --- a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/UserController.java +++ b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/UserController.java @@ -13,7 +13,7 @@ import io.swagger.model.User; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-17T22:41:52.290+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2016-08-20T17:24:26.037+08:00") public class UserController { /** * Uncomment and implement as you see fit. These operations will map diff --git a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/api/PetApi.java index fdb459a62c5..9e459c248dd 100644 --- a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/api/PetApi.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; import java.io.InputStream; import java.io.OutputStream; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApi.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApi.java new file mode 100644 index 00000000000..a87a5a4bb60 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApi.java @@ -0,0 +1,98 @@ +package io.swagger.api; + +import io.swagger.model.*; +import io.swagger.api.FakeApiService; +import io.swagger.api.factories.FakeApiServiceFactory; + +import io.swagger.annotations.ApiParam; +import io.swagger.jaxrs.*; + +import com.sun.jersey.multipart.FormDataParam; + +import io.swagger.model.Client; +import java.util.Date; +import java.math.BigDecimal; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.ws.rs.*; + +@Path("/fake") + + +@io.swagger.annotations.Api(description = "the fake API") + +public class FakeApi { + private final FakeApiService delegate = FakeApiServiceFactory.getFakeApi(); + + @PATCH + + @Consumes({ "application/json" }) + @Produces({ "application/json" }) + @io.swagger.annotations.ApiOperation(value = "To test \"client\" model", notes = "", response = Client.class, tags={ "fake", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Client.class) }) + public Response testClientModel( + @ApiParam(value = "client model" ,required=true) Client body, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.testClientModel(body,securityContext); + } + @POST + + @Consumes({ "application/xml; charset=utf-8", "application/json; charset=utf-8" }) + @Produces({ "application/xml; charset=utf-8", "application/json; charset=utf-8" }) + @io.swagger.annotations.ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", notes = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", response = void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "http_basic_test") + }, tags={ "fake", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = void.class), + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = void.class) }) + public Response testEndpointParameters( + @ApiParam(value = "None", required=true) @FormParam("number") BigDecimal number, + @ApiParam(value = "None", required=true) @FormParam("double") Double _double, + @ApiParam(value = "None", required=true) @FormParam("string") String string, + @ApiParam(value = "None", required=true) @FormParam("byte") byte[] _byte, + @ApiParam(value = "None") @FormParam("integer") Integer integer, + @ApiParam(value = "None") @FormParam("int32") Integer int32, + @ApiParam(value = "None") @FormParam("int64") Long int64, + @ApiParam(value = "None") @FormParam("float") Float _float, + @ApiParam(value = "None") @FormParam("binary") byte[] binary, + @ApiParam(value = "None") @FormParam("date") Date date, + @ApiParam(value = "None") @FormParam("dateTime") Date dateTime, + @ApiParam(value = "None") @FormParam("password") String password, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.testEndpointParameters(number,_double,string,_byte,integer,int32,int64,_float,binary,date,dateTime,password,securityContext); + } + @GET + + @Consumes({ "application/json" }) + @Produces({ "application/json" }) + @io.swagger.annotations.ApiOperation(value = "To test enum parameters", notes = "", response = void.class, tags={ "fake" }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid request", response = void.class), + @io.swagger.annotations.ApiResponse(code = 404, message = "Not found", response = void.class) }) + public Response testEnumParameters( + @ApiParam(value = "Form parameter enum test (string array)") @FormParam("enum_form_string_array") List enumFormStringArray, + @ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @DefaultValue("-efg") @FormParam("enum_form_string") String enumFormString, + @ApiParam(value = "Header parameter enum test (string array)" )@HeaderParam("enum_header_string_array") List enumHeaderStringArray, + @ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg")@HeaderParam("enum_header_string") String enumHeaderString, + @ApiParam(value = "Query parameter enum test (string array)", allowableValues=">, $") @QueryParam("enum_query_string_array") List enumQueryStringArray, + @ApiParam(value = "Query parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @DefaultValue("-efg") @QueryParam("enum_query_string") String enumQueryString, + @ApiParam(value = "Query parameter enum test (double)") @QueryParam("enum_query_integer") BigDecimal enumQueryInteger, + @ApiParam(value = "Query parameter enum test (double)") @FormParam("enum_query_double") Double enumQueryDouble, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.testEnumParameters(enumFormStringArray,enumFormString,enumHeaderStringArray,enumHeaderString,enumQueryStringArray,enumQueryString,enumQueryInteger,enumQueryDouble,securityContext); + } +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApiService.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApiService.java new file mode 100644 index 00000000000..8f37e8c4282 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApiService.java @@ -0,0 +1,31 @@ +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import com.sun.jersey.multipart.FormDataParam; + +import io.swagger.model.Client; +import java.util.Date; +import java.math.BigDecimal; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + + +public abstract class FakeApiService { + public abstract Response testClientModel(Client body,SecurityContext securityContext) + throws NotFoundException; + public abstract Response testEndpointParameters(BigDecimal number,Double _double,String string,byte[] _byte,Integer integer,Integer int32,Long int64,Float _float,byte[] binary,Date date,Date dateTime,String password,SecurityContext securityContext) + throws NotFoundException; + public abstract Response testEnumParameters(List enumFormStringArray,String enumFormString,List enumHeaderStringArray,String enumHeaderString,List enumQueryStringArray,String enumQueryString,BigDecimal enumQueryInteger,Double enumQueryDouble,SecurityContext securityContext) + throws NotFoundException; +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApi.java index 6ab33888e61..1fd238cc771 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApi.java @@ -5,6 +5,7 @@ import io.swagger.api.factories.PetApiServiceFactory; import io.swagger.annotations.ApiParam; +import io.swagger.jaxrs.*; import com.sun.jersey.multipart.FormDataParam; @@ -84,7 +85,7 @@ public Response deletePet( @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid status value", response = Pet.class, responseContainer = "List") }) public Response findPetsByStatus( - @ApiParam(value = "Status values that need to be considered for filter",required=true) @QueryParam("status") List status, + @ApiParam(value = "Status values that need to be considered for filter",required=true, allowableValues="available, pending, sold") @QueryParam("status") List status, @Context SecurityContext securityContext) throws NotFoundException { return delegate.findPetsByStatus(status,securityContext); @@ -159,8 +160,8 @@ public Response updatePet( @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = void.class) }) public Response updatePetWithForm( @ApiParam(value = "ID of pet that needs to be updated",required=true) @PathParam("petId") Long petId, - @ApiParam(value = "Updated name of the pet")@FormParam("name") String name, - @ApiParam(value = "Updated status of the pet")@FormParam("status") String status, + @ApiParam(value = "Updated name of the pet") @FormParam("name") String name, + @ApiParam(value = "Updated status of the pet") @FormParam("status") String status, @Context SecurityContext securityContext) throws NotFoundException { return delegate.updatePetWithForm(petId,name,status,securityContext); diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApi.java index 91c37506181..6742c34fe3e 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApi.java @@ -5,6 +5,7 @@ import io.swagger.api.factories.StoreApiServiceFactory; import io.swagger.annotations.ApiParam; +import io.swagger.jaxrs.*; import com.sun.jersey.multipart.FormDataParam; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApi.java index 5c53e751c4f..b0514bdd4e9 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApi.java @@ -5,6 +5,7 @@ import io.swagger.api.factories.UserApiServiceFactory; import io.swagger.annotations.ApiParam; +import io.swagger.jaxrs.*; import com.sun.jersey.multipart.FormDataParam; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..4cc945f4087 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java @@ -0,0 +1,113 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + + + +/** + * AdditionalPropertiesClass + */ + +public class AdditionalPropertiesClass { + @JsonProperty("map_property") + private Map mapProperty = new HashMap(); + + @JsonProperty("map_of_map_property") + private Map> mapOfMapProperty = new HashMap>(); + + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + this.mapProperty.put(key, mapPropertyItem); + return this; + } + + /** + * Get mapProperty + * @return mapProperty + **/ + @ApiModelProperty(value = "") + public Map getMapProperty() { + return mapProperty; + } + + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + return this; + } + + public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, Map mapOfMapPropertyItem) { + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + + /** + * Get mapOfMapProperty + * @return mapOfMapProperty + **/ + @ApiModelProperty(value = "") + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; + return Objects.equals(this.mapProperty, additionalPropertiesClass.mapProperty) && + Objects.equals(this.mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); + } + + @Override + public int hashCode() { + return Objects.hash(mapProperty, mapOfMapProperty); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Animal.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Animal.java new file mode 100644 index 00000000000..0e17c866e90 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Animal.java @@ -0,0 +1,100 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + +/** + * Animal + */ + +public class Animal { + @JsonProperty("className") + private String className = null; + + @JsonProperty("color") + private String color = "red"; + + public Animal className(String className) { + this.className = className; + return this; + } + + /** + * Get className + * @return className + **/ + @ApiModelProperty(required = true, value = "") + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + public Animal color(String color) { + this.color = color; + return this; + } + + /** + * Get color + * @return color + **/ + @ApiModelProperty(value = "") + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Animal animal = (Animal) o; + return Objects.equals(this.className, animal.className) && + Objects.equals(this.color, animal.color); + } + + @Override + public int hashCode() { + return Objects.hash(className, color); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Animal {\n"); + + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/AnimalFarm.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/AnimalFarm.java new file mode 100644 index 00000000000..6f35d1ecec1 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/AnimalFarm.java @@ -0,0 +1,53 @@ +package io.swagger.model; + +import java.util.Objects; +import io.swagger.model.Animal; +import java.util.ArrayList; +import java.util.List; + + + + +/** + * AnimalFarm + */ + +public class AnimalFarm extends ArrayList { + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + return true; + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 00000000000..dc044068238 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,85 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + + + + +/** + * ArrayOfArrayOfNumberOnly + */ + +public class ArrayOfArrayOfNumberOnly { + @JsonProperty("ArrayArrayNumber") + private List> arrayArrayNumber = new ArrayList>(); + + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + + /** + * Get arrayArrayNumber + * @return arrayArrayNumber + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayNumber() { + return arrayArrayNumber; + } + + public void setArrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly = (ArrayOfArrayOfNumberOnly) o; + return Objects.equals(this.arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayArrayNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfArrayOfNumberOnly {\n"); + + sb.append(" arrayArrayNumber: ").append(toIndentedString(arrayArrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java new file mode 100644 index 00000000000..f2906007107 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java @@ -0,0 +1,85 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + + + + +/** + * ArrayOfNumberOnly + */ + +public class ArrayOfNumberOnly { + @JsonProperty("ArrayNumber") + private List arrayNumber = new ArrayList(); + + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + this.arrayNumber.add(arrayNumberItem); + return this; + } + + /** + * Get arrayNumber + * @return arrayNumber + **/ + @ApiModelProperty(value = "") + public List getArrayNumber() { + return arrayNumber; + } + + public void setArrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfNumberOnly arrayOfNumberOnly = (ArrayOfNumberOnly) o; + return Objects.equals(this.arrayNumber, arrayOfNumberOnly.arrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfNumberOnly {\n"); + + sb.append(" arrayNumber: ").append(toIndentedString(arrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayTest.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayTest.java new file mode 100644 index 00000000000..c46fe7d9379 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayTest.java @@ -0,0 +1,141 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.ReadOnlyFirst; +import java.util.ArrayList; +import java.util.List; + + + + +/** + * ArrayTest + */ + +public class ArrayTest { + @JsonProperty("array_of_string") + private List arrayOfString = new ArrayList(); + + @JsonProperty("array_array_of_integer") + private List> arrayArrayOfInteger = new ArrayList>(); + + @JsonProperty("array_array_of_model") + private List> arrayArrayOfModel = new ArrayList>(); + + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + + /** + * Get arrayOfString + * @return arrayOfString + **/ + @ApiModelProperty(value = "") + public List getArrayOfString() { + return arrayOfString; + } + + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + return this; + } + + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + + /** + * Get arrayArrayOfInteger + * @return arrayArrayOfInteger + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + return this; + } + + public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + + /** + * Get arrayArrayOfModel + * @return arrayArrayOfModel + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayTest arrayTest = (ArrayTest) o; + return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && + Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); + } + + @Override + public int hashCode() { + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Cat.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Cat.java new file mode 100644 index 00000000000..c63afeb8ae1 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Cat.java @@ -0,0 +1,79 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Animal; + + + + +/** + * Cat + */ + +public class Cat extends Animal { + @JsonProperty("declawed") + private Boolean declawed = null; + + public Cat declawed(Boolean declawed) { + this.declawed = declawed; + return this; + } + + /** + * Get declawed + * @return declawed + **/ + @ApiModelProperty(value = "") + public Boolean getDeclawed() { + return declawed; + } + + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Cat cat = (Cat) o; + return Objects.equals(this.declawed, cat.declawed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(declawed, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Cat {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Category.java index 67bc75b3b10..502d1c42bda 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Category.java @@ -2,56 +2,63 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +/** + * Category + */ public class Category { - + @JsonProperty("id") private Long id = null; + + @JsonProperty("name") private String name = null; - /** - **/ public Category id(Long id) { this.id = id; return this; } - + /** + * Get id + * @return id + **/ @ApiModelProperty(value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public Category name(String name) { this.name = name; return this; } - + /** + * Get name + * @return name + **/ @ApiModelProperty(value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -59,8 +66,8 @@ public boolean equals(Object o) { return false; } Category category = (Category) o; - return Objects.equals(id, category.id) && - Objects.equals(name, category.name); + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); } @Override @@ -83,7 +90,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Client.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Client.java new file mode 100644 index 00000000000..bdfbb513c9e --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Client.java @@ -0,0 +1,77 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + +/** + * Client + */ + +public class Client { + @JsonProperty("client") + private String client = null; + + public Client client(String client) { + this.client = client; + return this; + } + + /** + * Get client + * @return client + **/ + @ApiModelProperty(value = "") + public String getClient() { + return client; + } + + public void setClient(String client) { + this.client = client; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Client client = (Client) o; + return Objects.equals(this.client, client.client); + } + + @Override + public int hashCode() { + return Objects.hash(client); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Client {\n"); + + sb.append(" client: ").append(toIndentedString(client)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Dog.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Dog.java new file mode 100644 index 00000000000..f0acafc1398 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Dog.java @@ -0,0 +1,79 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Animal; + + + + +/** + * Dog + */ + +public class Dog extends Animal { + @JsonProperty("breed") + private String breed = null; + + public Dog breed(String breed) { + this.breed = breed; + return this; + } + + /** + * Get breed + * @return breed + **/ + @ApiModelProperty(value = "") + public String getBreed() { + return breed; + } + + public void setBreed(String breed) { + this.breed = breed; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Dog dog = (Dog) o; + return Objects.equals(this.breed, dog.breed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(breed, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Dog {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumArrays.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumArrays.java new file mode 100644 index 00000000000..b737fb00c64 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumArrays.java @@ -0,0 +1,170 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.ArrayList; +import java.util.List; + + + + +/** + * EnumArrays + */ + +public class EnumArrays { + /** + * Gets or Sets justSymbol + */ + public enum JustSymbolEnum { + GREATER_THAN_OR_EQUAL_TO(">="), + + DOLLAR("$"); + + private String value; + + JustSymbolEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static JustSymbolEnum fromValue(String text) { + for (JustSymbolEnum b : JustSymbolEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("just_symbol") + private JustSymbolEnum justSymbol = null; + + /** + * Gets or Sets arrayEnum + */ + public enum ArrayEnumEnum { + FISH("fish"), + + CRAB("crab"); + + private String value; + + ArrayEnumEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static ArrayEnumEnum fromValue(String text) { + for (ArrayEnumEnum b : ArrayEnumEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("array_enum") + private List arrayEnum = new ArrayList(); + + public EnumArrays justSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + return this; + } + + /** + * Get justSymbol + * @return justSymbol + **/ + @ApiModelProperty(value = "") + public JustSymbolEnum getJustSymbol() { + return justSymbol; + } + + public void setJustSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + } + + public EnumArrays arrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + return this; + } + + public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { + this.arrayEnum.add(arrayEnumItem); + return this; + } + + /** + * Get arrayEnum + * @return arrayEnum + **/ + @ApiModelProperty(value = "") + public List getArrayEnum() { + return arrayEnum; + } + + public void setArrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumArrays enumArrays = (EnumArrays) o; + return Objects.equals(this.justSymbol, enumArrays.justSymbol) && + Objects.equals(this.arrayEnum, enumArrays.arrayEnum); + } + + @Override + public int hashCode() { + return Objects.hash(justSymbol, arrayEnum); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumArrays {\n"); + + sb.append(" justSymbol: ").append(toIndentedString(justSymbol)).append("\n"); + sb.append(" arrayEnum: ").append(toIndentedString(arrayEnum)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumClass.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumClass.java new file mode 100644 index 00000000000..ec7f34e4229 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumClass.java @@ -0,0 +1,44 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonValue; + + + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets EnumClass + */ +public enum EnumClass { + + _ABC("_abc"), + + _EFG("-efg"), + + _XYZ_("(xyz)"); + + private String value; + + EnumClass(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumClass fromValue(String text) { + for (EnumClass b : EnumClass.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} + + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumTest.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumTest.java new file mode 100644 index 00000000000..1f1f266c740 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumTest.java @@ -0,0 +1,217 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + +/** + * EnumTest + */ + +public class EnumTest { + /** + * Gets or Sets enumString + */ + public enum EnumStringEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + EnumStringEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumStringEnum fromValue(String text) { + for (EnumStringEnum b : EnumStringEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("enum_string") + private EnumStringEnum enumString = null; + + /** + * Gets or Sets enumInteger + */ + public enum EnumIntegerEnum { + NUMBER_1(1), + + NUMBER_MINUS_1(-1); + + private Integer value; + + EnumIntegerEnum(Integer value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumIntegerEnum fromValue(String text) { + for (EnumIntegerEnum b : EnumIntegerEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("enum_integer") + private EnumIntegerEnum enumInteger = null; + + /** + * Gets or Sets enumNumber + */ + public enum EnumNumberEnum { + NUMBER_1_DOT_1(1.1), + + NUMBER_MINUS_1_DOT_2(-1.2); + + private Double value; + + EnumNumberEnum(Double value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumNumberEnum fromValue(String text) { + for (EnumNumberEnum b : EnumNumberEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("enum_number") + private EnumNumberEnum enumNumber = null; + + public EnumTest enumString(EnumStringEnum enumString) { + this.enumString = enumString; + return this; + } + + /** + * Get enumString + * @return enumString + **/ + @ApiModelProperty(value = "") + public EnumStringEnum getEnumString() { + return enumString; + } + + public void setEnumString(EnumStringEnum enumString) { + this.enumString = enumString; + } + + public EnumTest enumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + return this; + } + + /** + * Get enumInteger + * @return enumInteger + **/ + @ApiModelProperty(value = "") + public EnumIntegerEnum getEnumInteger() { + return enumInteger; + } + + public void setEnumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + } + + public EnumTest enumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + return this; + } + + /** + * Get enumNumber + * @return enumNumber + **/ + @ApiModelProperty(value = "") + public EnumNumberEnum getEnumNumber() { + return enumNumber; + } + + public void setEnumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumTest enumTest = (EnumTest) o; + return Objects.equals(this.enumString, enumTest.enumString) && + Objects.equals(this.enumInteger, enumTest.enumInteger) && + Objects.equals(this.enumNumber, enumTest.enumNumber); + } + + @Override + public int hashCode() { + return Objects.hash(enumString, enumInteger, enumNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/FormatTest.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/FormatTest.java new file mode 100644 index 00000000000..9feaa2ffddb --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/FormatTest.java @@ -0,0 +1,365 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.Date; + + + + +/** + * FormatTest + */ + +public class FormatTest { + @JsonProperty("integer") + private Integer integer = null; + + @JsonProperty("int32") + private Integer int32 = null; + + @JsonProperty("int64") + private Long int64 = null; + + @JsonProperty("number") + private BigDecimal number = null; + + @JsonProperty("float") + private Float _float = null; + + @JsonProperty("double") + private Double _double = null; + + @JsonProperty("string") + private String string = null; + + @JsonProperty("byte") + private byte[] _byte = null; + + @JsonProperty("binary") + private byte[] binary = null; + + @JsonProperty("date") + private Date date = null; + + @JsonProperty("dateTime") + private Date dateTime = null; + + @JsonProperty("uuid") + private String uuid = null; + + @JsonProperty("password") + private String password = null; + + public FormatTest integer(Integer integer) { + this.integer = integer; + return this; + } + + /** + * Get integer + * minimum: 10.0 + * maximum: 100.0 + * @return integer + **/ + @ApiModelProperty(value = "") + public Integer getInteger() { + return integer; + } + + public void setInteger(Integer integer) { + this.integer = integer; + } + + public FormatTest int32(Integer int32) { + this.int32 = int32; + return this; + } + + /** + * Get int32 + * minimum: 20.0 + * maximum: 200.0 + * @return int32 + **/ + @ApiModelProperty(value = "") + public Integer getInt32() { + return int32; + } + + public void setInt32(Integer int32) { + this.int32 = int32; + } + + public FormatTest int64(Long int64) { + this.int64 = int64; + return this; + } + + /** + * Get int64 + * @return int64 + **/ + @ApiModelProperty(value = "") + public Long getInt64() { + return int64; + } + + public void setInt64(Long int64) { + this.int64 = int64; + } + + public FormatTest number(BigDecimal number) { + this.number = number; + return this; + } + + /** + * Get number + * minimum: 32.1 + * maximum: 543.2 + * @return number + **/ + @ApiModelProperty(required = true, value = "") + public BigDecimal getNumber() { + return number; + } + + public void setNumber(BigDecimal number) { + this.number = number; + } + + public FormatTest _float(Float _float) { + this._float = _float; + return this; + } + + /** + * Get _float + * minimum: 54.3 + * maximum: 987.6 + * @return _float + **/ + @ApiModelProperty(value = "") + public Float getFloat() { + return _float; + } + + public void setFloat(Float _float) { + this._float = _float; + } + + public FormatTest _double(Double _double) { + this._double = _double; + return this; + } + + /** + * Get _double + * minimum: 67.8 + * maximum: 123.4 + * @return _double + **/ + @ApiModelProperty(value = "") + public Double getDouble() { + return _double; + } + + public void setDouble(Double _double) { + this._double = _double; + } + + public FormatTest string(String string) { + this.string = string; + return this; + } + + /** + * Get string + * @return string + **/ + @ApiModelProperty(value = "") + public String getString() { + return string; + } + + public void setString(String string) { + this.string = string; + } + + public FormatTest _byte(byte[] _byte) { + this._byte = _byte; + return this; + } + + /** + * Get _byte + * @return _byte + **/ + @ApiModelProperty(required = true, value = "") + public byte[] getByte() { + return _byte; + } + + public void setByte(byte[] _byte) { + this._byte = _byte; + } + + public FormatTest binary(byte[] binary) { + this.binary = binary; + return this; + } + + /** + * Get binary + * @return binary + **/ + @ApiModelProperty(value = "") + public byte[] getBinary() { + return binary; + } + + public void setBinary(byte[] binary) { + this.binary = binary; + } + + public FormatTest date(Date date) { + this.date = date; + return this; + } + + /** + * Get date + * @return date + **/ + @ApiModelProperty(required = true, value = "") + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + public FormatTest dateTime(Date dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(value = "") + public Date getDateTime() { + return dateTime; + } + + public void setDateTime(Date dateTime) { + this.dateTime = dateTime; + } + + public FormatTest uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public FormatTest password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @ApiModelProperty(required = true, value = "") + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + FormatTest formatTest = (FormatTest) o; + return Objects.equals(this.integer, formatTest.integer) && + Objects.equals(this.int32, formatTest.int32) && + Objects.equals(this.int64, formatTest.int64) && + Objects.equals(this.number, formatTest.number) && + Objects.equals(this._float, formatTest._float) && + Objects.equals(this._double, formatTest._double) && + Objects.equals(this.string, formatTest.string) && + Objects.equals(this._byte, formatTest._byte) && + Objects.equals(this.binary, formatTest.binary) && + Objects.equals(this.date, formatTest.date) && + Objects.equals(this.dateTime, formatTest.dateTime) && + Objects.equals(this.uuid, formatTest.uuid) && + Objects.equals(this.password, formatTest.password); + } + + @Override + public int hashCode() { + return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, uuid, password); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FormatTest {\n"); + + sb.append(" integer: ").append(toIndentedString(integer)).append("\n"); + sb.append(" int32: ").append(toIndentedString(int32)).append("\n"); + sb.append(" int64: ").append(toIndentedString(int64)).append("\n"); + sb.append(" number: ").append(toIndentedString(number)).append("\n"); + sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); + sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); + sb.append(" string: ").append(toIndentedString(string)).append("\n"); + sb.append(" _byte: ").append(toIndentedString(_byte)).append("\n"); + sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); + sb.append(" date: ").append(toIndentedString(date)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/HasOnlyReadOnly.java new file mode 100644 index 00000000000..6574a2262dd --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/HasOnlyReadOnly.java @@ -0,0 +1,82 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + +/** + * HasOnlyReadOnly + */ + +public class HasOnlyReadOnly { + @JsonProperty("bar") + private String bar = null; + + @JsonProperty("foo") + private String foo = null; + + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(value = "") + public String getBar() { + return bar; + } + + /** + * Get foo + * @return foo + **/ + @ApiModelProperty(value = "") + public String getFoo() { + return foo; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HasOnlyReadOnly hasOnlyReadOnly = (HasOnlyReadOnly) o; + return Objects.equals(this.bar, hasOnlyReadOnly.bar) && + Objects.equals(this.foo, hasOnlyReadOnly.foo); + } + + @Override + public int hashCode() { + return Objects.hash(bar, foo); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HasOnlyReadOnly {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" foo: ").append(toIndentedString(foo)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/MapTest.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/MapTest.java new file mode 100644 index 00000000000..33cdfbbc65f --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/MapTest.java @@ -0,0 +1,145 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + + + +/** + * MapTest + */ + +public class MapTest { + @JsonProperty("map_map_of_string") + private Map> mapMapOfString = new HashMap>(); + + /** + * Gets or Sets inner + */ + public enum InnerEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + InnerEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static InnerEnum fromValue(String text) { + for (InnerEnum b : InnerEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("map_of_enum_string") + private Map mapOfEnumString = new HashMap(); + + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + + /** + * Get mapMapOfString + * @return mapMapOfString + **/ + @ApiModelProperty(value = "") + public Map> getMapMapOfString() { + return mapMapOfString; + } + + public void setMapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + } + + public MapTest mapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + return this; + } + + public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + + /** + * Get mapOfEnumString + * @return mapOfEnumString + **/ + @ApiModelProperty(value = "") + public Map getMapOfEnumString() { + return mapOfEnumString; + } + + public void setMapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MapTest mapTest = (MapTest) o; + return Objects.equals(this.mapMapOfString, mapTest.mapMapOfString) && + Objects.equals(this.mapOfEnumString, mapTest.mapOfEnumString); + } + + @Override + public int hashCode() { + return Objects.hash(mapMapOfString, mapOfEnumString); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MapTest {\n"); + + sb.append(" mapMapOfString: ").append(toIndentedString(mapMapOfString)).append("\n"); + sb.append(" mapOfEnumString: ").append(toIndentedString(mapOfEnumString)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..c9b476fa3b0 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,133 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Animal; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + + + +/** + * MixedPropertiesAndAdditionalPropertiesClass + */ + +public class MixedPropertiesAndAdditionalPropertiesClass { + @JsonProperty("uuid") + private String uuid = null; + + @JsonProperty("dateTime") + private Date dateTime = null; + + @JsonProperty("map") + private Map map = new HashMap(); + + public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public MixedPropertiesAndAdditionalPropertiesClass dateTime(Date dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(value = "") + public Date getDateTime() { + return dateTime; + } + + public void setDateTime(Date dateTime) { + this.dateTime = dateTime; + } + + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + this.map = map; + return this; + } + + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + this.map.put(key, mapItem); + return this; + } + + /** + * Get map + * @return map + **/ + @ApiModelProperty(value = "") + public Map getMap() { + return map; + } + + public void setMap(Map map) { + this.map = map; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; + return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(this.dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(this.map, mixedPropertiesAndAdditionalPropertiesClass.map); + } + + @Override + public int hashCode() { + return Objects.hash(uuid, dateTime, map); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Model200Response.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Model200Response.java new file mode 100644 index 00000000000..bd7a6532214 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Model200Response.java @@ -0,0 +1,104 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + +/** + * Model for testing model name starting with number + **/ + +/** + * Model for testing model name starting with number + */ +@ApiModel(description = "Model for testing model name starting with number") + +public class Model200Response { + @JsonProperty("name") + private Integer name = null; + + @JsonProperty("class") + private String PropertyClass = null; + + public Model200Response name(Integer name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public Integer getName() { + return name; + } + + public void setName(Integer name) { + this.name = name; + } + + public Model200Response PropertyClass(String PropertyClass) { + this.PropertyClass = PropertyClass; + return this; + } + + /** + * Get PropertyClass + * @return PropertyClass + **/ + @ApiModelProperty(value = "") + public String getPropertyClass() { + return PropertyClass; + } + + public void setPropertyClass(String PropertyClass) { + this.PropertyClass = PropertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Model200Response _200Response = (Model200Response) o; + return Objects.equals(this.name, _200Response.name) && + Objects.equals(this.PropertyClass, _200Response.PropertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(name, PropertyClass); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" PropertyClass: ").append(toIndentedString(PropertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelApiResponse.java index 5e3aa82bbee..a8375a0abba 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -2,74 +2,84 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +/** + * ModelApiResponse + */ public class ModelApiResponse { - + @JsonProperty("code") private Integer code = null; + + @JsonProperty("type") private String type = null; + + @JsonProperty("message") private String message = null; - /** - **/ public ModelApiResponse code(Integer code) { this.code = code; return this; } - + /** + * Get code + * @return code + **/ @ApiModelProperty(value = "") - @JsonProperty("code") public Integer getCode() { return code; } + public void setCode(Integer code) { this.code = code; } - /** - **/ public ModelApiResponse type(String type) { this.type = type; return this; } - + /** + * Get type + * @return type + **/ @ApiModelProperty(value = "") - @JsonProperty("type") public String getType() { return type; } + public void setType(String type) { this.type = type; } - /** - **/ public ModelApiResponse message(String message) { this.message = message; return this; } - + /** + * Get message + * @return message + **/ @ApiModelProperty(value = "") - @JsonProperty("message") public String getMessage() { return message; } + public void setMessage(String message) { this.message = message; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -77,9 +87,9 @@ public boolean equals(Object o) { return false; } ModelApiResponse _apiResponse = (ModelApiResponse) o; - return Objects.equals(code, _apiResponse.code) && - Objects.equals(type, _apiResponse.type) && - Objects.equals(message, _apiResponse.message); + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); } @Override @@ -103,7 +113,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelReturn.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelReturn.java new file mode 100644 index 00000000000..32df0e60bd4 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelReturn.java @@ -0,0 +1,81 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + +/** + * Model for testing reserved words + **/ + +/** + * Model for testing reserved words + */ +@ApiModel(description = "Model for testing reserved words") + +public class ModelReturn { + @JsonProperty("return") + private Integer _return = null; + + public ModelReturn _return(Integer _return) { + this._return = _return; + return this; + } + + /** + * Get _return + * @return _return + **/ + @ApiModelProperty(value = "") + public Integer getReturn() { + return _return; + } + + public void setReturn(Integer _return) { + this._return = _return; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelReturn _return = (ModelReturn) o; + return Objects.equals(this._return, _return._return); + } + + @Override + public int hashCode() { + return Objects.hash(_return); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelReturn {\n"); + + sb.append(" _return: ").append(toIndentedString(_return)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Name.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Name.java new file mode 100644 index 00000000000..36ddf799706 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Name.java @@ -0,0 +1,132 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + +/** + * Model for testing model name same as property name + **/ + +/** + * Model for testing model name same as property name + */ +@ApiModel(description = "Model for testing model name same as property name") + +public class Name { + @JsonProperty("name") + private Integer name = null; + + @JsonProperty("snake_case") + private Integer snakeCase = null; + + @JsonProperty("property") + private String property = null; + + @JsonProperty("123Number") + private Integer _123Number = null; + + public Name name(Integer name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(required = true, value = "") + public Integer getName() { + return name; + } + + public void setName(Integer name) { + this.name = name; + } + + /** + * Get snakeCase + * @return snakeCase + **/ + @ApiModelProperty(value = "") + public Integer getSnakeCase() { + return snakeCase; + } + + public Name property(String property) { + this.property = property; + return this; + } + + /** + * Get property + * @return property + **/ + @ApiModelProperty(value = "") + public String getProperty() { + return property; + } + + public void setProperty(String property) { + this.property = property; + } + + /** + * Get _123Number + * @return _123Number + **/ + @ApiModelProperty(value = "") + public Integer get123Number() { + return _123Number; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Name name = (Name) o; + return Objects.equals(this.name, name.name) && + Objects.equals(this.snakeCase, name.snakeCase) && + Objects.equals(this.property, name.property) && + Objects.equals(this._123Number, name._123Number); + } + + @Override + public int hashCode() { + return Objects.hash(name, snakeCase, property, _123Number); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Name {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); + sb.append(" property: ").append(toIndentedString(property)).append("\n"); + sb.append(" _123Number: ").append(toIndentedString(_123Number)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/NumberOnly.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/NumberOnly.java new file mode 100644 index 00000000000..5d13ab82782 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/NumberOnly.java @@ -0,0 +1,78 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; + + + + +/** + * NumberOnly + */ + +public class NumberOnly { + @JsonProperty("JustNumber") + private BigDecimal justNumber = null; + + public NumberOnly justNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + return this; + } + + /** + * Get justNumber + * @return justNumber + **/ + @ApiModelProperty(value = "") + public BigDecimal getJustNumber() { + return justNumber; + } + + public void setJustNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NumberOnly numberOnly = (NumberOnly) o; + return Objects.equals(this.justNumber, numberOnly.justNumber); + } + + @Override + public int hashCode() { + return Objects.hash(justNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NumberOnly {\n"); + + sb.append(" justNumber: ").append(toIndentedString(justNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Order.java index 825fa282b8b..11d16d8ed7b 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Order.java @@ -2,6 +2,7 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -10,19 +11,31 @@ - +/** + * Order + */ public class Order { - + @JsonProperty("id") private Long id = null; + + @JsonProperty("petId") private Long petId = null; + + @JsonProperty("quantity") private Integer quantity = null; - private Date shipDate = null; + @JsonProperty("shipDate") + private Date shipDate = null; + /** + * Order Status + */ public enum StatusEnum { PLACED("placed"), + APPROVED("approved"), + DELIVERED("delivered"); private String value; @@ -34,119 +47,137 @@ public enum StatusEnum { @Override @JsonValue public String toString() { - return value; + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; } } + @JsonProperty("status") private StatusEnum status = null; + + @JsonProperty("complete") private Boolean complete = false; - /** - **/ public Order id(Long id) { this.id = id; return this; } - + /** + * Get id + * @return id + **/ @ApiModelProperty(value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public Order petId(Long petId) { this.petId = petId; return this; } - + /** + * Get petId + * @return petId + **/ @ApiModelProperty(value = "") - @JsonProperty("petId") public Long getPetId() { return petId; } + public void setPetId(Long petId) { this.petId = petId; } - /** - **/ public Order quantity(Integer quantity) { this.quantity = quantity; return this; } - + /** + * Get quantity + * @return quantity + **/ @ApiModelProperty(value = "") - @JsonProperty("quantity") public Integer getQuantity() { return quantity; } + public void setQuantity(Integer quantity) { this.quantity = quantity; } - /** - **/ public Order shipDate(Date shipDate) { this.shipDate = shipDate; return this; } - + /** + * Get shipDate + * @return shipDate + **/ @ApiModelProperty(value = "") - @JsonProperty("shipDate") public Date getShipDate() { return shipDate; } + public void setShipDate(Date shipDate) { this.shipDate = shipDate; } - /** - * Order Status - **/ public Order status(StatusEnum status) { this.status = status; return this; } - + /** + * Order Status + * @return status + **/ @ApiModelProperty(value = "Order Status") - @JsonProperty("status") public StatusEnum getStatus() { return status; } + public void setStatus(StatusEnum status) { this.status = status; } - /** - **/ public Order complete(Boolean complete) { this.complete = complete; return this; } - + /** + * Get complete + * @return complete + **/ @ApiModelProperty(value = "") - @JsonProperty("complete") public Boolean getComplete() { return complete; } + public void setComplete(Boolean complete) { this.complete = complete; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -154,12 +185,12 @@ public boolean equals(Object o) { 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); + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); } @Override @@ -186,7 +217,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Pet.java index 24092cbee25..9189a91034b 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Pet.java @@ -2,6 +2,7 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -13,20 +14,34 @@ - +/** + * Pet + */ public class Pet { - + @JsonProperty("id") private Long id = null; + + @JsonProperty("category") private Category category = null; + + @JsonProperty("name") private String name = null; + + @JsonProperty("photoUrls") private List photoUrls = new ArrayList(); - private List tags = new ArrayList(); + @JsonProperty("tags") + private List tags = new ArrayList(); + /** + * pet status in the store + */ public enum StatusEnum { AVAILABLE("available"), + PENDING("pending"), + SOLD("sold"); private String value; @@ -38,118 +53,144 @@ public enum StatusEnum { @Override @JsonValue public String toString() { - return value; + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; } } + @JsonProperty("status") private StatusEnum status = null; - /** - **/ public Pet id(Long id) { this.id = id; return this; } - + /** + * Get id + * @return id + **/ @ApiModelProperty(value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public Pet category(Category category) { this.category = category; return this; } - + /** + * Get category + * @return category + **/ @ApiModelProperty(value = "") - @JsonProperty("category") public Category getCategory() { return category; } + public void setCategory(Category category) { this.category = category; } - /** - **/ public Pet name(String name) { this.name = name; return this; } - + /** + * Get name + * @return name + **/ @ApiModelProperty(example = "doggie", required = true, value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } - /** - **/ public Pet photoUrls(List photoUrls) { this.photoUrls = photoUrls; return this; } - + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + **/ @ApiModelProperty(required = true, value = "") - @JsonProperty("photoUrls") public List getPhotoUrls() { return photoUrls; } + public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } - /** - **/ public Pet tags(List tags) { this.tags = tags; return this; } - + public Pet addTagsItem(Tag tagsItem) { + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ @ApiModelProperty(value = "") - @JsonProperty("tags") public List getTags() { return tags; } + public void setTags(List tags) { this.tags = tags; } - /** - * pet status in the store - **/ public Pet status(StatusEnum status) { this.status = status; return this; } - + /** + * pet status in the store + * @return status + **/ @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) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -157,12 +198,12 @@ public boolean equals(Object o) { 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); + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); } @Override @@ -189,7 +230,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..826f7ca18c2 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ReadOnlyFirst.java @@ -0,0 +1,91 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + +/** + * ReadOnlyFirst + */ + +public class ReadOnlyFirst { + @JsonProperty("bar") + private String bar = null; + + @JsonProperty("baz") + private String baz = null; + + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(value = "") + public String getBar() { + return bar; + } + + public ReadOnlyFirst baz(String baz) { + this.baz = baz; + return this; + } + + /** + * Get baz + * @return baz + **/ + @ApiModelProperty(value = "") + public String getBaz() { + return baz; + } + + public void setBaz(String baz) { + this.baz = baz; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; + return Objects.equals(this.bar, readOnlyFirst.bar) && + Objects.equals(this.baz, readOnlyFirst.baz); + } + + @Override + public int hashCode() { + return Objects.hash(bar, baz); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/SpecialModelName.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/SpecialModelName.java new file mode 100644 index 00000000000..01b6be46d7f --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/SpecialModelName.java @@ -0,0 +1,77 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + +/** + * SpecialModelName + */ + +public class SpecialModelName { + @JsonProperty("$special[property.name]") + private Long specialPropertyName = null; + + public SpecialModelName specialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + return this; + } + + /** + * Get specialPropertyName + * @return specialPropertyName + **/ + @ApiModelProperty(value = "") + public Long getSpecialPropertyName() { + return specialPropertyName; + } + + public void setSpecialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SpecialModelName specialModelName = (SpecialModelName) o; + return Objects.equals(this.specialPropertyName, specialModelName.specialPropertyName); + } + + @Override + public int hashCode() { + return Objects.hash(specialPropertyName); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SpecialModelName {\n"); + + sb.append(" specialPropertyName: ").append(toIndentedString(specialPropertyName)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Tag.java index f26d84e74b2..e75d10df70e 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Tag.java @@ -2,56 +2,63 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +/** + * Tag + */ public class Tag { - + @JsonProperty("id") private Long id = null; + + @JsonProperty("name") private String name = null; - /** - **/ public Tag id(Long id) { this.id = id; return this; } - + /** + * Get id + * @return id + **/ @ApiModelProperty(value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public Tag name(String name) { this.name = name; return this; } - + /** + * Get name + * @return name + **/ @ApiModelProperty(value = "") - @JsonProperty("name") public String getName() { return name; } + public void setName(String name) { this.name = name; } @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -59,8 +66,8 @@ public boolean equals(Object o) { return false; } Tag tag = (Tag) o; - return Objects.equals(id, tag.id) && - Objects.equals(name, tag.name); + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); } @Override @@ -83,7 +90,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/User.java index 5dc291a7889..11a1a82a5cd 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/User.java @@ -2,165 +2,189 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +/** + * User + */ public class User { - + @JsonProperty("id") private Long id = null; + + @JsonProperty("username") private String username = null; + + @JsonProperty("firstName") private String firstName = null; + + @JsonProperty("lastName") private String lastName = null; + + @JsonProperty("email") private String email = null; + + @JsonProperty("password") private String password = null; + + @JsonProperty("phone") private String phone = null; + + @JsonProperty("userStatus") private Integer userStatus = null; - /** - **/ public User id(Long id) { this.id = id; return this; } - + /** + * Get id + * @return id + **/ @ApiModelProperty(value = "") - @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { this.id = id; } - /** - **/ public User username(String username) { this.username = username; return this; } - + /** + * Get username + * @return username + **/ @ApiModelProperty(value = "") - @JsonProperty("username") public String getUsername() { return username; } + public void setUsername(String username) { this.username = username; } - /** - **/ public User firstName(String firstName) { this.firstName = firstName; return this; } - + /** + * Get firstName + * @return firstName + **/ @ApiModelProperty(value = "") - @JsonProperty("firstName") public String getFirstName() { return firstName; } + public void setFirstName(String firstName) { this.firstName = firstName; } - /** - **/ public User lastName(String lastName) { this.lastName = lastName; return this; } - + /** + * Get lastName + * @return lastName + **/ @ApiModelProperty(value = "") - @JsonProperty("lastName") public String getLastName() { return lastName; } + public void setLastName(String lastName) { this.lastName = lastName; } - /** - **/ public User email(String email) { this.email = email; return this; } - + /** + * Get email + * @return email + **/ @ApiModelProperty(value = "") - @JsonProperty("email") public String getEmail() { return email; } + public void setEmail(String email) { this.email = email; } - /** - **/ public User password(String password) { this.password = password; return this; } - + /** + * Get password + * @return password + **/ @ApiModelProperty(value = "") - @JsonProperty("password") public String getPassword() { return password; } + public void setPassword(String password) { this.password = password; } - /** - **/ public User phone(String phone) { this.phone = phone; return this; } - + /** + * Get phone + * @return phone + **/ @ApiModelProperty(value = "") - @JsonProperty("phone") public String getPhone() { return phone; } + public void setPhone(String phone) { this.phone = phone; } - /** - * User Status - **/ public User userStatus(Integer userStatus) { this.userStatus = userStatus; return this; } - + /** + * User Status + * @return userStatus + **/ @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) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -168,14 +192,14 @@ public boolean equals(Object o) { 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); + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); } @Override @@ -204,7 +228,7 @@ public String toString() { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/Bootstrap.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/Bootstrap.java index 1f60ed6cf4b..5e5532439b7 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/Bootstrap.java +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/Bootstrap.java @@ -15,7 +15,7 @@ public class Bootstrap extends HttpServlet { public void init(ServletConfig config) throws ServletException { Info info = new Info() .title("Swagger Server") - .description("This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.") + .description("This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\") .termsOfService("http://swagger.io/terms/") .contact(new Contact() .email("apiteam@swagger.io")) diff --git a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/factories/FakeApiServiceFactory.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/factories/FakeApiServiceFactory.java new file mode 100644 index 00000000000..d4f8e013671 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/factories/FakeApiServiceFactory.java @@ -0,0 +1,13 @@ +package io.swagger.api.factories; + +import io.swagger.api.FakeApiService; +import io.swagger.api.impl.FakeApiServiceImpl; + + +public class FakeApiServiceFactory { + private final static FakeApiService service = new FakeApiServiceImpl(); + + public static FakeApiService getFakeApi() { + return service; + } +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java new file mode 100644 index 00000000000..2bc673c0121 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java @@ -0,0 +1,43 @@ +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import com.sun.jersey.multipart.FormDataParam; + +import io.swagger.model.Client; +import java.util.Date; +import java.math.BigDecimal; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + + +public class FakeApiServiceImpl extends FakeApiService { + @Override + public Response testClientModel(Client body, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, Date date, Date dateTime, String password, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } +} diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApi.java index 5f272c67e8c..22625b22746 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApi.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Client; -import java.time.OffsetDateTime; import java.time.LocalDate; +import java.time.OffsetDateTime; import java.math.BigDecimal; import io.swagger.annotations.*; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java index 8b23618a5a3..dca1545a5ef 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; import io.swagger.annotations.*; import org.springframework.http.HttpStatus; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/AdditionalPropertiesClass.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/AdditionalPropertiesClass.java index 4fee29a9ce9..4cc945f4087 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/AdditionalPropertiesClass.java @@ -17,8 +17,10 @@ */ public class AdditionalPropertiesClass { + @JsonProperty("map_property") private Map mapProperty = new HashMap(); + @JsonProperty("map_of_map_property") private Map> mapOfMapProperty = new HashMap>(); public AdditionalPropertiesClass mapProperty(Map mapProperty) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Animal.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Animal.java index 069968e1ea6..0e17c866e90 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Animal.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Animal.java @@ -14,8 +14,10 @@ */ public class Animal { + @JsonProperty("className") private String className = null; + @JsonProperty("color") private String color = "red"; public Animal className(String className) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java index 017b1439785..dc044068238 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java @@ -17,6 +17,7 @@ */ public class ArrayOfArrayOfNumberOnly { + @JsonProperty("ArrayArrayNumber") private List> arrayArrayNumber = new ArrayList>(); public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayOfNumberOnly.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayOfNumberOnly.java index 49edba4f8b1..f2906007107 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayOfNumberOnly.java @@ -17,6 +17,7 @@ */ public class ArrayOfNumberOnly { + @JsonProperty("ArrayNumber") private List arrayNumber = new ArrayList(); public ArrayOfNumberOnly arrayNumber(List arrayNumber) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayTest.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayTest.java index a4fff761563..c46fe7d9379 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayTest.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayTest.java @@ -17,10 +17,13 @@ */ public class ArrayTest { + @JsonProperty("array_of_string") private List arrayOfString = new ArrayList(); + @JsonProperty("array_array_of_integer") private List> arrayArrayOfInteger = new ArrayList>(); + @JsonProperty("array_array_of_model") private List> arrayArrayOfModel = new ArrayList>(); public ArrayTest arrayOfString(List arrayOfString) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Cat.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Cat.java index d36cbb7f2fa..c63afeb8ae1 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Cat.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Cat.java @@ -15,6 +15,7 @@ */ public class Cat extends Animal { + @JsonProperty("declawed") private Boolean declawed = null; public Cat declawed(Boolean declawed) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Category.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Category.java index 5039fd77a60..502d1c42bda 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Category.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Category.java @@ -14,8 +14,10 @@ */ public class Category { + @JsonProperty("id") private Long id = null; + @JsonProperty("name") private String name = null; public Category id(Long id) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Client.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Client.java index 8a793856bf1..bdfbb513c9e 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Client.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Client.java @@ -14,6 +14,7 @@ */ public class Client { + @JsonProperty("client") private String client = null; public Client client(String client) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Dog.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Dog.java index 4986d734b5c..f0acafc1398 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Dog.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Dog.java @@ -15,6 +15,7 @@ */ public class Dog extends Animal { + @JsonProperty("breed") private String breed = null; public Dog breed(String breed) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumArrays.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumArrays.java index c4b9601b6d1..b737fb00c64 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumArrays.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumArrays.java @@ -32,11 +32,23 @@ public enum JustSymbolEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static JustSymbolEnum fromValue(String text) { + for (JustSymbolEnum b : JustSymbolEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("just_symbol") private JustSymbolEnum justSymbol = null; /** @@ -54,11 +66,23 @@ public enum ArrayEnumEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static ArrayEnumEnum fromValue(String text) { + for (ArrayEnumEnum b : ArrayEnumEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("array_enum") private List arrayEnum = new ArrayList(); public EnumArrays justSymbol(JustSymbolEnum justSymbol) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumClass.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumClass.java index 2eb1a992f3e..ec7f34e4229 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumClass.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumClass.java @@ -5,6 +5,8 @@ +import com.fasterxml.jackson.annotation.JsonCreator; + /** * Gets or Sets EnumClass */ @@ -23,9 +25,20 @@ public enum EnumClass { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static EnumClass fromValue(String text) { + for (EnumClass b : EnumClass.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumTest.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumTest.java index 19e6568afc3..1f1f266c740 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumTest.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumTest.java @@ -30,11 +30,23 @@ public enum EnumStringEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static EnumStringEnum fromValue(String text) { + for (EnumStringEnum b : EnumStringEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("enum_string") private EnumStringEnum enumString = null; /** @@ -52,11 +64,23 @@ public enum EnumIntegerEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static EnumIntegerEnum fromValue(String text) { + for (EnumIntegerEnum b : EnumIntegerEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("enum_integer") private EnumIntegerEnum enumInteger = null; /** @@ -74,11 +98,23 @@ public enum EnumNumberEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static EnumNumberEnum fromValue(String text) { + for (EnumNumberEnum b : EnumNumberEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("enum_number") private EnumNumberEnum enumNumber = null; public EnumTest enumString(EnumStringEnum enumString) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/FormatTest.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/FormatTest.java index 4f2f7641bed..8b3c34fedb3 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/FormatTest.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/FormatTest.java @@ -17,30 +17,43 @@ */ public class FormatTest { + @JsonProperty("integer") private Integer integer = null; + @JsonProperty("int32") private Integer int32 = null; + @JsonProperty("int64") private Long int64 = null; + @JsonProperty("number") private BigDecimal number = null; + @JsonProperty("float") private Float _float = null; + @JsonProperty("double") private Double _double = null; + @JsonProperty("string") private String string = null; + @JsonProperty("byte") private byte[] _byte = null; + @JsonProperty("binary") private byte[] binary = null; + @JsonProperty("date") private LocalDate date = null; + @JsonProperty("dateTime") private OffsetDateTime dateTime = null; + @JsonProperty("uuid") private String uuid = null; + @JsonProperty("password") private String password = null; public FormatTest integer(Integer integer) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/HasOnlyReadOnly.java index 556b888eec8..6574a2262dd 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/HasOnlyReadOnly.java @@ -14,8 +14,10 @@ */ public class HasOnlyReadOnly { + @JsonProperty("bar") private String bar = null; + @JsonProperty("foo") private String foo = null; /** diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/MapTest.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/MapTest.java index 701aeb8baa8..33cdfbbc65f 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/MapTest.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/MapTest.java @@ -18,6 +18,7 @@ */ public class MapTest { + @JsonProperty("map_map_of_string") private Map> mapMapOfString = new HashMap>(); /** @@ -35,11 +36,23 @@ public enum InnerEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static InnerEnum fromValue(String text) { + for (InnerEnum b : InnerEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("map_of_enum_string") private Map mapOfEnumString = new HashMap(); public MapTest mapMapOfString(Map> mapMapOfString) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java index 8ca02f4aaa7..ecffd491f3f 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -19,10 +19,13 @@ */ public class MixedPropertiesAndAdditionalPropertiesClass { + @JsonProperty("uuid") private String uuid = null; + @JsonProperty("dateTime") private OffsetDateTime dateTime = null; + @JsonProperty("map") private Map map = new HashMap(); public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Model200Response.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Model200Response.java index e9f39c59bb5..bd7a6532214 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Model200Response.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Model200Response.java @@ -18,8 +18,10 @@ @ApiModel(description = "Model for testing model name starting with number") public class Model200Response { + @JsonProperty("name") private Integer name = null; + @JsonProperty("class") private String PropertyClass = null; public Model200Response name(Integer name) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelApiResponse.java index 512dcd5f43b..a8375a0abba 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelApiResponse.java @@ -14,10 +14,13 @@ */ public class ModelApiResponse { + @JsonProperty("code") private Integer code = null; + @JsonProperty("type") private String type = null; + @JsonProperty("message") private String message = null; public ModelApiResponse code(Integer code) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelReturn.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelReturn.java index 78513072ca1..32df0e60bd4 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelReturn.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelReturn.java @@ -18,6 +18,7 @@ @ApiModel(description = "Model for testing reserved words") public class ModelReturn { + @JsonProperty("return") private Integer _return = null; public ModelReturn _return(Integer _return) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Name.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Name.java index 5a2340d264b..36ddf799706 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Name.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Name.java @@ -18,12 +18,16 @@ @ApiModel(description = "Model for testing model name same as property name") public class Name { + @JsonProperty("name") private Integer name = null; + @JsonProperty("snake_case") private Integer snakeCase = null; + @JsonProperty("property") private String property = null; + @JsonProperty("123Number") private Integer _123Number = null; public Name name(Integer name) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/NumberOnly.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/NumberOnly.java index 12e9da2145a..5d13ab82782 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/NumberOnly.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/NumberOnly.java @@ -15,6 +15,7 @@ */ public class NumberOnly { + @JsonProperty("JustNumber") private BigDecimal justNumber = null; public NumberOnly justNumber(BigDecimal justNumber) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Order.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Order.java index b009933ed5b..03279ffa28a 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Order.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Order.java @@ -16,12 +16,16 @@ */ public class Order { + @JsonProperty("id") private Long id = null; + @JsonProperty("petId") private Long petId = null; + @JsonProperty("quantity") private Integer quantity = null; + @JsonProperty("shipDate") private OffsetDateTime shipDate = null; /** @@ -41,13 +45,26 @@ public enum StatusEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("status") private StatusEnum status = null; + @JsonProperty("complete") private Boolean complete = false; public Order id(Long id) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Pet.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Pet.java index 3592e1240dc..9189a91034b 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Pet.java @@ -19,14 +19,19 @@ */ public class Pet { + @JsonProperty("id") private Long id = null; + @JsonProperty("category") private Category category = null; + @JsonProperty("name") private String name = null; + @JsonProperty("photoUrls") private List photoUrls = new ArrayList(); + @JsonProperty("tags") private List tags = new ArrayList(); /** @@ -46,11 +51,23 @@ public enum StatusEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("status") private StatusEnum status = null; public Pet id(Long id) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ReadOnlyFirst.java index f9cd679d402..826f7ca18c2 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ReadOnlyFirst.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ReadOnlyFirst.java @@ -14,8 +14,10 @@ */ public class ReadOnlyFirst { + @JsonProperty("bar") private String bar = null; + @JsonProperty("baz") private String baz = null; /** diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/SpecialModelName.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/SpecialModelName.java index 1ebe4bc37d4..01b6be46d7f 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/SpecialModelName.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/SpecialModelName.java @@ -14,6 +14,7 @@ */ public class SpecialModelName { + @JsonProperty("$special[property.name]") private Long specialPropertyName = null; public SpecialModelName specialPropertyName(Long specialPropertyName) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Tag.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Tag.java index 9ebfa434af2..e75d10df70e 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Tag.java @@ -14,8 +14,10 @@ */ public class Tag { + @JsonProperty("id") private Long id = null; + @JsonProperty("name") private String name = null; public Tag id(Long id) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/User.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/User.java index 24abc50388a..11a1a82a5cd 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/User.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/User.java @@ -14,20 +14,28 @@ */ public class User { + @JsonProperty("id") private Long id = null; + @JsonProperty("username") private String username = null; + @JsonProperty("firstName") private String firstName = null; + @JsonProperty("lastName") private String lastName = null; + @JsonProperty("email") private String email = null; + @JsonProperty("password") private String password = null; + @JsonProperty("phone") private String phone = null; + @JsonProperty("userStatus") private Integer userStatus = null; public User id(Long id) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApi.java index f15fbe3b4ff..7efee499d27 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApi.java @@ -2,8 +2,8 @@ import io.swagger.model.Client; import org.joda.time.LocalDate; -import java.math.BigDecimal; import org.joda.time.DateTime; +import java.math.BigDecimal; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApiController.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApiController.java index 888a50ef542..95b2a742008 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApiController.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApiController.java @@ -2,8 +2,8 @@ import io.swagger.model.Client; import org.joda.time.LocalDate; -import java.math.BigDecimal; import org.joda.time.DateTime; +import java.math.BigDecimal; import io.swagger.annotations.*; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java index ea0122441c1..9b937019b32 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApiController.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApiController.java index 8b95d74de51..af909d49ab8 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApiController.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApiController.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; import io.swagger.annotations.*; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/AdditionalPropertiesClass.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/AdditionalPropertiesClass.java index 4fee29a9ce9..4cc945f4087 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/AdditionalPropertiesClass.java @@ -17,8 +17,10 @@ */ public class AdditionalPropertiesClass { + @JsonProperty("map_property") private Map mapProperty = new HashMap(); + @JsonProperty("map_of_map_property") private Map> mapOfMapProperty = new HashMap>(); public AdditionalPropertiesClass mapProperty(Map mapProperty) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Animal.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Animal.java index 069968e1ea6..0e17c866e90 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Animal.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Animal.java @@ -14,8 +14,10 @@ */ public class Animal { + @JsonProperty("className") private String className = null; + @JsonProperty("color") private String color = "red"; public Animal className(String className) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java index 017b1439785..dc044068238 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java @@ -17,6 +17,7 @@ */ public class ArrayOfArrayOfNumberOnly { + @JsonProperty("ArrayArrayNumber") private List> arrayArrayNumber = new ArrayList>(); public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayOfNumberOnly.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayOfNumberOnly.java index 49edba4f8b1..f2906007107 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayOfNumberOnly.java @@ -17,6 +17,7 @@ */ public class ArrayOfNumberOnly { + @JsonProperty("ArrayNumber") private List arrayNumber = new ArrayList(); public ArrayOfNumberOnly arrayNumber(List arrayNumber) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayTest.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayTest.java index a4fff761563..c46fe7d9379 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayTest.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayTest.java @@ -17,10 +17,13 @@ */ public class ArrayTest { + @JsonProperty("array_of_string") private List arrayOfString = new ArrayList(); + @JsonProperty("array_array_of_integer") private List> arrayArrayOfInteger = new ArrayList>(); + @JsonProperty("array_array_of_model") private List> arrayArrayOfModel = new ArrayList>(); public ArrayTest arrayOfString(List arrayOfString) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Cat.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Cat.java index d36cbb7f2fa..c63afeb8ae1 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Cat.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Cat.java @@ -15,6 +15,7 @@ */ public class Cat extends Animal { + @JsonProperty("declawed") private Boolean declawed = null; public Cat declawed(Boolean declawed) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Category.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Category.java index 5039fd77a60..502d1c42bda 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Category.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Category.java @@ -14,8 +14,10 @@ */ public class Category { + @JsonProperty("id") private Long id = null; + @JsonProperty("name") private String name = null; public Category id(Long id) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Client.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Client.java index 8a793856bf1..bdfbb513c9e 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Client.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Client.java @@ -14,6 +14,7 @@ */ public class Client { + @JsonProperty("client") private String client = null; public Client client(String client) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Dog.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Dog.java index 4986d734b5c..f0acafc1398 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Dog.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Dog.java @@ -15,6 +15,7 @@ */ public class Dog extends Animal { + @JsonProperty("breed") private String breed = null; public Dog breed(String breed) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumArrays.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumArrays.java index c4b9601b6d1..b737fb00c64 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumArrays.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumArrays.java @@ -32,11 +32,23 @@ public enum JustSymbolEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static JustSymbolEnum fromValue(String text) { + for (JustSymbolEnum b : JustSymbolEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("just_symbol") private JustSymbolEnum justSymbol = null; /** @@ -54,11 +66,23 @@ public enum ArrayEnumEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static ArrayEnumEnum fromValue(String text) { + for (ArrayEnumEnum b : ArrayEnumEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("array_enum") private List arrayEnum = new ArrayList(); public EnumArrays justSymbol(JustSymbolEnum justSymbol) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumClass.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumClass.java index 2eb1a992f3e..ec7f34e4229 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumClass.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumClass.java @@ -5,6 +5,8 @@ +import com.fasterxml.jackson.annotation.JsonCreator; + /** * Gets or Sets EnumClass */ @@ -23,9 +25,20 @@ public enum EnumClass { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static EnumClass fromValue(String text) { + for (EnumClass b : EnumClass.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumTest.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumTest.java index 19e6568afc3..1f1f266c740 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumTest.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumTest.java @@ -30,11 +30,23 @@ public enum EnumStringEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static EnumStringEnum fromValue(String text) { + for (EnumStringEnum b : EnumStringEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("enum_string") private EnumStringEnum enumString = null; /** @@ -52,11 +64,23 @@ public enum EnumIntegerEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static EnumIntegerEnum fromValue(String text) { + for (EnumIntegerEnum b : EnumIntegerEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("enum_integer") private EnumIntegerEnum enumInteger = null; /** @@ -74,11 +98,23 @@ public enum EnumNumberEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static EnumNumberEnum fromValue(String text) { + for (EnumNumberEnum b : EnumNumberEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("enum_number") private EnumNumberEnum enumNumber = null; public EnumTest enumString(EnumStringEnum enumString) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/FormatTest.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/FormatTest.java index e9f6852eae9..db755ca5137 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/FormatTest.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/FormatTest.java @@ -17,30 +17,43 @@ */ public class FormatTest { + @JsonProperty("integer") private Integer integer = null; + @JsonProperty("int32") private Integer int32 = null; + @JsonProperty("int64") private Long int64 = null; + @JsonProperty("number") private BigDecimal number = null; + @JsonProperty("float") private Float _float = null; + @JsonProperty("double") private Double _double = null; + @JsonProperty("string") private String string = null; + @JsonProperty("byte") private byte[] _byte = null; + @JsonProperty("binary") private byte[] binary = null; + @JsonProperty("date") private LocalDate date = null; + @JsonProperty("dateTime") private DateTime dateTime = null; + @JsonProperty("uuid") private String uuid = null; + @JsonProperty("password") private String password = null; public FormatTest integer(Integer integer) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/HasOnlyReadOnly.java index 556b888eec8..6574a2262dd 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/HasOnlyReadOnly.java @@ -14,8 +14,10 @@ */ public class HasOnlyReadOnly { + @JsonProperty("bar") private String bar = null; + @JsonProperty("foo") private String foo = null; /** diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/MapTest.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/MapTest.java index 701aeb8baa8..33cdfbbc65f 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/MapTest.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/MapTest.java @@ -18,6 +18,7 @@ */ public class MapTest { + @JsonProperty("map_map_of_string") private Map> mapMapOfString = new HashMap>(); /** @@ -35,11 +36,23 @@ public enum InnerEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static InnerEnum fromValue(String text) { + for (InnerEnum b : InnerEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("map_of_enum_string") private Map mapOfEnumString = new HashMap(); public MapTest mapMapOfString(Map> mapMapOfString) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java index 763614b8c9a..98597929ad6 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -19,10 +19,13 @@ */ public class MixedPropertiesAndAdditionalPropertiesClass { + @JsonProperty("uuid") private String uuid = null; + @JsonProperty("dateTime") private DateTime dateTime = null; + @JsonProperty("map") private Map map = new HashMap(); public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Model200Response.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Model200Response.java index e9f39c59bb5..bd7a6532214 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Model200Response.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Model200Response.java @@ -18,8 +18,10 @@ @ApiModel(description = "Model for testing model name starting with number") public class Model200Response { + @JsonProperty("name") private Integer name = null; + @JsonProperty("class") private String PropertyClass = null; public Model200Response name(Integer name) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ModelApiResponse.java index 512dcd5f43b..a8375a0abba 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ModelApiResponse.java @@ -14,10 +14,13 @@ */ public class ModelApiResponse { + @JsonProperty("code") private Integer code = null; + @JsonProperty("type") private String type = null; + @JsonProperty("message") private String message = null; public ModelApiResponse code(Integer code) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ModelReturn.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ModelReturn.java index 78513072ca1..32df0e60bd4 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ModelReturn.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ModelReturn.java @@ -18,6 +18,7 @@ @ApiModel(description = "Model for testing reserved words") public class ModelReturn { + @JsonProperty("return") private Integer _return = null; public ModelReturn _return(Integer _return) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Name.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Name.java index 5a2340d264b..36ddf799706 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Name.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Name.java @@ -18,12 +18,16 @@ @ApiModel(description = "Model for testing model name same as property name") public class Name { + @JsonProperty("name") private Integer name = null; + @JsonProperty("snake_case") private Integer snakeCase = null; + @JsonProperty("property") private String property = null; + @JsonProperty("123Number") private Integer _123Number = null; public Name name(Integer name) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/NumberOnly.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/NumberOnly.java index 12e9da2145a..5d13ab82782 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/NumberOnly.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/NumberOnly.java @@ -15,6 +15,7 @@ */ public class NumberOnly { + @JsonProperty("JustNumber") private BigDecimal justNumber = null; public NumberOnly justNumber(BigDecimal justNumber) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Order.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Order.java index 0cd70bfd939..09fe1ee39c3 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Order.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Order.java @@ -16,12 +16,16 @@ */ public class Order { + @JsonProperty("id") private Long id = null; + @JsonProperty("petId") private Long petId = null; + @JsonProperty("quantity") private Integer quantity = null; + @JsonProperty("shipDate") private DateTime shipDate = null; /** @@ -41,13 +45,26 @@ public enum StatusEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("status") private StatusEnum status = null; + @JsonProperty("complete") private Boolean complete = false; public Order id(Long id) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Pet.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Pet.java index 3592e1240dc..9189a91034b 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Pet.java @@ -19,14 +19,19 @@ */ public class Pet { + @JsonProperty("id") private Long id = null; + @JsonProperty("category") private Category category = null; + @JsonProperty("name") private String name = null; + @JsonProperty("photoUrls") private List photoUrls = new ArrayList(); + @JsonProperty("tags") private List tags = new ArrayList(); /** @@ -46,11 +51,23 @@ public enum StatusEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("status") private StatusEnum status = null; public Pet id(Long id) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ReadOnlyFirst.java index f9cd679d402..826f7ca18c2 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ReadOnlyFirst.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ReadOnlyFirst.java @@ -14,8 +14,10 @@ */ public class ReadOnlyFirst { + @JsonProperty("bar") private String bar = null; + @JsonProperty("baz") private String baz = null; /** diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/SpecialModelName.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/SpecialModelName.java index 1ebe4bc37d4..01b6be46d7f 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/SpecialModelName.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/SpecialModelName.java @@ -14,6 +14,7 @@ */ public class SpecialModelName { + @JsonProperty("$special[property.name]") private Long specialPropertyName = null; public SpecialModelName specialPropertyName(Long specialPropertyName) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Tag.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Tag.java index 9ebfa434af2..e75d10df70e 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Tag.java @@ -14,8 +14,10 @@ */ public class Tag { + @JsonProperty("id") private Long id = null; + @JsonProperty("name") private String name = null; public Tag id(Long id) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/User.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/User.java index 24abc50388a..11a1a82a5cd 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/User.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/User.java @@ -14,20 +14,28 @@ */ public class User { + @JsonProperty("id") private Long id = null; + @JsonProperty("username") private String username = null; + @JsonProperty("firstName") private String firstName = null; + @JsonProperty("lastName") private String lastName = null; + @JsonProperty("email") private String email = null; + @JsonProperty("password") private String password = null; + @JsonProperty("phone") private String phone = null; + @JsonProperty("userStatus") private Integer userStatus = null; public User id(Long id) { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApi.java index f15fbe3b4ff..7efee499d27 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApi.java @@ -2,8 +2,8 @@ import io.swagger.model.Client; import org.joda.time.LocalDate; -import java.math.BigDecimal; import org.joda.time.DateTime; +import java.math.BigDecimal; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApiController.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApiController.java index 888a50ef542..95b2a742008 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApiController.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApiController.java @@ -2,8 +2,8 @@ import io.swagger.model.Client; import org.joda.time.LocalDate; -import java.math.BigDecimal; import org.joda.time.DateTime; +import java.math.BigDecimal; import io.swagger.annotations.*; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java index ea0122441c1..9b937019b32 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java index 8b95d74de51..af909d49ab8 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; import io.swagger.annotations.*; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/AdditionalPropertiesClass.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/AdditionalPropertiesClass.java index 4fee29a9ce9..4cc945f4087 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/AdditionalPropertiesClass.java @@ -17,8 +17,10 @@ */ public class AdditionalPropertiesClass { + @JsonProperty("map_property") private Map mapProperty = new HashMap(); + @JsonProperty("map_of_map_property") private Map> mapOfMapProperty = new HashMap>(); public AdditionalPropertiesClass mapProperty(Map mapProperty) { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Animal.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Animal.java index 069968e1ea6..0e17c866e90 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Animal.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Animal.java @@ -14,8 +14,10 @@ */ public class Animal { + @JsonProperty("className") private String className = null; + @JsonProperty("color") private String color = "red"; public Animal className(String className) { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java index 017b1439785..dc044068238 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java @@ -17,6 +17,7 @@ */ public class ArrayOfArrayOfNumberOnly { + @JsonProperty("ArrayArrayNumber") private List> arrayArrayNumber = new ArrayList>(); public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ArrayOfNumberOnly.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ArrayOfNumberOnly.java index 49edba4f8b1..f2906007107 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ArrayOfNumberOnly.java @@ -17,6 +17,7 @@ */ public class ArrayOfNumberOnly { + @JsonProperty("ArrayNumber") private List arrayNumber = new ArrayList(); public ArrayOfNumberOnly arrayNumber(List arrayNumber) { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ArrayTest.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ArrayTest.java index a4fff761563..c46fe7d9379 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ArrayTest.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ArrayTest.java @@ -17,10 +17,13 @@ */ public class ArrayTest { + @JsonProperty("array_of_string") private List arrayOfString = new ArrayList(); + @JsonProperty("array_array_of_integer") private List> arrayArrayOfInteger = new ArrayList>(); + @JsonProperty("array_array_of_model") private List> arrayArrayOfModel = new ArrayList>(); public ArrayTest arrayOfString(List arrayOfString) { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Cat.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Cat.java index d36cbb7f2fa..c63afeb8ae1 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Cat.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Cat.java @@ -15,6 +15,7 @@ */ public class Cat extends Animal { + @JsonProperty("declawed") private Boolean declawed = null; public Cat declawed(Boolean declawed) { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Category.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Category.java index 5039fd77a60..502d1c42bda 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Category.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Category.java @@ -14,8 +14,10 @@ */ public class Category { + @JsonProperty("id") private Long id = null; + @JsonProperty("name") private String name = null; public Category id(Long id) { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Client.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Client.java index 8a793856bf1..bdfbb513c9e 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Client.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Client.java @@ -14,6 +14,7 @@ */ public class Client { + @JsonProperty("client") private String client = null; public Client client(String client) { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Dog.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Dog.java index 4986d734b5c..f0acafc1398 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Dog.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Dog.java @@ -15,6 +15,7 @@ */ public class Dog extends Animal { + @JsonProperty("breed") private String breed = null; public Dog breed(String breed) { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumArrays.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumArrays.java index c4b9601b6d1..b737fb00c64 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumArrays.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumArrays.java @@ -32,11 +32,23 @@ public enum JustSymbolEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static JustSymbolEnum fromValue(String text) { + for (JustSymbolEnum b : JustSymbolEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("just_symbol") private JustSymbolEnum justSymbol = null; /** @@ -54,11 +66,23 @@ public enum ArrayEnumEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static ArrayEnumEnum fromValue(String text) { + for (ArrayEnumEnum b : ArrayEnumEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("array_enum") private List arrayEnum = new ArrayList(); public EnumArrays justSymbol(JustSymbolEnum justSymbol) { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumClass.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumClass.java index 2eb1a992f3e..ec7f34e4229 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumClass.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumClass.java @@ -5,6 +5,8 @@ +import com.fasterxml.jackson.annotation.JsonCreator; + /** * Gets or Sets EnumClass */ @@ -23,9 +25,20 @@ public enum EnumClass { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static EnumClass fromValue(String text) { + for (EnumClass b : EnumClass.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumTest.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumTest.java index 19e6568afc3..1f1f266c740 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumTest.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumTest.java @@ -30,11 +30,23 @@ public enum EnumStringEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static EnumStringEnum fromValue(String text) { + for (EnumStringEnum b : EnumStringEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("enum_string") private EnumStringEnum enumString = null; /** @@ -52,11 +64,23 @@ public enum EnumIntegerEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static EnumIntegerEnum fromValue(String text) { + for (EnumIntegerEnum b : EnumIntegerEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("enum_integer") private EnumIntegerEnum enumInteger = null; /** @@ -74,11 +98,23 @@ public enum EnumNumberEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static EnumNumberEnum fromValue(String text) { + for (EnumNumberEnum b : EnumNumberEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("enum_number") private EnumNumberEnum enumNumber = null; public EnumTest enumString(EnumStringEnum enumString) { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/FormatTest.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/FormatTest.java index e9f6852eae9..db755ca5137 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/FormatTest.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/FormatTest.java @@ -17,30 +17,43 @@ */ public class FormatTest { + @JsonProperty("integer") private Integer integer = null; + @JsonProperty("int32") private Integer int32 = null; + @JsonProperty("int64") private Long int64 = null; + @JsonProperty("number") private BigDecimal number = null; + @JsonProperty("float") private Float _float = null; + @JsonProperty("double") private Double _double = null; + @JsonProperty("string") private String string = null; + @JsonProperty("byte") private byte[] _byte = null; + @JsonProperty("binary") private byte[] binary = null; + @JsonProperty("date") private LocalDate date = null; + @JsonProperty("dateTime") private DateTime dateTime = null; + @JsonProperty("uuid") private String uuid = null; + @JsonProperty("password") private String password = null; public FormatTest integer(Integer integer) { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/HasOnlyReadOnly.java index 556b888eec8..6574a2262dd 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/HasOnlyReadOnly.java @@ -14,8 +14,10 @@ */ public class HasOnlyReadOnly { + @JsonProperty("bar") private String bar = null; + @JsonProperty("foo") private String foo = null; /** diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/MapTest.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/MapTest.java index 701aeb8baa8..33cdfbbc65f 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/MapTest.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/MapTest.java @@ -18,6 +18,7 @@ */ public class MapTest { + @JsonProperty("map_map_of_string") private Map> mapMapOfString = new HashMap>(); /** @@ -35,11 +36,23 @@ public enum InnerEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static InnerEnum fromValue(String text) { + for (InnerEnum b : InnerEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("map_of_enum_string") private Map mapOfEnumString = new HashMap(); public MapTest mapMapOfString(Map> mapMapOfString) { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java index 763614b8c9a..98597929ad6 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -19,10 +19,13 @@ */ public class MixedPropertiesAndAdditionalPropertiesClass { + @JsonProperty("uuid") private String uuid = null; + @JsonProperty("dateTime") private DateTime dateTime = null; + @JsonProperty("map") private Map map = new HashMap(); public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Model200Response.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Model200Response.java index e9f39c59bb5..bd7a6532214 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Model200Response.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Model200Response.java @@ -18,8 +18,10 @@ @ApiModel(description = "Model for testing model name starting with number") public class Model200Response { + @JsonProperty("name") private Integer name = null; + @JsonProperty("class") private String PropertyClass = null; public Model200Response name(Integer name) { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelApiResponse.java index 512dcd5f43b..a8375a0abba 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelApiResponse.java @@ -14,10 +14,13 @@ */ public class ModelApiResponse { + @JsonProperty("code") private Integer code = null; + @JsonProperty("type") private String type = null; + @JsonProperty("message") private String message = null; public ModelApiResponse code(Integer code) { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelReturn.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelReturn.java index 78513072ca1..32df0e60bd4 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelReturn.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelReturn.java @@ -18,6 +18,7 @@ @ApiModel(description = "Model for testing reserved words") public class ModelReturn { + @JsonProperty("return") private Integer _return = null; public ModelReturn _return(Integer _return) { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Name.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Name.java index 5a2340d264b..36ddf799706 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Name.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Name.java @@ -18,12 +18,16 @@ @ApiModel(description = "Model for testing model name same as property name") public class Name { + @JsonProperty("name") private Integer name = null; + @JsonProperty("snake_case") private Integer snakeCase = null; + @JsonProperty("property") private String property = null; + @JsonProperty("123Number") private Integer _123Number = null; public Name name(Integer name) { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/NumberOnly.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/NumberOnly.java index 12e9da2145a..5d13ab82782 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/NumberOnly.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/NumberOnly.java @@ -15,6 +15,7 @@ */ public class NumberOnly { + @JsonProperty("JustNumber") private BigDecimal justNumber = null; public NumberOnly justNumber(BigDecimal justNumber) { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Order.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Order.java index 0cd70bfd939..09fe1ee39c3 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Order.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Order.java @@ -16,12 +16,16 @@ */ public class Order { + @JsonProperty("id") private Long id = null; + @JsonProperty("petId") private Long petId = null; + @JsonProperty("quantity") private Integer quantity = null; + @JsonProperty("shipDate") private DateTime shipDate = null; /** @@ -41,13 +45,26 @@ public enum StatusEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("status") private StatusEnum status = null; + @JsonProperty("complete") private Boolean complete = false; public Order id(Long id) { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Pet.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Pet.java index 3592e1240dc..9189a91034b 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Pet.java @@ -19,14 +19,19 @@ */ public class Pet { + @JsonProperty("id") private Long id = null; + @JsonProperty("category") private Category category = null; + @JsonProperty("name") private String name = null; + @JsonProperty("photoUrls") private List photoUrls = new ArrayList(); + @JsonProperty("tags") private List tags = new ArrayList(); /** @@ -46,11 +51,23 @@ public enum StatusEnum { } @Override + @JsonValue public String toString() { return String.valueOf(value); } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } } + @JsonProperty("status") private StatusEnum status = null; public Pet id(Long id) { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ReadOnlyFirst.java index f9cd679d402..826f7ca18c2 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ReadOnlyFirst.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ReadOnlyFirst.java @@ -14,8 +14,10 @@ */ public class ReadOnlyFirst { + @JsonProperty("bar") private String bar = null; + @JsonProperty("baz") private String baz = null; /** diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/SpecialModelName.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/SpecialModelName.java index 1ebe4bc37d4..01b6be46d7f 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/SpecialModelName.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/SpecialModelName.java @@ -14,6 +14,7 @@ */ public class SpecialModelName { + @JsonProperty("$special[property.name]") private Long specialPropertyName = null; public SpecialModelName specialPropertyName(Long specialPropertyName) { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Tag.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Tag.java index 9ebfa434af2..e75d10df70e 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Tag.java @@ -14,8 +14,10 @@ */ public class Tag { + @JsonProperty("id") private Long id = null; + @JsonProperty("name") private String name = null; public Tag id(Long id) { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/User.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/User.java index 24abc50388a..11a1a82a5cd 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/User.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/User.java @@ -14,20 +14,28 @@ */ public class User { + @JsonProperty("id") private Long id = null; + @JsonProperty("username") private String username = null; + @JsonProperty("firstName") private String firstName = null; + @JsonProperty("lastName") private String lastName = null; + @JsonProperty("email") private String email = null; + @JsonProperty("password") private String password = null; + @JsonProperty("phone") private String phone = null; + @JsonProperty("userStatus") private Integer userStatus = null; public User id(Long id) { From 44c8893ed5ca31345f6a7524394403b0b0358847 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 21 Aug 2016 12:18:45 +0800 Subject: [PATCH 266/470] update wording --- .github/ISSUE_TEMPLATE.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index 9a56dca7f02..89e344b08d2 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -5,7 +5,7 @@ Also please indicate in the issue title which language/library is concerned. Eg: ##### Description - + ##### Swagger-codegen version @@ -37,7 +37,7 @@ Also please indicate in the issue title which language/library is concerned. Eg: ##### Related issues - + ##### Suggest a Fix From 4d945119350e3c23452c33825148763596304cb4 Mon Sep 17 00:00:00 2001 From: regga-ws Date: Mon, 22 Aug 2016 10:04:53 +0200 Subject: [PATCH 267/470] Allowing generators to be aware of original inputSpec path (#3592) * Enabling knowledge of inputSpec path for custom generators * Enabling knowledge of inputSpec path for custom generators * Enabling direct use of "inputSpec" property in templates * Fixing spaces --- .../main/java/io/swagger/codegen/CodegenConfig.java | 4 ++++ .../main/java/io/swagger/codegen/DefaultCodegen.java | 11 ++++++++++- .../java/io/swagger/codegen/DefaultGenerator.java | 3 ++- .../swagger/codegen/config/CodegenConfigurator.java | 1 + 4 files changed, 17 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java index 1f3d59432bd..4b0ef89593f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java @@ -79,6 +79,10 @@ public interface CodegenConfig { List supportingFiles(); + String getInputSpec(); + + void setInputSpec(String inputSpec); + String getOutputDir(); void setOutputDir(String dir); 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 9ead076eb23..f7138a8f5f8 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 @@ -73,7 +73,8 @@ public class DefaultCodegen { protected static final Logger LOGGER = LoggerFactory.getLogger(DefaultCodegen.class); - + + protected String inputSpec; protected String outputFolder = ""; protected Set defaultIncludes = new HashSet(); protected Map typeMapping = new HashMap(); @@ -507,6 +508,14 @@ public String getOutputDir() { return outputFolder(); } + public String getInputSpec() { + return inputSpec; + } + + public void setInputSpec(String inputSpec) { + this.inputSpec = inputSpec; + } + public void setTemplateDir(String templateDir) { this.templateDir = templateDir; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index 2a095b8f914..90059a85b57 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -140,7 +140,8 @@ public List generate() { config.additionalProperties().put("generatedDate", DateTime.now().toString()); config.additionalProperties().put("generatorClass", config.getClass().toString()); - + config.additionalProperties().put("inputSpec", config.getInputSpec()); + if (swagger.getInfo() != null) { Info info = swagger.getInfo(); if (info.getTitle() != null) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java index 4ac39d5296f..5b572645513 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java @@ -352,6 +352,7 @@ public ClientOptInput toClientOptInput() { CodegenConfig config = CodegenConfigLoader.forName(lang); + config.setInputSpec(inputSpec); config.setOutputDir(outputDir); config.setSkipOverwrite(skipOverwrite); From a58845bb0f8b723429eb58ad40ecfb1f42c56fdb Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 22 Aug 2016 18:01:06 +0800 Subject: [PATCH 268/470] add function to handle missing delimiter in regex --- .../io/swagger/codegen/DefaultCodegen.java | 17 ++++- .../codegen/languages/RubyClientCodegen.java | 1 + ...ith-fake-endpoints-models-for-testing.yaml | 9 ++- samples/client/petstore/python/README.md | 14 ++-- .../client/petstore/python/docs/FakeApi.md | 10 ++- .../python/petstore_api/apis/fake_api.py | 34 +++++---- .../python/petstore_api/configuration.py | 14 ++-- samples/client/petstore/ruby/README.md | 16 ++-- samples/client/petstore/ruby/docs/FakeApi.md | 42 ++++++++--- .../ruby/lib/petstore/api/fake_api.rb | 75 ++++++++++++++----- .../ruby/lib/petstore/configuration.rb | 15 +++- 11 files changed, 171 insertions(+), 76 deletions(-) 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 9ead076eb23..81adc752af7 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 @@ -542,7 +542,7 @@ public void setEnsureUniqueParams(Boolean ensureUniqueParams) { * @return properly-escaped pattern */ public String toRegularExpression(String pattern) { - return escapeText(pattern); + return escapeText(addRegularExpressionDelimiter(pattern)); } /** @@ -3264,4 +3264,19 @@ public void updateCodegenPropertyEnum(CodegenProperty var) { } } } + + /** + * If the pattern misses the delimiter, add "/" to the beginning and end + * Otherwise, return the original pattern + * + * @param pattern the pattern (regular expression) + * @return the pattern with delimiter + */ + public String addRegularExpressionDelimiter(String pattern) { + if (pattern != null && !pattern.matches("^/.*")) { + return "/" + pattern + "/"; + } + + return pattern; + } } 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 a2fc199d586..eaf83992b5f 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 @@ -727,4 +727,5 @@ public String escapeQuotationMark(String input) { public String escapeUnsafeCharacters(String input) { return input.replace("=end", "=_end").replace("=begin", "=_begin"); } + } diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml index 266726ec4bc..2eab12fc9ba 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml @@ -597,7 +597,7 @@ paths: - name: enum_form_string_array type: array items: - tyep: string + type: string default: '$' enum: - '>' @@ -616,7 +616,7 @@ paths: - name: enum_header_string_array type: array items: - tyep: string + type: string default: '$' enum: - '>' @@ -737,6 +737,11 @@ paths: pattern: /[a-z]/i in: formData description: None + - name: pattern_without_delimiter + type: string + pattern: "^[A-Z].*" + in: formData + description: None required: true - name: byte type: string diff --git a/samples/client/petstore/python/README.md b/samples/client/petstore/python/README.md index 98e060ea271..db827de9ceb 100644 --- a/samples/client/petstore/python/README.md +++ b/samples/client/petstore/python/README.md @@ -5,7 +5,7 @@ This Python package is automatically generated by the [Swagger Codegen](https:// - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-08-15T23:29:03.602+01:00 +- Build date: 2016-08-22T17:54:52.358+08:00 - Build package: class io.swagger.codegen.languages.PythonClientCodegen ## Requirements. @@ -130,6 +130,12 @@ Class | Method | HTTP request | Description ## Documentation For Authorization +## api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + ## petstore_auth - **Type**: OAuth @@ -143,12 +149,6 @@ Class | Method | HTTP request | Description - **Type**: HTTP basic authentication -## api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - ## Author diff --git a/samples/client/petstore/python/docs/FakeApi.md b/samples/client/petstore/python/docs/FakeApi.md index 0d03962a8d5..cb88dd79d0d 100644 --- a/samples/client/petstore/python/docs/FakeApi.md +++ b/samples/client/petstore/python/docs/FakeApi.md @@ -55,7 +55,7 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **test_endpoint_parameters** -> test_endpoint_parameters(number, double, string, byte, integer=integer, int32=int32, int64=int64, float=float, binary=binary, date=date, date_time=date_time, password=password) +> test_endpoint_parameters(number, double, pattern_without_delimiter, byte, integer=integer, int32=int32, int64=int64, float=float, string=string, binary=binary, date=date, date_time=date_time, password=password) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -76,12 +76,13 @@ petstore_api.configuration.password = 'YOUR_PASSWORD' api_instance = petstore_api.FakeApi() number = 3.4 # float | None double = 1.2 # float | None -string = 'string_example' # str | None +pattern_without_delimiter = 'pattern_without_delimiter_example' # str | None byte = 'B' # str | None integer = 56 # int | None (optional) int32 = 56 # int | None (optional) int64 = 789 # int | None (optional) float = 3.4 # float | None (optional) +string = 'string_example' # str | None (optional) binary = 'B' # str | None (optional) date = '2013-10-20' # date | None (optional) date_time = '2013-10-20T19:20:30+01:00' # datetime | None (optional) @@ -89,7 +90,7 @@ password = 'password_example' # str | None (optional) try: # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - api_instance.test_endpoint_parameters(number, double, string, byte, integer=integer, int32=int32, int64=int64, float=float, binary=binary, date=date, date_time=date_time, password=password) + api_instance.test_endpoint_parameters(number, double, pattern_without_delimiter, byte, integer=integer, int32=int32, int64=int64, float=float, string=string, binary=binary, date=date, date_time=date_time, password=password) except ApiException as e: print "Exception when calling FakeApi->test_endpoint_parameters: %s\n" % e ``` @@ -100,12 +101,13 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **number** | **float**| None | **double** | **float**| None | - **string** | **str**| None | + **pattern_without_delimiter** | **str**| None | **byte** | **str**| None | **integer** | **int**| None | [optional] **int32** | **int**| None | [optional] **int64** | **int**| None | [optional] **float** | **float**| None | [optional] + **string** | **str**| None | [optional] **binary** | **str**| None | [optional] **date** | **date**| None | [optional] **date_time** | **datetime**| None | [optional] diff --git a/samples/client/petstore/python/petstore_api/apis/fake_api.py b/samples/client/petstore/python/petstore_api/apis/fake_api.py index 76cf960c6e9..6a2dd0b852a 100644 --- a/samples/client/petstore/python/petstore_api/apis/fake_api.py +++ b/samples/client/petstore/python/petstore_api/apis/fake_api.py @@ -155,7 +155,7 @@ def test_client_model_with_http_info(self, body, **kwargs): callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only')) - def test_endpoint_parameters(self, number, double, string, byte, **kwargs): + def test_endpoint_parameters(self, number, double, pattern_without_delimiter, byte, **kwargs): """ Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -166,18 +166,19 @@ def test_endpoint_parameters(self, number, double, string, byte, **kwargs): >>> def callback_function(response): >>> pprint(response) >>> - >>> thread = api.test_endpoint_parameters(number, double, string, byte, callback=callback_function) + >>> thread = api.test_endpoint_parameters(number, double, pattern_without_delimiter, byte, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param float number: None (required) :param float double: None (required) - :param str string: None (required) + :param str pattern_without_delimiter: None (required) :param str byte: None (required) :param int integer: None :param int int32: None :param int int64: None :param float float: None + :param str string: None :param str binary: None :param date date: None :param datetime date_time: None @@ -188,12 +189,12 @@ def test_endpoint_parameters(self, number, double, string, byte, **kwargs): """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): - return self.test_endpoint_parameters_with_http_info(number, double, string, byte, **kwargs) + return self.test_endpoint_parameters_with_http_info(number, double, pattern_without_delimiter, byte, **kwargs) else: - (data) = self.test_endpoint_parameters_with_http_info(number, double, string, byte, **kwargs) + (data) = self.test_endpoint_parameters_with_http_info(number, double, pattern_without_delimiter, byte, **kwargs) return data - def test_endpoint_parameters_with_http_info(self, number, double, string, byte, **kwargs): + def test_endpoint_parameters_with_http_info(self, number, double, pattern_without_delimiter, byte, **kwargs): """ Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -204,18 +205,19 @@ def test_endpoint_parameters_with_http_info(self, number, double, string, byte, >>> def callback_function(response): >>> pprint(response) >>> - >>> thread = api.test_endpoint_parameters_with_http_info(number, double, string, byte, callback=callback_function) + >>> thread = api.test_endpoint_parameters_with_http_info(number, double, pattern_without_delimiter, byte, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param float number: None (required) :param float double: None (required) - :param str string: None (required) + :param str pattern_without_delimiter: None (required) :param str byte: None (required) :param int integer: None :param int int32: None :param int int64: None :param float float: None + :param str string: None :param str binary: None :param date date: None :param datetime date_time: None @@ -225,7 +227,7 @@ def test_endpoint_parameters_with_http_info(self, number, double, string, byte, returns the request thread. """ - all_params = ['number', 'double', 'string', 'byte', 'integer', 'int32', 'int64', 'float', 'binary', 'date', 'date_time', 'password'] + all_params = ['number', 'double', 'pattern_without_delimiter', 'byte', 'integer', 'int32', 'int64', 'float', 'string', 'binary', 'date', 'date_time', 'password'] all_params.append('callback') all_params.append('_return_http_data_only') @@ -244,9 +246,9 @@ def test_endpoint_parameters_with_http_info(self, number, double, string, byte, # verify the required parameter 'double' is set if ('double' not in params) or (params['double'] is None): raise ValueError("Missing the required parameter `double` when calling `test_endpoint_parameters`") - # verify the required parameter 'string' is set - if ('string' not in params) or (params['string'] is None): - raise ValueError("Missing the required parameter `string` when calling `test_endpoint_parameters`") + # verify the required parameter 'pattern_without_delimiter' is set + if ('pattern_without_delimiter' not in params) or (params['pattern_without_delimiter'] is None): + raise ValueError("Missing the required parameter `pattern_without_delimiter` when calling `test_endpoint_parameters`") # verify the required parameter 'byte' is set if ('byte' not in params) or (params['byte'] is None): raise ValueError("Missing the required parameter `byte` when calling `test_endpoint_parameters`") @@ -259,8 +261,8 @@ def test_endpoint_parameters_with_http_info(self, number, double, string, byte, raise ValueError("Invalid value for parameter `double` when calling `test_endpoint_parameters`, must be a value less than or equal to `123.4`") if 'double' in params and params['double'] < 67.8: raise ValueError("Invalid value for parameter `double` when calling `test_endpoint_parameters`, must be a value greater than or equal to `67.8`") - if 'string' in params and not re.search('[a-z]', params['string'], flags=re.IGNORECASE): - raise ValueError("Invalid value for parameter `string` when calling `test_endpoint_parameters`, must conform to the pattern `/[a-z]/i`") + if 'pattern_without_delimiter' in params and not re.search('^[A-Z].*', params['pattern_without_delimiter']): + raise ValueError("Invalid value for parameter `pattern_without_delimiter` when calling `test_endpoint_parameters`, must conform to the pattern `/^[A-Z].*/`") if 'integer' in params and params['integer'] > 100.0: raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value less than or equal to `100.0`") if 'integer' in params and params['integer'] < 10.0: @@ -271,6 +273,8 @@ def test_endpoint_parameters_with_http_info(self, number, double, string, byte, raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value greater than or equal to `20.0`") if 'float' in params and params['float'] > 987.6: raise ValueError("Invalid value for parameter `float` when calling `test_endpoint_parameters`, must be a value less than or equal to `987.6`") + if 'string' in params and not re.search('[a-z]', params['string'], flags=re.IGNORECASE): + raise ValueError("Invalid value for parameter `string` when calling `test_endpoint_parameters`, must conform to the pattern `/[a-z]/i`") if 'password' in params and len(params['password']) > 64: raise ValueError("Invalid value for parameter `password` when calling `test_endpoint_parameters`, length must be less than or equal to `64`") if 'password' in params and len(params['password']) < 10: @@ -298,6 +302,8 @@ def test_endpoint_parameters_with_http_info(self, number, double, string, byte, form_params.append(('double', params['double'])) if 'string' in params: form_params.append(('string', params['string'])) + if 'pattern_without_delimiter' in params: + form_params.append(('pattern_without_delimiter', params['pattern_without_delimiter'])) if 'byte' in params: form_params.append(('byte', params['byte'])) if 'binary' in params: diff --git a/samples/client/petstore/python/petstore_api/configuration.py b/samples/client/petstore/python/petstore_api/configuration.py index 82d233a9f6b..d0db8fe5980 100644 --- a/samples/client/petstore/python/petstore_api/configuration.py +++ b/samples/client/petstore/python/petstore_api/configuration.py @@ -221,6 +221,13 @@ def auth_settings(self): :return: The Auth Settings information dict. """ return { + 'api_key': + { + 'type': 'api_key', + 'in': 'header', + 'key': 'api_key', + 'value': self.get_api_key_with_prefix('api_key') + }, 'petstore_auth': { @@ -236,13 +243,6 @@ def auth_settings(self): 'key': 'Authorization', 'value': self.get_basic_auth_token() }, - 'api_key': - { - 'type': 'api_key', - 'in': 'header', - 'key': 'api_key', - 'value': self.get_api_key_with_prefix('api_key') - }, } diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index f1f63920b6c..3d5441c5ab2 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -8,7 +8,7 @@ This SDK is automatically generated by the [Swagger Codegen](https://github.com/ - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-08-09T19:11:03.532+10:00 +- Build date: 2016-08-22T16:46:39.641+08:00 - Build package: class io.swagger.codegen.languages.RubyClientCodegen ## Installation @@ -78,7 +78,7 @@ Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- *Petstore::FakeApi* | [**test_client_model**](docs/FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model *Petstore::FakeApi* | [**test_endpoint_parameters**](docs/FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -*Petstore::FakeApi* | [**test_enum_query_parameters**](docs/FakeApi.md#test_enum_query_parameters) | **GET** /fake | To test enum query parameters +*Petstore::FakeApi* | [**test_enum_parameters**](docs/FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters *Petstore::PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store *Petstore::PetApi* | [**delete_pet**](docs/PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet *Petstore::PetApi* | [**find_pets_by_status**](docs/PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status @@ -137,6 +137,12 @@ Class | Method | HTTP request | Description ## Documentation for Authorization +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + ### petstore_auth - **Type**: OAuth @@ -146,9 +152,7 @@ Class | Method | HTTP request | Description - write:pets: modify pets in your account - read:pets: read your pets -### api_key +### http_basic_test -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header +- **Type**: HTTP basic authentication diff --git a/samples/client/petstore/ruby/docs/FakeApi.md b/samples/client/petstore/ruby/docs/FakeApi.md index 5e996ad0948..08207555c66 100644 --- a/samples/client/petstore/ruby/docs/FakeApi.md +++ b/samples/client/petstore/ruby/docs/FakeApi.md @@ -6,7 +6,7 @@ Method | HTTP request | Description ------------- | ------------- | ------------- [**test_client_model**](FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model [**test_endpoint_parameters**](FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -[**test_enum_query_parameters**](FakeApi.md#test_enum_query_parameters) | **GET** /fake | To test enum query parameters +[**test_enum_parameters**](FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters # **test_client_model** @@ -55,7 +55,7 @@ No authorization required # **test_endpoint_parameters** -> test_endpoint_parameters(number, double, string, byte, opts) +> test_endpoint_parameters(number, double, pattern_without_delimiter, byte, opts) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -65,6 +65,12 @@ Fake endpoint for testing various parameters 假端點 偽のエンドポイン ```ruby # load the gem require 'petstore' +# setup authorization +Petstore.configure do |config| + # Configure HTTP basic authorization: http_basic_test + config.username = 'YOUR USERNAME' + config.password = 'YOUR PASSWORD' +end api_instance = Petstore::FakeApi.new @@ -72,7 +78,7 @@ number = 3.4 # Float | None double = 1.2 # Float | None -string = "string_example" # String | None +pattern_without_delimiter = "pattern_without_delimiter_example" # String | None byte = "B" # String | None @@ -81,6 +87,7 @@ opts = { int32: 56, # Integer | None int64: 789, # Integer | None float: 3.4, # Float | None + string: "string_example", # String | None binary: "B", # String | None date: Date.parse("2013-10-20"), # Date | None date_time: DateTime.parse("2013-10-20T19:20:30+01:00"), # DateTime | None @@ -89,7 +96,7 @@ opts = { begin #Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - api_instance.test_endpoint_parameters(number, double, string, byte, opts) + api_instance.test_endpoint_parameters(number, double, pattern_without_delimiter, byte, opts) rescue Petstore::ApiError => e puts "Exception when calling FakeApi->test_endpoint_parameters: #{e}" end @@ -101,12 +108,13 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **number** | **Float**| None | **double** | **Float**| None | - **string** | **String**| None | + **pattern_without_delimiter** | **String**| None | **byte** | **String**| None | **integer** | **Integer**| None | [optional] **int32** | **Integer**| None | [optional] **int64** | **Integer**| None | [optional] **float** | **Float**| None | [optional] + **string** | **String**| None | [optional] **binary** | **String**| None | [optional] **date** | **Date**| None | [optional] **date_time** | **DateTime**| None | [optional] @@ -118,7 +126,7 @@ nil (empty response body) ### Authorization -No authorization required +[http_basic_test](../README.md#http_basic_test) ### HTTP request headers @@ -127,10 +135,10 @@ No authorization required -# **test_enum_query_parameters** -> test_enum_query_parameters(opts) +# **test_enum_parameters** +> test_enum_parameters(opts) -To test enum query parameters +To test enum parameters ### Example ```ruby @@ -140,16 +148,21 @@ require 'petstore' api_instance = Petstore::FakeApi.new opts = { + enum_form_string_array: ["enum_form_string_array_example"], # Array | Form parameter enum test (string array) + enum_form_string: "-efg", # String | Form parameter enum test (string) + enum_header_string_array: ["enum_header_string_array_example"], # Array | Header parameter enum test (string array) + enum_header_string: "-efg", # String | Header parameter enum test (string) + enum_query_string_array: ["enum_query_string_array_example"], # Array | Query parameter enum test (string array) enum_query_string: "-efg", # String | Query parameter enum test (string) enum_query_integer: 3.4, # Float | Query parameter enum test (double) enum_query_double: 1.2 # Float | Query parameter enum test (double) } begin - #To test enum query parameters - api_instance.test_enum_query_parameters(opts) + #To test enum parameters + api_instance.test_enum_parameters(opts) rescue Petstore::ApiError => e - puts "Exception when calling FakeApi->test_enum_query_parameters: #{e}" + puts "Exception when calling FakeApi->test_enum_parameters: #{e}" end ``` @@ -157,6 +170,11 @@ end Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- + **enum_form_string_array** | [**Array<String>**](String.md)| Form parameter enum test (string array) | [optional] + **enum_form_string** | **String**| Form parameter enum test (string) | [optional] [default to -efg] + **enum_header_string_array** | [**Array<String>**](String.md)| Header parameter enum test (string array) | [optional] + **enum_header_string** | **String**| Header parameter enum test (string) | [optional] [default to -efg] + **enum_query_string_array** | [**Array<String>**](String.md)| Query parameter enum test (string array) | [optional] **enum_query_string** | **String**| Query parameter enum test (string) | [optional] [default to -efg] **enum_query_integer** | **Float**| Query parameter enum test (double) | [optional] **enum_query_double** | **Float**| Query parameter enum test (double) | [optional] diff --git a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb index 95745e8f8b3..b83b97d2db5 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb @@ -92,20 +92,21 @@ def test_client_model_with_http_info(body, opts = {}) # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # @param number None # @param double None - # @param string None + # @param pattern_without_delimiter None # @param byte None # @param [Hash] opts the optional parameters # @option opts [Integer] :integer None # @option opts [Integer] :int32 None # @option opts [Integer] :int64 None # @option opts [Float] :float None + # @option opts [String] :string None # @option opts [String] :binary None # @option opts [Date] :date None # @option opts [DateTime] :date_time None # @option opts [String] :password None # @return [nil] - def test_endpoint_parameters(number, double, string, byte, opts = {}) - test_endpoint_parameters_with_http_info(number, double, string, byte, opts) + def test_endpoint_parameters(number, double, pattern_without_delimiter, byte, opts = {}) + test_endpoint_parameters_with_http_info(number, double, pattern_without_delimiter, byte, opts) return nil end @@ -113,19 +114,20 @@ def test_endpoint_parameters(number, double, string, byte, opts = {}) # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # @param number None # @param double None - # @param string None + # @param pattern_without_delimiter None # @param byte None # @param [Hash] opts the optional parameters # @option opts [Integer] :integer None # @option opts [Integer] :int32 None # @option opts [Integer] :int64 None # @option opts [Float] :float None + # @option opts [String] :string None # @option opts [String] :binary None # @option opts [Date] :date None # @option opts [DateTime] :date_time None # @option opts [String] :password None # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers - def test_endpoint_parameters_with_http_info(number, double, string, byte, opts = {}) + def test_endpoint_parameters_with_http_info(number, double, pattern_without_delimiter, byte, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug "Calling API: FakeApi.test_endpoint_parameters ..." end @@ -149,10 +151,10 @@ def test_endpoint_parameters_with_http_info(number, double, string, byte, opts = fail ArgumentError, 'invalid value for "double" when calling FakeApi.test_endpoint_parameters, must be greater than or equal to 67.8.' end - # verify the required parameter 'string' is set - fail ArgumentError, "Missing the required parameter 'string' when calling FakeApi.test_endpoint_parameters" if string.nil? - if string !~ Regexp.new(/[a-z]/i) - fail ArgumentError, 'invalid value for "string" when calling FakeApi.test_endpoint_parameters, must conform to the pattern /[a-z]/i.' + # verify the required parameter 'pattern_without_delimiter' is set + fail ArgumentError, "Missing the required parameter 'pattern_without_delimiter' when calling FakeApi.test_endpoint_parameters" if pattern_without_delimiter.nil? + if pattern_without_delimiter !~ Regexp.new(/^[A-Z].*/) + fail ArgumentError, 'invalid value for "pattern_without_delimiter" when calling FakeApi.test_endpoint_parameters, must conform to the pattern /^[A-Z].*/.' end # verify the required parameter 'byte' is set @@ -177,6 +179,10 @@ def test_endpoint_parameters_with_http_info(number, double, string, byte, opts = fail ArgumentError, 'invalid value for "opts[:"float"]" when calling FakeApi.test_endpoint_parameters, must be smaller than or equal to 987.6.' end + if !opts[:'string'].nil? && opts[:'string'] !~ Regexp.new(/[a-z]/i) + fail ArgumentError, 'invalid value for "opts[:"string"]" when calling FakeApi.test_endpoint_parameters, must conform to the pattern /[a-z]/i.' + end + if !opts[:'password'].nil? && opts[:'password'].to_s.length > 64 fail ArgumentError, 'invalid value for "opts[:"password"]" when calling FakeApi.test_endpoint_parameters, the character length must be smaller than or equal to 64.' end @@ -206,12 +212,13 @@ def test_endpoint_parameters_with_http_info(number, double, string, byte, opts = form_params = {} form_params["number"] = number form_params["double"] = double - form_params["string"] = string + form_params["pattern_without_delimiter"] = pattern_without_delimiter form_params["byte"] = byte form_params["integer"] = opts[:'integer'] if !opts[:'integer'].nil? form_params["int32"] = opts[:'int32'] if !opts[:'int32'].nil? form_params["int64"] = opts[:'int64'] if !opts[:'int64'].nil? form_params["float"] = opts[:'float'] if !opts[:'float'].nil? + form_params["string"] = opts[:'string'] if !opts[:'string'].nil? form_params["binary"] = opts[:'binary'] if !opts[:'binary'].nil? form_params["date"] = opts[:'date'] if !opts[:'date'].nil? form_params["dateTime"] = opts[:'date_time'] if !opts[:'date_time'].nil? @@ -219,7 +226,7 @@ def test_endpoint_parameters_with_http_info(number, double, string, byte, opts = # http body (model) post_body = nil - auth_names = [] + auth_names = ['http_basic_test'] data, status_code, headers = @api_client.call_api(:POST, local_var_path, :header_params => header_params, :query_params => query_params, @@ -232,28 +239,53 @@ def test_endpoint_parameters_with_http_info(number, double, string, byte, opts = return data, status_code, headers end - # To test enum query parameters + # To test enum parameters # # @param [Hash] opts the optional parameters + # @option opts [Array] :enum_form_string_array Form parameter enum test (string array) + # @option opts [String] :enum_form_string Form parameter enum test (string) (default to -efg) + # @option opts [Array] :enum_header_string_array Header parameter enum test (string array) + # @option opts [String] :enum_header_string Header parameter enum test (string) (default to -efg) + # @option opts [Array] :enum_query_string_array Query parameter enum test (string array) # @option opts [String] :enum_query_string Query parameter enum test (string) (default to -efg) # @option opts [Float] :enum_query_integer Query parameter enum test (double) # @option opts [Float] :enum_query_double Query parameter enum test (double) # @return [nil] - def test_enum_query_parameters(opts = {}) - test_enum_query_parameters_with_http_info(opts) + def test_enum_parameters(opts = {}) + test_enum_parameters_with_http_info(opts) return nil end - # To test enum query parameters + # To test enum parameters # # @param [Hash] opts the optional parameters + # @option opts [Array] :enum_form_string_array Form parameter enum test (string array) + # @option opts [String] :enum_form_string Form parameter enum test (string) + # @option opts [Array] :enum_header_string_array Header parameter enum test (string array) + # @option opts [String] :enum_header_string Header parameter enum test (string) + # @option opts [Array] :enum_query_string_array Query parameter enum test (string array) # @option opts [String] :enum_query_string Query parameter enum test (string) # @option opts [Float] :enum_query_integer Query parameter enum test (double) # @option opts [Float] :enum_query_double Query parameter enum test (double) # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers - def test_enum_query_parameters_with_http_info(opts = {}) + def test_enum_parameters_with_http_info(opts = {}) if @api_client.config.debugging - @api_client.config.logger.debug "Calling API: FakeApi.test_enum_query_parameters ..." + @api_client.config.logger.debug "Calling API: FakeApi.test_enum_parameters ..." + end + if opts[:'enum_form_string_array'] && !['>', '$'].include?(opts[:'enum_form_string_array']) + fail ArgumentError, 'invalid value for "enum_form_string_array", must be one of >, $' + end + if opts[:'enum_form_string'] && !['_abc', '-efg', '(xyz)'].include?(opts[:'enum_form_string']) + fail ArgumentError, 'invalid value for "enum_form_string", must be one of _abc, -efg, (xyz)' + end + if opts[:'enum_header_string_array'] && !['>', '$'].include?(opts[:'enum_header_string_array']) + fail ArgumentError, 'invalid value for "enum_header_string_array", must be one of >, $' + end + if opts[:'enum_header_string'] && !['_abc', '-efg', '(xyz)'].include?(opts[:'enum_header_string']) + fail ArgumentError, 'invalid value for "enum_header_string", must be one of _abc, -efg, (xyz)' + end + if opts[:'enum_query_string_array'] && !['>', '$'].include?(opts[:'enum_query_string_array']) + fail ArgumentError, 'invalid value for "enum_query_string_array", must be one of >, $' end if opts[:'enum_query_string'] && !['_abc', '-efg', '(xyz)'].include?(opts[:'enum_query_string']) fail ArgumentError, 'invalid value for "enum_query_string", must be one of _abc, -efg, (xyz)' @@ -263,6 +295,8 @@ def test_enum_query_parameters_with_http_info(opts = {}) # query parameters query_params = {} + query_params[:'enum_query_string_array'] = @api_client.build_collection_param(opts[:'enum_query_string_array'], :csv) if !opts[:'enum_query_string_array'].nil? + query_params[:'enum_query_string'] = opts[:'enum_query_string'] if !opts[:'enum_query_string'].nil? query_params[:'enum_query_integer'] = opts[:'enum_query_integer'] if !opts[:'enum_query_integer'].nil? # header parameters @@ -275,10 +309,13 @@ def test_enum_query_parameters_with_http_info(opts = {}) # HTTP header 'Content-Type' local_header_content_type = ['application/json'] header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + header_params[:'enum_header_string_array'] = @api_client.build_collection_param(opts[:'enum_header_string_array'], :csv) if !opts[:'enum_header_string_array'].nil? + header_params[:'enum_header_string'] = opts[:'enum_header_string'] if !opts[:'enum_header_string'].nil? # form parameters form_params = {} - form_params["enum_query_string"] = opts[:'enum_query_string'] if !opts[:'enum_query_string'].nil? + form_params["enum_form_string_array"] = @api_client.build_collection_param(opts[:'enum_form_string_array'], :csv) if !opts[:'enum_form_string_array'].nil? + form_params["enum_form_string"] = opts[:'enum_form_string'] if !opts[:'enum_form_string'].nil? form_params["enum_query_double"] = opts[:'enum_query_double'] if !opts[:'enum_query_double'].nil? # http body (model) @@ -291,7 +328,7 @@ def test_enum_query_parameters_with_http_info(opts = {}) :body => post_body, :auth_names => auth_names) if @api_client.config.debugging - @api_client.config.logger.debug "API called: FakeApi#test_enum_query_parameters\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + @api_client.config.logger.debug "API called: FakeApi#test_enum_parameters\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/configuration.rb b/samples/client/petstore/ruby/lib/petstore/configuration.rb index 4020a8cf118..2b2d15dff4d 100644 --- a/samples/client/petstore/ruby/lib/petstore/configuration.rb +++ b/samples/client/petstore/ruby/lib/petstore/configuration.rb @@ -201,6 +201,13 @@ def basic_auth_token # Returns Auth Settings hash for api client. def auth_settings { + 'api_key' => + { + type: 'api_key', + in: 'header', + key: 'api_key', + value: api_key_with_prefix('api_key') + }, 'petstore_auth' => { type: 'oauth2', @@ -208,12 +215,12 @@ def auth_settings key: 'Authorization', value: "Bearer #{access_token}" }, - 'api_key' => + 'http_basic_test' => { - type: 'api_key', + type: 'basic', in: 'header', - key: 'api_key', - value: api_key_with_prefix('api_key') + key: 'Authorization', + value: basic_auth_token }, } end From 9a77c485406f8a44029303065b0770951ef26a24 Mon Sep 17 00:00:00 2001 From: Yet Another Minion Date: Mon, 22 Aug 2016 07:52:10 -0400 Subject: [PATCH 269/470] For Qt5 server generator, add BaseIntegerProperty to default values (#3622) * For Qt5 server generator, add BaseIntegerProperty to default values * move base property check to after checks of extended properties --- .../java/io/swagger/codegen/languages/Qt5CPPGenerator.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java index 742b057003b..d922b6aec5a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java @@ -11,6 +11,7 @@ import io.swagger.models.properties.DecimalProperty; import io.swagger.models.properties.DoubleProperty; import io.swagger.models.properties.FloatProperty; +import io.swagger.models.properties.BaseIntegerProperty; import io.swagger.models.properties.IntegerProperty; import io.swagger.models.properties.LongProperty; import io.swagger.models.properties.MapProperty; @@ -270,6 +271,10 @@ public String toDefaultValue(Property p) { return "0"; } else if (p instanceof LongProperty) { return "0L"; + } else if (p instanceof BaseIntegerProperty) { + // catchall for any other format of the swagger specifiction + // integer type not explictly handled above + return "0"; } else if (p instanceof DecimalProperty) { return "0.0"; } else if (p instanceof MapProperty) { From 54fe7a731caec554d582b4b0a79defdc52751e05 Mon Sep 17 00:00:00 2001 From: Damien Pontifex Date: Mon, 22 Aug 2016 21:40:51 +0800 Subject: [PATCH 270/470] inject base_path opaque token for typescript angular2 (#3514) * inject base_path opaque token for typescript angular2 * Readme note on providing base path to service --- .../languages/TypeScriptAngular2ClientCodegen.java | 1 + .../resources/typescript-angular2/README.mustache | 11 +++++++++++ .../main/resources/typescript-angular2/api.mustache | 7 ++++--- .../main/resources/typescript-angular2/index.mustache | 3 ++- .../resources/typescript-angular2/variables.mustache | 3 +++ 5 files changed, 21 insertions(+), 4 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/typescript-angular2/variables.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngular2ClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngular2ClientCodegen.java index c9dd10b2a58..b8a9f772ad1 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngular2ClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngular2ClientCodegen.java @@ -68,6 +68,7 @@ public void processOpts() { supportingFiles.add(new SupportingFile("models.mustache", modelPackage().replace('.', File.separatorChar), "models.ts")); supportingFiles.add(new SupportingFile("apis.mustache", apiPackage().replace('.', File.separatorChar), "api.ts")); supportingFiles.add(new SupportingFile("index.mustache", getIndexDirectory(), "index.ts")); + supportingFiles.add(new SupportingFile("variables.mustache", getIndexDirectory(), "variables.ts")); supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/README.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/README.mustache index 73736fefb0c..218831c42d1 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/README.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/README.mustache @@ -31,3 +31,14 @@ npm install PATH_TO_GENERATED_PACKAGE --save In your angular2 project: TODO: paste example. + +### Set service base path +If different than the generated base path, during app bootstrap, you can provide the base path to your service. + +``` +import { BASE_PATH } from './path-to-swagger-gen-service/index'; + +bootstrap(AppComponent, [ + { provide: BASE_PATH, useValue: 'https://your-web-service.com' }, +]); +``` \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache index c0645280549..8565dee4c5a 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache @@ -1,8 +1,9 @@ {{>licenseInfo}} import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; -import {Injectable, Optional} from '@angular/core'; +import {Inject, Injectable, Optional} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; +import {BASE_PATH} from '../variables'; import 'rxjs/Rx'; /* tslint:disable:no-unused-variable member-ordering */ @@ -20,7 +21,7 @@ export class {{classname}} { protected basePath = '{{basePath}}'; public defaultHeaders : Headers = new Headers(); - constructor(protected http: Http, @Optional() basePath: string) { + constructor(protected http: Http, @Optional()@Inject(BASE_PATH) basePath: string) { if (basePath) { this.basePath = basePath; } @@ -32,7 +33,7 @@ export class {{classname}} { * {{notes}} {{#allParams}}* @param {{paramName}} {{description}} {{/allParams}}*/ - public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}extraHttpRequestParams?: any ) : Observable<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}{}{{/returnType}}> { + public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}extraHttpRequestParams?: any): Observable<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}{}{{/returnType}}> { const path = this.basePath + '{{path}}'{{#pathParams}} .replace('{' + '{{baseName}}' + '}', String({{paramName}})){{/pathParams}}; diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/index.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/index.mustache index 557365516ad..ec7dcae82b2 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/index.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/index.mustache @@ -1,2 +1,3 @@ export * from './api/api'; -export * from './model/models'; \ No newline at end of file +export * from './model/models'; +export * from './variables'; \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/variables.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/variables.mustache new file mode 100644 index 00000000000..27b987e9b23 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/variables.mustache @@ -0,0 +1,3 @@ +import { OpaqueToken } from '@angular/core'; + +export const BASE_PATH = new OpaqueToken('basePath'); \ No newline at end of file From c1f3c514270e50bcca8c707e766ca230d1f2f040 Mon Sep 17 00:00:00 2001 From: Ryan Martin Date: Mon, 11 Jul 2016 23:31:59 -0400 Subject: [PATCH 271/470] [Swift] Include HTTP status code and body data in response errors This is useful when differentiating different error responses. Example: if let e = error { switch e { case ErrorResponse.Error(400, _, _): responseLabel.text = "Unknown error" case ErrorResponse.Error(403, _, _): responseLabel.text = "Not logged in" default: responseLabel.text = "\(e)" } } The existing error is straight from Alamofire and only includes the HTTP status code in the body of the message (not broken out as a separate value). It also does not include the response body, which may be useful. --- .../swift/AlamofireImplementations.mustache | 8 +- .../src/main/resources/swift/Models.mustache | 4 + .../Classes/Swaggers/APIs/PetAPI.swift | 106 +++++++++--------- .../Classes/Swaggers/APIs/StoreAPI.swift | 64 +++++------ .../Classes/Swaggers/APIs/UserAPI.swift | 36 +++--- .../Swaggers/AlamofireImplementations.swift | 8 +- .../Classes/Swaggers/Models.swift | 4 + .../SwaggerClientTests/Pods/Manifest.lock | 2 +- .../Pods-SwaggerClient-resources.sh | 4 +- .../Pods-SwaggerClientTests-resources.sh | 4 +- .../SwaggerClient.xcodeproj/project.pbxproj | 12 +- .../SwaggerClientTests/PetAPITests.swift | 14 ++- .../SwaggerClientTests/StoreAPITests.swift | 14 ++- .../SwaggerClientTests/UserAPITests.swift | 55 +++++---- .../Classes/Swaggers/APIs/PetAPI.swift | 106 +++++++++--------- .../Classes/Swaggers/APIs/StoreAPI.swift | 64 +++++------ .../Classes/Swaggers/APIs/UserAPI.swift | 36 +++--- .../Swaggers/AlamofireImplementations.swift | 8 +- .../Classes/Swaggers/Models.swift | 4 + .../SwaggerClientTests/PetAPITests.swift | 14 ++- .../SwaggerClientTests/StoreAPITests.swift | 14 ++- .../SwaggerClientTests/UserAPITests.swift | 57 ++++++---- 22 files changed, 338 insertions(+), 300 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache index baa6d8aa72a..8e7cef70fed 100644 --- a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache @@ -63,7 +63,7 @@ class AlamofireRequestBuilder: RequestBuilder { } self.processRequest(uploadRequest, managerId, completion) case .Failure(let encodingError): - completion(response: nil, error: encodingError) + completion(response: nil, error: ErrorResponse.Error(415, nil, encodingError)) } } ) @@ -96,7 +96,7 @@ class AlamofireRequestBuilder: RequestBuilder { if (dataResponse.result.isFailure) { completion( response: nil, - error: dataResponse.result.error + error: ErrorResponse.Error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.result.error!) ) return } @@ -114,7 +114,7 @@ class AlamofireRequestBuilder: RequestBuilder { cleanupRequest() if response.result.isFailure { - completion(response: nil, error: response.result.error) + completion(response: nil, error: ErrorResponse.Error(response.response?.statusCode ?? 500, response.data, response.result.error!)) return } @@ -133,7 +133,7 @@ class AlamofireRequestBuilder: RequestBuilder { return } - completion(response: nil, error: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) + completion(response: nil, error: ErrorResponse.Error(500, nil, NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"]))) } } } diff --git a/modules/swagger-codegen/src/main/resources/swift/Models.mustache b/modules/swagger-codegen/src/main/resources/swift/Models.mustache index a79bbdea075..c082be97e3a 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Models.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Models.mustache @@ -10,6 +10,10 @@ protocol JSONEncodable { func encodeToJSON() -> AnyObject } +public enum ErrorResponse : ErrorType { + case Error(Int, NSData?, ErrorType) +} + public class Response { public let statusCode: Int public let header: [String: String] diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index cdbd4323e70..6e4ddc4227b 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -108,13 +108,13 @@ public class PetAPI: APIBase { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example={ + - examples: [{contentType=application/json, example={ "name" : "Puma", "type" : "Dog", "color" : "Black", "gender" : "Female", "breed" : "Mixed" -}, contentType=application/json}] +}}] - parameter status: (query) Status values that need to be considered for filter (optional, default to available) @@ -157,20 +157,20 @@ public class PetAPI: APIBase { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], + - examples: [{contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}, {contentType=application/xml, example= 123456 doggie @@ -179,21 +179,21 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] - - examples: [{example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}] + - examples: [{contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}, {contentType=application/xml, example= 123456 doggie @@ -202,7 +202,7 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] +}] - parameter tags: (query) Tags to filter by (optional) @@ -242,26 +242,26 @@ public class PetAPI: APIBase { Find pet by ID - GET /pet/{petId} - Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - - API Key: - - type: apiKey api_key - - name: api_key - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example={ - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], + - API Key: + - type: apiKey api_key + - name: api_key + - examples: [{contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -}, contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 doggie @@ -270,21 +270,21 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] - - examples: [{example={ - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}] + - examples: [{contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -}, contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 doggie @@ -293,7 +293,7 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] +}] - parameter petId: (path) ID of pet that needs to be fetched diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 1c575eb79f8..c51d8d37357 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -67,12 +67,12 @@ public class StoreAPI: APIBase { - API Key: - type: apiKey api_key - name: api_key - - examples: [{example={ + - examples: [{contentType=application/json, example={ "key" : 123 -}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}] - - examples: [{example={ +}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}] + - examples: [{contentType=application/json, example={ "key" : 123 -}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}] +}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}] - returns: RequestBuilder<[String:Int32]> */ @@ -108,36 +108,36 @@ public class StoreAPI: APIBase { Find purchase order by ID - GET /store/order/{orderId} - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - - examples: [{example={ - "id" : 123456789, + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] - - examples: [{example={ - "id" : 123456789, +}] + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] +}] - parameter orderId: (path) ID of pet that needs to be fetched @@ -176,36 +176,36 @@ public class StoreAPI: APIBase { Place an order for a pet - POST /store/order - - - examples: [{example={ - "id" : 123456789, + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] - - examples: [{example={ - "id" : 123456789, +}] + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] +}] - parameter body: (body) order placed for purchasing the pet (optional) diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index a7497487f85..d6df7754683 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -167,16 +167,16 @@ public class UserAPI: APIBase { Get user by user name - GET /user/{username} - - - examples: [{example={ - "id" : 123456789, + - examples: [{contentType=application/json, example={ + "firstName" : "aeiou", "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, "phone" : "aeiou", - "username" : "aeiou", + "id" : 123456789, "email" : "aeiou", - "userStatus" : 123, - "firstName" : "aeiou", - "password" : "aeiou" -}, contentType=application/json}, {example= + "username" : "aeiou" +}}, {contentType=application/xml, example= 123456 string string @@ -185,17 +185,17 @@ public class UserAPI: APIBase { string string 0 -, contentType=application/xml}] - - examples: [{example={ - "id" : 123456789, +}] + - examples: [{contentType=application/json, example={ + "firstName" : "aeiou", "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, "phone" : "aeiou", - "username" : "aeiou", + "id" : 123456789, "email" : "aeiou", - "userStatus" : 123, - "firstName" : "aeiou", - "password" : "aeiou" -}, contentType=application/json}, {example= + "username" : "aeiou" +}}, {contentType=application/xml, example= 123456 string string @@ -204,7 +204,7 @@ public class UserAPI: APIBase { string string 0 -, contentType=application/xml}] +}] - parameter username: (path) The name that needs to be fetched. Use user1 for testing. @@ -244,8 +244,8 @@ public class UserAPI: APIBase { Logs user into the system - GET /user/login - - - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}] - - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}] + - examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] + - examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] - parameter username: (query) The user name for login (optional) - parameter password: (query) The password for login in clear text (optional) diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index baa6d8aa72a..8e7cef70fed 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -63,7 +63,7 @@ class AlamofireRequestBuilder: RequestBuilder { } self.processRequest(uploadRequest, managerId, completion) case .Failure(let encodingError): - completion(response: nil, error: encodingError) + completion(response: nil, error: ErrorResponse.Error(415, nil, encodingError)) } } ) @@ -96,7 +96,7 @@ class AlamofireRequestBuilder: RequestBuilder { if (dataResponse.result.isFailure) { completion( response: nil, - error: dataResponse.result.error + error: ErrorResponse.Error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.result.error!) ) return } @@ -114,7 +114,7 @@ class AlamofireRequestBuilder: RequestBuilder { cleanupRequest() if response.result.isFailure { - completion(response: nil, error: response.result.error) + completion(response: nil, error: ErrorResponse.Error(response.response?.statusCode ?? 500, response.data, response.result.error!)) return } @@ -133,7 +133,7 @@ class AlamofireRequestBuilder: RequestBuilder { return } - completion(response: nil, error: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) + completion(response: nil, error: ErrorResponse.Error(500, nil, NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"]))) } } } diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models.swift index 519aa5cc787..a42fc32fdd5 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models.swift @@ -10,6 +10,10 @@ protocol JSONEncodable { func encodeToJSON() -> AnyObject } +public enum ErrorResponse : ErrorType { + case Error(Int, NSData?, ErrorType) +} + public class Response { public let statusCode: Int public let header: [String: String] diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Manifest.lock b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Manifest.lock index cb529f1abde..f5b98a5d811 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Manifest.lock +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Manifest.lock @@ -16,4 +16,4 @@ SPEC CHECKSUMS: PODFILE CHECKSUM: 84472aca2a88b7f7ed9fcd63e9f5fdb5ad4aab94 -COCOAPODS: 1.0.0 +COCOAPODS: 1.0.1 diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh index e768f92993e..0a1561528cb 100755 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh @@ -48,8 +48,8 @@ EOM ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ;; *.xib) - echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT}" - ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ;; *.framework) echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh index e768f92993e..0a1561528cb 100755 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh @@ -48,8 +48,8 @@ EOM ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ;; *.xib) - echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT}" - ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ;; *.framework) echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index 6f2be0a3811..2499f042aaf 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -143,7 +143,7 @@ isa = PBXNativeTarget; buildConfigurationList = 6D4EFBAE1C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClient" */; buildPhases = ( - CF310079E3CB0BE5BE604471 /* 📦 Check Pods Manifest.lock */, + CF310079E3CB0BE5BE604471 /* [CP] Check Pods Manifest.lock */, 1F03F780DC2D9727E5E64BA9 /* [CP] Check Pods Manifest.lock */, 6D4EFB8D1C692C6300B96B06 /* Sources */, 6D4EFB8E1C692C6300B96B06 /* Frameworks */, @@ -166,7 +166,7 @@ isa = PBXNativeTarget; buildConfigurationList = 6D4EFBB11C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */; buildPhases = ( - B4DB169E5F018305D6759D34 /* 📦 Check Pods Manifest.lock */, + B4DB169E5F018305D6759D34 /* [CP] Check Pods Manifest.lock */, 79FE27B09B2DD354C831BD49 /* [CP] Check Pods Manifest.lock */, 6D4EFBA11C692C6300B96B06 /* Sources */, 6D4EFBA21C692C6300B96B06 /* Frameworks */, @@ -365,14 +365,14 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh\"\n"; showEnvVarsInLog = 0; }; - B4DB169E5F018305D6759D34 /* 📦 Check Pods Manifest.lock */ = { + B4DB169E5F018305D6759D34 /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Check Pods Manifest.lock"; + name = "[CP] Check Pods Manifest.lock"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -380,14 +380,14 @@ shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; showEnvVarsInLog = 0; }; - CF310079E3CB0BE5BE604471 /* 📦 Check Pods Manifest.lock */ = { + CF310079E3CB0BE5BE604471 /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Check Pods Manifest.lock"; + name = "[CP] Check Pods Manifest.lock"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift index 3d3ca03392a..22a8057fbb1 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift @@ -74,15 +74,17 @@ class PetAPITests: XCTestCase { PetAPI.deletePet(petId: 1000) { (error) in // The server gives us no data back so Alamofire parsing fails - at least // verify that is the error we get here - // Error Domain=com.alamofire.error Code=-6006 "JSON could not be serialized. Input data was nil or zero - // length." UserInfo={NSLocalizedFailureReason=JSON could not be serialized. Input data was nil or zero - // length.} - guard let error = error where error._code == -6006 else { + guard let error = error else { XCTFail("error deleting pet") return } - - expectation.fulfill() + + switch error { + case ErrorResponse.Error(200, _, _): + expectation.fulfill() + default: + XCTFail("error deleting pet") + } } self.waitForExpectationsWithTimeout(testTimeout, handler: nil) diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift index 98ed9e07957..88178a319a0 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift @@ -76,15 +76,17 @@ class StoreAPITests: XCTestCase { StoreAPI.deleteOrder(orderId: "1000") { (error) in // The server gives us no data back so Alamofire parsing fails - at least // verify that is the error we get here - // Error Domain=com.alamofire.error Code=-6006 "JSON could not be serialized. Input data was nil or zero - // length." UserInfo={NSLocalizedFailureReason=JSON could not be serialized. Input data was nil or zero - // length.} - guard let error = error where error._code == -6006 else { + guard let error = error else { XCTFail("error deleting order") return } - - expectation.fulfill() + + switch error { + case ErrorResponse.Error(200, _, _): + expectation.fulfill() + default: + XCTFail("error deleting order") + } } self.waitForExpectationsWithTimeout(testTimeout, handler: nil) diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift index 213e69c56fe..30c90f2de53 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift @@ -30,14 +30,17 @@ class UserAPITests: XCTestCase { UserAPI.loginUser(username: "swiftTester", password: "swift") { (_, error) in // The server isn't returning JSON - and currently the alamofire implementation // always parses responses as JSON, so making an exception for this here - // Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." - // UserInfo={NSDebugDescription=Invalid value around character 0.} - guard let error = error where error._code == 3840 else { + guard let error = error else { XCTFail("error logging in") return } - - expectation.fulfill() + + switch error { + case ErrorResponse.Error(200, _, _): + expectation.fulfill() + default: + XCTFail("error logging in") + } } self.waitForExpectationsWithTimeout(testTimeout, handler: nil) @@ -49,15 +52,17 @@ class UserAPITests: XCTestCase { UserAPI.logoutUser { (error) in // The server gives us no data back so Alamofire parsing fails - at least // verify that is the error we get here - // Error Domain=com.alamofire.error Code=-6006 "JSON could not be serialized. Input data was nil or zero - // length." UserInfo={NSLocalizedFailureReason=JSON could not be serialized. Input data was nil or zero - // length.} - guard let error = error where error._code == -6006 else { + guard let error = error else { XCTFail("error logging out") return } - - expectation.fulfill() + + switch error { + case ErrorResponse.Error(200, _, _): + expectation.fulfill() + default: + XCTFail("error logging out") + } } self.waitForExpectationsWithTimeout(testTimeout, handler: nil) @@ -79,15 +84,17 @@ class UserAPITests: XCTestCase { UserAPI.createUser(body: newUser) { (error) in // The server gives us no data back so Alamofire parsing fails - at least // verify that is the error we get here - // Error Domain=com.alamofire.error Code=-6006 "JSON could not be serialized. Input data was nil or zero - // length." UserInfo={NSLocalizedFailureReason=JSON could not be serialized. Input data was nil or zero - // length.} - guard let error = error where error._code == -6006 else { + guard let error = error else { XCTFail("error creating user") return } - - expectation.fulfill() + + switch error { + case ErrorResponse.Error(200, _, _): + expectation.fulfill() + default: + XCTFail("error creating user") + } } self.waitForExpectationsWithTimeout(testTimeout, handler: nil) @@ -123,15 +130,17 @@ class UserAPITests: XCTestCase { UserAPI.deleteUser(username: "test@test.com") { (error) in // The server gives us no data back so Alamofire parsing fails - at least // verify that is the error we get here - // Error Domain=com.alamofire.error Code=-6006 "JSON could not be serialized. Input data was nil or zero - // length." UserInfo={NSLocalizedFailureReason=JSON could not be serialized. Input data was nil or zero - // length.} - guard let error = error where error._code == -6006 else { + guard let error = error else { XCTFail("error deleting user") return } - - expectation.fulfill() + + switch error { + case ErrorResponse.Error(200, _, _): + expectation.fulfill() + default: + XCTFail("error deleting user") + } } self.waitForExpectationsWithTimeout(testTimeout, handler: nil) diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index c7e5a6402b5..27000da5417 100644 --- a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -160,13 +160,13 @@ public class PetAPI: APIBase { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example={ + - examples: [{contentType=application/json, example={ "name" : "Puma", "type" : "Dog", "color" : "Black", "gender" : "Female", "breed" : "Mixed" -}, contentType=application/json}] +}}] - parameter status: (query) Status values that need to be considered for filter (optional, default to available) @@ -226,20 +226,20 @@ public class PetAPI: APIBase { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], + - examples: [{contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}, {contentType=application/xml, example= 123456 doggie @@ -248,21 +248,21 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] - - examples: [{example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}] + - examples: [{contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}, {contentType=application/xml, example= 123456 doggie @@ -271,7 +271,7 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] +}] - parameter tags: (query) Tags to filter by (optional) @@ -328,26 +328,26 @@ public class PetAPI: APIBase { Find pet by ID - GET /pet/{petId} - Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - - API Key: - - type: apiKey api_key - - name: api_key - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example={ - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], + - API Key: + - type: apiKey api_key + - name: api_key + - examples: [{contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -}, contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 doggie @@ -356,21 +356,21 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] - - examples: [{example={ - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}] + - examples: [{contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -}, contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 doggie @@ -379,7 +379,7 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] +}] - parameter petId: (path) ID of pet that needs to be fetched diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 8736f9ee2e0..ab072c821f8 100644 --- a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -101,12 +101,12 @@ public class StoreAPI: APIBase { - API Key: - type: apiKey api_key - name: api_key - - examples: [{example={ + - examples: [{contentType=application/json, example={ "key" : 123 -}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}] - - examples: [{example={ +}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}] + - examples: [{contentType=application/json, example={ "key" : 123 -}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}] +}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}] - returns: RequestBuilder<[String:Int32]> */ @@ -159,36 +159,36 @@ public class StoreAPI: APIBase { Find purchase order by ID - GET /store/order/{orderId} - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - - examples: [{example={ - "id" : 123456789, + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] - - examples: [{example={ - "id" : 123456789, +}] + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] +}] - parameter orderId: (path) ID of pet that needs to be fetched @@ -244,36 +244,36 @@ public class StoreAPI: APIBase { Place an order for a pet - POST /store/order - - - examples: [{example={ - "id" : 123456789, + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] - - examples: [{example={ - "id" : 123456789, +}] + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] +}] - parameter body: (body) order placed for purchasing the pet (optional) diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index 1b5ada9da67..98afec0c80a 100644 --- a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -253,16 +253,16 @@ public class UserAPI: APIBase { Get user by user name - GET /user/{username} - - - examples: [{example={ - "id" : 123456789, + - examples: [{contentType=application/json, example={ + "firstName" : "aeiou", "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, "phone" : "aeiou", - "username" : "aeiou", + "id" : 123456789, "email" : "aeiou", - "userStatus" : 123, - "firstName" : "aeiou", - "password" : "aeiou" -}, contentType=application/json}, {example= + "username" : "aeiou" +}}, {contentType=application/xml, example= 123456 string string @@ -271,17 +271,17 @@ public class UserAPI: APIBase { string string 0 -, contentType=application/xml}] - - examples: [{example={ - "id" : 123456789, +}] + - examples: [{contentType=application/json, example={ + "firstName" : "aeiou", "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, "phone" : "aeiou", - "username" : "aeiou", + "id" : 123456789, "email" : "aeiou", - "userStatus" : 123, - "firstName" : "aeiou", - "password" : "aeiou" -}, contentType=application/json}, {example= + "username" : "aeiou" +}}, {contentType=application/xml, example= 123456 string string @@ -290,7 +290,7 @@ public class UserAPI: APIBase { string string 0 -, contentType=application/xml}] +}] - parameter username: (path) The name that needs to be fetched. Use user1 for testing. @@ -348,8 +348,8 @@ public class UserAPI: APIBase { Logs user into the system - GET /user/login - - - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}] - - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}] + - examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] + - examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] - parameter username: (query) The user name for login (optional) - parameter password: (query) The password for login in clear text (optional) diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index baa6d8aa72a..8e7cef70fed 100644 --- a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -63,7 +63,7 @@ class AlamofireRequestBuilder: RequestBuilder { } self.processRequest(uploadRequest, managerId, completion) case .Failure(let encodingError): - completion(response: nil, error: encodingError) + completion(response: nil, error: ErrorResponse.Error(415, nil, encodingError)) } } ) @@ -96,7 +96,7 @@ class AlamofireRequestBuilder: RequestBuilder { if (dataResponse.result.isFailure) { completion( response: nil, - error: dataResponse.result.error + error: ErrorResponse.Error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.result.error!) ) return } @@ -114,7 +114,7 @@ class AlamofireRequestBuilder: RequestBuilder { cleanupRequest() if response.result.isFailure { - completion(response: nil, error: response.result.error) + completion(response: nil, error: ErrorResponse.Error(response.response?.statusCode ?? 500, response.data, response.result.error!)) return } @@ -133,7 +133,7 @@ class AlamofireRequestBuilder: RequestBuilder { return } - completion(response: nil, error: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) + completion(response: nil, error: ErrorResponse.Error(500, nil, NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"]))) } } } diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models.swift index 519aa5cc787..a42fc32fdd5 100644 --- a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models.swift +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models.swift @@ -10,6 +10,10 @@ protocol JSONEncodable { func encodeToJSON() -> AnyObject } +public enum ErrorResponse : ErrorType { + case Error(Int, NSData?, ErrorType) +} + public class Response { public let statusCode: Int public let header: [String: String] diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift index c5f9750c8bf..09f9dea54d0 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift @@ -68,13 +68,15 @@ class PetAPITests: XCTestCase { }.error { errorType -> Void in // The server gives us no data back so alamofire parsing fails - at least // verify that is the error we get here - // Error Domain=com.alamofire.error Code=-6006 "JSON could not be serialized. Input data was nil or zero - // length." UserInfo={NSLocalizedFailureReason=JSON could not be serialized. Input data was nil or zero - // length.} - let error = errorType as NSError - if error.code == -6006 { + guard let error = errorType as? ErrorResponse else { + XCTFail("error logging out") + return + } + + switch error { + case ErrorResponse.Error(200, _, _): expectation.fulfill() - } else { + default: XCTFail("error logging out") } } diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift index 210868dfb12..c41dfc69da2 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift @@ -68,13 +68,15 @@ class StoreAPITests: XCTestCase { }.error { errorType -> Void in // The server gives us no data back so alamofire parsing fails - at least // verify that is the error we get here - // Error Domain=com.alamofire.error Code=-6006 "JSON could not be serialized. Input data was nil or zero - // length." UserInfo={NSLocalizedFailureReason=JSON could not be serialized. Input data was nil or zero - // length.} - let error = errorType as NSError - if error.code == -6006 { + guard let error = errorType as? ErrorResponse else { + XCTFail("error deleting order") + return + } + + switch error { + case ErrorResponse.Error(200, _, _): expectation.fulfill() - } else { + default: XCTFail("error deleting order") } } diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift index 7129ecd226a..3cce03af756 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift @@ -34,12 +34,15 @@ class UserAPITests: XCTestCase { }.error { errorType -> Void in // The server isn't returning JSON - and currently the alamofire implementation // always parses responses as JSON, so making an exception for this here - // Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." - // UserInfo={NSDebugDescription=Invalid value around character 0.} - let error = errorType as NSError - if error.code == 3840 { + guard let error = errorType as? ErrorResponse else { + XCTFail("error logging in") + return + } + + switch error { + case ErrorResponse.Error(200, _, _): expectation.fulfill() - } else { + default: XCTFail("error logging in") } } @@ -55,13 +58,15 @@ class UserAPITests: XCTestCase { }.error { errorType -> Void in // The server gives us no data back so alamofire parsing fails - at least // verify that is the error we get here - // Error Domain=com.alamofire.error Code=-6006 "JSON could not be serialized. Input data was nil or zero - // length." UserInfo={NSLocalizedFailureReason=JSON could not be serialized. Input data was nil or zero - // length.} - let error = errorType as NSError - if error.code == -6006 { + guard let error = errorType as? ErrorResponse else { + XCTFail("error logging out") + return + } + + switch error { + case ErrorResponse.Error(200, _, _): expectation.fulfill() - } else { + default: XCTFail("error logging out") } } @@ -86,13 +91,15 @@ class UserAPITests: XCTestCase { }.error { errorType -> Void in // The server gives us no data back so alamofire parsing fails - at least // verify that is the error we get here - // Error Domain=com.alamofire.error Code=-6006 "JSON could not be serialized. Input data was nil or zero - // length." UserInfo={NSLocalizedFailureReason=JSON could not be serialized. Input data was nil or zero - // length.} - let error = errorType as NSError - if error.code == -6006 { + guard let error = errorType as? ErrorResponse else { + XCTFail("error creating user") + return + } + + switch error { + case ErrorResponse.Error(200, _, _): expectation.fulfill() - } else { + default: XCTFail("error creating user") } } @@ -126,14 +133,16 @@ class UserAPITests: XCTestCase { }.error { errorType -> Void in // The server gives us no data back so alamofire parsing fails - at least // verify that is the error we get here - // Error Domain=com.alamofire.error Code=-6006 "JSON could not be serialized. Input data was nil or zero - // length." UserInfo={NSLocalizedFailureReason=JSON could not be serialized. Input data was nil or zero - // length.} - let error = errorType as NSError - if error.code == -6006 { + guard let error = errorType as? ErrorResponse else { + XCTFail("error deleting user") + return + } + + switch error { + case ErrorResponse.Error(200, _, _): expectation.fulfill() - } else { - XCTFail("error logging out") + default: + XCTFail("error deleting user") } } self.waitForExpectationsWithTimeout(testTimeout, handler: nil) From 84de96ef6571b5351538253ae922873cf5c9fe50 Mon Sep 17 00:00:00 2001 From: Diego de Estrada Date: Mon, 22 Aug 2016 17:49:32 -0300 Subject: [PATCH 272/470] Adds flattener for ComposedModel --- .../src/main/java/io/swagger/codegen/InlineModelResolver.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/InlineModelResolver.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/InlineModelResolver.java index 44d2f9e5b3e..ca1a0317ee2 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/InlineModelResolver.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/InlineModelResolver.java @@ -179,6 +179,10 @@ else if (model instanceof ArrayModel) { } } } + } else if (model instanceof ComposedModel) { + ComposedModel m = (ComposedModel) model; + Map properties = m.getChild().getProperties(); + flattenProperties(properties, modelName); } } } From 3a457c6a7e0856a023901c906ba13f988447ee66 Mon Sep 17 00:00:00 2001 From: Jason Gavris Date: Tue, 23 Aug 2016 09:52:34 -0400 Subject: [PATCH 273/470] [Swift] Handle Void responses --- .../swift/AlamofireImplementations.mustache | 20 +++++++ .../src/main/resources/swift/Models.mustache | 6 +-- .../Swaggers/AlamofireImplementations.swift | 20 +++++++ .../Classes/Swaggers/Models.swift | 6 +-- .../SwaggerClientTests/PetAPITests.swift | 11 +--- .../SwaggerClientTests/StoreAPITests.swift | 11 +--- .../SwaggerClientTests/UserAPITests.swift | 33 +++--------- .../Swaggers/AlamofireImplementations.swift | 20 +++++++ .../Classes/Swaggers/Models.swift | 6 +-- .../SwaggerClientTests/PetAPITests.swift | 20 +------ .../SwaggerClientTests/StoreAPITests.swift | 18 +------ .../SwaggerClientTests/UserAPITests.swift | 54 ++----------------- 12 files changed, 85 insertions(+), 140 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache index 8e7cef70fed..7935598291f 100644 --- a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache @@ -89,6 +89,26 @@ class AlamofireRequestBuilder: RequestBuilder { let validatedRequest = request.validate() switch T.self { + case is Void.Type: + validatedRequest.responseData(completionHandler: { (voidResponse) in + cleanupRequest() + + if voidResponse.result.isFailure { + completion( + response: nil, + error: ErrorResponse.Error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.result.error!) + ) + return + } + + completion( + response: Response( + response: voidResponse.response!, + body: nil + ), + error: nil + ) + }) case is NSData.Type: validatedRequest.responseData(completionHandler: { (dataResponse) in cleanupRequest() diff --git a/modules/swagger-codegen/src/main/resources/swift/Models.mustache b/modules/swagger-codegen/src/main/resources/swift/Models.mustache index c082be97e3a..2d7c9094091 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Models.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Models.mustache @@ -17,15 +17,15 @@ public enum ErrorResponse : ErrorType { public class Response { public let statusCode: Int public let header: [String: String] - public let body: T + public let body: T? - public init(statusCode: Int, header: [String: String], body: T) { + public init(statusCode: Int, header: [String: String], body: T?) { self.statusCode = statusCode self.header = header self.body = body } - public convenience init(response: NSHTTPURLResponse, body: T) { + public convenience init(response: NSHTTPURLResponse, body: T?) { let rawHeader = response.allHeaderFields var header = [String:String]() for (key, value) in rawHeader { diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index 8e7cef70fed..7935598291f 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -89,6 +89,26 @@ class AlamofireRequestBuilder: RequestBuilder { let validatedRequest = request.validate() switch T.self { + case is Void.Type: + validatedRequest.responseData(completionHandler: { (voidResponse) in + cleanupRequest() + + if voidResponse.result.isFailure { + completion( + response: nil, + error: ErrorResponse.Error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.result.error!) + ) + return + } + + completion( + response: Response( + response: voidResponse.response!, + body: nil + ), + error: nil + ) + }) case is NSData.Type: validatedRequest.responseData(completionHandler: { (dataResponse) in cleanupRequest() diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models.swift index a42fc32fdd5..32175b605a3 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models.swift @@ -17,15 +17,15 @@ public enum ErrorResponse : ErrorType { public class Response { public let statusCode: Int public let header: [String: String] - public let body: T + public let body: T? - public init(statusCode: Int, header: [String: String], body: T) { + public init(statusCode: Int, header: [String: String], body: T?) { self.statusCode = statusCode self.header = header self.body = body } - public convenience init(response: NSHTTPURLResponse, body: T) { + public convenience init(response: NSHTTPURLResponse, body: T?) { let rawHeader = response.allHeaderFields var header = [String:String]() for (key, value) in rawHeader { diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift index 22a8057fbb1..7446c53aa3b 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift @@ -72,19 +72,12 @@ class PetAPITests: XCTestCase { let expectation = self.expectationWithDescription("testDeletePet") PetAPI.deletePet(petId: 1000) { (error) in - // The server gives us no data back so Alamofire parsing fails - at least - // verify that is the error we get here - guard let error = error else { + guard error == nil else { XCTFail("error deleting pet") return } - switch error { - case ErrorResponse.Error(200, _, _): - expectation.fulfill() - default: - XCTFail("error deleting pet") - } + expectation.fulfill() } self.waitForExpectationsWithTimeout(testTimeout, handler: nil) diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift index 88178a319a0..ba235ca32db 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift @@ -74,19 +74,12 @@ class StoreAPITests: XCTestCase { let expectation = self.expectationWithDescription("testDeleteOrder") StoreAPI.deleteOrder(orderId: "1000") { (error) in - // The server gives us no data back so Alamofire parsing fails - at least - // verify that is the error we get here - guard let error = error else { + guard error == nil else { XCTFail("error deleting order") return } - switch error { - case ErrorResponse.Error(200, _, _): - expectation.fulfill() - default: - XCTFail("error deleting order") - } + expectation.fulfill() } self.waitForExpectationsWithTimeout(testTimeout, handler: nil) diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift index 30c90f2de53..8c03ce18b1f 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift @@ -50,19 +50,12 @@ class UserAPITests: XCTestCase { let expectation = self.expectationWithDescription("testLogout") UserAPI.logoutUser { (error) in - // The server gives us no data back so Alamofire parsing fails - at least - // verify that is the error we get here - guard let error = error else { + guard error == nil else { XCTFail("error logging out") return } - switch error { - case ErrorResponse.Error(200, _, _): - expectation.fulfill() - default: - XCTFail("error logging out") - } + expectation.fulfill() } self.waitForExpectationsWithTimeout(testTimeout, handler: nil) @@ -82,19 +75,12 @@ class UserAPITests: XCTestCase { newUser.userStatus = 0 UserAPI.createUser(body: newUser) { (error) in - // The server gives us no data back so Alamofire parsing fails - at least - // verify that is the error we get here - guard let error = error else { + guard error == nil else { XCTFail("error creating user") return } - switch error { - case ErrorResponse.Error(200, _, _): - expectation.fulfill() - default: - XCTFail("error creating user") - } + expectation.fulfill() } self.waitForExpectationsWithTimeout(testTimeout, handler: nil) @@ -128,19 +114,12 @@ class UserAPITests: XCTestCase { let expectation = self.expectationWithDescription("testDeleteUser") UserAPI.deleteUser(username: "test@test.com") { (error) in - // The server gives us no data back so Alamofire parsing fails - at least - // verify that is the error we get here - guard let error = error else { + guard error == nil else { XCTFail("error deleting user") return } - switch error { - case ErrorResponse.Error(200, _, _): - expectation.fulfill() - default: - XCTFail("error deleting user") - } + expectation.fulfill() } self.waitForExpectationsWithTimeout(testTimeout, handler: nil) diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index 8e7cef70fed..7935598291f 100644 --- a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -89,6 +89,26 @@ class AlamofireRequestBuilder: RequestBuilder { let validatedRequest = request.validate() switch T.self { + case is Void.Type: + validatedRequest.responseData(completionHandler: { (voidResponse) in + cleanupRequest() + + if voidResponse.result.isFailure { + completion( + response: nil, + error: ErrorResponse.Error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.result.error!) + ) + return + } + + completion( + response: Response( + response: voidResponse.response!, + body: nil + ), + error: nil + ) + }) case is NSData.Type: validatedRequest.responseData(completionHandler: { (dataResponse) in cleanupRequest() diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models.swift index a42fc32fdd5..32175b605a3 100644 --- a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models.swift +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models.swift @@ -17,15 +17,15 @@ public enum ErrorResponse : ErrorType { public class Response { public let statusCode: Int public let header: [String: String] - public let body: T + public let body: T? - public init(statusCode: Int, header: [String: String], body: T) { + public init(statusCode: Int, header: [String: String], body: T?) { self.statusCode = statusCode self.header = header self.body = body } - public convenience init(response: NSHTTPURLResponse, body: T) { + public convenience init(response: NSHTTPURLResponse, body: T?) { let rawHeader = response.allHeaderFields var header = [String:String]() for (key, value) in rawHeader { diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift index 09f9dea54d0..e76c5700aa2 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift @@ -61,24 +61,8 @@ class PetAPITests: XCTestCase { func test3DeletePet() { let expectation = self.expectationWithDescription("testDeletePet") - PetAPI.deletePet(petId: 1000).always { - // expectation.fulfill() - }.always { - // Noop for now - }.error { errorType -> Void in - // The server gives us no data back so alamofire parsing fails - at least - // verify that is the error we get here - guard let error = errorType as? ErrorResponse else { - XCTFail("error logging out") - return - } - - switch error { - case ErrorResponse.Error(200, _, _): - expectation.fulfill() - default: - XCTFail("error logging out") - } + PetAPI.deletePet(petId: 1000).then { + expectation.fulfill() } self.waitForExpectationsWithTimeout(testTimeout, handler: nil) } diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift index c41dfc69da2..2e37e3d3917 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift @@ -62,23 +62,7 @@ class StoreAPITests: XCTestCase { func test3DeleteOrder() { let expectation = self.expectationWithDescription("testDeleteOrder") StoreAPI.deleteOrder(orderId: "1000").then { - expectation.fulfill() - }.always { - // Noop for now - }.error { errorType -> Void in - // The server gives us no data back so alamofire parsing fails - at least - // verify that is the error we get here - guard let error = errorType as? ErrorResponse else { - XCTFail("error deleting order") - return - } - - switch error { - case ErrorResponse.Error(200, _, _): - expectation.fulfill() - default: - XCTFail("error deleting order") - } + expectation.fulfill() } self.waitForExpectationsWithTimeout(testTimeout, handler: nil) } diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift index 3cce03af756..732103534b2 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift @@ -52,23 +52,7 @@ class UserAPITests: XCTestCase { func testLogout() { let expectation = self.expectationWithDescription("testLogout") UserAPI.logoutUser().then { - expectation.fulfill() - }.always { - // Noop for now - }.error { errorType -> Void in - // The server gives us no data back so alamofire parsing fails - at least - // verify that is the error we get here - guard let error = errorType as? ErrorResponse else { - XCTFail("error logging out") - return - } - - switch error { - case ErrorResponse.Error(200, _, _): - expectation.fulfill() - default: - XCTFail("error logging out") - } + expectation.fulfill() } self.waitForExpectationsWithTimeout(testTimeout, handler: nil) } @@ -85,23 +69,7 @@ class UserAPITests: XCTestCase { newUser.username = "test@test.com" newUser.userStatus = 0 UserAPI.createUser(body: newUser).then { - expectation.fulfill() - }.always { - // Noop for now - }.error { errorType -> Void in - // The server gives us no data back so alamofire parsing fails - at least - // verify that is the error we get here - guard let error = errorType as? ErrorResponse else { - XCTFail("error creating user") - return - } - - switch error { - case ErrorResponse.Error(200, _, _): - expectation.fulfill() - default: - XCTFail("error creating user") - } + expectation.fulfill() } self.waitForExpectationsWithTimeout(testTimeout, handler: nil) } @@ -127,23 +95,7 @@ class UserAPITests: XCTestCase { func test3DeleteUser() { let expectation = self.expectationWithDescription("testDeleteUser") UserAPI.deleteUser(username: "test@test.com").then { - expectation.fulfill() - }.always { - // Noop for now - }.error { errorType -> Void in - // The server gives us no data back so alamofire parsing fails - at least - // verify that is the error we get here - guard let error = errorType as? ErrorResponse else { - XCTFail("error deleting user") - return - } - - switch error { - case ErrorResponse.Error(200, _, _): - expectation.fulfill() - default: - XCTFail("error deleting user") - } + expectation.fulfill() } self.waitForExpectationsWithTimeout(testTimeout, handler: nil) } From e89f914e8b5468e0522fe4f2e70d69b134f0990f Mon Sep 17 00:00:00 2001 From: Jason Gavris Date: Tue, 23 Aug 2016 10:15:47 -0400 Subject: [PATCH 274/470] [Swift] Handle String responses --- .../swift/AlamofireImplementations.mustache | 20 +++++++++++++ .../Swaggers/AlamofireImplementations.swift | 20 +++++++++++++ .../SwaggerClientTests/UserAPITests.swift | 11 ++------ .../Swaggers/AlamofireImplementations.swift | 20 +++++++++++++ .../SwaggerClientTests/UserAPITests.swift | 28 +------------------ 5 files changed, 63 insertions(+), 36 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache index 7935598291f..693cd5efa84 100644 --- a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache @@ -89,6 +89,26 @@ class AlamofireRequestBuilder: RequestBuilder { let validatedRequest = request.validate() switch T.self { + case is String.Type: + validatedRequest.responseString(completionHandler: { (stringResponse) in + cleanupRequest() + + if stringResponse.result.isFailure { + completion( + response: nil, + error: ErrorResponse.Error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.result.error!) + ) + return + } + + completion( + response: Response( + response: stringResponse.response!, + body: (stringResponse.result.value ?? "") as! T + ), + error: nil + ) + }) case is Void.Type: validatedRequest.responseData(completionHandler: { (voidResponse) in cleanupRequest() diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index 7935598291f..693cd5efa84 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -89,6 +89,26 @@ class AlamofireRequestBuilder: RequestBuilder { let validatedRequest = request.validate() switch T.self { + case is String.Type: + validatedRequest.responseString(completionHandler: { (stringResponse) in + cleanupRequest() + + if stringResponse.result.isFailure { + completion( + response: nil, + error: ErrorResponse.Error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.result.error!) + ) + return + } + + completion( + response: Response( + response: stringResponse.response!, + body: (stringResponse.result.value ?? "") as! T + ), + error: nil + ) + }) case is Void.Type: validatedRequest.responseData(completionHandler: { (voidResponse) in cleanupRequest() diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift index 8c03ce18b1f..0bd94f524b6 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift +++ b/samples/client/petstore/swift/default/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift @@ -28,19 +28,12 @@ class UserAPITests: XCTestCase { let expectation = self.expectationWithDescription("testLogin") UserAPI.loginUser(username: "swiftTester", password: "swift") { (_, error) in - // The server isn't returning JSON - and currently the alamofire implementation - // always parses responses as JSON, so making an exception for this here - guard let error = error else { + guard error == nil else { XCTFail("error logging in") return } - switch error { - case ErrorResponse.Error(200, _, _): - expectation.fulfill() - default: - XCTFail("error logging in") - } + expectation.fulfill() } self.waitForExpectationsWithTimeout(testTimeout, handler: nil) diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index 7935598291f..693cd5efa84 100644 --- a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -89,6 +89,26 @@ class AlamofireRequestBuilder: RequestBuilder { let validatedRequest = request.validate() switch T.self { + case is String.Type: + validatedRequest.responseString(completionHandler: { (stringResponse) in + cleanupRequest() + + if stringResponse.result.isFailure { + completion( + response: nil, + error: ErrorResponse.Error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.result.error!) + ) + return + } + + completion( + response: Response( + response: stringResponse.response!, + body: (stringResponse.result.value ?? "") as! T + ), + error: nil + ) + }) case is Void.Type: validatedRequest.responseData(completionHandler: { (voidResponse) in cleanupRequest() diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift index 732103534b2..2caacc8d6da 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift @@ -14,37 +14,11 @@ import XCTest class UserAPITests: XCTestCase { let testTimeout = 10.0 - - override func setUp() { - super.setUp() - // Put setup code here. This method is called before the invocation of each test method in the class. - } - - override func tearDown() { - // Put teardown code here. This method is called after the invocation of each test method in the class. - super.tearDown() - } - + func testLogin() { let expectation = self.expectationWithDescription("testLogin") UserAPI.loginUser(username: "swiftTester", password: "swift").then { _ -> Void in expectation.fulfill() - }.always { - // Noop for now - }.error { errorType -> Void in - // The server isn't returning JSON - and currently the alamofire implementation - // always parses responses as JSON, so making an exception for this here - guard let error = errorType as? ErrorResponse else { - XCTFail("error logging in") - return - } - - switch error { - case ErrorResponse.Error(200, _, _): - expectation.fulfill() - default: - XCTFail("error logging in") - } } self.waitForExpectationsWithTimeout(testTimeout, handler: nil) } From 25a14f5d77c571e330dea84fb197ab979fa0acb8 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 24 Aug 2016 22:28:08 +0800 Subject: [PATCH 275/470] add http://www.plexxi.com/ --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 741fc21ef7f..70bbcef5275 100644 --- a/README.md +++ b/README.md @@ -781,6 +781,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [OSDN](https://osdn.jp) - [PagerDuty](https://www.pagerduty.com) - [Pepipost](https://www.pepipost.com) +- [Plexxi](http://www.plexxi.com) - [Pixoneye](http://www.pixoneye.com/) - [PostAffiliatePro](https://www.postaffiliatepro.com/) - [Rapid7](https://rapid7.com/) From 194c389a06853a67525c4e00d1c92f07ce27c16b Mon Sep 17 00:00:00 2001 From: cbornet Date: Wed, 24 Aug 2016 17:11:45 +0200 Subject: [PATCH 276/470] fix some inheritance/composition issues and add allOf unit tests Fix #3629 #3544 #3474 #3636 --- .../io/swagger/codegen/DefaultCodegen.java | 36 ++++- .../languages/JavascriptClientCodegen.java | 6 +- .../java/io/swagger/codegen/CodegenTest.java | 124 ++++++++++++++++++ .../src/test/resources/2_0/allOfTest.yaml | 104 +++++++++++++++ 4 files changed, 264 insertions(+), 6 deletions(-) create mode 100644 modules/swagger-codegen/src/test/resources/2_0/allOfTest.yaml 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 3ddba67f0d8..fd8e28d8a9a 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 @@ -100,6 +100,7 @@ public class DefaultCodegen { protected List cliOptions = new ArrayList(); protected boolean skipOverwrite; protected boolean supportsInheritance; + protected boolean supportsMixins; protected Map supportedLibraries = new LinkedHashMap(); protected String library; protected Boolean sortParamsByRequiredFlag = true; @@ -1233,7 +1234,7 @@ public CodegenModel fromModel(String name, Model model, Map allDe List required = new ArrayList(); Map allProperties; List allRequired; - if (supportsInheritance) { + if (supportsInheritance || supportsMixins) { allProperties = new LinkedHashMap(); allRequired = new ArrayList(); m.allVars = new ArrayList(); @@ -1254,17 +1255,20 @@ public CodegenModel fromModel(String name, Model model, Map allDe interfaceModel = allDefinitions.get(_interface.getSimpleRef()); } // set first interface with discriminator found as parent - if (parent == null && interfaceModel instanceof ModelImpl && ((ModelImpl) interfaceModel).getDiscriminator() != null) { + if (parent == null + && ((interfaceModel instanceof ModelImpl && ((ModelImpl) interfaceModel).getDiscriminator() != null) + || (interfaceModel instanceof ComposedModel && isDiscriminatorInInterfaceTree((ComposedModel) interfaceModel, allDefinitions)))) { parent = _interface; } else { final String interfaceRef = toModelName(_interface.getSimpleRef()); m.interfaces.add(interfaceRef); addImport(m, interfaceRef); if (allDefinitions != null) { + if (!supportsMixins) { + addProperties(properties, required, interfaceModel, allDefinitions); + } if (supportsInheritance) { addProperties(allProperties, allRequired, interfaceModel, allDefinitions); - } else { - addProperties(properties, required, interfaceModel, allDefinitions); } } } @@ -1323,6 +1327,30 @@ public CodegenModel fromModel(String name, Model model, Map allDe return m; } + /** + * Recursively look for a discriminator in the interface tree + */ + private boolean isDiscriminatorInInterfaceTree(ComposedModel model, Map allDefinitions) { + if (model == null || allDefinitions == null) + return false; + + Model child = ((ComposedModel) model).getChild(); + if (child instanceof ModelImpl && ((ModelImpl) child).getDiscriminator() != null) { + return true; + } + for (RefModel _interface : model.getInterfaces()) { + Model interfaceModel = allDefinitions.get(_interface.getSimpleRef()); + if (interfaceModel instanceof ModelImpl && ((ModelImpl) interfaceModel).getDiscriminator() != null) { + return true; + } + if (interfaceModel instanceof ComposedModel) { + + return isDiscriminatorInInterfaceTree((ComposedModel) interfaceModel, allDefinitions); + } + } + return false; + } + protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, ModelImpl swaggerModel) { MapProperty mapProperty = new MapProperty(swaggerModel.getAdditionalProperties()); addParentContainer(codegenModel, codegenModel.name, mapProperty); 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 950212197b7..549c1988dfb 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 @@ -223,6 +223,7 @@ public void processOpts() { setUseInheritance(Boolean.parseBoolean((String)additionalProperties.get(USE_INHERITANCE))); } else { supportsInheritance = true; + supportsMixins = true; } if (additionalProperties.containsKey(EMIT_MODEL_METHODS)) { setEmitModelMethods(Boolean.parseBoolean((String)additionalProperties.get(EMIT_MODEL_METHODS))); @@ -386,6 +387,7 @@ public void setUsePromises(boolean usePromises) { public void setUseInheritance(boolean useInheritance) { this.supportsInheritance = useInheritance; + this.supportsMixins = useInheritance; } public void setEmitModelMethods(boolean emitModelMethods) { @@ -889,7 +891,7 @@ public Map postProcessModels(Map objs) { // NOTE: can't use 'mandatory' as it is built from ModelImpl.getRequired(), which sorts names // alphabetically and in any case the document order of 'required' and 'properties' can differ. List required = new ArrayList<>(); - List allRequired = supportsInheritance ? new ArrayList() : required; + List allRequired = supportsInheritance || supportsMixins ? new ArrayList() : required; cm.vendorExtensions.put("x-required", required); cm.vendorExtensions.put("x-all-required", allRequired); @@ -903,7 +905,7 @@ public Map postProcessModels(Map objs) { } } - if (supportsInheritance) { + if (supportsInheritance || supportsMixins) { for (CodegenProperty var : cm.allVars) { if (Boolean.TRUE.equals(var.required)) { allRequired.add(var); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java index 9842258fb92..e96ad452806 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java @@ -1,5 +1,6 @@ package io.swagger.codegen; +import io.swagger.models.Model; import io.swagger.models.Operation; import io.swagger.models.Swagger; import io.swagger.models.properties.Property; @@ -187,6 +188,129 @@ public void discriminatorTest() { Assert.assertEquals(op.discriminator, "className"); } + @Test(description = "handle simple composition") + public void simpleCompositionTest() { + final Swagger swagger = parseAndPrepareSwagger("src/test/resources/2_0/allOfTest.yaml"); + final DefaultCodegen codegen = new DefaultCodegen(); + codegen.supportsInheritance = true; + final Model model = swagger.getDefinitions().get("SimpleComposition"); + CodegenModel composed = codegen.fromModel("SimpleComposition", model, swagger.getDefinitions()); + + Assert.assertEquals(composed.vars.size(), 3); + Assert.assertEquals(composed.vars.get(0).baseName, "modelOneProp"); + Assert.assertEquals(composed.vars.get(1).baseName, "modelTwoProp"); + Assert.assertEquals(composed.vars.get(2).baseName, "simpleCompositionProp"); + Assert.assertNull(composed.parent); + } + + @Test(description = "handle multi level composition") + public void multiCompositionTest() { + final Swagger swagger = parseAndPrepareSwagger("src/test/resources/2_0/allOfTest.yaml"); + final DefaultCodegen codegen = new DefaultCodegen(); + codegen.supportsInheritance = true; + final Model model = swagger.getDefinitions().get("CompositionOfSimpleComposition"); + CodegenModel composed = codegen.fromModel("CompositionOfSimpleComposition", model, swagger.getDefinitions()); + + Assert.assertEquals(composed.vars.size(), 5); + Assert.assertEquals(composed.vars.get(0).baseName, "modelOneProp"); + Assert.assertEquals(composed.vars.get(1).baseName, "modelTwoProp"); + Assert.assertEquals(composed.vars.get(2).baseName, "simpleCompositionProp"); + Assert.assertEquals(composed.vars.get(3).baseName, "modelThreeProp"); + Assert.assertEquals(composed.vars.get(4).baseName, "compositionOfSimpleCompositionProp"); + Assert.assertNull(composed.parent); + } + + @Test(description = "handle simple inheritance") + public void simpleInheritanceTest() { + final Swagger swagger = parseAndPrepareSwagger("src/test/resources/2_0/allOfTest.yaml"); + final DefaultCodegen codegen = new DefaultCodegen(); + codegen.supportsInheritance = true; + final Model model = swagger.getDefinitions().get("ChildOfSimpleParent"); + CodegenModel child = codegen.fromModel("ChildOfSimpleParent", model, swagger.getDefinitions()); + + Assert.assertEquals(child.vars.size(), 2); + Assert.assertEquals(child.vars.get(0).baseName, "modelOneProp"); + Assert.assertEquals(child.vars.get(1).baseName, "childOfSimpleParentProp"); + Assert.assertEquals(child.parent, "SimpleParent"); + } + + @Test(description = "handle multi level inheritance") + public void multiInheritanceTest() { + final Swagger swagger = parseAndPrepareSwagger("src/test/resources/2_0/allOfTest.yaml"); + final DefaultCodegen codegen = new DefaultCodegen(); + codegen.supportsInheritance = true; + final Model model = swagger.getDefinitions().get("ChildOfChildOfSimpleParent"); + CodegenModel child = codegen.fromModel("ChildOfChildOfSimpleParent", model, swagger.getDefinitions()); + + Assert.assertEquals(child.vars.size(), 1); + Assert.assertEquals(child.vars.get(0).baseName, "childOfChildOfSimpleParentProp"); + Assert.assertEquals(child.parent, "ChildOfSimpleParent"); + } + + @Test(description = "copy properties in multi level inheritance if supportsInheritance is false") + public void noSupportsInheritanceTest() { + final Swagger swagger = parseAndPrepareSwagger("src/test/resources/2_0/allOfTest.yaml"); + final DefaultCodegen codegen = new DefaultCodegen(); + final Model model = swagger.getDefinitions().get("ChildOfChildOfSimpleParent"); + CodegenModel child = codegen.fromModel("ChildOfChildOfSimpleParent", model, swagger.getDefinitions()); + + Assert.assertEquals(child.vars.size(), 5); + Assert.assertEquals(child.vars.get(0).baseName, "modelOneProp"); + Assert.assertEquals(child.vars.get(1).baseName, "disc"); + Assert.assertEquals(child.vars.get(2).baseName, "simpleParentProp"); + Assert.assertEquals(child.vars.get(3).baseName, "childOfSimpleParentProp"); + Assert.assertEquals(child.vars.get(4).baseName, "childOfChildOfSimpleParentProp"); + Assert.assertEquals(child.parent, "ChildOfSimpleParent"); + } + + @Test(description = "don't copy interfaces properties if supportsMixins is true") + public void supportsMixinsTest() { + final Swagger swagger = parseAndPrepareSwagger("src/test/resources/2_0/allOfTest.yaml"); + final DefaultCodegen codegen = new DefaultCodegen(); + codegen.supportsInheritance = true; + codegen.supportsMixins = true; + final Model model = swagger.getDefinitions().get("ChildOfChildOfSimpleParent"); + CodegenModel child = codegen.fromModel("ChildOfChildOfSimpleParent", model, swagger.getDefinitions()); + + Assert.assertEquals(child.vars.size(), 1); + Assert.assertEquals(child.vars.get(0).baseName, "childOfChildOfSimpleParentProp"); + Assert.assertEquals(child.allVars.size(), 5); + Assert.assertEquals(child.allVars.get(0).baseName, "modelOneProp"); + Assert.assertEquals(child.allVars.get(1).baseName, "disc"); + Assert.assertEquals(child.allVars.get(2).baseName, "simpleParentProp"); + Assert.assertEquals(child.allVars.get(3).baseName, "childOfSimpleParentProp"); + Assert.assertEquals(child.allVars.get(4).baseName, "childOfChildOfSimpleParentProp"); + + Assert.assertEquals(child.parent, "ChildOfSimpleParent"); + } + + @Test(description = "handle inheritance from composed model") + public void inheritanceOfComposedModelTest() { + final Swagger swagger = parseAndPrepareSwagger("src/test/resources/2_0/allOfTest.yaml"); + final DefaultCodegen codegen = new DefaultCodegen(); + codegen.supportsInheritance = true; + final Model model = swagger.getDefinitions().get("ChildOfComposedParent"); + CodegenModel child = codegen.fromModel("ChildOfComposedParent", model, swagger.getDefinitions()); + + Assert.assertEquals(child.vars.size(), 1); + Assert.assertEquals(child.vars.get(0).baseName, "childOfComposedParentProp"); + Assert.assertEquals(child.parent, "ComposedParent"); + } + + @Test(description = "handle multi level inheritance from composed model") + public void multiInheritanceOfComposedModelTest() { + final Swagger swagger = parseAndPrepareSwagger("src/test/resources/2_0/allOfTest.yaml"); + final DefaultCodegen codegen = new DefaultCodegen(); + codegen.supportsInheritance = true; + final Model model = swagger.getDefinitions().get("ChildOfChildOfComposedParent"); + CodegenModel child = codegen.fromModel("ChildOfChildOfComposedParent", model, swagger.getDefinitions()); + + Assert.assertEquals(child.vars.size(), 1); + Assert.assertEquals(child.vars.get(0).baseName, "childOfChildOfComposedParentProp"); + Assert.assertEquals(child.parent, "ChildOfComposedParent"); + } + + @Test(description = "use operation consumes and produces") public void localConsumesAndProducesTest() { final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/globalConsumesAndProduces.json"); diff --git a/modules/swagger-codegen/src/test/resources/2_0/allOfTest.yaml b/modules/swagger-codegen/src/test/resources/2_0/allOfTest.yaml new file mode 100644 index 00000000000..2636d4e7aa9 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/2_0/allOfTest.yaml @@ -0,0 +1,104 @@ +swagger: '2.0' +info: + version: 0.0.0 + title: Simple API +paths: + /: + get: + responses: + 200: + description: OK + +definitions: + + ModelOne: + type: object + properties: + modelOneProp: + type: string + + ModelTwo: + type: object + properties: + modelTwoProp: + type: string + + ModelThree: + type: object + properties: + modelThreeProp: + type: string + + SimpleComposition: + allOf: + - $ref: '#/definitions/ModelOne' + - $ref: '#/definitions/ModelTwo' + - type: object + properties: + simpleCompositionProp: + type: string + + CompositionOfSimpleComposition: + allOf: + - $ref: '#/definitions/SimpleComposition' + - $ref: '#/definitions/ModelThree' + - type: object + properties: + compositionOfSimpleCompositionProp: + type: string + + SimpleParent: + type: object + discriminator: disc + properties: + disc: + type: string + simpleParentProp: + type: string + required: [disc] + + ChildOfSimpleParent: + allOf: + - $ref: '#/definitions/ModelOne' + - $ref: '#/definitions/SimpleParent' + - type: object + properties: + childOfSimpleParentProp: + type: string + + ChildOfChildOfSimpleParent: + allOf: + - $ref: '#/definitions/ChildOfSimpleParent' + - type: object + properties: + childOfChildOfSimpleParentProp: + type: string + + ComposedParent: + allOf: + - $ref: '#/definitions/ModelOne' + - $ref: '#/definitions/ModelTwo' + - type: object + discriminator: disc + properties: + disc: + type: string + composedParentProp: + type: string + required: [disc] + + ChildOfComposedParent: + allOf: + - $ref: '#/definitions/ComposedParent' + - type: object + properties: + childOfComposedParentProp: + type: string + + ChildOfChildOfComposedParent: + allOf: + - $ref: '#/definitions/ChildOfComposedParent' + - type: object + properties: + childOfChildOfComposedParentProp: + type: string \ No newline at end of file From beaf1fc7aa1c6f81dd47fa8a9b668b8ea1bb928b Mon Sep 17 00:00:00 2001 From: Tony Wang Date: Thu, 25 Aug 2016 19:34:12 +0800 Subject: [PATCH 277/470] fix #3477, add RxSwift support for Swift (#3490) * fix #3477, add RxSwift support for Swift * make the SwaggerClient scheme shared --- bin/swift-petstore-all.sh | 4 + bin/swift-petstore-rxswift.json | 7 + bin/swift-petstore-rxswift.sh | 31 + .../codegen/languages/SwiftCodegen.java | 6 +- .../main/resources/swift/Cartfile.mustache | 3 +- .../src/main/resources/swift/Podspec.mustache | 3 +- .../src/main/resources/swift/api.mustache | 25 +- .../client/petstore/swift/rxswift/.gitignore | 63 + .../swift/rxswift/.swagger-codegen-ignore | 23 + .../client/petstore/swift/rxswift/Cartfile | 2 + samples/client/petstore/swift/rxswift/LICENSE | 201 ++ .../swift/rxswift/PetstoreClient.podspec | 14 + .../Classes/Swaggers/APIHelper.swift | 40 + .../Classes/Swaggers/APIs.swift | 75 + .../Classes/Swaggers/APIs/PetAPI.swift | 608 ++++++ .../Classes/Swaggers/APIs/StoreAPI.swift | 302 +++ .../Classes/Swaggers/APIs/UserAPI.swift | 498 +++++ .../Swaggers/AlamofireImplementations.swift | 148 ++ .../Classes/Swaggers/Extensions.swift | 84 + .../Classes/Swaggers/Models.swift | 224 +++ .../Classes/Swaggers/Models/Category.swift | 25 + .../Classes/Swaggers/Models/Order.swift | 39 + .../Classes/Swaggers/Models/Pet.swift | 39 + .../Classes/Swaggers/Models/Tag.swift | 25 + .../Classes/Swaggers/Models/User.swift | 38 + .../swift/rxswift/SwaggerClientTests/Podfile | 10 + .../SwaggerClientTests/Pods/Alamofire/LICENSE | 19 + .../Pods/Alamofire/README.md | 1149 +++++++++++ .../Pods/Alamofire/Source/Alamofire.swift | 368 ++++ .../Pods/Alamofire/Source/Download.swift | 244 +++ .../Pods/Alamofire/Source/Error.swift | 66 + .../Pods/Alamofire/Source/Manager.swift | 693 +++++++ .../Alamofire/Source/MultipartFormData.swift | 669 +++++++ .../Alamofire/Source/ParameterEncoding.swift | 251 +++ .../Pods/Alamofire/Source/Request.swift | 538 +++++ .../Pods/Alamofire/Source/Response.swift | 83 + .../Source/ResponseSerialization.swift | 355 ++++ .../Pods/Alamofire/Source/Result.swift | 101 + .../Alamofire/Source/ServerTrustPolicy.swift | 302 +++ .../Pods/Alamofire/Source/Stream.swift | 180 ++ .../Pods/Alamofire/Source/Upload.swift | 372 ++++ .../Pods/Alamofire/Source/Validation.swift | 189 ++ .../PetstoreClient.podspec.json | 25 + .../SwaggerClientTests/Pods/Manifest.lock | 22 + .../Pods/Pods.xcodeproj/project.pbxproj | 1731 +++++++++++++++++ .../Pods/RxSwift/LICENSE.md | 9 + .../SwaggerClientTests/Pods/RxSwift/README.md | 180 ++ .../Pods/RxSwift/RxSwift/AnyObserver.swift | 75 + .../Pods/RxSwift/RxSwift/Cancelable.swift | 19 + .../RxSwift/Concurrency/AsyncLock.swift | 104 + .../RxSwift/RxSwift/Concurrency/Lock.swift | 107 + .../RxSwift/Concurrency/LockOwnerType.swift | 23 + .../Concurrency/SynchronizedDisposeType.swift | 20 + .../Concurrency/SynchronizedOnType.swift | 20 + .../SynchronizedSubscribeType.swift | 20 + .../SynchronizedUnsubscribeType.swift | 15 + .../RxSwift/ConnectableObservableType.swift | 21 + .../RxSwift/RxSwift/DataStructures/Bag.swift | 328 ++++ .../DataStructures/InfiniteSequence.swift | 30 + .../DataStructures/PriorityQueue.swift | 120 ++ .../RxSwift/DataStructures/Queue.swift | 168 ++ .../Pods/RxSwift/RxSwift/Disposable.swift | 15 + .../Disposables/AnonymousDisposable.swift | 54 + .../Disposables/BinaryDisposable.swift | 54 + .../Disposables/BooleanDisposable.swift | 45 + .../Disposables/CompositeDisposable.swift | 135 ++ .../RxSwift/Disposables/DisposeBag.swift | 94 + .../RxSwift/Disposables/DisposeBase.swift | 26 + .../RxSwift/Disposables/NAryDisposable.swift | 10 + .../RxSwift/Disposables/NopDisposable.swift | 32 + .../Disposables/RefCountDisposable.swift | 127 ++ .../Disposables/ScheduledDisposable.swift | 58 + .../Disposables/SerialDisposable.swift | 85 + .../SingleAssignmentDisposable.swift | 89 + .../StableCompositeDisposable.swift | 15 + .../Disposables/SubscriptionDisposable.swift | 23 + .../Pods/RxSwift/RxSwift/Errors.swift | 72 + .../Pods/RxSwift/RxSwift/Event.swift | 66 + .../RxSwift/Extensions/String+Rx.swift | 26 + .../RxSwift/ImmediateSchedulerType.swift | 40 + .../RxSwift/Observable+Extensions.swift | 128 ++ .../Pods/RxSwift/RxSwift/Observable.swift | 51 + .../RxSwift/ObservableConvertibleType.swift | 26 + .../Pods/RxSwift/RxSwift/ObservableType.swift | 57 + .../Observables/Implementations/AddRef.swift | 47 + .../Observables/Implementations/Amb.swift | 122 ++ .../Implementations/AnonymousObservable.swift | 56 + .../Observables/Implementations/Buffer.swift | 119 ++ .../Observables/Implementations/Catch.swift | 162 ++ .../CombineLatest+CollectionType.swift | 125 ++ .../Implementations/CombineLatest+arity.swift | 724 +++++++ .../Implementations/CombineLatest.swift | 134 ++ .../Observables/Implementations/Concat.swift | 63 + .../ConnectableObservable.swift | 96 + .../Observables/Implementations/Debug.swift | 77 + .../Implementations/Deferred.swift | 61 + .../Implementations/DelaySubscription.swift | 52 + .../DistinctUntilChanged.swift | 70 + .../Observables/Implementations/Do.swift | 53 + .../Implementations/ElementAt.swift | 79 + .../Observables/Implementations/Empty.swift | 16 + .../Observables/Implementations/Error.swift | 22 + .../Observables/Implementations/Filter.swift | 60 + .../Implementations/Generate.swift | 71 + .../Observables/Implementations/Just.swift | 61 + .../Observables/Implementations/Map.swift | 140 ++ .../Observables/Implementations/Merge.swift | 423 ++++ .../Implementations/Multicast.swift | 71 + .../Observables/Implementations/Never.swift | 15 + .../Implementations/ObserveOn.swift | 133 ++ .../ObserveOnSerialDispatchQueue.swift | 81 + .../Implementations/Producer.swift | 30 + .../Observables/Implementations/Range.swift | 59 + .../Observables/Implementations/Reduce.swift | 74 + .../Implementations/RefCount.swift | 84 + .../Observables/Implementations/Repeat.swift | 44 + .../Implementations/RetryWhen.swift | 150 ++ .../Observables/Implementations/Sample.swift | 129 ++ .../Observables/Implementations/Scan.swift | 64 + .../Implementations/Sequence.swift | 58 + .../Implementations/ShareReplay1.swift | 101 + .../ShareReplay1WhileConnected.swift | 92 + .../Implementations/SingleAsync.swift | 76 + .../Observables/Implementations/Sink.swift | 57 + .../Observables/Implementations/Skip.swift | 128 ++ .../Implementations/SkipUntil.swift | 125 ++ .../Implementations/SkipWhile.swift | 115 ++ .../Implementations/StartWith.swift | 28 + .../Implementations/SubscribeOn.swift | 60 + .../Observables/Implementations/Switch.swift | 193 ++ .../Observables/Implementations/Take.swift | 144 ++ .../Implementations/TakeLast.swift | 63 + .../Implementations/TakeUntil.swift | 120 ++ .../Implementations/TakeWhile.swift | 132 ++ .../Implementations/Throttle.swift | 104 + .../Observables/Implementations/Timeout.swift | 120 ++ .../Observables/Implementations/Timer.swift | 72 + .../Observables/Implementations/ToArray.swift | 50 + .../Observables/Implementations/Using.swift | 78 + .../Observables/Implementations/Window.swift | 152 ++ .../Implementations/WithLatestFrom.swift | 122 ++ .../Implementations/Zip+CollectionType.swift | 137 ++ .../Implementations/Zip+arity.swift | 829 ++++++++ .../Observables/Implementations/Zip.swift | 157 ++ .../Observables/Observable+Aggregate.swift | 64 + .../Observables/Observable+Binding.swift | 190 ++ .../Observables/Observable+Concurrency.swift | 62 + .../Observables/Observable+Creation.swift | 219 +++ .../Observables/Observable+Debug.swift | 28 + .../Observables/Observable+Multiple.swift | 330 ++++ .../Observables/Observable+Single.swift | 258 +++ ...Observable+StandardSequenceOperators.swift | 323 +++ .../RxSwift/Observables/Observable+Time.swift | 274 +++ .../Pods/RxSwift/RxSwift/ObserverType.swift | 56 + .../RxSwift/Observers/AnonymousObserver.swift | 34 + .../RxSwift/Observers/ObserverBase.swift | 39 + .../RxSwift/Observers/TailRecursiveSink.swift | 151 ++ .../RxSwift/Platform/Platform.Darwin.swift | 45 + .../RxSwift/Platform/Platform.Linux.swift | 222 +++ .../Pods/RxSwift/RxSwift/Rx.swift | 42 + .../Pods/RxSwift/RxSwift/RxMutableBox.swift | 37 + .../Pods/RxSwift/RxSwift/SchedulerType.swift | 78 + .../ConcurrentDispatchQueueScheduler.swift | 147 ++ .../Schedulers/ConcurrentMainScheduler.swift | 90 + .../Schedulers/CurrentThreadScheduler.swift | 147 ++ .../DispatchQueueSchedulerQOS.swift | 54 + .../Schedulers/HistoricalScheduler.swift | 25 + .../HistoricalSchedulerTimeConverter.swift | 83 + .../Schedulers/ImmediateScheduler.swift | 39 + .../Internal/AnonymousInvocable.swift | 21 + .../Internal/InvocableScheduledItem.swift | 24 + .../Schedulers/Internal/InvocableType.swift | 19 + .../Schedulers/Internal/ScheduledItem.swift | 37 + .../Internal/ScheduledItemType.swift | 15 + .../RxSwift/Schedulers/MainScheduler.swift | 73 + .../Schedulers/OperationQueueScheduler.swift | 57 + .../Schedulers/RecursiveScheduler.swift | 193 ++ .../SchedulerServices+Emulation.swift | 63 + .../SerialDispatchQueueScheduler.swift | 184 ++ .../Schedulers/VirtualTimeConverterType.swift | 115 ++ .../Schedulers/VirtualTimeScheduler.swift | 292 +++ .../RxSwift/Subjects/BehaviorSubject.swift | 161 ++ .../RxSwift/Subjects/PublishSubject.swift | 139 ++ .../RxSwift/Subjects/ReplaySubject.swift | 263 +++ .../RxSwift/Subjects/SubjectType.swift | 29 + .../RxSwift/RxSwift/Subjects/Variable.swift | 69 + .../Alamofire/Alamofire-dummy.m | 5 + .../Alamofire/Alamofire-prefix.pch | 3 + .../Alamofire/Alamofire-umbrella.h | 5 + .../Alamofire/Alamofire.modulemap | 6 + .../Alamofire/Alamofire.xcconfig | 9 + .../Target Support Files/Alamofire/Info.plist | 26 + .../PetstoreClient/Info.plist | 26 + .../PetstoreClient/PetstoreClient-dummy.m | 5 + .../PetstoreClient/PetstoreClient-prefix.pch | 3 + .../PetstoreClient/PetstoreClient-umbrella.h | 5 + .../PetstoreClient/PetstoreClient.modulemap | 6 + .../PetstoreClient/PetstoreClient.xcconfig | 10 + .../Pods-SwaggerClient/Info.plist | 26 + ...ds-SwaggerClient-acknowledgements.markdown | 243 +++ .../Pods-SwaggerClient-acknowledgements.plist | 281 +++ .../Pods-SwaggerClient-dummy.m | 5 + .../Pods-SwaggerClient-frameworks.sh | 95 + .../Pods-SwaggerClient-resources.sh | 102 + .../Pods-SwaggerClient-umbrella.h | 5 + .../Pods-SwaggerClient.debug.xcconfig | 10 + .../Pods-SwaggerClient.modulemap | 6 + .../Pods-SwaggerClient.release.xcconfig | 10 + .../Pods-SwaggerClientTests/Info.plist | 26 + ...aggerClientTests-acknowledgements.markdown | 3 + ...-SwaggerClientTests-acknowledgements.plist | 29 + .../Pods-SwaggerClientTests-dummy.m | 5 + .../Pods-SwaggerClientTests-frameworks.sh | 83 + .../Pods-SwaggerClientTests-resources.sh | 102 + .../Pods-SwaggerClientTests-umbrella.h | 5 + .../Pods-SwaggerClientTests.debug.xcconfig | 7 + .../Pods-SwaggerClientTests.modulemap | 6 + .../Pods-SwaggerClientTests.release.xcconfig | 7 + .../Target Support Files/RxSwift/Info.plist | 26 + .../RxSwift/RxSwift-dummy.m | 5 + .../RxSwift/RxSwift-prefix.pch | 3 + .../RxSwift/RxSwift-umbrella.h | 5 + .../RxSwift/RxSwift.modulemap | 6 + .../RxSwift/RxSwift.xcconfig | 9 + .../SwaggerClient.xcodeproj/project.pbxproj | 553 ++++++ .../contents.xcworkspacedata | 7 + .../xcschemes/SwaggerClient.xcscheme | 101 + .../contents.xcworkspacedata | 10 + .../SwaggerClient/AppDelegate.swift | 45 + .../AppIcon.appiconset/Contents.json | 38 + .../Base.lproj/LaunchScreen.storyboard | 27 + .../SwaggerClient/Base.lproj/Main.storyboard | 25 + .../SwaggerClient/Info.plist | 58 + .../SwaggerClient/ViewController.swift | 24 + .../SwaggerClientTests/Info.plist | 35 + .../SwaggerClientTests/PetAPITests.swift | 78 + .../SwaggerClientTests/StoreAPITests.swift | 97 + .../SwaggerClientTests/UserAPITests.swift | 133 ++ .../swift/rxswift/SwaggerClientTests/pom.xml | 65 + .../client/petstore/swift/rxswift/git_push.sh | 51 + 240 files changed, 26914 insertions(+), 4 deletions(-) create mode 100644 bin/swift-petstore-rxswift.json create mode 100755 bin/swift-petstore-rxswift.sh create mode 100644 samples/client/petstore/swift/rxswift/.gitignore create mode 100644 samples/client/petstore/swift/rxswift/.swagger-codegen-ignore create mode 100644 samples/client/petstore/swift/rxswift/Cartfile create mode 100644 samples/client/petstore/swift/rxswift/LICENSE create mode 100644 samples/client/petstore/swift/rxswift/PetstoreClient.podspec create mode 100644 samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIHelper.swift create mode 100644 samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs.swift create mode 100644 samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift create mode 100644 samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift create mode 100644 samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift create mode 100644 samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift create mode 100644 samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Extensions.swift create mode 100644 samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models.swift create mode 100644 samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/Category.swift create mode 100644 samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/Order.swift create mode 100644 samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/Pet.swift create mode 100644 samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/Tag.swift create mode 100644 samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/User.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Podfile create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/LICENSE create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/README.md create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Download.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Error.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Request.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Response.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Result.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Manifest.lock create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/LICENSE.md create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/README.md create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/AnyObserver.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Cancelable.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/Lock.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedSubscribeType.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ConnectableObservableType.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/DataStructures/Bag.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/DataStructures/InfiniteSequence.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/DataStructures/PriorityQueue.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/DataStructures/Queue.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposable.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/NAryDisposable.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/StableCompositeDisposable.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Errors.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Event.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Extensions/String+Rx.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observable+Extensions.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observable.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObservableType.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/AddRef.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Amb.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/AnonymousObservable.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Buffer.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Catch.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/CombineLatest+CollectionType.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/CombineLatest+arity.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/CombineLatest.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Concat.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ConnectableObservable.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Debug.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Deferred.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/DelaySubscription.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/DistinctUntilChanged.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Do.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ElementAt.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Empty.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Error.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Filter.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Generate.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Just.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Map.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Merge.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Multicast.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Never.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ObserveOn.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ObserveOnSerialDispatchQueue.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Producer.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Range.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Reduce.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/RefCount.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Repeat.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/RetryWhen.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Sample.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Scan.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Sequence.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ShareReplay1.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ShareReplay1WhileConnected.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/SingleAsync.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Sink.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Skip.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/SkipUntil.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/SkipWhile.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/StartWith.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/SubscribeOn.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Switch.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Take.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/TakeLast.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/TakeUntil.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/TakeWhile.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Throttle.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Timeout.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Timer.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ToArray.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Using.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Window.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/WithLatestFrom.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Zip+CollectionType.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Zip+arity.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Zip.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Aggregate.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Binding.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Concurrency.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Creation.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Debug.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Multiple.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Single.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+StandardSequenceOperators.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Time.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObserverType.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Platform/Platform.Darwin.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Platform/Platform.Linux.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Rx.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/RxMutableBox.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/SchedulerType.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/DispatchQueueSchedulerQOS.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ImmediateScheduler.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/AnonymousInvocable.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Subjects/BehaviorSubject.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Subjects/PublishSubject.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Subjects/ReplaySubject.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Subjects/SubjectType.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Subjects/Variable.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-dummy.m create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.modulemap create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/Alamofire/Alamofire.xcconfig create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/Alamofire/Info.plist create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/Info.plist create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-dummy.m create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-prefix.pch create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient-umbrella.h create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.modulemap create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/PetstoreClient/PetstoreClient.xcconfig create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Info.plist create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.markdown create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-acknowledgements.plist create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-dummy.m create mode 100755 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh create mode 100755 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-resources.sh create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-umbrella.h create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.modulemap create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Info.plist create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-acknowledgements.markdown create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-acknowledgements.plist create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-dummy.m create mode 100755 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-frameworks.sh create mode 100755 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-resources.sh create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests-umbrella.h create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.modulemap create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/RxSwift/Info.plist create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/RxSwift/RxSwift-dummy.m create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/RxSwift/RxSwift-prefix.pch create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/RxSwift/RxSwift-umbrella.h create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/RxSwift/RxSwift.modulemap create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Target Support Files/RxSwift/RxSwift.xcconfig create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/SwaggerClient.xcodeproj/project.xcworkspace/contents.xcworkspacedata create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/SwaggerClient.xcodeproj/xcshareddata/xcschemes/SwaggerClient.xcscheme create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/SwaggerClient/AppDelegate.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/SwaggerClient/Assets.xcassets/AppIcon.appiconset/Contents.json create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/SwaggerClient/Base.lproj/LaunchScreen.storyboard create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/SwaggerClient/Base.lproj/Main.storyboard create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/SwaggerClient/Info.plist create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/SwaggerClient/ViewController.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/SwaggerClientTests/Info.plist create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/SwaggerClientTests/UserAPITests.swift create mode 100644 samples/client/petstore/swift/rxswift/SwaggerClientTests/pom.xml create mode 100644 samples/client/petstore/swift/rxswift/git_push.sh diff --git a/bin/swift-petstore-all.sh b/bin/swift-petstore-all.sh index e74eba37704..5d3f2b7f82d 100755 --- a/bin/swift-petstore-all.sh +++ b/bin/swift-petstore-all.sh @@ -34,3 +34,7 @@ java $JAVA_OPTS -jar $executable $ags ags="$@ generate -t modules/swagger-codegen/src/main/resources/swift -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l swift -c ./bin/swift-petstore-promisekit.json -o samples/client/petstore/swift/promisekit" echo "#### Petstore Swift API client (promisekit) ####" java $JAVA_OPTS -jar $executable $ags + +ags="$@ generate -t modules/swagger-codegen/src/main/resources/swift -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l swift -c ./bin/swift-petstore-rxswift.json -o samples/client/petstore/swift/rxswift" +echo "#### Petstore Swift API client (rxswift) ####" +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/swift-petstore-rxswift.json b/bin/swift-petstore-rxswift.json new file mode 100644 index 00000000000..3a81d53deed --- /dev/null +++ b/bin/swift-petstore-rxswift.json @@ -0,0 +1,7 @@ +{ + "podSummary": "PetstoreClient", + "podHomepage": "https://github.com/swagger-api/swagger-codegen", + "podAuthors": "", + "projectName": "PetstoreClient", + "responseAs": "RxSwift" +} diff --git a/bin/swift-petstore-rxswift.sh b/bin/swift-petstore-rxswift.sh new file mode 100755 index 00000000000..c140ed7f908 --- /dev/null +++ b/bin/swift-petstore-rxswift.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/swift -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l swift -c ./bin/swift-petstore-rxswift.json -o samples/client/petstore/swift/rxswift" + +java $JAVA_OPTS -jar $executable $ags diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java index 72e085ce596..3ce1342998d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java @@ -40,7 +40,8 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { public static final String SWIFT_USE_API_NAMESPACE = "swiftUseApiNamespace"; public static final String DEFAULT_POD_AUTHORS = "Swagger Codegen"; protected static final String LIBRARY_PROMISE_KIT = "PromiseKit"; - protected static final String[] RESPONSE_LIBRARIES = { LIBRARY_PROMISE_KIT }; + protected static final String LIBRARY_RX_SWIFT = "RxSwift"; + protected static final String[] RESPONSE_LIBRARIES = { LIBRARY_PROMISE_KIT, LIBRARY_RX_SWIFT }; protected String projectName = "SwaggerClient"; protected boolean unwrapRequired; protected boolean swiftUseApiNamespace; @@ -186,6 +187,9 @@ public void processOpts() { if (ArrayUtils.contains(responseAs, LIBRARY_PROMISE_KIT)) { additionalProperties.put("usePromiseKit", true); } + if (ArrayUtils.contains(responseAs, LIBRARY_RX_SWIFT)) { + additionalProperties.put("useRxSwift", true); + } // Setup swiftUseApiNamespace option, which makes all the API classes inner-class of {{projectName}}API if (additionalProperties.containsKey(SWIFT_USE_API_NAMESPACE)) { diff --git a/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache b/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache index a0906ba5969..101df9a7e04 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache @@ -1,2 +1,3 @@ github "Alamofire/Alamofire" >= 3.1.0{{#usePromiseKit}} -github "mxcl/PromiseKit" >=1.5.3{{/usePromiseKit}} +github "mxcl/PromiseKit" >=1.5.3{{/usePromiseKit}}{{#useRxSwift}} +github "ReactiveX/RxSwift" ~> 2.0{{/useRxSwift}} diff --git a/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache index f893182d9ab..b5b1d0efb63 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache @@ -15,6 +15,7 @@ Pod::Spec.new do |s| s.screenshots = {{& podScreenshots}}{{/podScreenshots}}{{#podDocumentationURL}} s.documentation_url = '{{podDocumentationURL}}'{{/podDocumentationURL}} s.source_files = '{{projectName}}/Classes/Swaggers/**/*.swift'{{#usePromiseKit}} - s.dependency 'PromiseKit', '~> 3.1.1'{{/usePromiseKit}} + s.dependency 'PromiseKit', '~> 3.1.1'{{/usePromiseKit}}{{#useRxSwift}} + s.dependency 'RxSwift', '~> 2.0'{{/useRxSwift}} s.dependency 'Alamofire', '~> 3.4.1' end diff --git a/modules/swagger-codegen/src/main/resources/swift/api.mustache b/modules/swagger-codegen/src/main/resources/swift/api.mustache index 8698c5da4e7..88fb5c33d8c 100644 --- a/modules/swagger-codegen/src/main/resources/swift/api.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/api.mustache @@ -6,7 +6,8 @@ // import Alamofire{{#usePromiseKit}} -import PromiseKit{{/usePromiseKit}} +import PromiseKit{{/usePromiseKit}}{{#useRxSwift}} +import RxSwift{{/useRxSwift}} {{#swiftUseApiNamespace}} extension {{projectName}}API { @@ -62,6 +63,28 @@ public class {{classname}}: APIBase { return deferred.promise } {{/usePromiseKit}} +{{#useRxSwift}} + /** + {{#summary}} + {{{summary}}} + {{/summary}}{{#allParams}} + - parameter {{paramName}}: ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}} + - returns: Observable<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> + */ + public class func {{operationId}}({{#allParams}}{{^secondaryParam}}{{paramName}} {{/secondaryParam}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Observable<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { + return Observable.create { observer -> Disposable in + {{operationId}}({{#allParams}}{{paramName}}: {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { {{#returnType}}data, {{/returnType}}error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next({{#returnType}}data!{{/returnType}})) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } +{{/useRxSwift}} /** {{#summary}} diff --git a/samples/client/petstore/swift/rxswift/.gitignore b/samples/client/petstore/swift/rxswift/.gitignore new file mode 100644 index 00000000000..fc4e330f8fa --- /dev/null +++ b/samples/client/petstore/swift/rxswift/.gitignore @@ -0,0 +1,63 @@ +# Xcode +# +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + +## Build generated +build/ +DerivedData + +## Various settings +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 +xcuserdata + +## Other +*.xccheckout +*.moved-aside +*.xcuserstate +*.xcscmblueprint + +## Obj-C/Swift specific +*.hmap +*.ipa + +## Playgrounds +timeline.xctimeline +playground.xcworkspace + +# Swift Package Manager +# +# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. +# Packages/ +.build/ + +# CocoaPods +# +# We recommend against adding the Pods directory to your .gitignore. However +# you should judge for yourself, the pros and cons are mentioned at: +# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control +# +# Pods/ + +# Carthage +# +# Add this line if you want to avoid checking in source code from Carthage dependencies. +# Carthage/Checkouts + +Carthage/Build + +# fastlane +# +# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the +# screenshots whenever they are needed. +# For more information about the recommended setup visit: +# https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md + +fastlane/report.xml +fastlane/screenshots diff --git a/samples/client/petstore/swift/rxswift/.swagger-codegen-ignore b/samples/client/petstore/swift/rxswift/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/swift/rxswift/Cartfile b/samples/client/petstore/swift/rxswift/Cartfile new file mode 100644 index 00000000000..d862ef91d09 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/Cartfile @@ -0,0 +1,2 @@ +github "Alamofire/Alamofire" >= 3.1.0 +github "ReactiveX/RxSwift" ~> 2.0 diff --git a/samples/client/petstore/swift/rxswift/LICENSE b/samples/client/petstore/swift/rxswift/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient.podspec b/samples/client/petstore/swift/rxswift/PetstoreClient.podspec new file mode 100644 index 00000000000..41010ccde4a --- /dev/null +++ b/samples/client/petstore/swift/rxswift/PetstoreClient.podspec @@ -0,0 +1,14 @@ +Pod::Spec.new do |s| + s.name = 'PetstoreClient' + s.ios.deployment_target = '8.0' + s.osx.deployment_target = '10.9' + s.version = '0.0.1' + s.source = { :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' } + s.authors = '' + s.license = 'Apache License, Version 2.0' + s.homepage = 'https://github.com/swagger-api/swagger-codegen' + s.summary = 'PetstoreClient' + s.source_files = 'PetstoreClient/Classes/Swaggers/**/*.swift' + s.dependency 'RxSwift', '~> 2.0' + s.dependency 'Alamofire', '~> 3.1.5' +end diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIHelper.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIHelper.swift new file mode 100644 index 00000000000..23e727b6b54 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIHelper.swift @@ -0,0 +1,40 @@ +// APIHelper.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +class APIHelper { + static func rejectNil(source: [String:AnyObject?]) -> [String:AnyObject]? { + var destination = [String:AnyObject]() + for (key, nillableValue) in source { + if let value: AnyObject = nillableValue { + destination[key] = value + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + static func convertBoolToString(source: [String: AnyObject]?) -> [String:AnyObject]? { + guard let source = source else { + return nil + } + var destination = [String:AnyObject]() + let theTrue = NSNumber(bool: true) + let theFalse = NSNumber(bool: false) + for (key, value) in source { + switch value { + case let x where x === theTrue || x === theFalse: + destination[key] = "\(value as! Bool)" + default: + destination[key] = value + } + } + return destination + } + +} diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs.swift new file mode 100644 index 00000000000..40253b7b32d --- /dev/null +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs.swift @@ -0,0 +1,75 @@ +// APIs.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +public class PetstoreClientAPI { + public static var basePath = "http://petstore.swagger.io/v2" + public static var credential: NSURLCredential? + public static var customHeaders: [String:String] = [:] + static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory() +} + +public class APIBase { + func toParameters(encodable: JSONEncodable?) -> [String: AnyObject]? { + let encoded: AnyObject? = encodable?.encodeToJSON() + + if encoded! is [AnyObject] { + var dictionary = [String:AnyObject]() + for (index, item) in (encoded as! [AnyObject]).enumerate() { + dictionary["\(index)"] = item + } + return dictionary + } else { + return encoded as? [String:AnyObject] + } + } +} + +public class RequestBuilder { + var credential: NSURLCredential? + var headers: [String:String] = [:] + let parameters: [String:AnyObject]? + let isBody: Bool + let method: String + let URLString: String + + /// Optional block to obtain a reference to the request's progress instance when available. + public var onProgressReady: ((NSProgress) -> ())? + + required public init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool) { + self.method = method + self.URLString = URLString + self.parameters = parameters + self.isBody = isBody + + addHeaders(PetstoreClientAPI.customHeaders) + } + + public func addHeaders(aHeaders:[String:String]) { + for (header, value) in aHeaders { + headers[header] = value + } + } + + public func execute(completion: (response: Response?, error: ErrorType?) -> Void) { } + + public func addHeader(name name: String, value: String) -> Self { + if !value.isEmpty { + headers[name] = value + } + return self + } + + public func addCredential() -> Self { + self.credential = PetstoreClientAPI.credential + return self + } +} + +protocol RequestBuilderFactory { + func getBuilder() -> RequestBuilder.Type +} diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift new file mode 100644 index 00000000000..ee5d73bf4c7 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -0,0 +1,608 @@ +// +// PetAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire +import RxSwift + + + +public class PetAPI: APIBase { + /** + Add a new pet to the store + + - parameter body: (body) Pet object that needs to be added to the store (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func addPet(body body: Pet? = nil, completion: ((error: ErrorType?) -> Void)) { + addPetWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error: error); + } + } + + /** + Add a new pet to the store + + - parameter body: (body) Pet object that needs to be added to the store (optional) + - returns: Observable + */ + public class func addPet(body body: Pet? = nil) -> Observable { + return Observable.create { observer -> Disposable in + addPet(body: body) { error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next()) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Add a new pet to the store + - POST /pet + - + - OAuth: + - type: oauth2 + - name: petstore_auth + + - parameter body: (body) Pet object that needs to be added to the store (optional) + + - returns: RequestBuilder + */ + public class func addPetWithRequestBuilder(body body: Pet? = nil) -> RequestBuilder { + let path = "/pet" + let URLString = PetstoreClientAPI.basePath + path + let parameters = body?.encodeToJSON() as? [String:AnyObject] + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Deletes a pet + + - parameter petId: (path) Pet id to delete + - parameter completion: completion handler to receive the data and the error objects + */ + public class func deletePet(petId petId: Int64, completion: ((error: ErrorType?) -> Void)) { + deletePetWithRequestBuilder(petId: petId).execute { (response, error) -> Void in + completion(error: error); + } + } + + /** + Deletes a pet + + - parameter petId: (path) Pet id to delete + - returns: Observable + */ + public class func deletePet(petId petId: Int64) -> Observable { + return Observable.create { observer -> Disposable in + deletePet(petId: petId) { error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next()) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Deletes a pet + - DELETE /pet/{petId} + - + - OAuth: + - type: oauth2 + - name: petstore_auth + + - parameter petId: (path) Pet id to delete + + - returns: RequestBuilder + */ + public class func deletePetWithRequestBuilder(petId petId: Int64) -> RequestBuilder { + var path = "/pet/{petId}" + path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Finds Pets by status + + - parameter status: (query) Status values that need to be considered for filter (optional, default to available) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func findPetsByStatus(status status: [String]? = nil, completion: ((data: [Pet]?, error: ErrorType?) -> Void)) { + findPetsByStatusWithRequestBuilder(status: status).execute { (response, error) -> Void in + completion(data: response?.body, error: error); + } + } + + /** + Finds Pets by status + + - parameter status: (query) Status values that need to be considered for filter (optional, default to available) + - returns: Observable<[Pet]> + */ + public class func findPetsByStatus(status status: [String]? = nil) -> Observable<[Pet]> { + return Observable.create { observer -> Disposable in + findPetsByStatus(status: status) { data, error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next(data!)) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Finds Pets by status + - GET /pet/findByStatus + - Multiple status values can be provided with comma seperated strings + - OAuth: + - type: oauth2 + - name: petstore_auth + - examples: [{example={ + "name" : "Puma", + "type" : "Dog", + "color" : "Black", + "gender" : "Female", + "breed" : "Mixed" +}, contentType=application/json}] + + - parameter status: (query) Status values that need to be considered for filter (optional, default to available) + + - returns: RequestBuilder<[Pet]> + */ + public class func findPetsByStatusWithRequestBuilder(status status: [String]? = nil) -> RequestBuilder<[Pet]> { + let path = "/pet/findByStatus" + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [ + "status": status + ] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) + } + + /** + Finds Pets by tags + + - parameter tags: (query) Tags to filter by (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func findPetsByTags(tags tags: [String]? = nil, completion: ((data: [Pet]?, error: ErrorType?) -> Void)) { + findPetsByTagsWithRequestBuilder(tags: tags).execute { (response, error) -> Void in + completion(data: response?.body, error: error); + } + } + + /** + Finds Pets by tags + + - parameter tags: (query) Tags to filter by (optional) + - returns: Observable<[Pet]> + */ + public class func findPetsByTags(tags tags: [String]? = nil) -> Observable<[Pet]> { + return Observable.create { observer -> Disposable in + findPetsByTags(tags: tags) { data, error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next(data!)) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Finds Pets by tags + - GET /pet/findByTags + - Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + - OAuth: + - type: oauth2 + - name: petstore_auth + - examples: [{example=[ { + "tags" : [ { + "id" : 123456789, + "name" : "aeiou" + } ], + "id" : 123456789, + "category" : { + "id" : 123456789, + "name" : "aeiou" + }, + "status" : "aeiou", + "name" : "doggie", + "photoUrls" : [ "aeiou" ] +} ], contentType=application/json}, {example= + 123456 + doggie + + string + + + + string +, contentType=application/xml}] + - examples: [{example=[ { + "tags" : [ { + "id" : 123456789, + "name" : "aeiou" + } ], + "id" : 123456789, + "category" : { + "id" : 123456789, + "name" : "aeiou" + }, + "status" : "aeiou", + "name" : "doggie", + "photoUrls" : [ "aeiou" ] +} ], contentType=application/json}, {example= + 123456 + doggie + + string + + + + string +, contentType=application/xml}] + + - parameter tags: (query) Tags to filter by (optional) + + - returns: RequestBuilder<[Pet]> + */ + public class func findPetsByTagsWithRequestBuilder(tags tags: [String]? = nil) -> RequestBuilder<[Pet]> { + let path = "/pet/findByTags" + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [ + "tags": tags + ] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) + } + + /** + Find pet by ID + + - parameter petId: (path) ID of pet that needs to be fetched + - parameter completion: completion handler to receive the data and the error objects + */ + public class func getPetById(petId petId: Int64, completion: ((data: Pet?, error: ErrorType?) -> Void)) { + getPetByIdWithRequestBuilder(petId: petId).execute { (response, error) -> Void in + completion(data: response?.body, error: error); + } + } + + /** + Find pet by ID + + - parameter petId: (path) ID of pet that needs to be fetched + - returns: Observable + */ + public class func getPetById(petId petId: Int64) -> Observable { + return Observable.create { observer -> Disposable in + getPetById(petId: petId) { data, error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next(data!)) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Find pet by ID + - GET /pet/{petId} + - Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + - API Key: + - type: apiKey api_key + - name: api_key + - OAuth: + - type: oauth2 + - name: petstore_auth + - examples: [{example={ + "tags" : [ { + "id" : 123456789, + "name" : "aeiou" + } ], + "id" : 123456789, + "category" : { + "id" : 123456789, + "name" : "aeiou" + }, + "status" : "aeiou", + "name" : "doggie", + "photoUrls" : [ "aeiou" ] +}, contentType=application/json}, {example= + 123456 + doggie + + string + + + + string +, contentType=application/xml}] + - examples: [{example={ + "tags" : [ { + "id" : 123456789, + "name" : "aeiou" + } ], + "id" : 123456789, + "category" : { + "id" : 123456789, + "name" : "aeiou" + }, + "status" : "aeiou", + "name" : "doggie", + "photoUrls" : [ "aeiou" ] +}, contentType=application/json}, {example= + 123456 + doggie + + string + + + + string +, contentType=application/xml}] + + - parameter petId: (path) ID of pet that needs to be fetched + + - returns: RequestBuilder + */ + public class func getPetByIdWithRequestBuilder(petId petId: Int64) -> RequestBuilder { + var path = "/pet/{petId}" + path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Update an existing pet + + - parameter body: (body) Pet object that needs to be added to the store (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func updatePet(body body: Pet? = nil, completion: ((error: ErrorType?) -> Void)) { + updatePetWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error: error); + } + } + + /** + Update an existing pet + + - parameter body: (body) Pet object that needs to be added to the store (optional) + - returns: Observable + */ + public class func updatePet(body body: Pet? = nil) -> Observable { + return Observable.create { observer -> Disposable in + updatePet(body: body) { error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next()) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Update an existing pet + - PUT /pet + - + - OAuth: + - type: oauth2 + - name: petstore_auth + + - parameter body: (body) Pet object that needs to be added to the store (optional) + + - returns: RequestBuilder + */ + public class func updatePetWithRequestBuilder(body body: Pet? = nil) -> RequestBuilder { + let path = "/pet" + let URLString = PetstoreClientAPI.basePath + path + let parameters = body?.encodeToJSON() as? [String:AnyObject] + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Updates a pet in the store with form data + + - parameter petId: (path) ID of pet that needs to be updated + - parameter name: (form) Updated name of the pet (optional) + - parameter status: (form) Updated status of the pet (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func updatePetWithForm(petId petId: String, name: String? = nil, status: String? = nil, completion: ((error: ErrorType?) -> Void)) { + updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (response, error) -> Void in + completion(error: error); + } + } + + /** + Updates a pet in the store with form data + + - parameter petId: (path) ID of pet that needs to be updated + - parameter name: (form) Updated name of the pet (optional) + - parameter status: (form) Updated status of the pet (optional) + - returns: Observable + */ + public class func updatePetWithForm(petId petId: String, name: String? = nil, status: String? = nil) -> Observable { + return Observable.create { observer -> Disposable in + updatePetWithForm(petId: petId, name: name, status: status) { error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next()) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Updates a pet in the store with form data + - POST /pet/{petId} + - + - OAuth: + - type: oauth2 + - name: petstore_auth + + - parameter petId: (path) ID of pet that needs to be updated + - parameter name: (form) Updated name of the pet (optional) + - parameter status: (form) Updated status of the pet (optional) + + - returns: RequestBuilder + */ + public class func updatePetWithFormWithRequestBuilder(petId petId: String, name: String? = nil, status: String? = nil) -> RequestBuilder { + var path = "/pet/{petId}" + path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [ + "name": name, + "status": status + ] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) + } + + /** + uploads an image + + - parameter petId: (path) ID of pet to update + - parameter additionalMetadata: (form) Additional data to pass to server (optional) + - parameter file: (form) file to upload (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func uploadFile(petId petId: Int64, additionalMetadata: String? = nil, file: NSURL? = nil, completion: ((error: ErrorType?) -> Void)) { + uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute { (response, error) -> Void in + completion(error: error); + } + } + + /** + uploads an image + + - parameter petId: (path) ID of pet to update + - parameter additionalMetadata: (form) Additional data to pass to server (optional) + - parameter file: (form) file to upload (optional) + - returns: Observable + */ + public class func uploadFile(petId petId: Int64, additionalMetadata: String? = nil, file: NSURL? = nil) -> Observable { + return Observable.create { observer -> Disposable in + uploadFile(petId: petId, additionalMetadata: additionalMetadata, file: file) { error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next()) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + uploads an image + - POST /pet/{petId}/uploadImage + - + - OAuth: + - type: oauth2 + - name: petstore_auth + + - parameter petId: (path) ID of pet to update + - parameter additionalMetadata: (form) Additional data to pass to server (optional) + - parameter file: (form) file to upload (optional) + + - returns: RequestBuilder + */ + public class func uploadFileWithRequestBuilder(petId petId: Int64, additionalMetadata: String? = nil, file: NSURL? = nil) -> RequestBuilder { + var path = "/pet/{petId}/uploadImage" + path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [ + "additionalMetadata": additionalMetadata, + "file": file + ] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) + } + +} diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift new file mode 100644 index 00000000000..a3de3380f82 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -0,0 +1,302 @@ +// +// StoreAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire +import RxSwift + + + +public class StoreAPI: APIBase { + /** + Delete purchase order by ID + + - parameter orderId: (path) ID of the order that needs to be deleted + - parameter completion: completion handler to receive the data and the error objects + */ + public class func deleteOrder(orderId orderId: String, completion: ((error: ErrorType?) -> Void)) { + deleteOrderWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in + completion(error: error); + } + } + + /** + Delete purchase order by ID + + - parameter orderId: (path) ID of the order that needs to be deleted + - returns: Observable + */ + public class func deleteOrder(orderId orderId: String) -> Observable { + return Observable.create { observer -> Disposable in + deleteOrder(orderId: orderId) { error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next()) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Delete purchase order by ID + - DELETE /store/order/{orderId} + - For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + + - parameter orderId: (path) ID of the order that needs to be deleted + + - returns: RequestBuilder + */ + public class func deleteOrderWithRequestBuilder(orderId orderId: String) -> RequestBuilder { + var path = "/store/order/{orderId}" + path = path.stringByReplacingOccurrencesOfString("{orderId}", withString: "\(orderId)", options: .LiteralSearch, range: nil) + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Returns pet inventories by status + + - parameter completion: completion handler to receive the data and the error objects + */ + public class func getInventory(completion: ((data: [String:Int32]?, error: ErrorType?) -> Void)) { + getInventoryWithRequestBuilder().execute { (response, error) -> Void in + completion(data: response?.body, error: error); + } + } + + /** + Returns pet inventories by status + + - returns: Observable<[String:Int32]> + */ + public class func getInventory() -> Observable<[String:Int32]> { + return Observable.create { observer -> Disposable in + getInventory() { data, error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next(data!)) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Returns pet inventories by status + - GET /store/inventory + - Returns a map of status codes to quantities + - API Key: + - type: apiKey api_key + - name: api_key + - examples: [{example={ + "key" : 123 +}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}] + - examples: [{example={ + "key" : 123 +}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}] + + - returns: RequestBuilder<[String:Int32]> + */ + public class func getInventoryWithRequestBuilder() -> RequestBuilder<[String:Int32]> { + let path = "/store/inventory" + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder<[String:Int32]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Find purchase order by ID + + - parameter orderId: (path) ID of pet that needs to be fetched + - parameter completion: completion handler to receive the data and the error objects + */ + public class func getOrderById(orderId orderId: String, completion: ((data: Order?, error: ErrorType?) -> Void)) { + getOrderByIdWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in + completion(data: response?.body, error: error); + } + } + + /** + Find purchase order by ID + + - parameter orderId: (path) ID of pet that needs to be fetched + - returns: Observable + */ + public class func getOrderById(orderId orderId: String) -> Observable { + return Observable.create { observer -> Disposable in + getOrderById(orderId: orderId) { data, error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next(data!)) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Find purchase order by ID + - GET /store/order/{orderId} + - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + - examples: [{example={ + "id" : 123456789, + "petId" : 123456789, + "complete" : true, + "status" : "aeiou", + "quantity" : 123, + "shipDate" : "2000-01-23T04:56:07.000+00:00" +}, contentType=application/json}, {example= + 123456 + 123456 + 0 + 2000-01-23T04:56:07.000Z + string + true +, contentType=application/xml}] + - examples: [{example={ + "id" : 123456789, + "petId" : 123456789, + "complete" : true, + "status" : "aeiou", + "quantity" : 123, + "shipDate" : "2000-01-23T04:56:07.000+00:00" +}, contentType=application/json}, {example= + 123456 + 123456 + 0 + 2000-01-23T04:56:07.000Z + string + true +, contentType=application/xml}] + + - parameter orderId: (path) ID of pet that needs to be fetched + + - returns: RequestBuilder + */ + public class func getOrderByIdWithRequestBuilder(orderId orderId: String) -> RequestBuilder { + var path = "/store/order/{orderId}" + path = path.stringByReplacingOccurrencesOfString("{orderId}", withString: "\(orderId)", options: .LiteralSearch, range: nil) + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Place an order for a pet + + - parameter body: (body) order placed for purchasing the pet (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func placeOrder(body body: Order? = nil, completion: ((data: Order?, error: ErrorType?) -> Void)) { + placeOrderWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(data: response?.body, error: error); + } + } + + /** + Place an order for a pet + + - parameter body: (body) order placed for purchasing the pet (optional) + - returns: Observable + */ + public class func placeOrder(body body: Order? = nil) -> Observable { + return Observable.create { observer -> Disposable in + placeOrder(body: body) { data, error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next(data!)) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Place an order for a pet + - POST /store/order + - + - examples: [{example={ + "id" : 123456789, + "petId" : 123456789, + "complete" : true, + "status" : "aeiou", + "quantity" : 123, + "shipDate" : "2000-01-23T04:56:07.000+00:00" +}, contentType=application/json}, {example= + 123456 + 123456 + 0 + 2000-01-23T04:56:07.000Z + string + true +, contentType=application/xml}] + - examples: [{example={ + "id" : 123456789, + "petId" : 123456789, + "complete" : true, + "status" : "aeiou", + "quantity" : 123, + "shipDate" : "2000-01-23T04:56:07.000+00:00" +}, contentType=application/json}, {example= + 123456 + 123456 + 0 + 2000-01-23T04:56:07.000Z + string + true +, contentType=application/xml}] + + - parameter body: (body) order placed for purchasing the pet (optional) + + - returns: RequestBuilder + */ + public class func placeOrderWithRequestBuilder(body body: Order? = nil) -> RequestBuilder { + let path = "/store/order" + let URLString = PetstoreClientAPI.basePath + path + let parameters = body?.encodeToJSON() as? [String:AnyObject] + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + } + +} diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift new file mode 100644 index 00000000000..31549870544 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -0,0 +1,498 @@ +// +// UserAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire +import RxSwift + + + +public class UserAPI: APIBase { + /** + Create user + + - parameter body: (body) Created user object (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func createUser(body body: User? = nil, completion: ((error: ErrorType?) -> Void)) { + createUserWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error: error); + } + } + + /** + Create user + + - parameter body: (body) Created user object (optional) + - returns: Observable + */ + public class func createUser(body body: User? = nil) -> Observable { + return Observable.create { observer -> Disposable in + createUser(body: body) { error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next()) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Create user + - POST /user + - This can only be done by the logged in user. + + - parameter body: (body) Created user object (optional) + + - returns: RequestBuilder + */ + public class func createUserWithRequestBuilder(body body: User? = nil) -> RequestBuilder { + let path = "/user" + let URLString = PetstoreClientAPI.basePath + path + let parameters = body?.encodeToJSON() as? [String:AnyObject] + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Creates list of users with given input array + + - parameter body: (body) List of user object (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func createUsersWithArrayInput(body body: [User]? = nil, completion: ((error: ErrorType?) -> Void)) { + createUsersWithArrayInputWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error: error); + } + } + + /** + Creates list of users with given input array + + - parameter body: (body) List of user object (optional) + - returns: Observable + */ + public class func createUsersWithArrayInput(body body: [User]? = nil) -> Observable { + return Observable.create { observer -> Disposable in + createUsersWithArrayInput(body: body) { error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next()) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Creates list of users with given input array + - POST /user/createWithArray + - + + - parameter body: (body) List of user object (optional) + + - returns: RequestBuilder + */ + public class func createUsersWithArrayInputWithRequestBuilder(body body: [User]? = nil) -> RequestBuilder { + let path = "/user/createWithArray" + let URLString = PetstoreClientAPI.basePath + path + let parameters = body?.encodeToJSON() as? [String:AnyObject] + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Creates list of users with given input array + + - parameter body: (body) List of user object (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func createUsersWithListInput(body body: [User]? = nil, completion: ((error: ErrorType?) -> Void)) { + createUsersWithListInputWithRequestBuilder(body: body).execute { (response, error) -> Void in + completion(error: error); + } + } + + /** + Creates list of users with given input array + + - parameter body: (body) List of user object (optional) + - returns: Observable + */ + public class func createUsersWithListInput(body body: [User]? = nil) -> Observable { + return Observable.create { observer -> Disposable in + createUsersWithListInput(body: body) { error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next()) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Creates list of users with given input array + - POST /user/createWithList + - + + - parameter body: (body) List of user object (optional) + + - returns: RequestBuilder + */ + public class func createUsersWithListInputWithRequestBuilder(body body: [User]? = nil) -> RequestBuilder { + let path = "/user/createWithList" + let URLString = PetstoreClientAPI.basePath + path + let parameters = body?.encodeToJSON() as? [String:AnyObject] + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Delete user + + - parameter username: (path) The name that needs to be deleted + - parameter completion: completion handler to receive the data and the error objects + */ + public class func deleteUser(username username: String, completion: ((error: ErrorType?) -> Void)) { + deleteUserWithRequestBuilder(username: username).execute { (response, error) -> Void in + completion(error: error); + } + } + + /** + Delete user + + - parameter username: (path) The name that needs to be deleted + - returns: Observable + */ + public class func deleteUser(username username: String) -> Observable { + return Observable.create { observer -> Disposable in + deleteUser(username: username) { error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next()) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Delete user + - DELETE /user/{username} + - This can only be done by the logged in user. + + - parameter username: (path) The name that needs to be deleted + + - returns: RequestBuilder + */ + public class func deleteUserWithRequestBuilder(username username: String) -> RequestBuilder { + var path = "/user/{username}" + path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil) + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Get user by user name + + - parameter username: (path) The name that needs to be fetched. Use user1 for testing. + - parameter completion: completion handler to receive the data and the error objects + */ + public class func getUserByName(username username: String, completion: ((data: User?, error: ErrorType?) -> Void)) { + getUserByNameWithRequestBuilder(username: username).execute { (response, error) -> Void in + completion(data: response?.body, error: error); + } + } + + /** + Get user by user name + + - parameter username: (path) The name that needs to be fetched. Use user1 for testing. + - returns: Observable + */ + public class func getUserByName(username username: String) -> Observable { + return Observable.create { observer -> Disposable in + getUserByName(username: username) { data, error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next(data!)) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Get user by user name + - GET /user/{username} + - + - examples: [{example={ + "id" : 123456789, + "lastName" : "aeiou", + "phone" : "aeiou", + "username" : "aeiou", + "email" : "aeiou", + "userStatus" : 123, + "firstName" : "aeiou", + "password" : "aeiou" +}, contentType=application/json}, {example= + 123456 + string + string + string + string + string + string + 0 +, contentType=application/xml}] + - examples: [{example={ + "id" : 123456789, + "lastName" : "aeiou", + "phone" : "aeiou", + "username" : "aeiou", + "email" : "aeiou", + "userStatus" : 123, + "firstName" : "aeiou", + "password" : "aeiou" +}, contentType=application/json}, {example= + 123456 + string + string + string + string + string + string + 0 +, contentType=application/xml}] + + - parameter username: (path) The name that needs to be fetched. Use user1 for testing. + + - returns: RequestBuilder + */ + public class func getUserByNameWithRequestBuilder(username username: String) -> RequestBuilder { + var path = "/user/{username}" + path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil) + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Logs user into the system + + - parameter username: (query) The user name for login (optional) + - parameter password: (query) The password for login in clear text (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func loginUser(username username: String? = nil, password: String? = nil, completion: ((data: String?, error: ErrorType?) -> Void)) { + loginUserWithRequestBuilder(username: username, password: password).execute { (response, error) -> Void in + completion(data: response?.body, error: error); + } + } + + /** + Logs user into the system + + - parameter username: (query) The user name for login (optional) + - parameter password: (query) The password for login in clear text (optional) + - returns: Observable + */ + public class func loginUser(username username: String? = nil, password: String? = nil) -> Observable { + return Observable.create { observer -> Disposable in + loginUser(username: username, password: password) { data, error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next(data!)) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Logs user into the system + - GET /user/login + - + - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}] + - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}] + + - parameter username: (query) The user name for login (optional) + - parameter password: (query) The password for login in clear text (optional) + + - returns: RequestBuilder + */ + public class func loginUserWithRequestBuilder(username username: String? = nil, password: String? = nil) -> RequestBuilder { + let path = "/user/login" + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [ + "username": username, + "password": password + ] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) + } + + /** + Logs out current logged in user session + + - parameter completion: completion handler to receive the data and the error objects + */ + public class func logoutUser(completion: ((error: ErrorType?) -> Void)) { + logoutUserWithRequestBuilder().execute { (response, error) -> Void in + completion(error: error); + } + } + + /** + Logs out current logged in user session + + - returns: Observable + */ + public class func logoutUser() -> Observable { + return Observable.create { observer -> Disposable in + logoutUser() { error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next()) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Logs out current logged in user session + - GET /user/logout + - + + - returns: RequestBuilder + */ + public class func logoutUserWithRequestBuilder() -> RequestBuilder { + let path = "/user/logout" + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + } + + /** + Updated user + + - parameter username: (path) name that need to be deleted + - parameter body: (body) Updated user object (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func updateUser(username username: String, body: User? = nil, completion: ((error: ErrorType?) -> Void)) { + updateUserWithRequestBuilder(username: username, body: body).execute { (response, error) -> Void in + completion(error: error); + } + } + + /** + Updated user + + - parameter username: (path) name that need to be deleted + - parameter body: (body) Updated user object (optional) + - returns: Observable + */ + public class func updateUser(username username: String, body: User? = nil) -> Observable { + return Observable.create { observer -> Disposable in + updateUser(username: username, body: body) { error in + if let error = error { + observer.on(.Error(error as ErrorType)) + } else { + observer.on(.Next()) + } + observer.on(.Completed) + } + return NopDisposable.instance + } + } + + /** + Updated user + - PUT /user/{username} + - This can only be done by the logged in user. + + - parameter username: (path) name that need to be deleted + - parameter body: (body) Updated user object (optional) + + - returns: RequestBuilder + */ + public class func updateUserWithRequestBuilder(username username: String, body: User? = nil) -> RequestBuilder { + var path = "/user/{username}" + path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil) + let URLString = PetstoreClientAPI.basePath + path + let parameters = body?.encodeToJSON() as? [String:AnyObject] + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true) + } + +} diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift new file mode 100644 index 00000000000..cabf67567b5 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -0,0 +1,148 @@ +// AlamofireImplementations.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire + +class AlamofireRequestBuilderFactory: RequestBuilderFactory { + func getBuilder() -> RequestBuilder.Type { + return AlamofireRequestBuilder.self + } +} + +// Store manager to retain its reference +private var managerStore: [String: Alamofire.Manager] = [:] + +class AlamofireRequestBuilder: RequestBuilder { + required init(method: String, URLString: String, parameters: [String : AnyObject]?, isBody: Bool) { + super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody) + } + + override func execute(completion: (response: Response?, error: ErrorType?) -> Void) { + let managerId = NSUUID().UUIDString + // Create a new manager for each request to customize its request header + let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() + configuration.HTTPAdditionalHeaders = buildHeaders() + let manager = Alamofire.Manager(configuration: configuration) + managerStore[managerId] = manager + + let encoding = isBody ? Alamofire.ParameterEncoding.JSON : Alamofire.ParameterEncoding.URL + let xMethod = Alamofire.Method(rawValue: method) + let fileKeys = parameters == nil ? [] : parameters!.filter { $1.isKindOfClass(NSURL) } + .map { $0.0 } + + if fileKeys.count > 0 { + manager.upload( + xMethod!, URLString, headers: nil, + multipartFormData: { mpForm in + for (k, v) in self.parameters! { + switch v { + case let fileURL as NSURL: + mpForm.appendBodyPart(fileURL: fileURL, name: k) + break + case let string as NSString: + mpForm.appendBodyPart(data: string.dataUsingEncoding(NSUTF8StringEncoding)!, name: k) + break + case let number as NSNumber: + mpForm.appendBodyPart(data: number.stringValue.dataUsingEncoding(NSUTF8StringEncoding)!, name: k) + break + default: + fatalError("Unprocessable value \(v) with key \(k)") + break + } + } + }, + encodingMemoryThreshold: Manager.MultipartFormDataEncodingMemoryThreshold, + encodingCompletion: { encodingResult in + switch encodingResult { + case .Success(let uploadRequest, _, _): + if let onProgressReady = self.onProgressReady { + onProgressReady(uploadRequest.progress) + } + self.processRequest(uploadRequest, managerId, completion) + case .Failure(let encodingError): + completion(response: nil, error: encodingError) + } + } + ) + } else { + let request = manager.request(xMethod!, URLString, parameters: parameters, encoding: encoding) + if let onProgressReady = self.onProgressReady { + onProgressReady(request.progress) + } + processRequest(request, managerId, completion) + } + + } + + private func processRequest(request: Request, _ managerId: String, _ completion: (response: Response?, error: ErrorType?) -> Void) { + if let credential = self.credential { + request.authenticate(usingCredential: credential) + } + + let cleanupRequest = { + managerStore.removeValueForKey(managerId) + } + + let validatedRequest = request.validate() + + switch T.self { + case is NSData.Type: + validatedRequest.responseData({ (dataResponse) in + cleanupRequest() + + if (dataResponse.result.isFailure) { + completion( + response: nil, + error: dataResponse.result.error + ) + return + } + + completion( + response: Response( + response: dataResponse.response!, + body: dataResponse.data as! T + ), + error: nil + ) + }) + default: + validatedRequest.responseJSON(options: .AllowFragments) { response in + cleanupRequest() + + if response.result.isFailure { + completion(response: nil, error: response.result.error) + return + } + + if () is T { + completion(response: Response(response: response.response!, body: () as! T), error: nil) + return + } + if let json: AnyObject = response.result.value { + let body = Decoders.decode(clazz: T.self, source: json) + completion(response: Response(response: response.response!, body: body), error: nil) + return + } else if "" is T { + // swagger-parser currently doesn't support void, which will be fixed in future swagger-parser release + // https://github.com/swagger-api/swagger-parser/pull/34 + completion(response: Response(response: response.response!, body: "" as! T), error: nil) + return + } + + completion(response: nil, error: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) + } + } + } + + private func buildHeaders() -> [String: AnyObject] { + var httpHeaders = Manager.defaultHTTPHeaders + for (key, value) in self.headers { + httpHeaders[key] = value + } + return httpHeaders + } +} diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Extensions.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Extensions.swift new file mode 100644 index 00000000000..1dbb47e625f --- /dev/null +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Extensions.swift @@ -0,0 +1,84 @@ +// Extensions.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire + +extension Bool: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +extension Float: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +extension Int: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +extension Int32: JSONEncodable { + func encodeToJSON() -> AnyObject { return NSNumber(int: self) } +} + +extension Int64: JSONEncodable { + func encodeToJSON() -> AnyObject { return NSNumber(longLong: self) } +} + +extension Double: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +extension String: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +private func encodeIfPossible(object: T) -> AnyObject { + if object is JSONEncodable { + return (object as! JSONEncodable).encodeToJSON() + } else { + return object as! AnyObject + } +} + +extension Array: JSONEncodable { + func encodeToJSON() -> AnyObject { + return self.map(encodeIfPossible) + } +} + +extension Dictionary: JSONEncodable { + func encodeToJSON() -> AnyObject { + var dictionary = [NSObject:AnyObject]() + for (key, value) in self { + dictionary[key as! NSObject] = encodeIfPossible(value) + } + return dictionary + } +} + +extension NSData: JSONEncodable { + func encodeToJSON() -> AnyObject { + return self.base64EncodedStringWithOptions(NSDataBase64EncodingOptions()) + } +} + +private let dateFormatter: NSDateFormatter = { + let fmt = NSDateFormatter() + fmt.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + fmt.locale = NSLocale(localeIdentifier: "en_US_POSIX") + return fmt +}() + +extension NSDate: JSONEncodable { + func encodeToJSON() -> AnyObject { + return dateFormatter.stringFromDate(self) + } +} + +extension NSUUID: JSONEncodable { + func encodeToJSON() -> AnyObject { + return self.UUIDString + } +} diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models.swift new file mode 100644 index 00000000000..731bcc28d07 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models.swift @@ -0,0 +1,224 @@ +// Models.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +protocol JSONEncodable { + func encodeToJSON() -> AnyObject +} + +public class Response { + public let statusCode: Int + public let header: [String: String] + public let body: T + + public init(statusCode: Int, header: [String: String], body: T) { + self.statusCode = statusCode + self.header = header + self.body = body + } + + public convenience init(response: NSHTTPURLResponse, body: T) { + let rawHeader = response.allHeaderFields + var header = [String:String]() + for (key, value) in rawHeader { + header[key as! String] = value as? String + } + self.init(statusCode: response.statusCode, header: header, body: body) + } +} + +private var once = dispatch_once_t() +class Decoders { + static private var decoders = Dictionary AnyObject)>() + + static func addDecoder(clazz clazz: T.Type, decoder: ((AnyObject) -> T)) { + let key = "\(T.self)" + decoders[key] = { decoder($0) as! AnyObject } + } + + static func decode(clazz clazz: [T].Type, source: AnyObject) -> [T] { + let array = source as! [AnyObject] + return array.map { Decoders.decode(clazz: T.self, source: $0) } + } + + static func decode(clazz clazz: [Key:T].Type, source: AnyObject) -> [Key:T] { + let sourceDictionary = source as! [Key: AnyObject] + var dictionary = [Key:T]() + for (key, value) in sourceDictionary { + dictionary[key] = Decoders.decode(clazz: T.self, source: value) + } + return dictionary + } + + static func decode(clazz clazz: T.Type, source: AnyObject) -> T { + initialize() + if T.self is Int32.Type && source is NSNumber { + return source.intValue as! T; + } + if T.self is Int64.Type && source is NSNumber { + return source.longLongValue as! T; + } + if T.self is NSUUID.Type && source is String { + return NSUUID(UUIDString: source as! String) as! T + } + if source is T { + return source as! T + } + if T.self is NSData.Type && source is String { + return NSData(base64EncodedString: source as! String, options: NSDataBase64DecodingOptions()) as! T + } + + let key = "\(T.self)" + if let decoder = decoders[key] { + return decoder(source) as! T + } else { + fatalError("Source \(source) is not convertible to type \(clazz): Maybe swagger file is insufficient") + } + } + + static func decodeOptional(clazz clazz: T.Type, source: AnyObject?) -> T? { + if source is NSNull { + return nil + } + return source.map { (source: AnyObject) -> T in + Decoders.decode(clazz: clazz, source: source) + } + } + + static func decodeOptional(clazz clazz: [T].Type, source: AnyObject?) -> [T]? { + if source is NSNull { + return nil + } + return source.map { (someSource: AnyObject) -> [T] in + Decoders.decode(clazz: clazz, source: someSource) + } + } + + static func decodeOptional(clazz clazz: [Key:T].Type, source: AnyObject?) -> [Key:T]? { + if source is NSNull { + return nil + } + return source.map { (someSource: AnyObject) -> [Key:T] in + Decoders.decode(clazz: clazz, source: someSource) + } + } + + static private func initialize() { + dispatch_once(&once) { + let formatters = [ + "yyyy-MM-dd", + "yyyy-MM-dd'T'HH:mm:ssZZZZZ", + "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ", + "yyyy-MM-dd'T'HH:mm:ss'Z'", + "yyyy-MM-dd'T'HH:mm:ss.SSS" + ].map { (format: String) -> NSDateFormatter in + let formatter = NSDateFormatter() + formatter.dateFormat = format + return formatter + } + // Decoder for NSDate + Decoders.addDecoder(clazz: NSDate.self) { (source: AnyObject) -> NSDate in + if let sourceString = source as? String { + for formatter in formatters { + if let date = formatter.dateFromString(sourceString) { + return date + } + } + + } + if let sourceInt = source as? Int { + // treat as a java date + return NSDate(timeIntervalSince1970: Double(sourceInt / 1000) ) + } + fatalError("formatter failed to parse \(source)") + } + + // Decoder for [Category] + Decoders.addDecoder(clazz: [Category].self) { (source: AnyObject) -> [Category] in + return Decoders.decode(clazz: [Category].self, source: source) + } + // Decoder for Category + Decoders.addDecoder(clazz: Category.self) { (source: AnyObject) -> Category in + let sourceDictionary = source as! [NSObject:AnyObject] + let instance = Category() + instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"]) + instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"]) + return instance + } + + + // Decoder for [Order] + Decoders.addDecoder(clazz: [Order].self) { (source: AnyObject) -> [Order] in + return Decoders.decode(clazz: [Order].self, source: source) + } + // Decoder for Order + Decoders.addDecoder(clazz: Order.self) { (source: AnyObject) -> Order in + let sourceDictionary = source as! [NSObject:AnyObject] + let instance = Order() + instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"]) + instance.petId = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["petId"]) + instance.quantity = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["quantity"]) + instance.shipDate = Decoders.decodeOptional(clazz: NSDate.self, source: sourceDictionary["shipDate"]) + instance.status = Order.Status(rawValue: (sourceDictionary["status"] as? String) ?? "") + instance.complete = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["complete"]) + return instance + } + + + // Decoder for [Pet] + Decoders.addDecoder(clazz: [Pet].self) { (source: AnyObject) -> [Pet] in + return Decoders.decode(clazz: [Pet].self, source: source) + } + // Decoder for Pet + Decoders.addDecoder(clazz: Pet.self) { (source: AnyObject) -> Pet in + let sourceDictionary = source as! [NSObject:AnyObject] + let instance = Pet() + instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"]) + instance.category = Decoders.decodeOptional(clazz: Category.self, source: sourceDictionary["category"]) + instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"]) + instance.photoUrls = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["photoUrls"]) + instance.tags = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["tags"]) + instance.status = Pet.Status(rawValue: (sourceDictionary["status"] as? String) ?? "") + return instance + } + + + // Decoder for [Tag] + Decoders.addDecoder(clazz: [Tag].self) { (source: AnyObject) -> [Tag] in + return Decoders.decode(clazz: [Tag].self, source: source) + } + // Decoder for Tag + Decoders.addDecoder(clazz: Tag.self) { (source: AnyObject) -> Tag in + let sourceDictionary = source as! [NSObject:AnyObject] + let instance = Tag() + instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"]) + instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"]) + return instance + } + + + // Decoder for [User] + Decoders.addDecoder(clazz: [User].self) { (source: AnyObject) -> [User] in + return Decoders.decode(clazz: [User].self, source: source) + } + // Decoder for User + Decoders.addDecoder(clazz: User.self) { (source: AnyObject) -> User in + let sourceDictionary = source as! [NSObject:AnyObject] + let instance = User() + instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"]) + instance.username = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["username"]) + instance.firstName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["firstName"]) + instance.lastName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["lastName"]) + instance.email = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["email"]) + instance.password = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["password"]) + instance.phone = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["phone"]) + instance.userStatus = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["userStatus"]) + return instance + } + } + } +} diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/Category.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/Category.swift new file mode 100644 index 00000000000..89ce2ccb616 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/Category.swift @@ -0,0 +1,25 @@ +// +// Category.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public class Category: JSONEncodable { + public var id: Int64? + public var name: String? + + public init() {} + + // MARK: JSONEncodable + func encodeToJSON() -> AnyObject { + var nillableDictionary = [String:AnyObject?]() + nillableDictionary["id"] = self.id?.encodeToJSON() + nillableDictionary["name"] = self.name + let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/Order.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/Order.swift new file mode 100644 index 00000000000..14efcf0d0c9 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/Order.swift @@ -0,0 +1,39 @@ +// +// Order.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public class Order: JSONEncodable { + public enum Status: String { + case Placed = "placed" + case Approved = "approved" + case Delivered = "delivered" + } + public var id: Int64? + public var petId: Int64? + public var quantity: Int32? + public var shipDate: NSDate? + /** Order Status */ + public var status: Status? + public var complete: Bool? + + public init() {} + + // MARK: JSONEncodable + func encodeToJSON() -> AnyObject { + var nillableDictionary = [String:AnyObject?]() + nillableDictionary["id"] = self.id?.encodeToJSON() + nillableDictionary["petId"] = self.petId?.encodeToJSON() + nillableDictionary["quantity"] = self.quantity?.encodeToJSON() + nillableDictionary["shipDate"] = self.shipDate?.encodeToJSON() + nillableDictionary["status"] = self.status?.rawValue + nillableDictionary["complete"] = self.complete + let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/Pet.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/Pet.swift new file mode 100644 index 00000000000..7d1a6256121 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/Pet.swift @@ -0,0 +1,39 @@ +// +// Pet.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public class Pet: JSONEncodable { + public enum Status: String { + case Available = "available" + case Pending = "pending" + case Sold = "sold" + } + public var id: Int64? + public var category: Category? + public var name: String? + public var photoUrls: [String]? + public var tags: [Tag]? + /** pet status in the store */ + public var status: Status? + + public init() {} + + // MARK: JSONEncodable + func encodeToJSON() -> AnyObject { + var nillableDictionary = [String:AnyObject?]() + nillableDictionary["id"] = self.id?.encodeToJSON() + nillableDictionary["category"] = self.category?.encodeToJSON() + nillableDictionary["name"] = self.name + nillableDictionary["photoUrls"] = self.photoUrls?.encodeToJSON() + nillableDictionary["tags"] = self.tags?.encodeToJSON() + nillableDictionary["status"] = self.status?.rawValue + let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/Tag.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/Tag.swift new file mode 100644 index 00000000000..774f91557e6 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/Tag.swift @@ -0,0 +1,25 @@ +// +// Tag.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public class Tag: JSONEncodable { + public var id: Int64? + public var name: String? + + public init() {} + + // MARK: JSONEncodable + func encodeToJSON() -> AnyObject { + var nillableDictionary = [String:AnyObject?]() + nillableDictionary["id"] = self.id?.encodeToJSON() + nillableDictionary["name"] = self.name + let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/User.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/User.swift new file mode 100644 index 00000000000..67b72a61922 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/Models/User.swift @@ -0,0 +1,38 @@ +// +// User.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public class User: JSONEncodable { + public var id: Int64? + public var username: String? + public var firstName: String? + public var lastName: String? + public var email: String? + public var password: String? + public var phone: String? + /** User Status */ + public var userStatus: Int32? + + public init() {} + + // MARK: JSONEncodable + func encodeToJSON() -> AnyObject { + var nillableDictionary = [String:AnyObject?]() + nillableDictionary["id"] = self.id?.encodeToJSON() + nillableDictionary["username"] = self.username + nillableDictionary["firstName"] = self.firstName + nillableDictionary["lastName"] = self.lastName + nillableDictionary["email"] = self.email + nillableDictionary["password"] = self.password + nillableDictionary["phone"] = self.phone + nillableDictionary["userStatus"] = self.userStatus?.encodeToJSON() + let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Podfile b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Podfile new file mode 100644 index 00000000000..29843508b65 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Podfile @@ -0,0 +1,10 @@ +use_frameworks! +source 'https://github.com/CocoaPods/Specs.git' + +target 'SwaggerClient' do + pod "PetstoreClient", :path => "../" + + target 'SwaggerClientTests' do + inherit! :search_paths + end +end diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/LICENSE b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/LICENSE new file mode 100644 index 00000000000..bf300e4482e --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/README.md b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/README.md new file mode 100644 index 00000000000..a109cdf9b2f --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/README.md @@ -0,0 +1,1149 @@ +![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/assets/alamofire.png) + +[![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg)](https://travis-ci.org/Alamofire/Alamofire) +[![Cocoapods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.svg) +[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) +[![Platform](https://img.shields.io/cocoapods/p/Alamofire.svg?style=flat)](http://cocoadocs.org/docsets/Alamofire) +[![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat)](http://twitter.com/AlamofireSF) + +Alamofire is an HTTP networking library written in Swift. + +## Features + +- [x] Chainable Request / Response methods +- [x] URL / JSON / plist Parameter Encoding +- [x] Upload File / Data / Stream / MultipartFormData +- [x] Download using Request or Resume data +- [x] Authentication with NSURLCredential +- [x] HTTP Response Validation +- [x] TLS Certificate and Public Key Pinning +- [x] Progress Closure & NSProgress +- [x] cURL Debug Output +- [x] Comprehensive Unit Test Coverage +- [x] [Complete Documentation](http://cocoadocs.org/docsets/Alamofire) + +## Requirements + +- iOS 8.0+ / Mac OS X 10.9+ / tvOS 9.0+ / watchOS 2.0+ +- Xcode 7.2+ + +## Migration Guides + +- [Alamofire 3.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md) +- [Alamofire 2.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%202.0%20Migration%20Guide.md) + +## Communication + +- If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/alamofire). (Tag 'alamofire') +- If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/alamofire). +- If you **found a bug**, open an issue. +- If you **have a feature request**, open an issue. +- If you **want to contribute**, submit a pull request. + +## Installation + +> **Embedded frameworks require a minimum deployment target of iOS 8 or OS X Mavericks (10.9).** +> +> Alamofire is no longer supported on iOS 7 due to the lack of support for frameworks. Without frameworks, running Travis-CI against iOS 7 would require a second duplicated test target. The separate test suite would need to import all the Swift files and the tests would need to be duplicated and re-written. This split would be too difficult to maintain to ensure the highest possible quality of the Alamofire ecosystem. + +### CocoaPods + +[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command: + +```bash +$ gem install cocoapods +``` + +> CocoaPods 0.39.0+ is required to build Alamofire 3.0.0+. + +To integrate Alamofire into your Xcode project using CocoaPods, specify it in your `Podfile`: + +```ruby +source 'https://github.com/CocoaPods/Specs.git' +platform :ios, '8.0' +use_frameworks! + +pod 'Alamofire', '~> 3.0' +``` + +Then, run the following command: + +```bash +$ pod install +``` + +### Carthage + +[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. + +You can install Carthage with [Homebrew](http://brew.sh/) using the following command: + +```bash +$ brew update +$ brew install carthage +``` + +To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: + +```ogdl +github "Alamofire/Alamofire" ~> 3.0 +``` + +Run `carthage update` to build the framework and drag the built `Alamofire.framework` into your Xcode project. + +### Manually + +If you prefer not to use either of the aforementioned dependency managers, you can integrate Alamofire into your project manually. + +#### Embedded Framework + +- Open up Terminal, `cd` into your top-level project directory, and run the following command "if" your project is not initialized as a git repository: + +```bash +$ git init +``` + +- Add Alamofire as a git [submodule](http://git-scm.com/docs/git-submodule) by running the following command: + +```bash +$ git submodule add https://github.com/Alamofire/Alamofire.git +``` + +- Open the new `Alamofire` folder, and drag the `Alamofire.xcodeproj` into the Project Navigator of your application's Xcode project. + + > It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter. + +- Select the `Alamofire.xcodeproj` in the Project Navigator and verify the deployment target matches that of your application target. +- Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar. +- In the tab bar at the top of that window, open the "General" panel. +- Click on the `+` button under the "Embedded Binaries" section. +- You will see two different `Alamofire.xcodeproj` folders each with two different versions of the `Alamofire.framework` nested inside a `Products` folder. + + > It does not matter which `Products` folder you choose from, but it does matter whether you choose the top or bottom `Alamofire.framework`. + +- Select the top `Alamofire.framework` for iOS and the bottom one for OS X. + + > You can verify which one you selected by inspecting the build log for your project. The build target for `Alamofire` will be listed as either `Alamofire iOS` or `Alamofire OSX`. + +- And that's it! + +> The `Alamofire.framework` is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device. + +--- + +## Usage + +### Making a Request + +```swift +import Alamofire + +Alamofire.request(.GET, "https://httpbin.org/get") +``` + +### Response Handling + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .responseJSON { response in + print(response.request) // original URL request + print(response.response) // URL response + print(response.data) // server data + print(response.result) // result of response serialization + + if let JSON = response.result.value { + print("JSON: \(JSON)") + } + } +``` + +> Networking in Alamofire is done _asynchronously_. Asynchronous programming may be a source of frustration to programmers unfamiliar with the concept, but there are [very good reasons](https://developer.apple.com/library/ios/qa/qa1693/_index.html) for doing it this way. + +> Rather than blocking execution to wait for a response from the server, a [callback](http://en.wikipedia.org/wiki/Callback_%28computer_programming%29) is specified to handle the response once it's received. The result of a request is only available inside the scope of a response handler. Any execution contingent on the response or data received from the server must be done within a handler. + +### Response Serialization + +**Built-in Response Methods** + +- `response()` +- `responseData()` +- `responseString(encoding: NSStringEncoding)` +- `responseJSON(options: NSJSONReadingOptions)` +- `responsePropertyList(options: NSPropertyListReadOptions)` + +#### Response Handler + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .response { request, response, data, error in + print(request) + print(response) + print(data) + print(error) + } +``` + +> The `response` serializer does NOT evaluate any of the response data. It merely forwards on all the information directly from the URL session delegate. We strongly encourage you to leverage the other responser serializers taking advantage of `Response` and `Result` types. + +#### Response Data Handler + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .responseData { response in + print(response.request) + print(response.response) + print(response.result) + } +``` + +#### Response String Handler + +```swift +Alamofire.request(.GET, "https://httpbin.org/get") + .responseString { response in + print("Success: \(response.result.isSuccess)") + print("Response String: \(response.result.value)") + } +``` + +#### Response JSON Handler + +```swift +Alamofire.request(.GET, "https://httpbin.org/get") + .responseJSON { response in + debugPrint(response) + } +``` + +#### Chained Response Handlers + +Response handlers can even be chained: + +```swift +Alamofire.request(.GET, "https://httpbin.org/get") + .responseString { response in + print("Response String: \(response.result.value)") + } + .responseJSON { response in + print("Response JSON: \(response.result.value)") + } +``` + +### HTTP Methods + +`Alamofire.Method` lists the HTTP methods defined in [RFC 7231 §4.3](http://tools.ietf.org/html/rfc7231#section-4.3): + +```swift +public enum Method: String { + case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT +} +``` + +These values can be passed as the first argument of the `Alamofire.request` method: + +```swift +Alamofire.request(.POST, "https://httpbin.org/post") + +Alamofire.request(.PUT, "https://httpbin.org/put") + +Alamofire.request(.DELETE, "https://httpbin.org/delete") +``` + +### Parameters + +#### GET Request With URL-Encoded Parameters + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) +// https://httpbin.org/get?foo=bar +``` + +#### POST Request With URL-Encoded Parameters + +```swift +let parameters = [ + "foo": "bar", + "baz": ["a", 1], + "qux": [ + "x": 1, + "y": 2, + "z": 3 + ] +] + +Alamofire.request(.POST, "https://httpbin.org/post", parameters: parameters) +// HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3 +``` + +### Parameter Encoding + +Parameters can also be encoded as JSON, Property List, or any custom format, using the `ParameterEncoding` enum: + +```swift +enum ParameterEncoding { + case URL + case URLEncodedInURL + case JSON + case PropertyList(format: NSPropertyListFormat, options: NSPropertyListWriteOptions) + case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?)) + + func encode(request: NSURLRequest, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) + { ... } +} +``` + +- `URL`: A query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE` requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded`. _Since there is no published specification for how to encode collection types, Alamofire follows the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`)._ +- `URLEncodedInURL`: Creates query string to be set as or appended to any existing URL query. Uses the same implementation as the `.URL` case, but always applies the encoded result to the URL. +- `JSON`: Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. +- `PropertyList`: Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`. +- `Custom`: Uses the associated closure value to construct a new request given an existing request and parameters. + +#### Manual Parameter Encoding of an NSURLRequest + +```swift +let URL = NSURL(string: "https://httpbin.org/get")! +var request = NSMutableURLRequest(URL: URL) + +let parameters = ["foo": "bar"] +let encoding = Alamofire.ParameterEncoding.URL +(request, _) = encoding.encode(request, parameters: parameters) +``` + +#### POST Request with JSON-encoded Parameters + +```swift +let parameters = [ + "foo": [1,2,3], + "bar": [ + "baz": "qux" + ] +] + +Alamofire.request(.POST, "https://httpbin.org/post", parameters: parameters, encoding: .JSON) +// HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "qux"}} +``` + +### HTTP Headers + +Adding a custom HTTP header to a `Request` is supported directly in the global `request` method. This makes it easy to attach HTTP headers to a `Request` that can be constantly changing. + +> For HTTP headers that do not change, it is recommended to set them on the `NSURLSessionConfiguration` so they are automatically applied to any `NSURLSessionTask` created by the underlying `NSURLSession`. + +```swift +let headers = [ + "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", + "Content-Type": "application/x-www-form-urlencoded" +] + +Alamofire.request(.GET, "https://httpbin.org/get", headers: headers) + .responseJSON { response in + debugPrint(response) + } +``` + +### Caching + +Caching is handled on the system framework level by [`NSURLCache`](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLCache_Class/Reference/Reference.html#//apple_ref/occ/cl/NSURLCache). + +### Uploading + +**Supported Upload Types** + +- File +- Data +- Stream +- MultipartFormData + +#### Uploading a File + +```swift +let fileURL = NSBundle.mainBundle().URLForResource("Default", withExtension: "png") +Alamofire.upload(.POST, "https://httpbin.org/post", file: fileURL) +``` + +#### Uploading with Progress + +```swift +Alamofire.upload(.POST, "https://httpbin.org/post", file: fileURL) + .progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in + print(totalBytesWritten) + + // This closure is NOT called on the main queue for performance + // reasons. To update your ui, dispatch to the main queue. + dispatch_async(dispatch_get_main_queue()) { + print("Total bytes written on main queue: \(totalBytesWritten)") + } + } + .responseJSON { response in + debugPrint(response) + } +``` + +#### Uploading MultipartFormData + +```swift +Alamofire.upload( + .POST, + "https://httpbin.org/post", + multipartFormData: { multipartFormData in + multipartFormData.appendBodyPart(fileURL: unicornImageURL, name: "unicorn") + multipartFormData.appendBodyPart(fileURL: rainbowImageURL, name: "rainbow") + }, + encodingCompletion: { encodingResult in + switch encodingResult { + case .Success(let upload, _, _): + upload.responseJSON { response in + debugPrint(response) + } + case .Failure(let encodingError): + print(encodingError) + } + } +) +``` + +### Downloading + +**Supported Download Types** + +- Request +- Resume Data + +#### Downloading a File + +```swift +Alamofire.download(.GET, "https://httpbin.org/stream/100") { temporaryURL, response in + let fileManager = NSFileManager.defaultManager() + let directoryURL = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] + let pathComponent = response.suggestedFilename + + return directoryURL.URLByAppendingPathComponent(pathComponent!) +} +``` + +#### Using the Default Download Destination + +```swift +let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask) +Alamofire.download(.GET, "https://httpbin.org/stream/100", destination: destination) +``` + +#### Downloading a File w/Progress + +```swift +Alamofire.download(.GET, "https://httpbin.org/stream/100", destination: destination) + .progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in + print(totalBytesRead) + + // This closure is NOT called on the main queue for performance + // reasons. To update your ui, dispatch to the main queue. + dispatch_async(dispatch_get_main_queue()) { + print("Total bytes read on main queue: \(totalBytesRead)") + } + } + .response { _, _, _, error in + if let error = error { + print("Failed with error: \(error)") + } else { + print("Downloaded file successfully") + } + } +``` + +#### Accessing Resume Data for Failed Downloads + +```swift +Alamofire.download(.GET, "https://httpbin.org/stream/100", destination: destination) + .response { _, _, data, _ in + if let + data = data, + resumeDataString = NSString(data: data, encoding: NSUTF8StringEncoding) + { + print("Resume Data: \(resumeDataString)") + } else { + print("Resume Data was empty") + } + } +``` + +> The `data` parameter is automatically populated with the `resumeData` if available. + +```swift +let download = Alamofire.download(.GET, "https://httpbin.org/stream/100", destination: destination) +download.response { _, _, _, _ in + if let + resumeData = download.resumeData, + resumeDataString = NSString(data: resumeData, encoding: NSUTF8StringEncoding) + { + print("Resume Data: \(resumeDataString)") + } else { + print("Resume Data was empty") + } +} +``` + +### Authentication + +Authentication is handled on the system framework level by [`NSURLCredential` and `NSURLAuthenticationChallenge`](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLAuthenticationChallenge_Class/Reference/Reference.html). + +**Supported Authentication Schemes** + +- [HTTP Basic](http://en.wikipedia.org/wiki/Basic_access_authentication) +- [HTTP Digest](http://en.wikipedia.org/wiki/Digest_access_authentication) +- [Kerberos](http://en.wikipedia.org/wiki/Kerberos_%28protocol%29) +- [NTLM](http://en.wikipedia.org/wiki/NT_LAN_Manager) + +#### HTTP Basic Authentication + +The `authenticate` method on a `Request` will automatically provide an `NSURLCredential` to an `NSURLAuthenticationChallenge` when appropriate: + +```swift +let user = "user" +let password = "password" + +Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)") + .authenticate(user: user, password: password) + .responseJSON { response in + debugPrint(response) + } +``` + +Depending upon your server implementation, an `Authorization` header may also be appropriate: + +```swift +let user = "user" +let password = "password" + +let credentialData = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding)! +let base64Credentials = credentialData.base64EncodedStringWithOptions([]) + +let headers = ["Authorization": "Basic \(base64Credentials)"] + +Alamofire.request(.GET, "https://httpbin.org/basic-auth/user/password", headers: headers) + .responseJSON { response in + debugPrint(response) + } +``` + +#### Authentication with NSURLCredential + +```swift +let user = "user" +let password = "password" + +let credential = NSURLCredential(user: user, password: password, persistence: .ForSession) + +Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)") + .authenticate(usingCredential: credential) + .responseJSON { response in + debugPrint(response) + } +``` + +### Validation + +By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling `validate` before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type. + +#### Manual Validation + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .validate(statusCode: 200..<300) + .validate(contentType: ["application/json"]) + .response { response in + print(response) + } +``` + +#### Automatic Validation + +Automatically validates status code within `200...299` range, and that the `Content-Type` header of the response matches the `Accept` header of the request, if one is provided. + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .validate() + .responseJSON { response in + switch response.result { + case .Success: + print("Validation Successful") + case .Failure(let error): + print(error) + } + } +``` + +### Printable + +```swift +let request = Alamofire.request(.GET, "https://httpbin.org/ip") + +print(request) +// GET https://httpbin.org/ip (200) +``` + +### DebugPrintable + +```swift +let request = Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + +debugPrint(request) +``` + +#### Output (cURL) + +```bash +$ curl -i \ + -H "User-Agent: Alamofire" \ + -H "Accept-Encoding: Accept-Encoding: gzip;q=1.0,compress;q=0.5" \ + -H "Accept-Language: en;q=1.0,fr;q=0.9,de;q=0.8,zh-Hans;q=0.7,zh-Hant;q=0.6,ja;q=0.5" \ + "https://httpbin.org/get?foo=bar" +``` + +--- + +## Advanced Usage + +> Alamofire is built on `NSURLSession` and the Foundation URL Loading System. To make the most of +this framework, it is recommended that you be familiar with the concepts and capabilities of the underlying networking stack. + +**Recommended Reading** + +- [URL Loading System Programming Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html) +- [NSURLSession Class Reference](https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSURLSession_class/Introduction/Introduction.html#//apple_ref/occ/cl/NSURLSession) +- [NSURLCache Class Reference](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLCache_Class/Reference/Reference.html#//apple_ref/occ/cl/NSURLCache) +- [NSURLAuthenticationChallenge Class Reference](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLAuthenticationChallenge_Class/Reference/Reference.html) + +### Manager + +Top-level convenience methods like `Alamofire.request` use a shared instance of `Alamofire.Manager`, which is configured with the default `NSURLSessionConfiguration`. + +As such, the following two statements are equivalent: + +```swift +Alamofire.request(.GET, "https://httpbin.org/get") +``` + +```swift +let manager = Alamofire.Manager.sharedInstance +manager.request(NSURLRequest(URL: NSURL(string: "https://httpbin.org/get")!)) +``` + +Applications can create managers for background and ephemeral sessions, as well as new managers that customize the default session configuration, such as for default headers (`HTTPAdditionalHeaders`) or timeout interval (`timeoutIntervalForRequest`). + +#### Creating a Manager with Default Configuration + +```swift +let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() +let manager = Alamofire.Manager(configuration: configuration) +``` + +#### Creating a Manager with Background Configuration + +```swift +let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("com.example.app.background") +let manager = Alamofire.Manager(configuration: configuration) +``` + +#### Creating a Manager with Ephemeral Configuration + +```swift +let configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration() +let manager = Alamofire.Manager(configuration: configuration) +``` + +#### Modifying Session Configuration + +```swift +var defaultHeaders = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders ?? [:] +defaultHeaders["DNT"] = "1 (Do Not Track Enabled)" + +let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() +configuration.HTTPAdditionalHeaders = defaultHeaders + +let manager = Alamofire.Manager(configuration: configuration) +``` + +> This is **not** recommended for `Authorization` or `Content-Type` headers. Instead, use `URLRequestConvertible` and `ParameterEncoding`, respectively. + +### Request + +The result of a `request`, `upload`, or `download` method is an instance of `Alamofire.Request`. A request is always created using a constructor method from an owning manager, and never initialized directly. + +Methods like `authenticate`, `validate` and `responseData` return the caller in order to facilitate chaining. + +Requests can be suspended, resumed, and cancelled: + +- `suspend()`: Suspends the underlying task and dispatch queue +- `resume()`: Resumes the underlying task and dispatch queue. If the owning manager does not have `startRequestsImmediately` set to `true`, the request must call `resume()` in order to start. +- `cancel()`: Cancels the underlying task, producing an error that is passed to any registered response handlers. + +### Response Serialization + +#### Creating a Custom Response Serializer + +Alamofire provides built-in response serialization for strings, JSON, and property lists, but others can be added in extensions on `Alamofire.Request`. + +For example, here's how a response handler using [Ono](https://github.com/mattt/Ono) might be implemented: + +```swift +extension Request { + public static func XMLResponseSerializer() -> ResponseSerializer { + return ResponseSerializer { request, response, data, error in + guard error == nil else { return .Failure(error!) } + + guard let validData = data else { + let failureReason = "Data could not be serialized. Input data was nil." + let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason) + return .Failure(error) + } + + do { + let XML = try ONOXMLDocument(data: validData) + return .Success(XML) + } catch { + return .Failure(error as NSError) + } + } + } + + public func responseXMLDocument(completionHandler: Response -> Void) -> Self { + return response(responseSerializer: Request.XMLResponseSerializer(), completionHandler: completionHandler) + } +} +``` + +#### Generic Response Object Serialization + +Generics can be used to provide automatic, type-safe response object serialization. + +```swift +public protocol ResponseObjectSerializable { + init?(response: NSHTTPURLResponse, representation: AnyObject) +} + +extension Request { + public func responseObject(completionHandler: Response -> Void) -> Self { + let responseSerializer = ResponseSerializer { request, response, data, error in + guard error == nil else { return .Failure(error!) } + + let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments) + let result = JSONResponseSerializer.serializeResponse(request, response, data, error) + + switch result { + case .Success(let value): + if let + response = response, + responseObject = T(response: response, representation: value) + { + return .Success(responseObject) + } else { + let failureReason = "JSON could not be serialized into response object: \(value)" + let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason) + return .Failure(error) + } + case .Failure(let error): + return .Failure(error) + } + } + + return response(responseSerializer: responseSerializer, completionHandler: completionHandler) + } +} +``` + +```swift +final class User: ResponseObjectSerializable { + let username: String + let name: String + + init?(response: NSHTTPURLResponse, representation: AnyObject) { + self.username = response.URL!.lastPathComponent! + self.name = representation.valueForKeyPath("name") as! String + } +} +``` + +```swift +Alamofire.request(.GET, "https://example.com/users/mattt") + .responseObject { (response: Response) in + debugPrint(response) + } +``` + +The same approach can also be used to handle endpoints that return a representation of a collection of objects: + +```swift +public protocol ResponseCollectionSerializable { + static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [Self] +} + +extension Alamofire.Request { + public func responseCollection(completionHandler: Response<[T], NSError> -> Void) -> Self { + let responseSerializer = ResponseSerializer<[T], NSError> { request, response, data, error in + guard error == nil else { return .Failure(error!) } + + let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments) + let result = JSONSerializer.serializeResponse(request, response, data, error) + + switch result { + case .Success(let value): + if let response = response { + return .Success(T.collection(response: response, representation: value)) + } else { + let failureReason = "Response collection could not be serialized due to nil response" + let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason) + return .Failure(error) + } + case .Failure(let error): + return .Failure(error) + } + } + + return response(responseSerializer: responseSerializer, completionHandler: completionHandler) + } +} +``` + +```swift +final class User: ResponseObjectSerializable, ResponseCollectionSerializable { + let username: String + let name: String + + init?(response: NSHTTPURLResponse, representation: AnyObject) { + self.username = response.URL!.lastPathComponent! + self.name = representation.valueForKeyPath("name") as! String + } + + static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [User] { + var users: [User] = [] + + if let representation = representation as? [[String: AnyObject]] { + for userRepresentation in representation { + if let user = User(response: response, representation: userRepresentation) { + users.append(user) + } + } + } + + return users + } +} +``` + +```swift +Alamofire.request(.GET, "http://example.com/users") + .responseCollection { (response: Response<[User], NSError>) in + debugPrint(response) + } +``` + +### URLStringConvertible + +Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to construct URL requests. `NSString`, `NSURL`, `NSURLComponents`, and `NSURLRequest` conform to `URLStringConvertible` by default, allowing any of them to be passed as `URLString` parameters to the `request`, `upload`, and `download` methods: + +```swift +let string = NSString(string: "https://httpbin.org/post") +Alamofire.request(.POST, string) + +let URL = NSURL(string: string)! +Alamofire.request(.POST, URL) + +let URLRequest = NSURLRequest(URL: URL) +Alamofire.request(.POST, URLRequest) // overrides `HTTPMethod` of `URLRequest` + +let URLComponents = NSURLComponents(URL: URL, resolvingAgainstBaseURL: true) +Alamofire.request(.POST, URLComponents) +``` + +Applications interacting with web applications in a significant manner are encouraged to have custom types conform to `URLStringConvertible` as a convenient way to map domain-specific models to server resources. + +#### Type-Safe Routing + +```swift +extension User: URLStringConvertible { + static let baseURLString = "http://example.com" + + var URLString: String { + return User.baseURLString + "/users/\(username)/" + } +} +``` + +```swift +let user = User(username: "mattt") +Alamofire.request(.GET, user) // http://example.com/users/mattt +``` + +### URLRequestConvertible + +Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. `NSURLRequest` conforms to `URLRequestConvertible` by default, allowing it to be passed into `request`, `upload`, and `download` methods directly (this is the recommended way to specify custom HTTP body for individual requests): + +```swift +let URL = NSURL(string: "https://httpbin.org/post")! +let mutableURLRequest = NSMutableURLRequest(URL: URL) +mutableURLRequest.HTTPMethod = "POST" + +let parameters = ["foo": "bar"] + +do { + mutableURLRequest.HTTPBody = try NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions()) +} catch { + // No-op +} + +mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + +Alamofire.request(mutableURLRequest) +``` + +Applications interacting with web applications in a significant manner are encouraged to have custom types conform to `URLRequestConvertible` as a way to ensure consistency of requested endpoints. Such an approach can be used to abstract away server-side inconsistencies and provide type-safe routing, as well as manage authentication credentials and other state. + +#### API Parameter Abstraction + +```swift +enum Router: URLRequestConvertible { + static let baseURLString = "http://example.com" + static let perPage = 50 + + case Search(query: String, page: Int) + + // MARK: URLRequestConvertible + + var URLRequest: NSMutableURLRequest { + let result: (path: String, parameters: [String: AnyObject]) = { + switch self { + case .Search(let query, let page) where page > 1: + return ("/search", ["q": query, "offset": Router.perPage * page]) + case .Search(let query, _): + return ("/search", ["q": query]) + } + }() + + let URL = NSURL(string: Router.baseURLString)! + let URLRequest = NSURLRequest(URL: URL.URLByAppendingPathComponent(result.path)) + let encoding = Alamofire.ParameterEncoding.URL + + return encoding.encode(URLRequest, parameters: result.parameters).0 + } +} +``` + +```swift +Alamofire.request(Router.Search(query: "foo bar", page: 1)) // ?q=foo%20bar&offset=50 +``` + +#### CRUD & Authorization + +```swift +enum Router: URLRequestConvertible { + static let baseURLString = "http://example.com" + static var OAuthToken: String? + + case CreateUser([String: AnyObject]) + case ReadUser(String) + case UpdateUser(String, [String: AnyObject]) + case DestroyUser(String) + + var method: Alamofire.Method { + switch self { + case .CreateUser: + return .POST + case .ReadUser: + return .GET + case .UpdateUser: + return .PUT + case .DestroyUser: + return .DELETE + } + } + + var path: String { + switch self { + case .CreateUser: + return "/users" + case .ReadUser(let username): + return "/users/\(username)" + case .UpdateUser(let username, _): + return "/users/\(username)" + case .DestroyUser(let username): + return "/users/\(username)" + } + } + + // MARK: URLRequestConvertible + + var URLRequest: NSMutableURLRequest { + let URL = NSURL(string: Router.baseURLString)! + let mutableURLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path)) + mutableURLRequest.HTTPMethod = method.rawValue + + if let token = Router.OAuthToken { + mutableURLRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") + } + + switch self { + case .CreateUser(let parameters): + return Alamofire.ParameterEncoding.JSON.encode(mutableURLRequest, parameters: parameters).0 + case .UpdateUser(_, let parameters): + return Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: parameters).0 + default: + return mutableURLRequest + } + } +} +``` + +```swift +Alamofire.request(Router.ReadUser("mattt")) // GET /users/mattt +``` + +### Security + +Using a secure HTTPS connection when communicating with servers and web services is an important step in securing sensitive data. By default, Alamofire will evaluate the certificate chain provided by the server using Apple's built in validation provided by the Security framework. While this guarantees the certificate chain is valid, it does not prevent man-in-the-middle (MITM) attacks or other potential vulnerabilities. In order to mitigate MITM attacks, applications dealing with sensitive customer data or financial information should use certificate or public key pinning provided by the `ServerTrustPolicy`. + +#### ServerTrustPolicy + +The `ServerTrustPolicy` enumeration evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when connecting to a server over a secure HTTPS connection. + +```swift +let serverTrustPolicy = ServerTrustPolicy.PinCertificates( + certificates: ServerTrustPolicy.certificatesInBundle(), + validateCertificateChain: true, + validateHost: true +) +``` + +There are many different cases of server trust evaluation giving you complete control over the validation process: + +* `PerformDefaultEvaluation`: Uses the default server trust evaluation while allowing you to control whether to validate the host provided by the challenge. +* `PinCertificates`: Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned certificates match one of the server certificates. +* `PinPublicKeys`: Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned public keys match one of the server certificate public keys. +* `DisableEvaluation`: Disables all evaluation which in turn will always consider any server trust as valid. +* `CustomEvaluation`: Uses the associated closure to evaluate the validity of the server trust thus giving you complete control over the validation process. Use with caution. + +#### Server Trust Policy Manager + +The `ServerTrustPolicyManager` is responsible for storing an internal mapping of server trust policies to a particular host. This allows Alamofire to evaluate each host against a different server trust policy. + +```swift +let serverTrustPolicies: [String: ServerTrustPolicy] = [ + "test.example.com": .PinCertificates( + certificates: ServerTrustPolicy.certificatesInBundle(), + validateCertificateChain: true, + validateHost: true + ), + "insecure.expired-apis.com": .DisableEvaluation +] + +let manager = Manager( + serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies) +) +``` + +> Make sure to keep a reference to the new `Manager` instance, otherwise your requests will all get cancelled when your `manager` is deallocated. + +These server trust policies will result in the following behavior: + +* `test.example.com` will always use certificate pinning with certificate chain and host validation enabled thus requiring the following criteria to be met to allow the TLS handshake to succeed: + * Certificate chain MUST be valid. + * Certificate chain MUST include one of the pinned certificates. + * Challenge host MUST match the host in the certificate chain's leaf certificate. +* `insecure.expired-apis.com` will never evaluate the certificate chain and will always allow the TLS handshake to succeed. +* All other hosts will use the default evaluation provided by Apple. + +##### Subclassing Server Trust Policy Manager + +If you find yourself needing more flexible server trust policy matching behavior (i.e. wildcarded domains), then subclass the `ServerTrustPolicyManager` and override the `serverTrustPolicyForHost` method with your own custom implementation. + +```swift +class CustomServerTrustPolicyManager: ServerTrustPolicyManager { + override func serverTrustPolicyForHost(host: String) -> ServerTrustPolicy? { + var policy: ServerTrustPolicy? + + // Implement your custom domain matching behavior... + + return policy + } +} +``` + +#### Validating the Host + +The `.PerformDefaultEvaluation`, `.PinCertificates` and `.PinPublicKeys` server trust policies all take a `validateHost` parameter. Setting the value to `true` will cause the server trust evaluation to verify that hostname in the certificate matches the hostname of the challenge. If they do not match, evaluation will fail. A `validateHost` value of `false` will still evaluate the full certificate chain, but will not validate the hostname of the leaf certificate. + +> It is recommended that `validateHost` always be set to `true` in production environments. + +#### Validating the Certificate Chain + +Pinning certificates and public keys both have the option of validating the certificate chain using the `validateCertificateChain` parameter. By setting this value to `true`, the full certificate chain will be evaluated in addition to performing a byte equality check against the pinned certficates or public keys. A value of `false` will skip the certificate chain validation, but will still perform the byte equality check. + +There are several cases where it may make sense to disable certificate chain validation. The most common use cases for disabling validation are self-signed and expired certificates. The evaluation would always fail in both of these cases, but the byte equality check will still ensure you are receiving the certificate you expect from the server. + +> It is recommended that `validateCertificateChain` always be set to `true` in production environments. + +#### App Transport Security + +With the addition of App Transport Security (ATS) in iOS 9, it is possible that using a custom `ServerTrustPolicyManager` with several `ServerTrustPolicy` objects will have no effect. If you continuously see `CFNetwork SSLHandshake failed (-9806)` errors, you have probably run into this problem. Apple's ATS system overrides the entire challenge system unless you configure the ATS settings in your app's plist to disable enough of it to allow your app to evaluate the server trust. + +If you run into this problem (high probability with self-signed certificates), you can work around this issue by adding the following to your `Info.plist`. + +```xml + + NSAppTransportSecurity + + NSExceptionDomains + + example.com + + NSExceptionAllowsInsecureHTTPLoads + + NSExceptionRequiresForwardSecrecy + + NSIncludesSubdomains + + + NSTemporaryExceptionMinimumTLSVersion + TLSv1.2 + + + + +``` + +Whether you need to set the `NSExceptionRequiresForwardSecrecy` to `NO` depends on whether your TLS connection is using an allowed cipher suite. In certain cases, it will need to be set to `NO`. The `NSExceptionAllowsInsecureHTTPLoads` MUST be set to `YES` in order to allow the `SessionDelegate` to receive challenge callbacks. Once the challenge callbacks are being called, the `ServerTrustPolicyManager` will take over the server trust evaluation. You may also need to specify the `NSTemporaryExceptionMinimumTLSVersion` if you're trying to connect to a host that only supports TLS versions less than `1.2`. + +> It is recommended to always use valid certificates in production environments. + +--- + +## Component Libraries + +In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem. + +* [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache and a priority-based image downloading system. + +## Open Rdars + +The following rdars have some affect on the current implementation of Alamofire. + +* [rdar://21349340](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in test case + +## FAQ + +### What's the origin of the name Alamofire? + +Alamofire is named after the [Alamo Fire flower](https://aggie-horticulture.tamu.edu/wildseed/alamofire.html), a hybrid variant of the Bluebonnet, the official state flower of Texas. + +--- + +## Credits + +Alamofire is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). You can follow them on Twitter at [@AlamofireSF](https://twitter.com/AlamofireSF) for project updates and releases. + +### Security Disclosure + +If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. + +## License + +Alamofire is released under the MIT license. See LICENSE for details. diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift new file mode 100644 index 00000000000..5a8bf14e3bf --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift @@ -0,0 +1,368 @@ +// Alamofire.swift +// +// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +// MARK: - URLStringConvertible + +/** + Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to + construct URL requests. +*/ +public protocol URLStringConvertible { + /** + A URL that conforms to RFC 2396. + + Methods accepting a `URLStringConvertible` type parameter parse it according to RFCs 1738 and 1808. + + See https://tools.ietf.org/html/rfc2396 + See https://tools.ietf.org/html/rfc1738 + See https://tools.ietf.org/html/rfc1808 + */ + var URLString: String { get } +} + +extension String: URLStringConvertible { + public var URLString: String { + return self + } +} + +extension NSURL: URLStringConvertible { + public var URLString: String { + return absoluteString + } +} + +extension NSURLComponents: URLStringConvertible { + public var URLString: String { + return URL!.URLString + } +} + +extension NSURLRequest: URLStringConvertible { + public var URLString: String { + return URL!.URLString + } +} + +// MARK: - URLRequestConvertible + +/** + Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. +*/ +public protocol URLRequestConvertible { + /// The URL request. + var URLRequest: NSMutableURLRequest { get } +} + +extension NSURLRequest: URLRequestConvertible { + public var URLRequest: NSMutableURLRequest { + return self.mutableCopy() as! NSMutableURLRequest + } +} + +// MARK: - Convenience + +func URLRequest( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil) + -> NSMutableURLRequest +{ + let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString.URLString)!) + mutableURLRequest.HTTPMethod = method.rawValue + + if let headers = headers { + for (headerField, headerValue) in headers { + mutableURLRequest.setValue(headerValue, forHTTPHeaderField: headerField) + } + } + + return mutableURLRequest +} + +// MARK: - Request Methods + +/** + Creates a request using the shared manager instance for the specified method, URL string, parameters, and + parameter encoding. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter parameters: The parameters. `nil` by default. + - parameter encoding: The parameter encoding. `.URL` by default. + - parameter headers: The HTTP headers. `nil` by default. + + - returns: The created request. +*/ +public func request( + method: Method, + _ URLString: URLStringConvertible, + parameters: [String: AnyObject]? = nil, + encoding: ParameterEncoding = .URL, + headers: [String: String]? = nil) + -> Request +{ + return Manager.sharedInstance.request( + method, + URLString, + parameters: parameters, + encoding: encoding, + headers: headers + ) +} + +/** + Creates a request using the shared manager instance for the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter URLRequest: The URL request + + - returns: The created request. +*/ +public func request(URLRequest: URLRequestConvertible) -> Request { + return Manager.sharedInstance.request(URLRequest.URLRequest) +} + +// MARK: - Upload Methods + +// MARK: File + +/** + Creates an upload request using the shared manager instance for the specified method, URL string, and file. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter headers: The HTTP headers. `nil` by default. + - parameter file: The file to upload. + + - returns: The created upload request. +*/ +public func upload( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil, + file: NSURL) + -> Request +{ + return Manager.sharedInstance.upload(method, URLString, headers: headers, file: file) +} + +/** + Creates an upload request using the shared manager instance for the specified URL request and file. + + - parameter URLRequest: The URL request. + - parameter file: The file to upload. + + - returns: The created upload request. +*/ +public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request { + return Manager.sharedInstance.upload(URLRequest, file: file) +} + +// MARK: Data + +/** + Creates an upload request using the shared manager instance for the specified method, URL string, and data. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter headers: The HTTP headers. `nil` by default. + - parameter data: The data to upload. + + - returns: The created upload request. +*/ +public func upload( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil, + data: NSData) + -> Request +{ + return Manager.sharedInstance.upload(method, URLString, headers: headers, data: data) +} + +/** + Creates an upload request using the shared manager instance for the specified URL request and data. + + - parameter URLRequest: The URL request. + - parameter data: The data to upload. + + - returns: The created upload request. +*/ +public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request { + return Manager.sharedInstance.upload(URLRequest, data: data) +} + +// MARK: Stream + +/** + Creates an upload request using the shared manager instance for the specified method, URL string, and stream. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter headers: The HTTP headers. `nil` by default. + - parameter stream: The stream to upload. + + - returns: The created upload request. +*/ +public func upload( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil, + stream: NSInputStream) + -> Request +{ + return Manager.sharedInstance.upload(method, URLString, headers: headers, stream: stream) +} + +/** + Creates an upload request using the shared manager instance for the specified URL request and stream. + + - parameter URLRequest: The URL request. + - parameter stream: The stream to upload. + + - returns: The created upload request. +*/ +public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request { + return Manager.sharedInstance.upload(URLRequest, stream: stream) +} + +// MARK: MultipartFormData + +/** + Creates an upload request using the shared manager instance for the specified method and URL string. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter headers: The HTTP headers. `nil` by default. + - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. + - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. + `MultipartFormDataEncodingMemoryThreshold` by default. + - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. +*/ +public func upload( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil, + multipartFormData: MultipartFormData -> Void, + encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, + encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?) +{ + return Manager.sharedInstance.upload( + method, + URLString, + headers: headers, + multipartFormData: multipartFormData, + encodingMemoryThreshold: encodingMemoryThreshold, + encodingCompletion: encodingCompletion + ) +} + +/** + Creates an upload request using the shared manager instance for the specified method and URL string. + + - parameter URLRequest: The URL request. + - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. + - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. + `MultipartFormDataEncodingMemoryThreshold` by default. + - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. +*/ +public func upload( + URLRequest: URLRequestConvertible, + multipartFormData: MultipartFormData -> Void, + encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, + encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?) +{ + return Manager.sharedInstance.upload( + URLRequest, + multipartFormData: multipartFormData, + encodingMemoryThreshold: encodingMemoryThreshold, + encodingCompletion: encodingCompletion + ) +} + +// MARK: - Download Methods + +// MARK: URL Request + +/** + Creates a download request using the shared manager instance for the specified method and URL string. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter parameters: The parameters. `nil` by default. + - parameter encoding: The parameter encoding. `.URL` by default. + - parameter headers: The HTTP headers. `nil` by default. + - parameter destination: The closure used to determine the destination of the downloaded file. + + - returns: The created download request. +*/ +public func download( + method: Method, + _ URLString: URLStringConvertible, + parameters: [String: AnyObject]? = nil, + encoding: ParameterEncoding = .URL, + headers: [String: String]? = nil, + destination: Request.DownloadFileDestination) + -> Request +{ + return Manager.sharedInstance.download( + method, + URLString, + parameters: parameters, + encoding: encoding, + headers: headers, + destination: destination + ) +} + +/** + Creates a download request using the shared manager instance for the specified URL request. + + - parameter URLRequest: The URL request. + - parameter destination: The closure used to determine the destination of the downloaded file. + + - returns: The created download request. +*/ +public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request { + return Manager.sharedInstance.download(URLRequest, destination: destination) +} + +// MARK: Resume Data + +/** + Creates a request using the shared manager instance for downloading from the resume data produced from a + previous request cancellation. + + - parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` + when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional + information. + - parameter destination: The closure used to determine the destination of the downloaded file. + + - returns: The created download request. +*/ +public func download(resumeData data: NSData, destination: Request.DownloadFileDestination) -> Request { + return Manager.sharedInstance.download(data, destination: destination) +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Download.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Download.swift new file mode 100644 index 00000000000..22dd402a765 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Download.swift @@ -0,0 +1,244 @@ +// Download.swift +// +// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +extension Manager { + private enum Downloadable { + case Request(NSURLRequest) + case ResumeData(NSData) + } + + private func download(downloadable: Downloadable, destination: Request.DownloadFileDestination) -> Request { + var downloadTask: NSURLSessionDownloadTask! + + switch downloadable { + case .Request(let request): + dispatch_sync(queue) { + downloadTask = self.session.downloadTaskWithRequest(request) + } + case .ResumeData(let resumeData): + dispatch_sync(queue) { + downloadTask = self.session.downloadTaskWithResumeData(resumeData) + } + } + + let request = Request(session: session, task: downloadTask) + + if let downloadDelegate = request.delegate as? Request.DownloadTaskDelegate { + downloadDelegate.downloadTaskDidFinishDownloadingToURL = { session, downloadTask, URL in + return destination(URL, downloadTask.response as! NSHTTPURLResponse) + } + } + + delegate[request.delegate.task] = request.delegate + + if startRequestsImmediately { + request.resume() + } + + return request + } + + // MARK: Request + + /** + Creates a download request for the specified method, URL string, parameters, parameter encoding, headers + and destination. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter parameters: The parameters. `nil` by default. + - parameter encoding: The parameter encoding. `.URL` by default. + - parameter headers: The HTTP headers. `nil` by default. + - parameter destination: The closure used to determine the destination of the downloaded file. + + - returns: The created download request. + */ + public func download( + method: Method, + _ URLString: URLStringConvertible, + parameters: [String: AnyObject]? = nil, + encoding: ParameterEncoding = .URL, + headers: [String: String]? = nil, + destination: Request.DownloadFileDestination) + -> Request + { + let mutableURLRequest = URLRequest(method, URLString, headers: headers) + let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0 + + return download(encodedURLRequest, destination: destination) + } + + /** + Creates a request for downloading from the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter URLRequest: The URL request + - parameter destination: The closure used to determine the destination of the downloaded file. + + - returns: The created download request. + */ + public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request { + return download(.Request(URLRequest.URLRequest), destination: destination) + } + + // MARK: Resume Data + + /** + Creates a request for downloading from the resume data produced from a previous request cancellation. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` + when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for + additional information. + - parameter destination: The closure used to determine the destination of the downloaded file. + + - returns: The created download request. + */ + public func download(resumeData: NSData, destination: Request.DownloadFileDestination) -> Request { + return download(.ResumeData(resumeData), destination: destination) + } +} + +// MARK: - + +extension Request { + /** + A closure executed once a request has successfully completed in order to determine where to move the temporary + file written to during the download process. The closure takes two arguments: the temporary file URL and the URL + response, and returns a single argument: the file URL where the temporary file should be moved. + */ + public typealias DownloadFileDestination = (NSURL, NSHTTPURLResponse) -> NSURL + + /** + Creates a download file destination closure which uses the default file manager to move the temporary file to a + file URL in the first available directory with the specified search path directory and search path domain mask. + + - parameter directory: The search path directory. `.DocumentDirectory` by default. + - parameter domain: The search path domain mask. `.UserDomainMask` by default. + + - returns: A download file destination closure. + */ + public class func suggestedDownloadDestination( + directory directory: NSSearchPathDirectory = .DocumentDirectory, + domain: NSSearchPathDomainMask = .UserDomainMask) + -> DownloadFileDestination + { + return { temporaryURL, response -> NSURL in + let directoryURLs = NSFileManager.defaultManager().URLsForDirectory(directory, inDomains: domain) + + if !directoryURLs.isEmpty { + return directoryURLs[0].URLByAppendingPathComponent(response.suggestedFilename!) + } + + return temporaryURL + } + } + + /// The resume data of the underlying download task if available after a failure. + public var resumeData: NSData? { + var data: NSData? + + if let delegate = delegate as? DownloadTaskDelegate { + data = delegate.resumeData + } + + return data + } + + // MARK: - DownloadTaskDelegate + + class DownloadTaskDelegate: TaskDelegate, NSURLSessionDownloadDelegate { + var downloadTask: NSURLSessionDownloadTask? { return task as? NSURLSessionDownloadTask } + var downloadProgress: ((Int64, Int64, Int64) -> Void)? + + var resumeData: NSData? + override var data: NSData? { return resumeData } + + // MARK: - NSURLSessionDownloadDelegate + + // MARK: Override Closures + + var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> NSURL)? + var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)? + var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)? + + // MARK: Delegate Methods + + func URLSession( + session: NSURLSession, + downloadTask: NSURLSessionDownloadTask, + didFinishDownloadingToURL location: NSURL) + { + if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { + do { + let destination = downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) + try NSFileManager.defaultManager().moveItemAtURL(location, toURL: destination) + } catch { + self.error = error as NSError + } + } + } + + func URLSession( + session: NSURLSession, + downloadTask: NSURLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) + { + if let downloadTaskDidWriteData = downloadTaskDidWriteData { + downloadTaskDidWriteData( + session, + downloadTask, + bytesWritten, + totalBytesWritten, + totalBytesExpectedToWrite + ) + } else { + progress.totalUnitCount = totalBytesExpectedToWrite + progress.completedUnitCount = totalBytesWritten + + downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) + } + } + + func URLSession( + session: NSURLSession, + downloadTask: NSURLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) + { + if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { + downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) + } else { + progress.totalUnitCount = expectedTotalBytes + progress.completedUnitCount = fileOffset + } + } + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Error.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Error.swift new file mode 100644 index 00000000000..7a813f1b813 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Error.swift @@ -0,0 +1,66 @@ +// Error.swift +// +// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/// The `Error` struct provides a convenience for creating custom Alamofire NSErrors. +public struct Error { + /// The domain used for creating all Alamofire errors. + public static let Domain = "com.alamofire.error" + + /// The custom error codes generated by Alamofire. + public enum Code: Int { + case InputStreamReadFailed = -6000 + case OutputStreamWriteFailed = -6001 + case ContentTypeValidationFailed = -6002 + case StatusCodeValidationFailed = -6003 + case DataSerializationFailed = -6004 + case StringSerializationFailed = -6005 + case JSONSerializationFailed = -6006 + case PropertyListSerializationFailed = -6007 + } + + /** + Creates an `NSError` with the given error code and failure reason. + + - parameter code: The error code. + - parameter failureReason: The failure reason. + + - returns: An `NSError` with the given error code and failure reason. + */ + public static func errorWithCode(code: Code, failureReason: String) -> NSError { + return errorWithCode(code.rawValue, failureReason: failureReason) + } + + /** + Creates an `NSError` with the given error code and failure reason. + + - parameter code: The error code. + - parameter failureReason: The failure reason. + + - returns: An `NSError` with the given error code and failure reason. + */ + public static func errorWithCode(code: Int, failureReason: String) -> NSError { + let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] + return NSError(domain: Domain, code: code, userInfo: userInfo) + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift new file mode 100644 index 00000000000..4051baf2403 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Manager.swift @@ -0,0 +1,693 @@ +// Manager.swift +// +// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/** + Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`. +*/ +public class Manager { + + // MARK: - Properties + + /** + A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly + for any ad hoc requests. + */ + public static let sharedInstance: Manager = { + let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() + configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders + + return Manager(configuration: configuration) + }() + + /** + Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers. + */ + public static let defaultHTTPHeaders: [String: String] = { + // Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3 + let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5" + + // Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5 + let acceptLanguage = NSLocale.preferredLanguages().prefix(6).enumerate().map { index, languageCode in + let quality = 1.0 - (Double(index) * 0.1) + return "\(languageCode);q=\(quality)" + }.joinWithSeparator(", ") + + // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 + let userAgent: String = { + if let info = NSBundle.mainBundle().infoDictionary { + let executable: AnyObject = info[kCFBundleExecutableKey as String] ?? "Unknown" + let bundle: AnyObject = info[kCFBundleIdentifierKey as String] ?? "Unknown" + let version: AnyObject = info[kCFBundleVersionKey as String] ?? "Unknown" + let os: AnyObject = NSProcessInfo.processInfo().operatingSystemVersionString ?? "Unknown" + + var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString + let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString + + if CFStringTransform(mutableUserAgent, UnsafeMutablePointer(nil), transform, false) { + return mutableUserAgent as String + } + } + + return "Alamofire" + }() + + return [ + "Accept-Encoding": acceptEncoding, + "Accept-Language": acceptLanguage, + "User-Agent": userAgent + ] + }() + + let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL) + + /// The underlying session. + public let session: NSURLSession + + /// The session delegate handling all the task and session delegate callbacks. + public let delegate: SessionDelegate + + /// Whether to start requests immediately after being constructed. `true` by default. + public var startRequestsImmediately: Bool = true + + /** + The background completion handler closure provided by the UIApplicationDelegate + `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background + completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation + will automatically call the handler. + + If you need to handle your own events before the handler is called, then you need to override the + SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished. + + `nil` by default. + */ + public var backgroundCompletionHandler: (() -> Void)? + + // MARK: - Lifecycle + + /** + Initializes the `Manager` instance with the specified configuration, delegate and server trust policy. + + - parameter configuration: The configuration used to construct the managed session. + `NSURLSessionConfiguration.defaultSessionConfiguration()` by default. + - parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by + default. + - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust + challenges. `nil` by default. + + - returns: The new `Manager` instance. + */ + public init( + configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration(), + delegate: SessionDelegate = SessionDelegate(), + serverTrustPolicyManager: ServerTrustPolicyManager? = nil) + { + self.delegate = delegate + self.session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) + + commonInit(serverTrustPolicyManager: serverTrustPolicyManager) + } + + /** + Initializes the `Manager` instance with the specified session, delegate and server trust policy. + + - parameter session: The URL session. + - parameter delegate: The delegate of the URL session. Must equal the URL session's delegate. + - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust + challenges. `nil` by default. + + - returns: The new `Manager` instance if the URL session's delegate matches the delegate parameter. + */ + public init?( + session: NSURLSession, + delegate: SessionDelegate, + serverTrustPolicyManager: ServerTrustPolicyManager? = nil) + { + self.delegate = delegate + self.session = session + + guard delegate === session.delegate else { return nil } + + commonInit(serverTrustPolicyManager: serverTrustPolicyManager) + } + + private func commonInit(serverTrustPolicyManager serverTrustPolicyManager: ServerTrustPolicyManager?) { + session.serverTrustPolicyManager = serverTrustPolicyManager + + delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in + guard let strongSelf = self else { return } + dispatch_async(dispatch_get_main_queue()) { strongSelf.backgroundCompletionHandler?() } + } + } + + deinit { + session.invalidateAndCancel() + } + + // MARK: - Request + + /** + Creates a request for the specified method, URL string, parameters, parameter encoding and headers. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter parameters: The parameters. `nil` by default. + - parameter encoding: The parameter encoding. `.URL` by default. + - parameter headers: The HTTP headers. `nil` by default. + + - returns: The created request. + */ + public func request( + method: Method, + _ URLString: URLStringConvertible, + parameters: [String: AnyObject]? = nil, + encoding: ParameterEncoding = .URL, + headers: [String: String]? = nil) + -> Request + { + let mutableURLRequest = URLRequest(method, URLString, headers: headers) + let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0 + return request(encodedURLRequest) + } + + /** + Creates a request for the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter URLRequest: The URL request + + - returns: The created request. + */ + public func request(URLRequest: URLRequestConvertible) -> Request { + var dataTask: NSURLSessionDataTask! + dispatch_sync(queue) { dataTask = self.session.dataTaskWithRequest(URLRequest.URLRequest) } + + let request = Request(session: session, task: dataTask) + delegate[request.delegate.task] = request.delegate + + if startRequestsImmediately { + request.resume() + } + + return request + } + + // MARK: - SessionDelegate + + /** + Responsible for handling all delegate callbacks for the underlying session. + */ + public final class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate { + private var subdelegates: [Int: Request.TaskDelegate] = [:] + private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) + + subscript(task: NSURLSessionTask) -> Request.TaskDelegate? { + get { + var subdelegate: Request.TaskDelegate? + dispatch_sync(subdelegateQueue) { subdelegate = self.subdelegates[task.taskIdentifier] } + + return subdelegate + } + + set { + dispatch_barrier_async(subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue } + } + } + + /** + Initializes the `SessionDelegate` instance. + + - returns: The new `SessionDelegate` instance. + */ + public override init() { + super.init() + } + + // MARK: - NSURLSessionDelegate + + // MARK: Override Closures + + /// Overrides default behavior for NSURLSessionDelegate method `URLSession:didBecomeInvalidWithError:`. + public var sessionDidBecomeInvalidWithError: ((NSURLSession, NSError?) -> Void)? + + /// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`. + public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? + + /// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`. + public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)? + + // MARK: Delegate Methods + + /** + Tells the delegate that the session has been invalidated. + + - parameter session: The session object that was invalidated. + - parameter error: The error that caused invalidation, or nil if the invalidation was explicit. + */ + public func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) { + sessionDidBecomeInvalidWithError?(session, error) + } + + /** + Requests credentials from the delegate in response to a session-level authentication request from the remote server. + + - parameter session: The session containing the task that requested authentication. + - parameter challenge: An object that contains the request for authentication. + - parameter completionHandler: A handler that your delegate method must call providing the disposition and credential. + */ + public func URLSession( + session: NSURLSession, + didReceiveChallenge challenge: NSURLAuthenticationChallenge, + completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) + { + var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling + var credential: NSURLCredential? + + if let sessionDidReceiveChallenge = sessionDidReceiveChallenge { + (disposition, credential) = sessionDidReceiveChallenge(session, challenge) + } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { + let host = challenge.protectionSpace.host + + if let + serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host), + serverTrust = challenge.protectionSpace.serverTrust + { + if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) { + disposition = .UseCredential + credential = NSURLCredential(forTrust: serverTrust) + } else { + disposition = .CancelAuthenticationChallenge + } + } + } + + completionHandler(disposition, credential) + } + + /** + Tells the delegate that all messages enqueued for a session have been delivered. + + - parameter session: The session that no longer has any outstanding requests. + */ + public func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) { + sessionDidFinishEventsForBackgroundURLSession?(session) + } + + // MARK: - NSURLSessionTaskDelegate + + // MARK: Override Closures + + /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`. + public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? + + /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`. + public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? + + /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`. + public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream!)? + + /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`. + public var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)? + + /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didCompleteWithError:`. + public var taskDidComplete: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)? + + // MARK: Delegate Methods + + /** + Tells the delegate that the remote server requested an HTTP redirect. + + - parameter session: The session containing the task whose request resulted in a redirect. + - parameter task: The task whose request resulted in a redirect. + - parameter response: An object containing the server’s response to the original request. + - parameter request: A URL request object filled out with the new location. + - parameter completionHandler: A closure that your handler should call with either the value of the request + parameter, a modified URL request object, or NULL to refuse the redirect and + return the body of the redirect response. + */ + public func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + willPerformHTTPRedirection response: NSHTTPURLResponse, + newRequest request: NSURLRequest, + completionHandler: ((NSURLRequest?) -> Void)) + { + var redirectRequest: NSURLRequest? = request + + if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { + redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) + } + + completionHandler(redirectRequest) + } + + /** + Requests credentials from the delegate in response to an authentication request from the remote server. + + - parameter session: The session containing the task whose request requires authentication. + - parameter task: The task whose request requires authentication. + - parameter challenge: An object that contains the request for authentication. + - parameter completionHandler: A handler that your delegate method must call providing the disposition and credential. + */ + public func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + didReceiveChallenge challenge: NSURLAuthenticationChallenge, + completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) + { + if let taskDidReceiveChallenge = taskDidReceiveChallenge { + completionHandler(taskDidReceiveChallenge(session, task, challenge)) + } else if let delegate = self[task] { + delegate.URLSession( + session, + task: task, + didReceiveChallenge: challenge, + completionHandler: completionHandler + ) + } else { + URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler) + } + } + + /** + Tells the delegate when a task requires a new request body stream to send to the remote server. + + - parameter session: The session containing the task that needs a new body stream. + - parameter task: The task that needs a new body stream. + - parameter completionHandler: A completion handler that your delegate method should call with the new body stream. + */ + public func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + needNewBodyStream completionHandler: ((NSInputStream?) -> Void)) + { + if let taskNeedNewBodyStream = taskNeedNewBodyStream { + completionHandler(taskNeedNewBodyStream(session, task)) + } else if let delegate = self[task] { + delegate.URLSession(session, task: task, needNewBodyStream: completionHandler) + } + } + + /** + Periodically informs the delegate of the progress of sending body content to the server. + + - parameter session: The session containing the data task. + - parameter task: The data task. + - parameter bytesSent: The number of bytes sent since the last time this delegate method was called. + - parameter totalBytesSent: The total number of bytes sent so far. + - parameter totalBytesExpectedToSend: The expected length of the body data. + */ + public func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) + { + if let taskDidSendBodyData = taskDidSendBodyData { + taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) + } else if let delegate = self[task] as? Request.UploadTaskDelegate { + delegate.URLSession( + session, + task: task, + didSendBodyData: bytesSent, + totalBytesSent: totalBytesSent, + totalBytesExpectedToSend: totalBytesExpectedToSend + ) + } + } + + /** + Tells the delegate that the task finished transferring data. + + - parameter session: The session containing the task whose request finished transferring data. + - parameter task: The task whose request finished transferring data. + - parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil. + */ + public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { + if let taskDidComplete = taskDidComplete { + taskDidComplete(session, task, error) + } else if let delegate = self[task] { + delegate.URLSession(session, task: task, didCompleteWithError: error) + } + + self[task] = nil + } + + // MARK: - NSURLSessionDataDelegate + + // MARK: Override Closures + + /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`. + public var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)? + + /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`. + public var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)? + + /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveData:`. + public var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)? + + /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`. + public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse!)? + + // MARK: Delegate Methods + + /** + Tells the delegate that the data task received the initial reply (headers) from the server. + + - parameter session: The session containing the data task that received an initial reply. + - parameter dataTask: The data task that received an initial reply. + - parameter response: A URL response object populated with headers. + - parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a + constant to indicate whether the transfer should continue as a data task or + should become a download task. + */ + public func URLSession( + session: NSURLSession, + dataTask: NSURLSessionDataTask, + didReceiveResponse response: NSURLResponse, + completionHandler: ((NSURLSessionResponseDisposition) -> Void)) + { + var disposition: NSURLSessionResponseDisposition = .Allow + + if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { + disposition = dataTaskDidReceiveResponse(session, dataTask, response) + } + + completionHandler(disposition) + } + + /** + Tells the delegate that the data task was changed to a download task. + + - parameter session: The session containing the task that was replaced by a download task. + - parameter dataTask: The data task that was replaced by a download task. + - parameter downloadTask: The new download task that replaced the data task. + */ + public func URLSession( + session: NSURLSession, + dataTask: NSURLSessionDataTask, + didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) + { + if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask { + dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask) + } else { + let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask) + self[downloadTask] = downloadDelegate + } + } + + /** + Tells the delegate that the data task has received some of the expected data. + + - parameter session: The session containing the data task that provided data. + - parameter dataTask: The data task that provided data. + - parameter data: A data object containing the transferred data. + */ + public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { + if let dataTaskDidReceiveData = dataTaskDidReceiveData { + dataTaskDidReceiveData(session, dataTask, data) + } else if let delegate = self[dataTask] as? Request.DataTaskDelegate { + delegate.URLSession(session, dataTask: dataTask, didReceiveData: data) + } + } + + /** + Asks the delegate whether the data (or upload) task should store the response in the cache. + + - parameter session: The session containing the data (or upload) task. + - parameter dataTask: The data (or upload) task. + - parameter proposedResponse: The default caching behavior. This behavior is determined based on the current + caching policy and the values of certain received headers, such as the Pragma + and Cache-Control headers. + - parameter completionHandler: A block that your handler must call, providing either the original proposed + response, a modified version of that response, or NULL to prevent caching the + response. If your delegate implements this method, it must call this completion + handler; otherwise, your app leaks memory. + */ + public func URLSession( + session: NSURLSession, + dataTask: NSURLSessionDataTask, + willCacheResponse proposedResponse: NSCachedURLResponse, + completionHandler: ((NSCachedURLResponse?) -> Void)) + { + if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { + completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) + } else if let delegate = self[dataTask] as? Request.DataTaskDelegate { + delegate.URLSession( + session, + dataTask: dataTask, + willCacheResponse: proposedResponse, + completionHandler: completionHandler + ) + } else { + completionHandler(proposedResponse) + } + } + + // MARK: - NSURLSessionDownloadDelegate + + // MARK: Override Closures + + /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didFinishDownloadingToURL:`. + public var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> Void)? + + /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`. + public var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)? + + /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`. + public var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)? + + // MARK: Delegate Methods + + /** + Tells the delegate that a download task has finished downloading. + + - parameter session: The session containing the download task that finished. + - parameter downloadTask: The download task that finished. + - parameter location: A file URL for the temporary file. Because the file is temporary, you must either + open the file for reading or move it to a permanent location in your app’s sandbox + container directory before returning from this delegate method. + */ + public func URLSession( + session: NSURLSession, + downloadTask: NSURLSessionDownloadTask, + didFinishDownloadingToURL location: NSURL) + { + if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { + downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) + } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { + delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location) + } + } + + /** + Periodically informs the delegate about the download’s progress. + + - parameter session: The session containing the download task. + - parameter downloadTask: The download task. + - parameter bytesWritten: The number of bytes transferred since the last time this delegate + method was called. + - parameter totalBytesWritten: The total number of bytes transferred so far. + - parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length + header. If this header was not provided, the value is + `NSURLSessionTransferSizeUnknown`. + */ + public func URLSession( + session: NSURLSession, + downloadTask: NSURLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) + { + if let downloadTaskDidWriteData = downloadTaskDidWriteData { + downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) + } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { + delegate.URLSession( + session, + downloadTask: downloadTask, + didWriteData: bytesWritten, + totalBytesWritten: totalBytesWritten, + totalBytesExpectedToWrite: totalBytesExpectedToWrite + ) + } + } + + /** + Tells the delegate that the download task has resumed downloading. + + - parameter session: The session containing the download task that finished. + - parameter downloadTask: The download task that resumed. See explanation in the discussion. + - parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the + existing content, then this value is zero. Otherwise, this value is an + integer representing the number of bytes on disk that do not need to be + retrieved again. + - parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header. + If this header was not provided, the value is NSURLSessionTransferSizeUnknown. + */ + public func URLSession( + session: NSURLSession, + downloadTask: NSURLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) + { + if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { + downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) + } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { + delegate.URLSession( + session, + downloadTask: downloadTask, + didResumeAtOffset: fileOffset, + expectedTotalBytes: expectedTotalBytes + ) + } + } + + // MARK: - NSURLSessionStreamDelegate + + var _streamTaskReadClosed: Any? + var _streamTaskWriteClosed: Any? + var _streamTaskBetterRouteDiscovered: Any? + var _streamTaskDidBecomeInputStream: Any? + + // MARK: - NSObject + + public override func respondsToSelector(selector: Selector) -> Bool { + switch selector { + case "URLSession:didBecomeInvalidWithError:": + return sessionDidBecomeInvalidWithError != nil + case "URLSession:didReceiveChallenge:completionHandler:": + return sessionDidReceiveChallenge != nil + case "URLSessionDidFinishEventsForBackgroundURLSession:": + return sessionDidFinishEventsForBackgroundURLSession != nil + case "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:": + return taskWillPerformHTTPRedirection != nil + case "URLSession:dataTask:didReceiveResponse:completionHandler:": + return dataTaskDidReceiveResponse != nil + default: + return self.dynamicType.instancesRespondToSelector(selector) + } + } + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift new file mode 100644 index 00000000000..9e9b26c8b44 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift @@ -0,0 +1,669 @@ +// MultipartFormData.swift +// +// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +#if os(iOS) || os(watchOS) || os(tvOS) +import MobileCoreServices +#elseif os(OSX) +import CoreServices +#endif + +/** + Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode + multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead + to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the + data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for + larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset. + + For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well + and the w3 form documentation. + + - https://www.ietf.org/rfc/rfc2388.txt + - https://www.ietf.org/rfc/rfc2045.txt + - https://www.w3.org/TR/html401/interact/forms.html#h-17.13 +*/ +public class MultipartFormData { + + // MARK: - Helper Types + + struct EncodingCharacters { + static let CRLF = "\r\n" + } + + struct BoundaryGenerator { + enum BoundaryType { + case Initial, Encapsulated, Final + } + + static func randomBoundary() -> String { + return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random()) + } + + static func boundaryData(boundaryType boundaryType: BoundaryType, boundary: String) -> NSData { + let boundaryText: String + + switch boundaryType { + case .Initial: + boundaryText = "--\(boundary)\(EncodingCharacters.CRLF)" + case .Encapsulated: + boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)\(EncodingCharacters.CRLF)" + case .Final: + boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)--\(EncodingCharacters.CRLF)" + } + + return boundaryText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! + } + } + + class BodyPart { + let headers: [String: String] + let bodyStream: NSInputStream + let bodyContentLength: UInt64 + var hasInitialBoundary = false + var hasFinalBoundary = false + + init(headers: [String: String], bodyStream: NSInputStream, bodyContentLength: UInt64) { + self.headers = headers + self.bodyStream = bodyStream + self.bodyContentLength = bodyContentLength + } + } + + // MARK: - Properties + + /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`. + public var contentType: String { return "multipart/form-data; boundary=\(boundary)" } + + /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries. + public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } } + + /// The boundary used to separate the body parts in the encoded form data. + public let boundary: String + + private var bodyParts: [BodyPart] + private var bodyPartError: NSError? + private let streamBufferSize: Int + + // MARK: - Lifecycle + + /** + Creates a multipart form data object. + + - returns: The multipart form data object. + */ + public init() { + self.boundary = BoundaryGenerator.randomBoundary() + self.bodyParts = [] + + /** + * The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more + * information, please refer to the following article: + * - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html + */ + + self.streamBufferSize = 1024 + } + + // MARK: - Body Parts + + /** + Creates a body part from the data and appends it to the multipart form data object. + + The body part data will be encoded using the following format: + + - `Content-Disposition: form-data; name=#{name}` (HTTP Header) + - Encoded data + - Multipart form boundary + + - parameter data: The data to encode into the multipart form data. + - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. + */ + public func appendBodyPart(data data: NSData, name: String) { + let headers = contentHeaders(name: name) + let stream = NSInputStream(data: data) + let length = UInt64(data.length) + + appendBodyPart(stream: stream, length: length, headers: headers) + } + + /** + Creates a body part from the data and appends it to the multipart form data object. + + The body part data will be encoded using the following format: + + - `Content-Disposition: form-data; name=#{name}` (HTTP Header) + - `Content-Type: #{generated mimeType}` (HTTP Header) + - Encoded data + - Multipart form boundary + + - parameter data: The data to encode into the multipart form data. + - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. + - parameter mimeType: The MIME type to associate with the data content type in the `Content-Type` HTTP header. + */ + public func appendBodyPart(data data: NSData, name: String, mimeType: String) { + let headers = contentHeaders(name: name, mimeType: mimeType) + let stream = NSInputStream(data: data) + let length = UInt64(data.length) + + appendBodyPart(stream: stream, length: length, headers: headers) + } + + /** + Creates a body part from the data and appends it to the multipart form data object. + + The body part data will be encoded using the following format: + + - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) + - `Content-Type: #{mimeType}` (HTTP Header) + - Encoded file data + - Multipart form boundary + + - parameter data: The data to encode into the multipart form data. + - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. + - parameter fileName: The filename to associate with the data in the `Content-Disposition` HTTP header. + - parameter mimeType: The MIME type to associate with the data in the `Content-Type` HTTP header. + */ + public func appendBodyPart(data data: NSData, name: String, fileName: String, mimeType: String) { + let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType) + let stream = NSInputStream(data: data) + let length = UInt64(data.length) + + appendBodyPart(stream: stream, length: length, headers: headers) + } + + /** + Creates a body part from the file and appends it to the multipart form data object. + + The body part data will be encoded using the following format: + + - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header) + - `Content-Type: #{generated mimeType}` (HTTP Header) + - Encoded file data + - Multipart form boundary + + The filename in the `Content-Disposition` HTTP header is generated from the last path component of the + `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the + system associated MIME type. + + - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. + - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. + */ + public func appendBodyPart(fileURL fileURL: NSURL, name: String) { + if let + fileName = fileURL.lastPathComponent, + pathExtension = fileURL.pathExtension + { + let mimeType = mimeTypeForPathExtension(pathExtension) + appendBodyPart(fileURL: fileURL, name: name, fileName: fileName, mimeType: mimeType) + } else { + let failureReason = "Failed to extract the fileName of the provided URL: \(fileURL)" + setBodyPartError(Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)) + } + } + + /** + Creates a body part from the file and appends it to the multipart form data object. + + The body part data will be encoded using the following format: + + - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header) + - Content-Type: #{mimeType} (HTTP Header) + - Encoded file data + - Multipart form boundary + + - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. + - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. + - parameter fileName: The filename to associate with the file content in the `Content-Disposition` HTTP header. + - parameter mimeType: The MIME type to associate with the file content in the `Content-Type` HTTP header. + */ + public func appendBodyPart(fileURL fileURL: NSURL, name: String, fileName: String, mimeType: String) { + let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType) + + //============================================================ + // Check 1 - is file URL? + //============================================================ + + guard fileURL.fileURL else { + let failureReason = "The file URL does not point to a file URL: \(fileURL)" + let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) + setBodyPartError(error) + return + } + + //============================================================ + // Check 2 - is file URL reachable? + //============================================================ + + var isReachable = true + + if #available(OSX 10.10, *) { + isReachable = fileURL.checkPromisedItemIsReachableAndReturnError(nil) + } + + guard isReachable else { + let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)") + setBodyPartError(error) + return + } + + //============================================================ + // Check 3 - is file URL a directory? + //============================================================ + + var isDirectory: ObjCBool = false + + guard let + path = fileURL.path + where NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) && !isDirectory else + { + let failureReason = "The file URL is a directory, not a file: \(fileURL)" + let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) + setBodyPartError(error) + return + } + + //============================================================ + // Check 4 - can the file size be extracted? + //============================================================ + + var bodyContentLength: UInt64? + + do { + if let + path = fileURL.path, + fileSize = try NSFileManager.defaultManager().attributesOfItemAtPath(path)[NSFileSize] as? NSNumber + { + bodyContentLength = fileSize.unsignedLongLongValue + } + } catch { + // No-op + } + + guard let length = bodyContentLength else { + let failureReason = "Could not fetch attributes from the file URL: \(fileURL)" + let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) + setBodyPartError(error) + return + } + + //============================================================ + // Check 5 - can a stream be created from file URL? + //============================================================ + + guard let stream = NSInputStream(URL: fileURL) else { + let failureReason = "Failed to create an input stream from the file URL: \(fileURL)" + let error = Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason) + setBodyPartError(error) + return + } + + appendBodyPart(stream: stream, length: length, headers: headers) + } + + /** + Creates a body part from the stream and appends it to the multipart form data object. + + The body part data will be encoded using the following format: + + - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) + - `Content-Type: #{mimeType}` (HTTP Header) + - Encoded stream data + - Multipart form boundary + + - parameter stream: The input stream to encode in the multipart form data. + - parameter length: The content length of the stream. + - parameter name: The name to associate with the stream content in the `Content-Disposition` HTTP header. + - parameter fileName: The filename to associate with the stream content in the `Content-Disposition` HTTP header. + - parameter mimeType: The MIME type to associate with the stream content in the `Content-Type` HTTP header. + */ + public func appendBodyPart( + stream stream: NSInputStream, + length: UInt64, + name: String, + fileName: String, + mimeType: String) + { + let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType) + appendBodyPart(stream: stream, length: length, headers: headers) + } + + /** + Creates a body part with the headers, stream and length and appends it to the multipart form data object. + + The body part data will be encoded using the following format: + + - HTTP headers + - Encoded stream data + - Multipart form boundary + + - parameter stream: The input stream to encode in the multipart form data. + - parameter length: The content length of the stream. + - parameter headers: The HTTP headers for the body part. + */ + public func appendBodyPart(stream stream: NSInputStream, length: UInt64, headers: [String: String]) { + let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length) + bodyParts.append(bodyPart) + } + + // MARK: - Data Encoding + + /** + Encodes all the appended body parts into a single `NSData` object. + + It is important to note that this method will load all the appended body parts into memory all at the same + time. This method should only be used when the encoded data will have a small memory footprint. For large data + cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method. + + - throws: An `NSError` if encoding encounters an error. + + - returns: The encoded `NSData` if encoding is successful. + */ + public func encode() throws -> NSData { + if let bodyPartError = bodyPartError { + throw bodyPartError + } + + let encoded = NSMutableData() + + bodyParts.first?.hasInitialBoundary = true + bodyParts.last?.hasFinalBoundary = true + + for bodyPart in bodyParts { + let encodedData = try encodeBodyPart(bodyPart) + encoded.appendData(encodedData) + } + + return encoded + } + + /** + Writes the appended body parts into the given file URL. + + This process is facilitated by reading and writing with input and output streams, respectively. Thus, + this approach is very memory efficient and should be used for large body part data. + + - parameter fileURL: The file URL to write the multipart form data into. + + - throws: An `NSError` if encoding encounters an error. + */ + public func writeEncodedDataToDisk(fileURL: NSURL) throws { + if let bodyPartError = bodyPartError { + throw bodyPartError + } + + if let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path) { + let failureReason = "A file already exists at the given file URL: \(fileURL)" + throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) + } else if !fileURL.fileURL { + let failureReason = "The URL does not point to a valid file: \(fileURL)" + throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) + } + + let outputStream: NSOutputStream + + if let possibleOutputStream = NSOutputStream(URL: fileURL, append: false) { + outputStream = possibleOutputStream + } else { + let failureReason = "Failed to create an output stream with the given URL: \(fileURL)" + throw Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason) + } + + outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) + outputStream.open() + + self.bodyParts.first?.hasInitialBoundary = true + self.bodyParts.last?.hasFinalBoundary = true + + for bodyPart in self.bodyParts { + try writeBodyPart(bodyPart, toOutputStream: outputStream) + } + + outputStream.close() + outputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) + } + + // MARK: - Private - Body Part Encoding + + private func encodeBodyPart(bodyPart: BodyPart) throws -> NSData { + let encoded = NSMutableData() + + let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() + encoded.appendData(initialData) + + let headerData = encodeHeaderDataForBodyPart(bodyPart) + encoded.appendData(headerData) + + let bodyStreamData = try encodeBodyStreamDataForBodyPart(bodyPart) + encoded.appendData(bodyStreamData) + + if bodyPart.hasFinalBoundary { + encoded.appendData(finalBoundaryData()) + } + + return encoded + } + + private func encodeHeaderDataForBodyPart(bodyPart: BodyPart) -> NSData { + var headerText = "" + + for (key, value) in bodyPart.headers { + headerText += "\(key): \(value)\(EncodingCharacters.CRLF)" + } + headerText += EncodingCharacters.CRLF + + return headerText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! + } + + private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) throws -> NSData { + let inputStream = bodyPart.bodyStream + inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) + inputStream.open() + + var error: NSError? + let encoded = NSMutableData() + + while inputStream.hasBytesAvailable { + var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0) + let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) + + if inputStream.streamError != nil { + error = inputStream.streamError + break + } + + if bytesRead > 0 { + encoded.appendBytes(buffer, length: bytesRead) + } else if bytesRead < 0 { + let failureReason = "Failed to read from input stream: \(inputStream)" + error = Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason) + break + } else { + break + } + } + + inputStream.close() + inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) + + if let error = error { + throw error + } + + return encoded + } + + // MARK: - Private - Writing Body Part to Output Stream + + private func writeBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { + try writeInitialBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream) + try writeHeaderDataForBodyPart(bodyPart, toOutputStream: outputStream) + try writeBodyStreamForBodyPart(bodyPart, toOutputStream: outputStream) + try writeFinalBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream) + } + + private func writeInitialBoundaryDataForBodyPart( + bodyPart: BodyPart, + toOutputStream outputStream: NSOutputStream) + throws + { + let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() + return try writeData(initialData, toOutputStream: outputStream) + } + + private func writeHeaderDataForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { + let headerData = encodeHeaderDataForBodyPart(bodyPart) + return try writeData(headerData, toOutputStream: outputStream) + } + + private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { + let inputStream = bodyPart.bodyStream + inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) + inputStream.open() + + while inputStream.hasBytesAvailable { + var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0) + let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) + + if let streamError = inputStream.streamError { + throw streamError + } + + if bytesRead > 0 { + if buffer.count != bytesRead { + buffer = Array(buffer[0.. 0 { + if outputStream.hasSpaceAvailable { + let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite) + + if let streamError = outputStream.streamError { + throw streamError + } + + if bytesWritten < 0 { + let failureReason = "Failed to write to output stream: \(outputStream)" + throw Error.errorWithCode(.OutputStreamWriteFailed, failureReason: failureReason) + } + + bytesToWrite -= bytesWritten + + if bytesToWrite > 0 { + buffer = Array(buffer[bytesWritten.. String { + if let + id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil)?.takeRetainedValue(), + contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() + { + return contentType as String + } + + return "application/octet-stream" + } + + // MARK: - Private - Content Headers + + private func contentHeaders(name name: String) -> [String: String] { + return ["Content-Disposition": "form-data; name=\"\(name)\""] + } + + private func contentHeaders(name name: String, mimeType: String) -> [String: String] { + return [ + "Content-Disposition": "form-data; name=\"\(name)\"", + "Content-Type": "\(mimeType)" + ] + } + + private func contentHeaders(name name: String, fileName: String, mimeType: String) -> [String: String] { + return [ + "Content-Disposition": "form-data; name=\"\(name)\"; filename=\"\(fileName)\"", + "Content-Type": "\(mimeType)" + ] + } + + // MARK: - Private - Boundary Encoding + + private func initialBoundaryData() -> NSData { + return BoundaryGenerator.boundaryData(boundaryType: .Initial, boundary: boundary) + } + + private func encapsulatedBoundaryData() -> NSData { + return BoundaryGenerator.boundaryData(boundaryType: .Encapsulated, boundary: boundary) + } + + private func finalBoundaryData() -> NSData { + return BoundaryGenerator.boundaryData(boundaryType: .Final, boundary: boundary) + } + + // MARK: - Private - Errors + + private func setBodyPartError(error: NSError) { + if bodyPartError == nil { + bodyPartError = error + } + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift new file mode 100644 index 00000000000..09ea00f812c --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift @@ -0,0 +1,251 @@ +// ParameterEncoding.swift +// +// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/** + HTTP method definitions. + + See https://tools.ietf.org/html/rfc7231#section-4.3 +*/ +public enum Method: String { + case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT +} + +// MARK: ParameterEncoding + +/** + Used to specify the way in which a set of parameters are applied to a URL request. + + - `URL`: Creates a query string to be set as or appended to any existing URL query for `GET`, `HEAD`, + and `DELETE` requests, or set as the body for requests with any other HTTP method. The + `Content-Type` HTTP header field of an encoded request with HTTP body is set to + `application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification + for how to encode collection types, the convention of appending `[]` to the key for array + values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested + dictionary values (`foo[bar]=baz`). + + - `URLEncodedInURL`: Creates query string to be set as or appended to any existing URL query. Uses the same + implementation as the `.URL` case, but always applies the encoded result to the URL. + + - `JSON`: Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is + set as the body of the request. The `Content-Type` HTTP header field of an encoded request is + set to `application/json`. + + - `PropertyList`: Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, + according to the associated format and write options values, which is set as the body of the + request. The `Content-Type` HTTP header field of an encoded request is set to + `application/x-plist`. + + - `Custom`: Uses the associated closure value to construct a new request given an existing request and + parameters. +*/ +public enum ParameterEncoding { + case URL + case URLEncodedInURL + case JSON + case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions) + case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?)) + + /** + Creates a URL request by encoding parameters and applying them onto an existing request. + + - parameter URLRequest: The request to have parameters applied + - parameter parameters: The parameters to apply + + - returns: A tuple containing the constructed request and the error that occurred during parameter encoding, + if any. + */ + public func encode( + URLRequest: URLRequestConvertible, + parameters: [String: AnyObject]?) + -> (NSMutableURLRequest, NSError?) + { + var mutableURLRequest = URLRequest.URLRequest + + guard let parameters = parameters where !parameters.isEmpty else { + return (mutableURLRequest, nil) + } + + var encodingError: NSError? = nil + + switch self { + case .URL, .URLEncodedInURL: + func query(parameters: [String: AnyObject]) -> String { + var components: [(String, String)] = [] + + for key in parameters.keys.sort(<) { + let value = parameters[key]! + components += queryComponents(key, value) + } + + return (components.map { "\($0)=\($1)" } as [String]).joinWithSeparator("&") + } + + func encodesParametersInURL(method: Method) -> Bool { + switch self { + case .URLEncodedInURL: + return true + default: + break + } + + switch method { + case .GET, .HEAD, .DELETE: + return true + default: + return false + } + } + + if let method = Method(rawValue: mutableURLRequest.HTTPMethod) where encodesParametersInURL(method) { + if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) { + let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) + URLComponents.percentEncodedQuery = percentEncodedQuery + mutableURLRequest.URL = URLComponents.URL + } + } else { + if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil { + mutableURLRequest.setValue( + "application/x-www-form-urlencoded; charset=utf-8", + forHTTPHeaderField: "Content-Type" + ) + } + + mutableURLRequest.HTTPBody = query(parameters).dataUsingEncoding( + NSUTF8StringEncoding, + allowLossyConversion: false + ) + } + case .JSON: + do { + let options = NSJSONWritingOptions() + let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: options) + + mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + mutableURLRequest.HTTPBody = data + } catch { + encodingError = error as NSError + } + case .PropertyList(let format, let options): + do { + let data = try NSPropertyListSerialization.dataWithPropertyList( + parameters, + format: format, + options: options + ) + mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") + mutableURLRequest.HTTPBody = data + } catch { + encodingError = error as NSError + } + case .Custom(let closure): + (mutableURLRequest, encodingError) = closure(mutableURLRequest, parameters) + } + + return (mutableURLRequest, encodingError) + } + + /** + Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion. + + - parameter key: The key of the query component. + - parameter value: The value of the query component. + + - returns: The percent-escaped, URL encoded query string components. + */ + public func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] { + var components: [(String, String)] = [] + + if let dictionary = value as? [String: AnyObject] { + for (nestedKey, value) in dictionary { + components += queryComponents("\(key)[\(nestedKey)]", value) + } + } else if let array = value as? [AnyObject] { + for value in array { + components += queryComponents("\(key)[]", value) + } + } else { + components.append((escape(key), escape("\(value)"))) + } + + return components + } + + /** + Returns a percent-escaped string following RFC 3986 for a query string key or value. + + RFC 3986 states that the following characters are "reserved" characters. + + - General Delimiters: ":", "#", "[", "]", "@", "?", "/" + - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" + + In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow + query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" + should be percent-escaped in the query string. + + - parameter string: The string to be percent-escaped. + + - returns: The percent-escaped string. + */ + public func escape(string: String) -> String { + let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 + let subDelimitersToEncode = "!$&'()*+,;=" + + let allowedCharacterSet = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as! NSMutableCharacterSet + allowedCharacterSet.removeCharactersInString(generalDelimitersToEncode + subDelimitersToEncode) + + var escaped = "" + + //========================================================================================================== + // + // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few + // hundred Chinense characters causes various malloc error crashes. To avoid this issue until iOS 8 is no + // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more + // info, please refer to: + // + // - https://github.com/Alamofire/Alamofire/issues/206 + // + //========================================================================================================== + + if #available(iOS 8.3, OSX 10.10, *) { + escaped = string.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? string + } else { + let batchSize = 50 + var index = string.startIndex + + while index != string.endIndex { + let startIndex = index + let endIndex = index.advancedBy(batchSize, limit: string.endIndex) + let range = Range(start: startIndex, end: endIndex) + + let substring = string.substringWithRange(range) + + escaped += substring.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? substring + + index = endIndex + } + } + + return escaped + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Request.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Request.swift new file mode 100644 index 00000000000..93a7acb2ab2 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Request.swift @@ -0,0 +1,538 @@ +// Request.swift +// +// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/** + Responsible for sending a request and receiving the response and associated data from the server, as well as + managing its underlying `NSURLSessionTask`. +*/ +public class Request { + + // MARK: - Properties + + /// The delegate for the underlying task. + public let delegate: TaskDelegate + + /// The underlying task. + public var task: NSURLSessionTask { return delegate.task } + + /// The session belonging to the underlying task. + public let session: NSURLSession + + /// The request sent or to be sent to the server. + public var request: NSURLRequest? { return task.originalRequest } + + /// The response received from the server, if any. + public var response: NSHTTPURLResponse? { return task.response as? NSHTTPURLResponse } + + /// The progress of the request lifecycle. + public var progress: NSProgress { return delegate.progress } + + // MARK: - Lifecycle + + init(session: NSURLSession, task: NSURLSessionTask) { + self.session = session + + switch task { + case is NSURLSessionUploadTask: + self.delegate = UploadTaskDelegate(task: task) + case is NSURLSessionDataTask: + self.delegate = DataTaskDelegate(task: task) + case is NSURLSessionDownloadTask: + self.delegate = DownloadTaskDelegate(task: task) + default: + self.delegate = TaskDelegate(task: task) + } + } + + // MARK: - Authentication + + /** + Associates an HTTP Basic credential with the request. + + - parameter user: The user. + - parameter password: The password. + - parameter persistence: The URL credential persistence. `.ForSession` by default. + + - returns: The request. + */ + public func authenticate( + user user: String, + password: String, + persistence: NSURLCredentialPersistence = .ForSession) + -> Self + { + let credential = NSURLCredential(user: user, password: password, persistence: persistence) + + return authenticate(usingCredential: credential) + } + + /** + Associates a specified credential with the request. + + - parameter credential: The credential. + + - returns: The request. + */ + public func authenticate(usingCredential credential: NSURLCredential) -> Self { + delegate.credential = credential + + return self + } + + // MARK: - Progress + + /** + Sets a closure to be called periodically during the lifecycle of the request as data is written to or read + from the server. + + - For uploads, the progress closure returns the bytes written, total bytes written, and total bytes expected + to write. + - For downloads and data tasks, the progress closure returns the bytes read, total bytes read, and total bytes + expected to read. + + - parameter closure: The code to be executed periodically during the lifecycle of the request. + + - returns: The request. + */ + public func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self { + if let uploadDelegate = delegate as? UploadTaskDelegate { + uploadDelegate.uploadProgress = closure + } else if let dataDelegate = delegate as? DataTaskDelegate { + dataDelegate.dataProgress = closure + } else if let downloadDelegate = delegate as? DownloadTaskDelegate { + downloadDelegate.downloadProgress = closure + } + + return self + } + + /** + Sets a closure to be called periodically during the lifecycle of the request as data is read from the server. + + This closure returns the bytes most recently received from the server, not including data from previous calls. + If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is + also important to note that the `response` closure will be called with nil `responseData`. + + - parameter closure: The code to be executed periodically during the lifecycle of the request. + + - returns: The request. + */ + public func stream(closure: (NSData -> Void)? = nil) -> Self { + if let dataDelegate = delegate as? DataTaskDelegate { + dataDelegate.dataStream = closure + } + + return self + } + + // MARK: - State + + /** + Suspends the request. + */ + public func suspend() { + task.suspend() + } + + /** + Resumes the request. + */ + public func resume() { + task.resume() + } + + /** + Cancels the request. + */ + public func cancel() { + if let + downloadDelegate = delegate as? DownloadTaskDelegate, + downloadTask = downloadDelegate.downloadTask + { + downloadTask.cancelByProducingResumeData { data in + downloadDelegate.resumeData = data + } + } else { + task.cancel() + } + } + + // MARK: - TaskDelegate + + /** + The task delegate is responsible for handling all delegate callbacks for the underlying task as well as + executing all operations attached to the serial operation queue upon task completion. + */ + public class TaskDelegate: NSObject { + + /// The serial operation queue used to execute all operations after the task completes. + public let queue: NSOperationQueue + + let task: NSURLSessionTask + let progress: NSProgress + + var data: NSData? { return nil } + var error: NSError? + + var credential: NSURLCredential? + + init(task: NSURLSessionTask) { + self.task = task + self.progress = NSProgress(totalUnitCount: 0) + self.queue = { + let operationQueue = NSOperationQueue() + operationQueue.maxConcurrentOperationCount = 1 + operationQueue.suspended = true + + if #available(OSX 10.10, *) { + operationQueue.qualityOfService = NSQualityOfService.Utility + } + + return operationQueue + }() + } + + deinit { + queue.cancelAllOperations() + queue.suspended = false + } + + // MARK: - NSURLSessionTaskDelegate + + // MARK: Override Closures + + var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? + var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? + var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)? + var taskDidCompleteWithError: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)? + + // MARK: Delegate Methods + + func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + willPerformHTTPRedirection response: NSHTTPURLResponse, + newRequest request: NSURLRequest, + completionHandler: ((NSURLRequest?) -> Void)) + { + var redirectRequest: NSURLRequest? = request + + if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { + redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) + } + + completionHandler(redirectRequest) + } + + func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + didReceiveChallenge challenge: NSURLAuthenticationChallenge, + completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) + { + var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling + var credential: NSURLCredential? + + if let taskDidReceiveChallenge = taskDidReceiveChallenge { + (disposition, credential) = taskDidReceiveChallenge(session, task, challenge) + } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { + let host = challenge.protectionSpace.host + + if let + serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host), + serverTrust = challenge.protectionSpace.serverTrust + { + if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) { + disposition = .UseCredential + credential = NSURLCredential(forTrust: serverTrust) + } else { + disposition = .CancelAuthenticationChallenge + } + } + } else { + if challenge.previousFailureCount > 0 { + disposition = .CancelAuthenticationChallenge + } else { + credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace) + + if credential != nil { + disposition = .UseCredential + } + } + } + + completionHandler(disposition, credential) + } + + func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + needNewBodyStream completionHandler: ((NSInputStream?) -> Void)) + { + var bodyStream: NSInputStream? + + if let taskNeedNewBodyStream = taskNeedNewBodyStream { + bodyStream = taskNeedNewBodyStream(session, task) + } + + completionHandler(bodyStream) + } + + func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { + if let taskDidCompleteWithError = taskDidCompleteWithError { + taskDidCompleteWithError(session, task, error) + } else { + if let error = error { + self.error = error + + if let + downloadDelegate = self as? DownloadTaskDelegate, + userInfo = error.userInfo as? [String: AnyObject], + resumeData = userInfo[NSURLSessionDownloadTaskResumeData] as? NSData + { + downloadDelegate.resumeData = resumeData + } + } + + queue.suspended = false + } + } + } + + // MARK: - DataTaskDelegate + + class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate { + var dataTask: NSURLSessionDataTask? { return task as? NSURLSessionDataTask } + + private var totalBytesReceived: Int64 = 0 + private var mutableData: NSMutableData + override var data: NSData? { + if dataStream != nil { + return nil + } else { + return mutableData + } + } + + private var expectedContentLength: Int64? + private var dataProgress: ((bytesReceived: Int64, totalBytesReceived: Int64, totalBytesExpectedToReceive: Int64) -> Void)? + private var dataStream: ((data: NSData) -> Void)? + + override init(task: NSURLSessionTask) { + mutableData = NSMutableData() + super.init(task: task) + } + + // MARK: - NSURLSessionDataDelegate + + // MARK: Override Closures + + var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)? + var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)? + var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)? + var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)? + + // MARK: Delegate Methods + + func URLSession( + session: NSURLSession, + dataTask: NSURLSessionDataTask, + didReceiveResponse response: NSURLResponse, + completionHandler: (NSURLSessionResponseDisposition -> Void)) + { + var disposition: NSURLSessionResponseDisposition = .Allow + + expectedContentLength = response.expectedContentLength + + if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { + disposition = dataTaskDidReceiveResponse(session, dataTask, response) + } + + completionHandler(disposition) + } + + func URLSession( + session: NSURLSession, + dataTask: NSURLSessionDataTask, + didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) + { + dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask) + } + + func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { + if let dataTaskDidReceiveData = dataTaskDidReceiveData { + dataTaskDidReceiveData(session, dataTask, data) + } else { + if let dataStream = dataStream { + dataStream(data: data) + } else { + mutableData.appendData(data) + } + + totalBytesReceived += data.length + let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown + + progress.totalUnitCount = totalBytesExpected + progress.completedUnitCount = totalBytesReceived + + dataProgress?( + bytesReceived: Int64(data.length), + totalBytesReceived: totalBytesReceived, + totalBytesExpectedToReceive: totalBytesExpected + ) + } + } + + func URLSession( + session: NSURLSession, + dataTask: NSURLSessionDataTask, + willCacheResponse proposedResponse: NSCachedURLResponse, + completionHandler: ((NSCachedURLResponse?) -> Void)) + { + var cachedResponse: NSCachedURLResponse? = proposedResponse + + if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { + cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse) + } + + completionHandler(cachedResponse) + } + } +} + +// MARK: - CustomStringConvertible + +extension Request: CustomStringConvertible { + + /** + The textual representation used when written to an output stream, which includes the HTTP method and URL, as + well as the response status code if a response has been received. + */ + public var description: String { + var components: [String] = [] + + if let HTTPMethod = request?.HTTPMethod { + components.append(HTTPMethod) + } + + if let URLString = request?.URL?.absoluteString { + components.append(URLString) + } + + if let response = response { + components.append("(\(response.statusCode))") + } + + return components.joinWithSeparator(" ") + } +} + +// MARK: - CustomDebugStringConvertible + +extension Request: CustomDebugStringConvertible { + func cURLRepresentation() -> String { + var components = ["$ curl -i"] + + guard let + request = self.request, + URL = request.URL, + host = URL.host + else { + return "$ curl command could not be created" + } + + if let HTTPMethod = request.HTTPMethod where HTTPMethod != "GET" { + components.append("-X \(HTTPMethod)") + } + + if let credentialStorage = self.session.configuration.URLCredentialStorage { + let protectionSpace = NSURLProtectionSpace( + host: host, + port: URL.port?.integerValue ?? 0, + `protocol`: URL.scheme, + realm: host, + authenticationMethod: NSURLAuthenticationMethodHTTPBasic + ) + + if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values { + for credential in credentials { + components.append("-u \(credential.user!):\(credential.password!)") + } + } else { + if let credential = delegate.credential { + components.append("-u \(credential.user!):\(credential.password!)") + } + } + } + + if session.configuration.HTTPShouldSetCookies { + if let + cookieStorage = session.configuration.HTTPCookieStorage, + cookies = cookieStorage.cookiesForURL(URL) where !cookies.isEmpty + { + let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value ?? String());" } + components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"") + } + } + + if let headerFields = request.allHTTPHeaderFields { + for (field, value) in headerFields { + switch field { + case "Cookie": + continue + default: + components.append("-H \"\(field): \(value)\"") + } + } + } + + if let additionalHeaders = session.configuration.HTTPAdditionalHeaders { + for (field, value) in additionalHeaders { + switch field { + case "Cookie": + continue + default: + components.append("-H \"\(field): \(value)\"") + } + } + } + + if let + HTTPBodyData = request.HTTPBody, + HTTPBody = String(data: HTTPBodyData, encoding: NSUTF8StringEncoding) + { + let escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\"", withString: "\\\"") + components.append("-d \"\(escapedBody)\"") + } + + components.append("\"\(URL.absoluteString)\"") + + return components.joinWithSeparator(" \\\n\t") + } + + /// The textual representation used when written to an output stream, in the form of a cURL command. + public var debugDescription: String { + return cURLRepresentation() + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Response.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Response.swift new file mode 100644 index 00000000000..f79f9f302e4 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Response.swift @@ -0,0 +1,83 @@ +// Response.swift +// +// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/// Used to store all response data returned from a completed `Request`. +public struct Response { + /// The URL request sent to the server. + public let request: NSURLRequest? + + /// The server's response to the URL request. + public let response: NSHTTPURLResponse? + + /// The data returned by the server. + public let data: NSData? + + /// The result of response serialization. + public let result: Result + + /** + Initializes the `Response` instance with the specified URL request, URL response, server data and response + serialization result. + + - parameter request: The URL request sent to the server. + - parameter response: The server's response to the URL request. + - parameter data: The data returned by the server. + - parameter result: The result of response serialization. + + - returns: the new `Response` instance. + */ + public init(request: NSURLRequest?, response: NSHTTPURLResponse?, data: NSData?, result: Result) { + self.request = request + self.response = response + self.data = data + self.result = result + } +} + +// MARK: - CustomStringConvertible + +extension Response: CustomStringConvertible { + /// The textual representation used when written to an output stream, which includes whether the result was a + /// success or failure. + public var description: String { + return result.debugDescription + } +} + +// MARK: - CustomDebugStringConvertible + +extension Response: CustomDebugStringConvertible { + /// The debug textual representation used when written to an output stream, which includes the URL request, the URL + /// response, the server data and the response serialization result. + public var debugDescription: String { + var output: [String] = [] + + output.append(request != nil ? "[Request]: \(request!)" : "[Request]: nil") + output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") + output.append("[Data]: \(data?.length ?? 0) bytes") + output.append("[Result]: \(result.debugDescription)") + + return output.joinWithSeparator("\n") + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift new file mode 100644 index 00000000000..0ba6f2b718a --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift @@ -0,0 +1,355 @@ +// ResponseSerialization.swift +// +// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +// MARK: ResponseSerializer + +/** + The type in which all response serializers must conform to in order to serialize a response. +*/ +public protocol ResponseSerializerType { + /// The type of serialized object to be created by this `ResponseSerializerType`. + typealias SerializedObject + + /// The type of error to be created by this `ResponseSerializer` if serialization fails. + typealias ErrorObject: ErrorType + + /** + A closure used by response handlers that takes a request, response, data and error and returns a result. + */ + var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result { get } +} + +// MARK: - + +/** + A generic `ResponseSerializerType` used to serialize a request, response, and data into a serialized object. +*/ +public struct ResponseSerializer: ResponseSerializerType { + /// The type of serialized object to be created by this `ResponseSerializer`. + public typealias SerializedObject = Value + + /// The type of error to be created by this `ResponseSerializer` if serialization fails. + public typealias ErrorObject = Error + + /** + A closure used by response handlers that takes a request, response, data and error and returns a result. + */ + public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result + + /** + Initializes the `ResponseSerializer` instance with the given serialize response closure. + + - parameter serializeResponse: The closure used to serialize the response. + + - returns: The new generic response serializer instance. + */ + public init(serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result) { + self.serializeResponse = serializeResponse + } +} + +// MARK: - Default + +extension Request { + + /** + Adds a handler to be called once the request has finished. + + - parameter queue: The queue on which the completion handler is dispatched. + - parameter completionHandler: The code to be executed once the request has finished. + + - returns: The request. + */ + public func response( + queue queue: dispatch_queue_t? = nil, + completionHandler: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Void) + -> Self + { + delegate.queue.addOperationWithBlock { + dispatch_async(queue ?? dispatch_get_main_queue()) { + completionHandler(self.request, self.response, self.delegate.data, self.delegate.error) + } + } + + return self + } + + /** + Adds a handler to be called once the request has finished. + + - parameter queue: The queue on which the completion handler is dispatched. + - parameter responseSerializer: The response serializer responsible for serializing the request, response, + and data. + - parameter completionHandler: The code to be executed once the request has finished. + + - returns: The request. + */ + public func response( + queue queue: dispatch_queue_t? = nil, + responseSerializer: T, + completionHandler: Response -> Void) + -> Self + { + delegate.queue.addOperationWithBlock { + let result = responseSerializer.serializeResponse( + self.request, + self.response, + self.delegate.data, + self.delegate.error + ) + + dispatch_async(queue ?? dispatch_get_main_queue()) { + let response = Response( + request: self.request, + response: self.response, + data: self.delegate.data, + result: result + ) + + completionHandler(response) + } + } + + return self + } +} + +// MARK: - Data + +extension Request { + + /** + Creates a response serializer that returns the associated data as-is. + + - returns: A data response serializer. + */ + public static func dataResponseSerializer() -> ResponseSerializer { + return ResponseSerializer { _, response, data, error in + guard error == nil else { return .Failure(error!) } + + if let response = response where response.statusCode == 204 { return .Success(NSData()) } + + guard let validData = data else { + let failureReason = "Data could not be serialized. Input data was nil." + let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason) + return .Failure(error) + } + + return .Success(validData) + } + } + + /** + Adds a handler to be called once the request has finished. + + - parameter completionHandler: The code to be executed once the request has finished. + + - returns: The request. + */ + public func responseData(completionHandler: Response -> Void) -> Self { + return response(responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler) + } +} + +// MARK: - String + +extension Request { + + /** + Creates a response serializer that returns a string initialized from the response data with the specified + string encoding. + + - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server + response, falling back to the default HTTP default character set, ISO-8859-1. + + - returns: A string response serializer. + */ + public static func stringResponseSerializer( + var encoding encoding: NSStringEncoding? = nil) + -> ResponseSerializer + { + return ResponseSerializer { _, response, data, error in + guard error == nil else { return .Failure(error!) } + + if let response = response where response.statusCode == 204 { return .Success("") } + + guard let validData = data else { + let failureReason = "String could not be serialized. Input data was nil." + let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason) + return .Failure(error) + } + + if let encodingName = response?.textEncodingName where encoding == nil { + encoding = CFStringConvertEncodingToNSStringEncoding( + CFStringConvertIANACharSetNameToEncoding(encodingName) + ) + } + + let actualEncoding = encoding ?? NSISOLatin1StringEncoding + + if let string = String(data: validData, encoding: actualEncoding) { + return .Success(string) + } else { + let failureReason = "String could not be serialized with encoding: \(actualEncoding)" + let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason) + return .Failure(error) + } + } + } + + /** + Adds a handler to be called once the request has finished. + + - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the + server response, falling back to the default HTTP default character set, + ISO-8859-1. + - parameter completionHandler: A closure to be executed once the request has finished. + + - returns: The request. + */ + public func responseString( + encoding encoding: NSStringEncoding? = nil, + completionHandler: Response -> Void) + -> Self + { + return response( + responseSerializer: Request.stringResponseSerializer(encoding: encoding), + completionHandler: completionHandler + ) + } +} + +// MARK: - JSON + +extension Request { + + /** + Creates a response serializer that returns a JSON object constructed from the response data using + `NSJSONSerialization` with the specified reading options. + + - parameter options: The JSON serialization reading options. `.AllowFragments` by default. + + - returns: A JSON object response serializer. + */ + public static func JSONResponseSerializer( + options options: NSJSONReadingOptions = .AllowFragments) + -> ResponseSerializer + { + return ResponseSerializer { _, response, data, error in + guard error == nil else { return .Failure(error!) } + + if let response = response where response.statusCode == 204 { return .Success(NSNull()) } + + guard let validData = data where validData.length > 0 else { + let failureReason = "JSON could not be serialized. Input data was nil or zero length." + let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason) + return .Failure(error) + } + + do { + let JSON = try NSJSONSerialization.JSONObjectWithData(validData, options: options) + return .Success(JSON) + } catch { + return .Failure(error as NSError) + } + } + } + + /** + Adds a handler to be called once the request has finished. + + - parameter options: The JSON serialization reading options. `.AllowFragments` by default. + - parameter completionHandler: A closure to be executed once the request has finished. + + - returns: The request. + */ + public func responseJSON( + options options: NSJSONReadingOptions = .AllowFragments, + completionHandler: Response -> Void) + -> Self + { + return response( + responseSerializer: Request.JSONResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +// MARK: - Property List + +extension Request { + + /** + Creates a response serializer that returns an object constructed from the response data using + `NSPropertyListSerialization` with the specified reading options. + + - parameter options: The property list reading options. `NSPropertyListReadOptions()` by default. + + - returns: A property list object response serializer. + */ + public static func propertyListResponseSerializer( + options options: NSPropertyListReadOptions = NSPropertyListReadOptions()) + -> ResponseSerializer + { + return ResponseSerializer { _, response, data, error in + guard error == nil else { return .Failure(error!) } + + if let response = response where response.statusCode == 204 { return .Success(NSNull()) } + + guard let validData = data where validData.length > 0 else { + let failureReason = "Property list could not be serialized. Input data was nil or zero length." + let error = Error.errorWithCode(.PropertyListSerializationFailed, failureReason: failureReason) + return .Failure(error) + } + + do { + let plist = try NSPropertyListSerialization.propertyListWithData(validData, options: options, format: nil) + return .Success(plist) + } catch { + return .Failure(error as NSError) + } + } + } + + /** + Adds a handler to be called once the request has finished. + + - parameter options: The property list reading options. `0` by default. + - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3 + arguments: the URL request, the URL response, the server data and the result + produced while creating the property list. + + - returns: The request. + */ + public func responsePropertyList( + options options: NSPropertyListReadOptions = NSPropertyListReadOptions(), + completionHandler: Response -> Void) + -> Self + { + return response( + responseSerializer: Request.propertyListResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Result.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Result.swift new file mode 100644 index 00000000000..614a3529ac6 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Result.swift @@ -0,0 +1,101 @@ +// Result.swift +// +// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/** + Used to represent whether a request was successful or encountered an error. + + - Success: The request and all post processing operations were successful resulting in the serialization of the + provided associated value. + - Failure: The request encountered an error resulting in a failure. The associated values are the original data + provided by the server as well as the error that caused the failure. +*/ +public enum Result { + case Success(Value) + case Failure(Error) + + /// Returns `true` if the result is a success, `false` otherwise. + public var isSuccess: Bool { + switch self { + case .Success: + return true + case .Failure: + return false + } + } + + /// Returns `true` if the result is a failure, `false` otherwise. + public var isFailure: Bool { + return !isSuccess + } + + /// Returns the associated value if the result is a success, `nil` otherwise. + public var value: Value? { + switch self { + case .Success(let value): + return value + case .Failure: + return nil + } + } + + /// Returns the associated error value if the result is a failure, `nil` otherwise. + public var error: Error? { + switch self { + case .Success: + return nil + case .Failure(let error): + return error + } + } +} + +// MARK: - CustomStringConvertible + +extension Result: CustomStringConvertible { + /// The textual representation used when written to an output stream, which includes whether the result was a + /// success or failure. + public var description: String { + switch self { + case .Success: + return "SUCCESS" + case .Failure: + return "FAILURE" + } + } +} + +// MARK: - CustomDebugStringConvertible + +extension Result: CustomDebugStringConvertible { + /// The debug textual representation used when written to an output stream, which includes whether the result was a + /// success or failure in addition to the value or error. + public var debugDescription: String { + switch self { + case .Success(let value): + return "SUCCESS: \(value)" + case .Failure(let error): + return "FAILURE: \(error)" + } + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift new file mode 100644 index 00000000000..6887d778d23 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift @@ -0,0 +1,302 @@ +// ServerTrustPolicy.swift +// +// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/// Responsible for managing the mapping of `ServerTrustPolicy` objects to a given host. +public class ServerTrustPolicyManager { + /// The dictionary of policies mapped to a particular host. + public let policies: [String: ServerTrustPolicy] + + /** + Initializes the `ServerTrustPolicyManager` instance with the given policies. + + Since different servers and web services can have different leaf certificates, intermediate and even root + certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This + allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key + pinning for host3 and disabling evaluation for host4. + + - parameter policies: A dictionary of all policies mapped to a particular host. + + - returns: The new `ServerTrustPolicyManager` instance. + */ + public init(policies: [String: ServerTrustPolicy]) { + self.policies = policies + } + + /** + Returns the `ServerTrustPolicy` for the given host if applicable. + + By default, this method will return the policy that perfectly matches the given host. Subclasses could override + this method and implement more complex mapping implementations such as wildcards. + + - parameter host: The host to use when searching for a matching policy. + + - returns: The server trust policy for the given host if found. + */ + public func serverTrustPolicyForHost(host: String) -> ServerTrustPolicy? { + return policies[host] + } +} + +// MARK: - + +extension NSURLSession { + private struct AssociatedKeys { + static var ManagerKey = "NSURLSession.ServerTrustPolicyManager" + } + + var serverTrustPolicyManager: ServerTrustPolicyManager? { + get { + return objc_getAssociatedObject(self, &AssociatedKeys.ManagerKey) as? ServerTrustPolicyManager + } + set (manager) { + objc_setAssociatedObject(self, &AssociatedKeys.ManagerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } +} + +// MARK: - ServerTrustPolicy + +/** + The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when + connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust + with a given set of criteria to determine whether the server trust is valid and the connection should be made. + + Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other + vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged + to route all communication over an HTTPS connection with pinning enabled. + + - PerformDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to + validate the host provided by the challenge. Applications are encouraged to always + validate the host in production environments to guarantee the validity of the server's + certificate chain. + + - PinCertificates: Uses the pinned certificates to validate the server trust. The server trust is + considered valid if one of the pinned certificates match one of the server certificates. + By validating both the certificate chain and host, certificate pinning provides a very + secure form of server trust validation mitigating most, if not all, MITM attacks. + Applications are encouraged to always validate the host and require a valid certificate + chain in production environments. + + - PinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered + valid if one of the pinned public keys match one of the server certificate public keys. + By validating both the certificate chain and host, public key pinning provides a very + secure form of server trust validation mitigating most, if not all, MITM attacks. + Applications are encouraged to always validate the host and require a valid certificate + chain in production environments. + + - DisableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid. + + - CustomEvaluation: Uses the associated closure to evaluate the validity of the server trust. +*/ +public enum ServerTrustPolicy { + case PerformDefaultEvaluation(validateHost: Bool) + case PinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool) + case PinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool) + case DisableEvaluation + case CustomEvaluation((serverTrust: SecTrust, host: String) -> Bool) + + // MARK: - Bundle Location + + /** + Returns all certificates within the given bundle with a `.cer` file extension. + + - parameter bundle: The bundle to search for all `.cer` files. + + - returns: All certificates within the given bundle. + */ + public static func certificatesInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecCertificate] { + var certificates: [SecCertificate] = [] + + let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in + bundle.pathsForResourcesOfType(fileExtension, inDirectory: nil) + }.flatten()) + + for path in paths { + if let + certificateData = NSData(contentsOfFile: path), + certificate = SecCertificateCreateWithData(nil, certificateData) + { + certificates.append(certificate) + } + } + + return certificates + } + + /** + Returns all public keys within the given bundle with a `.cer` file extension. + + - parameter bundle: The bundle to search for all `*.cer` files. + + - returns: All public keys within the given bundle. + */ + public static func publicKeysInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecKey] { + var publicKeys: [SecKey] = [] + + for certificate in certificatesInBundle(bundle) { + if let publicKey = publicKeyForCertificate(certificate) { + publicKeys.append(publicKey) + } + } + + return publicKeys + } + + // MARK: - Evaluation + + /** + Evaluates whether the server trust is valid for the given host. + + - parameter serverTrust: The server trust to evaluate. + - parameter host: The host of the challenge protection space. + + - returns: Whether the server trust is valid. + */ + public func evaluateServerTrust(serverTrust: SecTrust, isValidForHost host: String) -> Bool { + var serverTrustIsValid = false + + switch self { + case let .PerformDefaultEvaluation(validateHost): + let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) + SecTrustSetPolicies(serverTrust, [policy]) + + serverTrustIsValid = trustIsValid(serverTrust) + case let .PinCertificates(pinnedCertificates, validateCertificateChain, validateHost): + if validateCertificateChain { + let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) + SecTrustSetPolicies(serverTrust, [policy]) + + SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates) + SecTrustSetAnchorCertificatesOnly(serverTrust, true) + + serverTrustIsValid = trustIsValid(serverTrust) + } else { + let serverCertificatesDataArray = certificateDataForTrust(serverTrust) + let pinnedCertificatesDataArray = certificateDataForCertificates(pinnedCertificates) + + outerLoop: for serverCertificateData in serverCertificatesDataArray { + for pinnedCertificateData in pinnedCertificatesDataArray { + if serverCertificateData.isEqualToData(pinnedCertificateData) { + serverTrustIsValid = true + break outerLoop + } + } + } + } + case let .PinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost): + var certificateChainEvaluationPassed = true + + if validateCertificateChain { + let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) + SecTrustSetPolicies(serverTrust, [policy]) + + certificateChainEvaluationPassed = trustIsValid(serverTrust) + } + + if certificateChainEvaluationPassed { + outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeysForTrust(serverTrust) as [AnyObject] { + for pinnedPublicKey in pinnedPublicKeys as [AnyObject] { + if serverPublicKey.isEqual(pinnedPublicKey) { + serverTrustIsValid = true + break outerLoop + } + } + } + } + case .DisableEvaluation: + serverTrustIsValid = true + case let .CustomEvaluation(closure): + serverTrustIsValid = closure(serverTrust: serverTrust, host: host) + } + + return serverTrustIsValid + } + + // MARK: - Private - Trust Validation + + private func trustIsValid(trust: SecTrust) -> Bool { + var isValid = false + + var result = SecTrustResultType(kSecTrustResultInvalid) + let status = SecTrustEvaluate(trust, &result) + + if status == errSecSuccess { + let unspecified = SecTrustResultType(kSecTrustResultUnspecified) + let proceed = SecTrustResultType(kSecTrustResultProceed) + + isValid = result == unspecified || result == proceed + } + + return isValid + } + + // MARK: - Private - Certificate Data + + private func certificateDataForTrust(trust: SecTrust) -> [NSData] { + var certificates: [SecCertificate] = [] + + for index in 0.. [NSData] { + return certificates.map { SecCertificateCopyData($0) as NSData } + } + + // MARK: - Private - Public Key Extraction + + private static func publicKeysForTrust(trust: SecTrust) -> [SecKey] { + var publicKeys: [SecKey] = [] + + for index in 0.. SecKey? { + var publicKey: SecKey? + + let policy = SecPolicyCreateBasicX509() + var trust: SecTrust? + let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust) + + if let trust = trust where trustCreationStatus == errSecSuccess { + publicKey = SecTrustCopyPublicKey(trust) + } + + return publicKey + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift new file mode 100644 index 00000000000..bc9ee450c5a --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Stream.swift @@ -0,0 +1,180 @@ +// Stream.swift +// +// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +#if !os(watchOS) + +@available(iOS 9.0, OSX 10.11, *) +extension Manager { + private enum Streamable { + case Stream(String, Int) + case NetService(NSNetService) + } + + private func stream(streamable: Streamable) -> Request { + var streamTask: NSURLSessionStreamTask! + + switch streamable { + case .Stream(let hostName, let port): + dispatch_sync(queue) { + streamTask = self.session.streamTaskWithHostName(hostName, port: port) + } + case .NetService(let netService): + dispatch_sync(queue) { + streamTask = self.session.streamTaskWithNetService(netService) + } + } + + let request = Request(session: session, task: streamTask) + + delegate[request.delegate.task] = request.delegate + + if startRequestsImmediately { + request.resume() + } + + return request + } + + /** + Creates a request for bidirectional streaming with the given hostname and port. + + - parameter hostName: The hostname of the server to connect to. + - parameter port: The port of the server to connect to. + + :returns: The created stream request. + */ + public func stream(hostName hostName: String, port: Int) -> Request { + return stream(.Stream(hostName, port)) + } + + /** + Creates a request for bidirectional streaming with the given `NSNetService`. + + - parameter netService: The net service used to identify the endpoint. + + - returns: The created stream request. + */ + public func stream(netService netService: NSNetService) -> Request { + return stream(.NetService(netService)) + } +} + +// MARK: - + +@available(iOS 9.0, OSX 10.11, *) +extension Manager.SessionDelegate: NSURLSessionStreamDelegate { + + // MARK: Override Closures + + /// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:readClosedForStreamTask:`. + public var streamTaskReadClosed: ((NSURLSession, NSURLSessionStreamTask) -> Void)? { + get { + return _streamTaskReadClosed as? (NSURLSession, NSURLSessionStreamTask) -> Void + } + set { + _streamTaskReadClosed = newValue + } + } + + /// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:writeClosedForStreamTask:`. + public var streamTaskWriteClosed: ((NSURLSession, NSURLSessionStreamTask) -> Void)? { + get { + return _streamTaskWriteClosed as? (NSURLSession, NSURLSessionStreamTask) -> Void + } + set { + _streamTaskWriteClosed = newValue + } + } + + /// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:betterRouteDiscoveredForStreamTask:`. + public var streamTaskBetterRouteDiscovered: ((NSURLSession, NSURLSessionStreamTask) -> Void)? { + get { + return _streamTaskBetterRouteDiscovered as? (NSURLSession, NSURLSessionStreamTask) -> Void + } + set { + _streamTaskBetterRouteDiscovered = newValue + } + } + + /// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:streamTask:didBecomeInputStream:outputStream:`. + public var streamTaskDidBecomeInputStream: ((NSURLSession, NSURLSessionStreamTask, NSInputStream, NSOutputStream) -> Void)? { + get { + return _streamTaskDidBecomeInputStream as? (NSURLSession, NSURLSessionStreamTask, NSInputStream, NSOutputStream) -> Void + } + set { + _streamTaskDidBecomeInputStream = newValue + } + } + + // MARK: Delegate Methods + + /** + Tells the delegate that the read side of the connection has been closed. + + - parameter session: The session. + - parameter streamTask: The stream task. + */ + public func URLSession(session: NSURLSession, readClosedForStreamTask streamTask: NSURLSessionStreamTask) { + streamTaskReadClosed?(session, streamTask) + } + + /** + Tells the delegate that the write side of the connection has been closed. + + - parameter session: The session. + - parameter streamTask: The stream task. + */ + public func URLSession(session: NSURLSession, writeClosedForStreamTask streamTask: NSURLSessionStreamTask) { + streamTaskWriteClosed?(session, streamTask) + } + + /** + Tells the delegate that the system has determined that a better route to the host is available. + + - parameter session: The session. + - parameter streamTask: The stream task. + */ + public func URLSession(session: NSURLSession, betterRouteDiscoveredForStreamTask streamTask: NSURLSessionStreamTask) { + streamTaskBetterRouteDiscovered?(session, streamTask) + } + + /** + Tells the delegate that the stream task has been completed and provides the unopened stream objects. + + - parameter session: The session. + - parameter streamTask: The stream task. + - parameter inputStream: The new input stream. + - parameter outputStream: The new output stream. + */ + public func URLSession( + session: NSURLSession, + streamTask: NSURLSessionStreamTask, + didBecomeInputStream inputStream: NSInputStream, + outputStream: NSOutputStream) + { + streamTaskDidBecomeInputStream?(session, streamTask, inputStream, outputStream) + } +} + +#endif diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift new file mode 100644 index 00000000000..640b05c8775 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Upload.swift @@ -0,0 +1,372 @@ +// Upload.swift +// +// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +extension Manager { + private enum Uploadable { + case Data(NSURLRequest, NSData) + case File(NSURLRequest, NSURL) + case Stream(NSURLRequest, NSInputStream) + } + + private func upload(uploadable: Uploadable) -> Request { + var uploadTask: NSURLSessionUploadTask! + var HTTPBodyStream: NSInputStream? + + switch uploadable { + case .Data(let request, let data): + dispatch_sync(queue) { + uploadTask = self.session.uploadTaskWithRequest(request, fromData: data) + } + case .File(let request, let fileURL): + dispatch_sync(queue) { + uploadTask = self.session.uploadTaskWithRequest(request, fromFile: fileURL) + } + case .Stream(let request, let stream): + dispatch_sync(queue) { + uploadTask = self.session.uploadTaskWithStreamedRequest(request) + } + + HTTPBodyStream = stream + } + + let request = Request(session: session, task: uploadTask) + + if HTTPBodyStream != nil { + request.delegate.taskNeedNewBodyStream = { _, _ in + return HTTPBodyStream + } + } + + delegate[request.delegate.task] = request.delegate + + if startRequestsImmediately { + request.resume() + } + + return request + } + + // MARK: File + + /** + Creates a request for uploading a file to the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter URLRequest: The URL request + - parameter file: The file to upload + + - returns: The created upload request. + */ + public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request { + return upload(.File(URLRequest.URLRequest, file)) + } + + /** + Creates a request for uploading a file to the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter headers: The HTTP headers. `nil` by default. + - parameter file: The file to upload + + - returns: The created upload request. + */ + public func upload( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil, + file: NSURL) + -> Request + { + let mutableURLRequest = URLRequest(method, URLString, headers: headers) + return upload(mutableURLRequest, file: file) + } + + // MARK: Data + + /** + Creates a request for uploading data to the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter URLRequest: The URL request. + - parameter data: The data to upload. + + - returns: The created upload request. + */ + public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request { + return upload(.Data(URLRequest.URLRequest, data)) + } + + /** + Creates a request for uploading data to the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter headers: The HTTP headers. `nil` by default. + - parameter data: The data to upload + + - returns: The created upload request. + */ + public func upload( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil, + data: NSData) + -> Request + { + let mutableURLRequest = URLRequest(method, URLString, headers: headers) + + return upload(mutableURLRequest, data: data) + } + + // MARK: Stream + + /** + Creates a request for uploading a stream to the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter URLRequest: The URL request. + - parameter stream: The stream to upload. + + - returns: The created upload request. + */ + public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request { + return upload(.Stream(URLRequest.URLRequest, stream)) + } + + /** + Creates a request for uploading a stream to the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter headers: The HTTP headers. `nil` by default. + - parameter stream: The stream to upload. + + - returns: The created upload request. + */ + public func upload( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil, + stream: NSInputStream) + -> Request + { + let mutableURLRequest = URLRequest(method, URLString, headers: headers) + + return upload(mutableURLRequest, stream: stream) + } + + // MARK: MultipartFormData + + /// Default memory threshold used when encoding `MultipartFormData`. + public static let MultipartFormDataEncodingMemoryThreshold: UInt64 = 10 * 1024 * 1024 + + /** + Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as + associated values. + + - Success: Represents a successful `MultipartFormData` encoding and contains the new `Request` along with + streaming information. + - Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding + error. + */ + public enum MultipartFormDataEncodingResult { + case Success(request: Request, streamingFromDisk: Bool, streamFileURL: NSURL?) + case Failure(ErrorType) + } + + /** + Encodes the `MultipartFormData` and creates a request to upload the result to the specified URL request. + + It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative + payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + used for larger payloads such as video content. + + The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, + encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + technique was used. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter headers: The HTTP headers. `nil` by default. + - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. + - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. + `MultipartFormDataEncodingMemoryThreshold` by default. + - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. + */ + public func upload( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil, + multipartFormData: MultipartFormData -> Void, + encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, + encodingCompletion: (MultipartFormDataEncodingResult -> Void)?) + { + let mutableURLRequest = URLRequest(method, URLString, headers: headers) + + return upload( + mutableURLRequest, + multipartFormData: multipartFormData, + encodingMemoryThreshold: encodingMemoryThreshold, + encodingCompletion: encodingCompletion + ) + } + + /** + Encodes the `MultipartFormData` and creates a request to upload the result to the specified URL request. + + It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative + payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + used for larger payloads such as video content. + + The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, + encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + technique was used. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter URLRequest: The URL request. + - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. + - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. + `MultipartFormDataEncodingMemoryThreshold` by default. + - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. + */ + public func upload( + URLRequest: URLRequestConvertible, + multipartFormData: MultipartFormData -> Void, + encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, + encodingCompletion: (MultipartFormDataEncodingResult -> Void)?) + { + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { + let formData = MultipartFormData() + multipartFormData(formData) + + let URLRequestWithContentType = URLRequest.URLRequest + URLRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type") + + let isBackgroundSession = self.session.configuration.identifier != nil + + if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession { + do { + let data = try formData.encode() + let encodingResult = MultipartFormDataEncodingResult.Success( + request: self.upload(URLRequestWithContentType, data: data), + streamingFromDisk: false, + streamFileURL: nil + ) + + dispatch_async(dispatch_get_main_queue()) { + encodingCompletion?(encodingResult) + } + } catch { + dispatch_async(dispatch_get_main_queue()) { + encodingCompletion?(.Failure(error as NSError)) + } + } + } else { + let fileManager = NSFileManager.defaultManager() + let tempDirectoryURL = NSURL(fileURLWithPath: NSTemporaryDirectory()) + let directoryURL = tempDirectoryURL.URLByAppendingPathComponent("com.alamofire.manager/multipart.form.data") + let fileName = NSUUID().UUIDString + let fileURL = directoryURL.URLByAppendingPathComponent(fileName) + + do { + try fileManager.createDirectoryAtURL(directoryURL, withIntermediateDirectories: true, attributes: nil) + try formData.writeEncodedDataToDisk(fileURL) + + dispatch_async(dispatch_get_main_queue()) { + let encodingResult = MultipartFormDataEncodingResult.Success( + request: self.upload(URLRequestWithContentType, file: fileURL), + streamingFromDisk: true, + streamFileURL: fileURL + ) + encodingCompletion?(encodingResult) + } + } catch { + dispatch_async(dispatch_get_main_queue()) { + encodingCompletion?(.Failure(error as NSError)) + } + } + } + } + } +} + +// MARK: - + +extension Request { + + // MARK: - UploadTaskDelegate + + class UploadTaskDelegate: DataTaskDelegate { + var uploadTask: NSURLSessionUploadTask? { return task as? NSURLSessionUploadTask } + var uploadProgress: ((Int64, Int64, Int64) -> Void)! + + // MARK: - NSURLSessionTaskDelegate + + // MARK: Override Closures + + var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)? + + // MARK: Delegate Methods + + func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) + { + if let taskDidSendBodyData = taskDidSendBodyData { + taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) + } else { + progress.totalUnitCount = totalBytesExpectedToSend + progress.completedUnitCount = totalBytesSent + + uploadProgress?(bytesSent, totalBytesSent, totalBytesExpectedToSend) + } + } + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift new file mode 100644 index 00000000000..88234551965 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift @@ -0,0 +1,189 @@ +// Validation.swift +// +// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +extension Request { + + /** + Used to represent whether validation was successful or encountered an error resulting in a failure. + + - Success: The validation was successful. + - Failure: The validation failed encountering the provided error. + */ + public enum ValidationResult { + case Success + case Failure(NSError) + } + + /** + A closure used to validate a request that takes a URL request and URL response, and returns whether the + request was valid. + */ + public typealias Validation = (NSURLRequest?, NSHTTPURLResponse) -> ValidationResult + + /** + Validates the request, using the specified closure. + + If validation fails, subsequent calls to response handlers will have an associated error. + + - parameter validation: A closure to validate the request. + + - returns: The request. + */ + public func validate(validation: Validation) -> Self { + delegate.queue.addOperationWithBlock { + if let + response = self.response where self.delegate.error == nil, + case let .Failure(error) = validation(self.request, response) + { + self.delegate.error = error + } + } + + return self + } + + // MARK: - Status Code + + /** + Validates that the response has a status code in the specified range. + + If validation fails, subsequent calls to response handlers will have an associated error. + + - parameter range: The range of acceptable status codes. + + - returns: The request. + */ + public func validate(statusCode acceptableStatusCode: S) -> Self { + return validate { _, response in + if acceptableStatusCode.contains(response.statusCode) { + return .Success + } else { + let failureReason = "Response status code was unacceptable: \(response.statusCode)" + return .Failure(Error.errorWithCode(.StatusCodeValidationFailed, failureReason: failureReason)) + } + } + } + + // MARK: - Content-Type + + private struct MIMEType { + let type: String + let subtype: String + + init?(_ string: String) { + let components: [String] = { + let stripped = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) + let split = stripped.substringToIndex(stripped.rangeOfString(";")?.startIndex ?? stripped.endIndex) + return split.componentsSeparatedByString("/") + }() + + if let + type = components.first, + subtype = components.last + { + self.type = type + self.subtype = subtype + } else { + return nil + } + } + + func matches(MIME: MIMEType) -> Bool { + switch (type, subtype) { + case (MIME.type, MIME.subtype), (MIME.type, "*"), ("*", MIME.subtype), ("*", "*"): + return true + default: + return false + } + } + } + + /** + Validates that the response has a content type in the specified array. + + If validation fails, subsequent calls to response handlers will have an associated error. + + - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. + + - returns: The request. + */ + public func validate(contentType acceptableContentTypes: S) -> Self { + return validate { _, response in + guard let validData = self.delegate.data where validData.length > 0 else { return .Success } + + if let + responseContentType = response.MIMEType, + responseMIMEType = MIMEType(responseContentType) + { + for contentType in acceptableContentTypes { + if let acceptableMIMEType = MIMEType(contentType) where acceptableMIMEType.matches(responseMIMEType) { + return .Success + } + } + } else { + for contentType in acceptableContentTypes { + if let MIMEType = MIMEType(contentType) where MIMEType.type == "*" && MIMEType.subtype == "*" { + return .Success + } + } + } + + let failureReason: String + + if let responseContentType = response.MIMEType { + failureReason = ( + "Response content type \"\(responseContentType)\" does not match any acceptable " + + "content types: \(acceptableContentTypes)" + ) + } else { + failureReason = "Response content type was missing and acceptable content type does not match \"*/*\"" + } + + return .Failure(Error.errorWithCode(.ContentTypeValidationFailed, failureReason: failureReason)) + } + } + + // MARK: - Automatic + + /** + Validates that the response has a status code in the default acceptable range of 200...299, and that the content + type matches any specified in the Accept HTTP header field. + + If validation fails, subsequent calls to response handlers will have an associated error. + + - returns: The request. + */ + public func validate() -> Self { + let acceptableStatusCodes: Range = 200..<300 + let acceptableContentTypes: [String] = { + if let accept = request?.valueForHTTPHeaderField("Accept") { + return accept.componentsSeparatedByString(",") + } + + return ["*/*"] + }() + + return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes) + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json new file mode 100644 index 00000000000..ca12bdffe3b --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Local Podspecs/PetstoreClient.podspec.json @@ -0,0 +1,25 @@ +{ + "name": "PetstoreClient", + "platforms": { + "ios": "8.0", + "osx": "10.9" + }, + "version": "0.0.1", + "source": { + "git": "git@github.com:swagger-api/swagger-mustache.git", + "tag": "v1.0.0" + }, + "authors": "", + "license": "Apache License, Version 2.0", + "homepage": "https://github.com/swagger-api/swagger-codegen", + "summary": "PetstoreClient", + "source_files": "PetstoreClient/Classes/Swaggers/**/*.swift", + "dependencies": { + "RxSwift": [ + "~> 2.0" + ], + "Alamofire": [ + "~> 3.1.5" + ] + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Manifest.lock b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Manifest.lock new file mode 100644 index 00000000000..9ea49e930da --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Manifest.lock @@ -0,0 +1,22 @@ +PODS: + - Alamofire (3.1.5) + - PetstoreClient (0.0.1): + - Alamofire (~> 3.1.5) + - RxSwift (~> 2.0) + - RxSwift (2.6.0) + +DEPENDENCIES: + - PetstoreClient (from `../`) + +EXTERNAL SOURCES: + PetstoreClient: + :path: "../" + +SPEC CHECKSUMS: + Alamofire: 5f730ba29fd113b7ddd71c1e65d0c630acf5d7b0 + PetstoreClient: 0baad893079f270b6bcf2e868ba68d8b9ce36812 + RxSwift: 77f3a0b15324baa7a1c9bfa9f199648a82424e26 + +PODFILE CHECKSUM: cedb3058b02f4776d7c31f6d92ae2f674fdf424d + +COCOAPODS: 1.0.1 diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj new file mode 100644 index 00000000000..a56a15dfc60 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj @@ -0,0 +1,1731 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 00A528BBED5B1D5DF26B8ADE64C5B3F2 /* CompositeDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9B3FF9A09AF9E0D7751789D55FDDDCA2 /* CompositeDisposable.swift */; }; + 00D1D0E4C3E6F9EA952C2EDEF2C13DE9 /* NopDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6156CD5049D33CC68DF29760B398B408 /* NopDisposable.swift */; }; + 0268E70939A7BFBC91C0557D16DDD027 /* ScheduledDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17881314399342A30A86EF8655AFD35C /* ScheduledDisposable.swift */; }; + 028C4C90CAA75222DAA6CA7B37F16A84 /* ConcurrentDispatchQueueScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A95956A18890D406F52B50CE636C417 /* ConcurrentDispatchQueueScheduler.swift */; }; + 030667BEF4154402A2317126A893E459 /* ConnectableObservable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 76485D1ACD1F13E0E68638CA3D9E175C /* ConnectableObservable.swift */; }; + 03F494989CC1A8857B68A317D5D6860F /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EB61DA897ED3DE273EC2B5824A42DF0 /* Response.swift */; }; + 04509FBE687E186C45C9E2F78E6F6946 /* CombineLatest+CollectionType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5CF9673331C58F7D9396CDEC9CE940A9 /* CombineLatest+CollectionType.swift */; }; + 0487B12B08D927162A20CB2A56A2D077 /* Just.swift in Sources */ = {isa = PBXBuildFile; fileRef = 72AAAA3FE5DDA94BC0636A15F9F4F7EF /* Just.swift */; }; + 04923B3851BD1F857A9B207EE9EC8CDB /* SubjectType.swift in Sources */ = {isa = PBXBuildFile; fileRef = E64D15D1795EA999578C393A507A882F /* SubjectType.swift */; }; + 0607BCCDD781FF7FFD3629BF4A8BAD23 /* Sample.swift in Sources */ = {isa = PBXBuildFile; fileRef = DBC29FB0F89F4B2B863A122A41D07007 /* Sample.swift */; }; + 0681ADC8BAE2C3185F13487BAAB4D9DD /* Upload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E78A6B0E3334E11FE5615FE4CC506E8 /* Upload.swift */; }; + 07E83400AACF1430C5B3DF482167A0F1 /* Reduce.swift in Sources */ = {isa = PBXBuildFile; fileRef = D5438FA602118A769102A572D66E5EDD /* Reduce.swift */; }; + 08D2C4B252A264F837733A22CBFB2481 /* APIs.swift in Sources */ = {isa = PBXBuildFile; fileRef = D8072E1108951F272C003553FC8926C7 /* APIs.swift */; }; + 0A5F6F590DCE147853B2E21487ABA4AA /* RetryWhen.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7678CC14BE55592C2250C4C122EADEF3 /* RetryWhen.swift */; }; + 0A9698AC9DD60FC3721809C6AB9BCE81 /* User.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B248364ABF60ACD7DB31A17DCFDFD0C /* User.swift */; }; + 0AEB6185484DD9137068A40CE70D4B85 /* SchedulerServices+Emulation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 10D1C22E4BBFB16E5C966FF77E92F296 /* SchedulerServices+Emulation.swift */; }; + 0BD8B4E55E72312366130E97A1204CD8 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9610BA4403551C05999CF892D495F516 /* Foundation.framework */; }; + 0D6AD3708152BB59E38D5839A0B0377F /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A3658B178A16F05FFD28C46A18EF8E8 /* Map.swift */; }; + 107E73472222CFD28A8C640F332DA52A /* Scan.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD709EBAF5345AC238B7849DE5BCB273 /* Scan.swift */; }; + 110E6B43666A729745E9980F080944C4 /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AA9C5856BEAE5090A7D1EB450A10C04F /* Alamofire.framework */; }; + 12999CCB3E22F57CB230F85534EF6930 /* SingleAssignmentDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = DE3076AFBC266A6E88C8171467D6C5A5 /* SingleAssignmentDisposable.swift */; }; + 14DD51004DF8C27A7D0491AEFEC5F464 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9610BA4403551C05999CF892D495F516 /* Foundation.framework */; }; + 159C262BD23A08981D11D3B94340848B /* SynchronizedSubscribeType.swift in Sources */ = {isa = PBXBuildFile; fileRef = A4D4B50A66CA7EB372C9BCE21D117CEC /* SynchronizedSubscribeType.swift */; }; + 165531B0C3FF4D343825C3DB0B79FD68 /* Observable+Time.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFB1B59D84F8B11F82B8DF1A2150846 /* Observable+Time.swift */; }; + 1A11209BABC1DE84187BFAEA3E91602D /* RxMutableBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1F0C939A9E2A83A661C6EA3D4EE8DC54 /* RxMutableBox.swift */; }; + 1CBCB4FF2C9CDB144871C2A0856EB44D /* ConnectableObservableType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 39E5209D93CDC3C851C2F4454601FF04 /* ConnectableObservableType.swift */; }; + 2023E24B94C04CC05DDFB499ECA760FB /* Never.swift in Sources */ = {isa = PBXBuildFile; fileRef = FCF668BEB868B23FA177F79EA8B5D5CF /* Never.swift */; }; + 207AB9AAE48F202AF774554ED7545D98 /* InvocableScheduledItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 06C46F9E4863BA39300A28EEBB2FED44 /* InvocableScheduledItem.swift */; }; + 22C91CF507223CEE1A7E1302E912DC8B /* AddRef.swift in Sources */ = {isa = PBXBuildFile; fileRef = 47C4BE1760C078A0188C4A66807F2C29 /* AddRef.swift */; }; + 22C9E40BB4DFB30DAAFD8555EF69BC08 /* HistoricalScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 52611EC9CCB565A24C2C007F5A2CB6C3 /* HistoricalScheduler.swift */; }; + 23CA1BD96C4742DE71082211C8DBFF5F /* SchedulerType.swift in Sources */ = {isa = PBXBuildFile; fileRef = EC88FCE0410EAE3C16E64A8A8108D142 /* SchedulerType.swift */; }; + 252E1D07E589566E0B8F49C2B9131976 /* WithLatestFrom.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7E2F61612759130FD3873E3FBE0E2CC0 /* WithLatestFrom.swift */; }; + 26E95A382D3F6848E571EF506D91B1C1 /* InvocableType.swift in Sources */ = {isa = PBXBuildFile; fileRef = E97A3908B642D476F00987B50894F4C9 /* InvocableType.swift */; }; + 2BEA24EE395DA16EFEBC08B8D450F00A /* ObservableType.swift in Sources */ = {isa = PBXBuildFile; fileRef = A371B67E1A1BC9D198E470D4B54FEE87 /* ObservableType.swift */; }; + 2C5450AC69398958CF6F7539EF7D99E5 /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 3341D7B714515136B34354D7D32202DB /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 2DF21CC164C25ED6947C67198879DE12 /* Variable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 101E84FB1E5F4A753DAF7518FB9BF0A7 /* Variable.swift */; }; + 313FCC5057970674AB6016DEF7A05902 /* SynchronizedUnsubscribeType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 292B4E8722DE17F6767ABED8D62A4C9E /* SynchronizedUnsubscribeType.swift */; }; + 3200EF8FA76EE92E0108DF928FB39CCB /* Switch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 636788473300310D67C31CCE1A571AC4 /* Switch.swift */; }; + 33393FE8FB3933A22617E02FA3FFA780 /* Skip.swift in Sources */ = {isa = PBXBuildFile; fileRef = 99A31BA1E446FA35628A7DED964EF04F /* Skip.swift */; }; + 393372CC0F931D0D192179C4B16DF65E /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9610BA4403551C05999CF892D495F516 /* Foundation.framework */; }; + 39F4B474510DFC1711DD2EF809EA101B /* Catch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2FE2208C0198E8412BDD034563E2B1A7 /* Catch.swift */; }; + 3AAB4B14DB0A02456F909B482400C142 /* DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0567A0BF989778CA9FF9575D62613B8E /* DistinctUntilChanged.swift */; }; + 3ADB6687421BF63BCC8A8C8D62E0C4F2 /* RefCount.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5ADB3F22CC2D987B4C7E76A7B502DE81 /* RefCount.swift */; }; + 3DAFF4DA4C977B85B5C5B35728001AF2 /* Concat.swift in Sources */ = {isa = PBXBuildFile; fileRef = E8B5CE5592D5B0BD393B7D599B053BFA /* Concat.swift */; }; + 3EE9F1D7EB9C05CB5821E18136EF812E /* SingleAsync.swift in Sources */ = {isa = PBXBuildFile; fileRef = BA1AAD8792DE618CDBBF78CA8E642111 /* SingleAsync.swift */; }; + 402BB7DBAC4D93AD381A0075D7BDDDBA /* Zip+CollectionType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6204091F721976FA7C97D74AC93B9637 /* Zip+CollectionType.swift */; }; + 4266AE0D8F9A4FA69F408AAC9118320A /* Merge.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9144FDC8DC22962DE80692307106EF74 /* Merge.swift */; }; + 434C2C5108A8B9EEA916566F7DB0EDF6 /* Deferred.swift in Sources */ = {isa = PBXBuildFile; fileRef = A6E7F9EA5FCA01B648E37743D97B9D57 /* Deferred.swift */; }; + 437C3354F611D5412125ADF24F4FDEE1 /* Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = A98250195E2C07F9A7DB5E4BB333ACE9 /* Rx.swift */; }; + 480B2F9937EF953E12DE12FCB177C32A /* TakeLast.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75D5E40EFDE70F2D69310639B473B817 /* TakeLast.swift */; }; + 498A556404BCE59DD962113CD29165A0 /* Errors.swift in Sources */ = {isa = PBXBuildFile; fileRef = F250B545A022C0627A401DF08D2B7339 /* Errors.swift */; }; + 4A216C127342712EDE589085CBB58962 /* ElementAt.swift in Sources */ = {isa = PBXBuildFile; fileRef = DABFA04B3B312B12F4703582A14EEE51 /* ElementAt.swift */; }; + 4AE52A909A95E3E4A6DC2F48BD8FC758 /* SerialDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7FA9B23245D415690FB894178BBF20F /* SerialDisposable.swift */; }; + 4B059D5D108F9D2A4E51A6D1B477A2F5 /* Tag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 211F73A46D90346F7FC6D0D29640EE4F /* Tag.swift */; }; + 4C5244B7F2D69F1DFC083E31070E3B0F /* Sink.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37E5E51602A7EC243D3CC5A8B0FBC7E3 /* Sink.swift */; }; + 4CA85A5CF8897D7D46BC6D0D76C8189A /* Producer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7AD0626709B8BF22F5F6B42379D4C1EB /* Producer.swift */; }; + 4DB1B23F5FAF7C5E02520AFE08646AF2 /* BinaryDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5124609C66364357A0450CE5890AB140 /* BinaryDisposable.swift */; }; + 4DE5FCC41D100B113B6645EA64410F16 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3107BC52C0E01198FAE330F1ADC0BF3C /* ParameterEncoding.swift */; }; + 4E1394BCD39E2E3470805196E884B68B /* PetstoreClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */; }; + 4EF8849290BCC9D36D8D75969F6753E7 /* ScheduledItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 72DC2CBE50494D6723773E2C3E89C3C1 /* ScheduledItem.swift */; }; + 4F8D754FA3405C5B692B644166A0F02A /* AnonymousObservable.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2CEC38D6994E89F7BD53BCE73AB7F89 /* AnonymousObservable.swift */; }; + 501A111A5AE07BC13E3265DB49EE0A1B /* Observable+Debug.swift in Sources */ = {isa = PBXBuildFile; fileRef = 051BE7827FDD01F32E6822EC2DE1CE1C /* Observable+Debug.swift */; }; + 527C7425A5831BFC30CC9EC216506393 /* TailRecursiveSink.swift in Sources */ = {isa = PBXBuildFile; fileRef = D02FE9C7BBEB944DACB0B057F631B40C /* TailRecursiveSink.swift */; }; + 54325B7F87498350C604C429751BEC97 /* APIHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = D2BAD338E56EF3CAA6E54490FE0C5DF9 /* APIHelper.swift */; }; + 55D355CC26824B52E1A7420802FB5DC5 /* ImmediateSchedulerType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 09BD8ACFD826D9E6CCCAAB5DDB0132BF /* ImmediateSchedulerType.swift */; }; + 569684CF06CEDCEA569BEC7910FC6E5B /* Category.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4DF0604EDC1460935E6E445A47023A4 /* Category.swift */; }; + 58023FA401993154E36E604471265263 /* DisposeBase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 983586C602A5C7D5B4FD91982F3711D0 /* DisposeBase.swift */; }; + 58344FE826FA6ED012A3450ACB0BF93D /* RxSwift.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 19296A8C5E948345E5744A748B1CC720 /* RxSwift.framework */; }; + 5997C0F97BD6687648224D5C6442B862 /* DelaySubscription.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3C0CED57E33C91E281A79EE0195FCAC2 /* DelaySubscription.swift */; }; + 5B721FAF55FEDB8046F23843565833A2 /* Repeat.swift in Sources */ = {isa = PBXBuildFile; fileRef = B2B14E7D38A4727796ABDFA4079BD210 /* Repeat.swift */; }; + 5BD263D28F10A84969A6521CA166957C /* Empty.swift in Sources */ = {isa = PBXBuildFile; fileRef = BE69C5E6F8BF09D066522463F69EB8A6 /* Empty.swift */; }; + 5BDF0811AEFBD49A7DE4AF35DA3BD34F /* Multicast.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D488959FBBFCF0351F42E7D150C1942 /* Multicast.swift */; }; + 5C8C1A80AB947F293430868D52A910C2 /* HistoricalSchedulerTimeConverter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E9064EE8CEF10A602EFC90A26D1DC39 /* HistoricalSchedulerTimeConverter.swift */; }; + 5CF87E88489D3832C46FAFCE191F78F9 /* TakeWhile.swift in Sources */ = {isa = PBXBuildFile; fileRef = 72F5796E9AA6A65EA2149A206ADE4289 /* TakeWhile.swift */; }; + 6007585CC5912D979404BDB047CD36C4 /* Platform.Darwin.swift in Sources */ = {isa = PBXBuildFile; fileRef = FC3B7613AC16E246F73123670BAED3F5 /* Platform.Darwin.swift */; }; + 618251D2C3027F214154D2CDFE1900AB /* Observable+Creation.swift in Sources */ = {isa = PBXBuildFile; fileRef = EBED49C45F40708D9355E7D2CFFE4602 /* Observable+Creation.swift */; }; + 6414AAC9ED1AD7417B005D50D04341F5 /* ObserveOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 315D8F39A79B562AA2268250BED93150 /* ObserveOn.swift */; }; + 66D9046FEDE40E6732F8B3E090007268 /* RefCountDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 62EC50E209B29C93EAECE01AD46DBAE7 /* RefCountDisposable.swift */; }; + 68614EDB167FFFA6FBEC851368044FB3 /* Observable+Multiple.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9B0F57917A904327F2D141C7E2E8623F /* Observable+Multiple.swift */; }; + 69AC467220269CE474E1C1156912C9DD /* RxSwift-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = BDA5F3724FE84CF94299E36A8DF89017 /* RxSwift-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 717576C9ABD8ABE8163D441ABE1C4A8D /* SynchronizedOnType.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7B5D80C0F71324ED10DBE73D28402DB /* SynchronizedOnType.swift */; }; + 725EED04ED27CA8159CB2683F1EFD45A /* Pods-SwaggerClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 72CF8071AF37B85C1DE763805C39A3AB /* Lock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1974F6C69B156C91AE3DD56FAC5A3808 /* Lock.swift */; }; + 731E6ACE4939DCE8F6AF47FA1A00D595 /* Observable+Single.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8033FB9B41A3E314A0CC6C50015B835D /* Observable+Single.swift */; }; + 751E794A58F9FCB7738D4ED30D10DD19 /* AnyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = FF0E5B19D36827BBE8598B8ACC2EC189 /* AnyObserver.swift */; }; + 7574EBA19BA114D77C76D2CC1B58E73C /* Timeout.swift in Sources */ = {isa = PBXBuildFile; fileRef = EDC79FC8F9A849970B716868E7F51D2C /* Timeout.swift */; }; + 75D86B4420906282E6B3393E98837360 /* Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5412898DEB10F1983487A10453C6B9CB /* Extensions.swift */; }; + 77D1DB57FAA744C6ECBA7242836D6479 /* AnonymousObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 914B1C0C6B1C0BB87F3EB1E7F1060425 /* AnonymousObserver.swift */; }; + 79F6454BBF28D094A211494E22A07327 /* SkipUntil.swift in Sources */ = {isa = PBXBuildFile; fileRef = D69A080DF8671D7B4CEB7E706EF4667F /* SkipUntil.swift */; }; + 7A6597623E723E6F8350D2CA30A2CD9C /* Observable+Aggregate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3C2489BF8D3C006E1A6E9FA8E1275FC1 /* Observable+Aggregate.swift */; }; + 7E11CAC09AC72BD412078441E2F7BC21 /* VirtualTimeConverterType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3B5E5E7372652C9D351B65002A966365 /* VirtualTimeConverterType.swift */; }; + 7E6DD4CEE210B03B7E3A0F01A36A7624 /* Sequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 075BA1FDBF8D0B4B1D383DF8FD3BE509 /* Sequence.swift */; }; + 7F8297BE677C9A67B915F044DB16C0BE /* ShareReplay1WhileConnected.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35A3C82BD63330195DE669D3836B7E41 /* ShareReplay1WhileConnected.swift */; }; + 7F82F4EE1BA91C32CE75312176ACD4F0 /* Take.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CAF565A8B834CB6FD86DDFF010D4E4B /* Take.swift */; }; + 80F496237530D382A045A29654D8C11C /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6C4F5E9ABF91F6B2FF369456D3804258 /* ServerTrustPolicy.swift */; }; + 82971968CBDAB224212EEB4607C9FB8D /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = BABA671A27CF29C8AA31D5C66D34CBA3 /* Result.swift */; }; + 82DB09296E2BC713C6D363528657A3FD /* ToArray.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17534D83D8298C9D739F4506816D218F /* ToArray.swift */; }; + 8399DBEE3E2D98EB1F466132E476F4D9 /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7D21C15998D42252EF80A55181C7D18 /* MultipartFormData.swift */; }; + 84B43422CBE09278E477D1BFF27B07A1 /* Window.swift in Sources */ = {isa = PBXBuildFile; fileRef = 81BA6471D19E57603D3AF0A0A49939B9 /* Window.swift */; }; + 84B93CFEFA6412E49988C92153998357 /* AnonymousInvocable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 257C3EC4A4AA8458E5B4BE717014B450 /* AnonymousInvocable.swift */; }; + 85E0465919F9DC7C97DD593CB49BB5E0 /* ShareReplay1.swift in Sources */ = {isa = PBXBuildFile; fileRef = DFB51688711C8369A2961F69330DCC99 /* ShareReplay1.swift */; }; + 8634F37209E5506667C604C1973F630D /* StoreAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A3E5E3CD673B025FD8AC260E67AB47E /* StoreAPI.swift */; }; + 88CCC2ADA43F75CB4708A701F5031643 /* ObserverBase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6F1954F056E7EC88AD642B7E7D937664 /* ObserverBase.swift */; }; + 897283A0B7F5299913327CC8FD6CC997 /* Pods-SwaggerClientTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8B68A752ED9CC80E5478E4FEC5A5F721 /* Pods-SwaggerClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */; }; + 8BDC4F0F424CA9A8190F28E7A02417A8 /* Cancelable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 09414F47E12D9B51147335D651E0D536 /* Cancelable.swift */; }; + 8D3CD54E3BACC9DB116DDA2DC30420CF /* ObserverType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B9FE8B611FD713A03D461C686322726 /* ObserverType.swift */; }; + 92450B928E8001F2B28A80072611F4C1 /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 14EB178F75EE27270C8F21ADA50D9C41 /* Error.swift */; }; + 9543E1505CCD2189D86456DAA0D55A22 /* BehaviorSubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 88A83A4C472835F0F6BDC178F2EF51A6 /* BehaviorSubject.swift */; }; + 956216483BCB853794F52B0292831E9C /* DispatchQueueSchedulerQOS.swift in Sources */ = {isa = PBXBuildFile; fileRef = 609B0D6771C363A74DDB9B2FFF4A9BAC /* DispatchQueueSchedulerQOS.swift */; }; + 96A03A2C4325A59DE2B02913FE351815 /* BooleanDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = F0B81B0D0B0B21977235410AAD4CFECB /* BooleanDisposable.swift */; }; + 97AB8959ABA0C9B8D4F400FD814BBB65 /* UserAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 552D15E0340BF58CC1922B82E864AEC9 /* UserAPI.swift */; }; + 983C8A7CA7087B8FD905B6392B05B790 /* AlamofireImplementations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 92734297B64DFE0EB0EDE1EA821163DB /* AlamofireImplementations.swift */; }; + 98FA1CFF63A5E74A7DB3255DA60C1843 /* DisposeBag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B72DF27B30B51C1091F485174052F1D /* DisposeBag.swift */; }; + 99F6DFF51E7C238DF99CA788144C732A /* CombineLatest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 516C671101243A9465AF2A689641D598 /* CombineLatest.swift */; }; + 9C3C83B09DE882AA526C40FDA31B69C8 /* Throttle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31D3B68FA022AAECF54F3CBFB928B666 /* Throttle.swift */; }; + 9C824A364077ED1458CEF9776F2FB44A /* String+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 64FED6C504DC2686A1BF8615B1D0213F /* String+Rx.swift */; }; + 9FDB94097AD437CDE44A507037AE4010 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9610BA4403551C05999CF892D495F516 /* Foundation.framework */; }; + A0A18CB5F889D7C2F80D6024EA568BEA /* Observable+Concurrency.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8CA8E405CD1F1D51078388FDE3498848 /* Observable+Concurrency.swift */; }; + A1B963DD34D20B255430C99DD78A1D43 /* Order.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A545673F09F49CDD60A13B4B0AF1020 /* Order.swift */; }; + A23E9C4262ED3ED9FF20A9E6E1FA2121 /* SerialDispatchQueueScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1BE009E15582DF43271F4102E7EC30F5 /* SerialDispatchQueueScheduler.swift */; }; + A2C172FE407C0BC3478ADCA91A6C9CEC /* Manager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 25A12681F026446EDBE1C55D22872F9D /* Manager.swift */; }; + A3505FA2FB3067D53847AD288AC04F03 /* Download.swift in Sources */ = {isa = PBXBuildFile; fileRef = 64491633490DB74E1E8D2CED2021C746 /* Download.swift */; }; + A4FBC2BD1A93FA52B5C97E79CDB9302F /* ImmediateScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7E056012594D80C40AF86E23AAD413A0 /* ImmediateScheduler.swift */; }; + A606E44DA4B92B1FFBA177125D55F6AA /* Buffer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31889B2EAD6E61A01714C04A70E0DF6F /* Buffer.swift */; }; + A67CCBFC004EF58E785FA7ED4A1B69B6 /* Generate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 48F68420AE4974226AE95592AB01F5C3 /* Generate.swift */; }; + AC265ECE8E2AF91D58A755022E7DF802 /* PriorityQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1F9095E4F9CC417FB1536F011BCAFACA /* PriorityQueue.swift */; }; + AD9D268210ED449C3BE591513FD0CFB8 /* RecursiveScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DEE36ACBCF70F5F1553D055175D1622 /* RecursiveScheduler.swift */; }; + ADC582F488BC636CC4292513053F6992 /* AsyncLock.swift in Sources */ = {isa = PBXBuildFile; fileRef = AEC4CF736B6956856103762EC255EEA2 /* AsyncLock.swift */; }; + AF3E5D2CE5E3448DB881E0F40F2F334F /* Do.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5D1009B6CD1857E5025278FDFACF63C /* Do.swift */; }; + AFF9AA31B242BF7F011D018D1B2A12FC /* PetAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 261F03A3C73374FD19333EEA59CCD59F /* PetAPI.swift */; }; + B0EAF63B91ABFD39C96353392D157D19 /* Zip.swift in Sources */ = {isa = PBXBuildFile; fileRef = 321E8BEC99166D3ED7E88CDBACBE407A /* Zip.swift */; }; + B0F20FEA2B9A800D016EF5B46EFDECE9 /* CombineLatest+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = B4D9A8D2D89ACE5DBF27150F182DE34E /* CombineLatest+arity.swift */; }; + B0FB4B01682814B9E3D32F9DC4A5E762 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 621056D7E34F3276D7ECDB147918DBEC /* Alamofire.swift */; }; + B22405A127912A4943AEFBDD57E7A267 /* AnonymousDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0DE7F5B430FDC646F58271F85B672788 /* AnonymousDisposable.swift */; }; + B28CA824CA5CD903042D8A07E9C5950E /* ReplaySubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 19C0FF31F56DFA84FE0CDF777CF56845 /* ReplaySubject.swift */; }; + B33369A55E29C11FA5F5977B5A47F1D4 /* RxSwift-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 24D7DE1FFF6AE5D438E4DAC777A8B8F2 /* RxSwift-dummy.m */; }; + B45CADB404E006E0EA39D7239C81C64F /* StableCompositeDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC813A2800E1E5B7D9C9A9A095B0D51E /* StableCompositeDisposable.swift */; }; + B590B3C59D3A327452D2532766F2F630 /* MainScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2B77AAD2C4150B81817D5833C2B78B7C /* MainScheduler.swift */; }; + B6D2DC3E3DA44CD382B9B425F40E11C1 /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 14BA42A836361E4416D38DECBEFE25C0 /* Alamofire-dummy.m */; }; + B754E33E17893DF35DECA754DE819A66 /* Queue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 97C78DB1DE41EDF5A70DBAB37DA9904B /* Queue.swift */; }; + B7DCF4199B0EEF4CB2FE0DFF23F99049 /* SkipWhile.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F329D6196F35CB573BEBA0D2379035F /* SkipWhile.swift */; }; + BB03FC085AE6A19821878DE92116DDD5 /* Models.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F0266C5AE0B23A436291F6647902086 /* Models.swift */; }; + BB3A568E8ED6C1792B43708A36A66F3D /* Event.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CAB8BECDF386291E0D615DE5171B181 /* Event.swift */; }; + BB5C8DC43B5072BBC05F56BF4DFD8CC5 /* Zip+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = ACF6B90536554BCC5A32E2DC7731D9FD /* Zip+arity.swift */; }; + BC10CEE813861D2F71E501E2F06532AB /* ScheduledItemType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 07017B36556829104C6CC52B3E0DFDA4 /* ScheduledItemType.swift */; }; + C3739BDF471B57AECC84085608EC9CE6 /* InfiniteSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 34DB4ED4653A16819871618F69B3182D /* InfiniteSequence.swift */; }; + C5099A3F4D955165F503506F2D10065D /* SynchronizedDisposeType.swift in Sources */ = {isa = PBXBuildFile; fileRef = C239D292236A2F59F0F6F5F1DB31795E /* SynchronizedDisposeType.swift */; }; + C546890220177F840E8AFC829D0E3FEB /* Pods-SwaggerClientTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */; }; + C6EFFFF6D9947B99945FE08559733EF6 /* Timer.swift in Sources */ = {isa = PBXBuildFile; fileRef = A03FE8BD209B0504BE052CBD44BD277A /* Timer.swift */; }; + C75519F0450166A6F28126ECC7664E9C /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = F31DEFD11FF950B319F5E3A97C41178F /* Validation.swift */; }; + CA4A98FD2226B57E5F59E0BA2E1A97EC /* OperationQueueScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = A38E6FD240ADA8F1BCE82B9426E6EF8F /* OperationQueueScheduler.swift */; }; + CD00FDDA48E9BC390530672F9F09D8CF /* Amb.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1EF617EC4E8045D4B384E618B83B2F6F /* Amb.swift */; }; + CDF08B0C84BE839E79DF99C271453406 /* SubscriptionDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3F52905F2DED9823E28E154C2CD365A0 /* SubscriptionDisposable.swift */; }; + CF13D1D873436D3890EC7392DEDE0B3E /* ObserveOnSerialDispatchQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 922907F82CF71DEBAE0585263AEF4518 /* ObserveOnSerialDispatchQueue.swift */; }; + D0F5068C6F5C0489E8A41A9912A09016 /* Range.swift in Sources */ = {isa = PBXBuildFile; fileRef = 509773F27764F1FF30E06C5F91E1FF0D /* Range.swift */; }; + D180CF545583D5DCDF770FBAA36F5DB0 /* Filter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9B5BDA8EA0E40E1A09E34DD0FF21BAD9 /* Filter.swift */; }; + D190592C39D806474770AF30FCC4EF4E /* Bag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2529676E540C411C575AB0CD27CCEF57 /* Bag.swift */; }; + D21B7325B3642887BFBE977E021F2D26 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = A56FED751BA06FF779D945B5D478065C /* ResponseSerialization.swift */; }; + D4789D8318C97E380412D03C1C321A88 /* Platform.Linux.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0668CCF084235C10B605A3F640FB98D8 /* Platform.Linux.swift */; }; + D5ECB1C860D3F53280EE2C5E54D470BD /* Using.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93ECB6F232D07DFDE4F782C41FFD85FE /* Using.swift */; }; + D75CA395D510E08C404E55F5BDAE55CE /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 526E73E2F71E0EC1442DFF1E6C3D7626 /* Error.swift */; }; + D932A3F3727B26175B547BA865A76B81 /* TakeUntil.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2AC78F9679615E991FC6F18D85FCF21C /* TakeUntil.swift */; }; + D99C59116FC2BC799C9C9DE4D0282EB9 /* Observable+Binding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9E0FD7CAAFFDA1BCA65C0DE4AB27B4 /* Observable+Binding.swift */; }; + DA18B15A9632B7282CF91FE4771C0B60 /* Observable.swift in Sources */ = {isa = PBXBuildFile; fileRef = A272A3BAB4634A80251132C7FB980D8A /* Observable.swift */; }; + DA202CAFA730E897B4D302C8C603A7E1 /* Pet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 284B3DE9B793FCC633E971DB1798AFAF /* Pet.swift */; }; + DB5B0A5C01527330DCD4CEF9740C7140 /* PublishSubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84665902C00313BF6D709D279E597AF9 /* PublishSubject.swift */; }; + DC9EF51CEA903F88D43F7B3A96923DFD /* SubscribeOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 46BB6E8D195D7B7711B8B0B50213D36B /* SubscribeOn.swift */; }; + DFF7D509E6FC70067A71C1CF0441AD48 /* PetstoreClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + E16A421C7269D0E81CB5E59344E63391 /* NAryDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C6944EFCED2081E91C44EEF357D1EA3 /* NAryDisposable.swift */; }; + E315A5FF56451DF73C7FE3140D5E2C6C /* ObservableConvertibleType.swift in Sources */ = {isa = PBXBuildFile; fileRef = D072A90162699810B672895226A27C43 /* ObservableConvertibleType.swift */; }; + E51F4BE281ADBC629708A4D131E9190C /* Disposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD65E96303458AB841FAD17494E26AAD /* Disposable.swift */; }; + E61B26D220A1A27E3BE7AD3F9BE35C76 /* Observable+StandardSequenceOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 372C2E8DD6FEE19981359253F88A881F /* Observable+StandardSequenceOperators.swift */; }; + E8CAB3FA190277C8E609F992A51EA9D2 /* StartWith.swift in Sources */ = {isa = PBXBuildFile; fileRef = F17B79123C6F61E5E5DBBF14710E6012 /* StartWith.swift */; }; + ECFCC7B806126EF7788D0DE094711905 /* CurrentThreadScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51171A514198E93AF767FD06958653FA /* CurrentThreadScheduler.swift */; }; + EE42701AD3887754AF7695978852957E /* Observable+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = DB5D61F564F3FF7A53825B0EF70E98B4 /* Observable+Extensions.swift */; }; + F206C370F63155D3468E0C188498C5DC /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9610BA4403551C05999CF892D495F516 /* Foundation.framework */; }; + F2246690EA6DEBF52D4CACA089B7FFC0 /* LockOwnerType.swift in Sources */ = {isa = PBXBuildFile; fileRef = ED580EA15AD5B2541B7EBE483BEE21EE /* LockOwnerType.swift */; }; + F460F46DBA5EE0D4FABB3CD0BEFE6CE3 /* Debug.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0E21F1428A7A2D51A86015D1E4531D87 /* Debug.swift */; }; + FC14480CECE872865A9C6E584F886DA3 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 86C5082D39612A1F1FD675C33932AEC9 /* Request.swift */; }; + FEDA6187E5CC1CFB1781F8F4947E160C /* ConcurrentMainScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6DBCE4DC8C3C8888BE09F0BC0EFCB3EA /* ConcurrentMainScheduler.swift */; }; + FEF0D7653948988B804226129471C1EC /* Stream.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6EF1F005F839FD46AD74F13986274F1B /* Stream.swift */; }; + FFDD18622776D270EAFE1CF94726C96D /* VirtualTimeScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 25C6BCDF18A3A22B7FEDE36B0A580C0E /* VirtualTimeScheduler.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 1B1D2D2B5F790067C63584DC46E8DEED /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 432ECC54282C84882B482CCB4CF227FC; + remoteInfo = Alamofire; + }; + 1E7EDC9660FD64A123EAC6BDA4C055AC /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = F316854D76F084E9539BFEF85DCBCF9D; + remoteInfo = RxSwift; + }; + 80996B8BB3446668F158E7817336A6E4 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 432ECC54282C84882B482CCB4CF227FC; + remoteInfo = Alamofire; + }; + C11AB97FC44865EAFD37FD7629B96B72 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = F316854D76F084E9539BFEF85DCBCF9D; + remoteInfo = RxSwift; + }; + D6508A8A1DB5D04976ECA9641101DB50 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = B3F4219972B712BDBD25392781A43848; + remoteInfo = PetstoreClient; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 00ACB4396DD1B4E4539E4E81C1D7A14E /* Pods-SwaggerClientTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = "Pods-SwaggerClientTests.modulemap"; sourceTree = ""; }; + 02F28E719AA874BE9213D6CF8CE7E36B /* Pods-SwaggerClientTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClientTests-acknowledgements.plist"; sourceTree = ""; }; + 051BE7827FDD01F32E6822EC2DE1CE1C /* Observable+Debug.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Observable+Debug.swift"; path = "RxSwift/Observables/Observable+Debug.swift"; sourceTree = ""; }; + 0567A0BF989778CA9FF9575D62613B8E /* DistinctUntilChanged.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DistinctUntilChanged.swift; path = RxSwift/Observables/Implementations/DistinctUntilChanged.swift; sourceTree = ""; }; + 057FC3E5DE19EA8F4DD600557D771032 /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 0668CCF084235C10B605A3F640FB98D8 /* Platform.Linux.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Platform.Linux.swift; path = RxSwift/Platform/Platform.Linux.swift; sourceTree = ""; }; + 06C46F9E4863BA39300A28EEBB2FED44 /* InvocableScheduledItem.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = InvocableScheduledItem.swift; path = RxSwift/Schedulers/Internal/InvocableScheduledItem.swift; sourceTree = ""; }; + 07017B36556829104C6CC52B3E0DFDA4 /* ScheduledItemType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ScheduledItemType.swift; path = RxSwift/Schedulers/Internal/ScheduledItemType.swift; sourceTree = ""; }; + 075BA1FDBF8D0B4B1D383DF8FD3BE509 /* Sequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Sequence.swift; path = RxSwift/Observables/Implementations/Sequence.swift; sourceTree = ""; }; + 09414F47E12D9B51147335D651E0D536 /* Cancelable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Cancelable.swift; path = RxSwift/Cancelable.swift; sourceTree = ""; }; + 09BD8ACFD826D9E6CCCAAB5DDB0132BF /* ImmediateSchedulerType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImmediateSchedulerType.swift; path = RxSwift/ImmediateSchedulerType.swift; sourceTree = ""; }; + 0A545673F09F49CDD60A13B4B0AF1020 /* Order.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Order.swift; sourceTree = ""; }; + 0B72DF27B30B51C1091F485174052F1D /* DisposeBag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DisposeBag.swift; path = RxSwift/Disposables/DisposeBag.swift; sourceTree = ""; }; + 0B9FE8B611FD713A03D461C686322726 /* ObserverType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObserverType.swift; path = RxSwift/ObserverType.swift; sourceTree = ""; }; + 0CAB8BECDF386291E0D615DE5171B181 /* Event.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Event.swift; path = RxSwift/Event.swift; sourceTree = ""; }; + 0DE7F5B430FDC646F58271F85B672788 /* AnonymousDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnonymousDisposable.swift; path = RxSwift/Disposables/AnonymousDisposable.swift; sourceTree = ""; }; + 0E21F1428A7A2D51A86015D1E4531D87 /* Debug.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Debug.swift; path = RxSwift/Observables/Implementations/Debug.swift; sourceTree = ""; }; + 101E84FB1E5F4A753DAF7518FB9BF0A7 /* Variable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Variable.swift; path = RxSwift/Subjects/Variable.swift; sourceTree = ""; }; + 10D1C22E4BBFB16E5C966FF77E92F296 /* SchedulerServices+Emulation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "SchedulerServices+Emulation.swift"; path = "RxSwift/Schedulers/SchedulerServices+Emulation.swift"; sourceTree = ""; }; + 14BA42A836361E4416D38DECBEFE25C0 /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; + 14EB178F75EE27270C8F21ADA50D9C41 /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = RxSwift/Observables/Implementations/Error.swift; sourceTree = ""; }; + 14F8F74E862AC5CA39F8E5132F1C00B9 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 17534D83D8298C9D739F4506816D218F /* ToArray.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ToArray.swift; path = RxSwift/Observables/Implementations/ToArray.swift; sourceTree = ""; }; + 17881314399342A30A86EF8655AFD35C /* ScheduledDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ScheduledDisposable.swift; path = RxSwift/Disposables/ScheduledDisposable.swift; sourceTree = ""; }; + 19296A8C5E948345E5744A748B1CC720 /* RxSwift.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = RxSwift.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 1974F6C69B156C91AE3DD56FAC5A3808 /* Lock.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Lock.swift; path = RxSwift/Concurrency/Lock.swift; sourceTree = ""; }; + 19C0FF31F56DFA84FE0CDF777CF56845 /* ReplaySubject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ReplaySubject.swift; path = RxSwift/Subjects/ReplaySubject.swift; sourceTree = ""; }; + 1A3E5E3CD673B025FD8AC260E67AB47E /* StoreAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = StoreAPI.swift; sourceTree = ""; }; + 1BE009E15582DF43271F4102E7EC30F5 /* SerialDispatchQueueScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SerialDispatchQueueScheduler.swift; path = RxSwift/Schedulers/SerialDispatchQueueScheduler.swift; sourceTree = ""; }; + 1C7A9744D1553CE8C58822392FE251D8 /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; + 1EF617EC4E8045D4B384E618B83B2F6F /* Amb.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Amb.swift; path = RxSwift/Observables/Implementations/Amb.swift; sourceTree = ""; }; + 1F0C939A9E2A83A661C6EA3D4EE8DC54 /* RxMutableBox.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxMutableBox.swift; path = RxSwift/RxMutableBox.swift; sourceTree = ""; }; + 1F9095E4F9CC417FB1536F011BCAFACA /* PriorityQueue.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PriorityQueue.swift; path = RxSwift/DataStructures/PriorityQueue.swift; sourceTree = ""; }; + 211F73A46D90346F7FC6D0D29640EE4F /* Tag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Tag.swift; sourceTree = ""; }; + 24D7DE1FFF6AE5D438E4DAC777A8B8F2 /* RxSwift-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "RxSwift-dummy.m"; sourceTree = ""; }; + 2529676E540C411C575AB0CD27CCEF57 /* Bag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Bag.swift; path = RxSwift/DataStructures/Bag.swift; sourceTree = ""; }; + 257C3EC4A4AA8458E5B4BE717014B450 /* AnonymousInvocable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnonymousInvocable.swift; path = RxSwift/Schedulers/Internal/AnonymousInvocable.swift; sourceTree = ""; }; + 25A12681F026446EDBE1C55D22872F9D /* Manager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Manager.swift; path = Source/Manager.swift; sourceTree = ""; }; + 25C6BCDF18A3A22B7FEDE36B0A580C0E /* VirtualTimeScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = VirtualTimeScheduler.swift; path = RxSwift/Schedulers/VirtualTimeScheduler.swift; sourceTree = ""; }; + 25D1E84FDF56D9C05CACE85F684D9965 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 261F03A3C73374FD19333EEA59CCD59F /* PetAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PetAPI.swift; sourceTree = ""; }; + 284B3DE9B793FCC633E971DB1798AFAF /* Pet.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Pet.swift; sourceTree = ""; }; + 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClient-dummy.m"; sourceTree = ""; }; + 292B4E8722DE17F6767ABED8D62A4C9E /* SynchronizedUnsubscribeType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SynchronizedUnsubscribeType.swift; path = RxSwift/Concurrency/SynchronizedUnsubscribeType.swift; sourceTree = ""; }; + 2AC78F9679615E991FC6F18D85FCF21C /* TakeUntil.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TakeUntil.swift; path = RxSwift/Observables/Implementations/TakeUntil.swift; sourceTree = ""; }; + 2B77AAD2C4150B81817D5833C2B78B7C /* MainScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MainScheduler.swift; path = RxSwift/Schedulers/MainScheduler.swift; sourceTree = ""; }; + 2FE2208C0198E8412BDD034563E2B1A7 /* Catch.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Catch.swift; path = RxSwift/Observables/Implementations/Catch.swift; sourceTree = ""; }; + 2FF17440CCD2E1A69791A4AA23325AD5 /* Pods-SwaggerClient-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClient-acknowledgements.markdown"; sourceTree = ""; }; + 3107BC52C0E01198FAE330F1ADC0BF3C /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; + 315D8F39A79B562AA2268250BED93150 /* ObserveOn.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObserveOn.swift; path = RxSwift/Observables/Implementations/ObserveOn.swift; sourceTree = ""; }; + 31889B2EAD6E61A01714C04A70E0DF6F /* Buffer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Buffer.swift; path = RxSwift/Observables/Implementations/Buffer.swift; sourceTree = ""; }; + 31D3B68FA022AAECF54F3CBFB928B666 /* Throttle.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Throttle.swift; path = RxSwift/Observables/Implementations/Throttle.swift; sourceTree = ""; }; + 321E8BEC99166D3ED7E88CDBACBE407A /* Zip.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Zip.swift; path = RxSwift/Observables/Implementations/Zip.swift; sourceTree = ""; }; + 3341D7B714515136B34354D7D32202DB /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; + 34DB4ED4653A16819871618F69B3182D /* InfiniteSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = InfiniteSequence.swift; path = RxSwift/DataStructures/InfiniteSequence.swift; sourceTree = ""; }; + 35A3C82BD63330195DE669D3836B7E41 /* ShareReplay1WhileConnected.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ShareReplay1WhileConnected.swift; path = RxSwift/Observables/Implementations/ShareReplay1WhileConnected.swift; sourceTree = ""; }; + 372C2E8DD6FEE19981359253F88A881F /* Observable+StandardSequenceOperators.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Observable+StandardSequenceOperators.swift"; path = "RxSwift/Observables/Observable+StandardSequenceOperators.swift"; sourceTree = ""; }; + 37E5E51602A7EC243D3CC5A8B0FBC7E3 /* Sink.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Sink.swift; path = RxSwift/Observables/Implementations/Sink.swift; sourceTree = ""; }; + 39E5209D93CDC3C851C2F4454601FF04 /* ConnectableObservableType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConnectableObservableType.swift; path = RxSwift/ConnectableObservableType.swift; sourceTree = ""; }; + 3B5E5E7372652C9D351B65002A966365 /* VirtualTimeConverterType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = VirtualTimeConverterType.swift; path = RxSwift/Schedulers/VirtualTimeConverterType.swift; sourceTree = ""; }; + 3C0CED57E33C91E281A79EE0195FCAC2 /* DelaySubscription.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DelaySubscription.swift; path = RxSwift/Observables/Implementations/DelaySubscription.swift; sourceTree = ""; }; + 3C2489BF8D3C006E1A6E9FA8E1275FC1 /* Observable+Aggregate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Observable+Aggregate.swift"; path = "RxSwift/Observables/Observable+Aggregate.swift"; sourceTree = ""; }; + 3EB61DA897ED3DE273EC2B5824A42DF0 /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; + 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-SwaggerClient-umbrella.h"; sourceTree = ""; }; + 3F16B43ABD2C8CD4A311AA1AB3B6C02F /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 3F52905F2DED9823E28E154C2CD365A0 /* SubscriptionDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SubscriptionDisposable.swift; path = RxSwift/Disposables/SubscriptionDisposable.swift; sourceTree = ""; }; + 43FC49AA70D3E2A84CAED9C37BE9C4B5 /* Pods-SwaggerClientTests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-frameworks.sh"; sourceTree = ""; }; + 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "PetstoreClient-dummy.m"; sourceTree = ""; }; + 46BB6E8D195D7B7711B8B0B50213D36B /* SubscribeOn.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SubscribeOn.swift; path = RxSwift/Observables/Implementations/SubscribeOn.swift; sourceTree = ""; }; + 47C4BE1760C078A0188C4A66807F2C29 /* AddRef.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AddRef.swift; path = RxSwift/Observables/Implementations/AddRef.swift; sourceTree = ""; }; + 48F68420AE4974226AE95592AB01F5C3 /* Generate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Generate.swift; path = RxSwift/Observables/Implementations/Generate.swift; sourceTree = ""; }; + 4A3658B178A16F05FFD28C46A18EF8E8 /* Map.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Map.swift; path = RxSwift/Observables/Implementations/Map.swift; sourceTree = ""; }; + 4CAF565A8B834CB6FD86DDFF010D4E4B /* Take.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Take.swift; path = RxSwift/Observables/Implementations/Take.swift; sourceTree = ""; }; + 509773F27764F1FF30E06C5F91E1FF0D /* Range.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Range.swift; path = RxSwift/Observables/Implementations/Range.swift; sourceTree = ""; }; + 51171A514198E93AF767FD06958653FA /* CurrentThreadScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CurrentThreadScheduler.swift; path = RxSwift/Schedulers/CurrentThreadScheduler.swift; sourceTree = ""; }; + 5124609C66364357A0450CE5890AB140 /* BinaryDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BinaryDisposable.swift; path = RxSwift/Disposables/BinaryDisposable.swift; sourceTree = ""; }; + 516C671101243A9465AF2A689641D598 /* CombineLatest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CombineLatest.swift; path = RxSwift/Observables/Implementations/CombineLatest.swift; sourceTree = ""; }; + 52611EC9CCB565A24C2C007F5A2CB6C3 /* HistoricalScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HistoricalScheduler.swift; path = RxSwift/Schedulers/HistoricalScheduler.swift; sourceTree = ""; }; + 526E73E2F71E0EC1442DFF1E6C3D7626 /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = Source/Error.swift; sourceTree = ""; }; + 5412898DEB10F1983487A10453C6B9CB /* Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Extensions.swift; sourceTree = ""; }; + 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.debug.xcconfig"; sourceTree = ""; }; + 552D15E0340BF58CC1922B82E864AEC9 /* UserAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = UserAPI.swift; sourceTree = ""; }; + 5ADB3F22CC2D987B4C7E76A7B502DE81 /* RefCount.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RefCount.swift; path = RxSwift/Observables/Implementations/RefCount.swift; sourceTree = ""; }; + 5B248364ABF60ACD7DB31A17DCFDFD0C /* User.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = User.swift; sourceTree = ""; }; + 5B598E168B47485DC60F9DBBCBEEF5BB /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 5C6944EFCED2081E91C44EEF357D1EA3 /* NAryDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NAryDisposable.swift; path = RxSwift/Disposables/NAryDisposable.swift; sourceTree = ""; }; + 5CF9673331C58F7D9396CDEC9CE940A9 /* CombineLatest+CollectionType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "CombineLatest+CollectionType.swift"; path = "RxSwift/Observables/Implementations/CombineLatest+CollectionType.swift"; sourceTree = ""; }; + 5DEE36ACBCF70F5F1553D055175D1622 /* RecursiveScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RecursiveScheduler.swift; path = RxSwift/Schedulers/RecursiveScheduler.swift; sourceTree = ""; }; + 609B0D6771C363A74DDB9B2FFF4A9BAC /* DispatchQueueSchedulerQOS.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DispatchQueueSchedulerQOS.swift; path = RxSwift/Schedulers/DispatchQueueSchedulerQOS.swift; sourceTree = ""; }; + 6156CD5049D33CC68DF29760B398B408 /* NopDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NopDisposable.swift; path = RxSwift/Disposables/NopDisposable.swift; sourceTree = ""; }; + 6204091F721976FA7C97D74AC93B9637 /* Zip+CollectionType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Zip+CollectionType.swift"; path = "RxSwift/Observables/Implementations/Zip+CollectionType.swift"; sourceTree = ""; }; + 621056D7E34F3276D7ECDB147918DBEC /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; + 62EC50E209B29C93EAECE01AD46DBAE7 /* RefCountDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RefCountDisposable.swift; path = RxSwift/Disposables/RefCountDisposable.swift; sourceTree = ""; }; + 636788473300310D67C31CCE1A571AC4 /* Switch.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Switch.swift; path = RxSwift/Observables/Implementations/Switch.swift; sourceTree = ""; }; + 64491633490DB74E1E8D2CED2021C746 /* Download.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Download.swift; path = Source/Download.swift; sourceTree = ""; }; + 64FED6C504DC2686A1BF8615B1D0213F /* String+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "String+Rx.swift"; path = "RxSwift/Extensions/String+Rx.swift"; sourceTree = ""; }; + 66429A42B7499250307412ECB7AF627E /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; + 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-SwaggerClientTests-dummy.m"; sourceTree = ""; }; + 6C4F5E9ABF91F6B2FF369456D3804258 /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; + 6DBCE4DC8C3C8888BE09F0BC0EFCB3EA /* ConcurrentMainScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConcurrentMainScheduler.swift; path = RxSwift/Schedulers/ConcurrentMainScheduler.swift; sourceTree = ""; }; + 6EBAF7A3F8D6D888BC91244485ECD2AA /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = Alamofire.modulemap; sourceTree = ""; }; + 6EF1F005F839FD46AD74F13986274F1B /* Stream.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Stream.swift; path = Source/Stream.swift; sourceTree = ""; }; + 6F1954F056E7EC88AD642B7E7D937664 /* ObserverBase.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObserverBase.swift; path = RxSwift/Observers/ObserverBase.swift; sourceTree = ""; }; + 72AAAA3FE5DDA94BC0636A15F9F4F7EF /* Just.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Just.swift; path = RxSwift/Observables/Implementations/Just.swift; sourceTree = ""; }; + 72DC2CBE50494D6723773E2C3E89C3C1 /* ScheduledItem.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ScheduledItem.swift; path = RxSwift/Schedulers/Internal/ScheduledItem.swift; sourceTree = ""; }; + 72F5796E9AA6A65EA2149A206ADE4289 /* TakeWhile.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TakeWhile.swift; path = RxSwift/Observables/Implementations/TakeWhile.swift; sourceTree = ""; }; + 75D5E40EFDE70F2D69310639B473B817 /* TakeLast.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TakeLast.swift; path = RxSwift/Observables/Implementations/TakeLast.swift; sourceTree = ""; }; + 76485D1ACD1F13E0E68638CA3D9E175C /* ConnectableObservable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConnectableObservable.swift; path = RxSwift/Observables/Implementations/ConnectableObservable.swift; sourceTree = ""; }; + 7678CC14BE55592C2250C4C122EADEF3 /* RetryWhen.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RetryWhen.swift; path = RxSwift/Observables/Implementations/RetryWhen.swift; sourceTree = ""; }; + 7AD0626709B8BF22F5F6B42379D4C1EB /* Producer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Producer.swift; path = RxSwift/Observables/Implementations/Producer.swift; sourceTree = ""; }; + 7C8E63660D346FD8ED2A97242E74EA09 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 7D488959FBBFCF0351F42E7D150C1942 /* Multicast.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Multicast.swift; path = RxSwift/Observables/Implementations/Multicast.swift; sourceTree = ""; }; + 7D9E0FD7CAAFFDA1BCA65C0DE4AB27B4 /* Observable+Binding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Observable+Binding.swift"; path = "RxSwift/Observables/Observable+Binding.swift"; sourceTree = ""; }; + 7E056012594D80C40AF86E23AAD413A0 /* ImmediateScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImmediateScheduler.swift; path = RxSwift/Schedulers/ImmediateScheduler.swift; sourceTree = ""; }; + 7E2F61612759130FD3873E3FBE0E2CC0 /* WithLatestFrom.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = WithLatestFrom.swift; path = RxSwift/Observables/Implementations/WithLatestFrom.swift; sourceTree = ""; }; + 8033FB9B41A3E314A0CC6C50015B835D /* Observable+Single.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Observable+Single.swift"; path = "RxSwift/Observables/Observable+Single.swift"; sourceTree = ""; }; + 81BA6471D19E57603D3AF0A0A49939B9 /* Window.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Window.swift; path = RxSwift/Observables/Implementations/Window.swift; sourceTree = ""; }; + 84665902C00313BF6D709D279E597AF9 /* PublishSubject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PublishSubject.swift; path = RxSwift/Subjects/PublishSubject.swift; sourceTree = ""; }; + 849FECBC6CC67F2B6800F982927E3A9E /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; + 84A09D760BA2EA13D5BE269086BAD34C /* RxSwift.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = RxSwift.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 8611EB072B953093474C20B1B11F76CC /* RxSwift.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = RxSwift.modulemap; sourceTree = ""; }; + 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; + 86C5082D39612A1F1FD675C33932AEC9 /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; + 88A83A4C472835F0F6BDC178F2EF51A6 /* BehaviorSubject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BehaviorSubject.swift; path = RxSwift/Subjects/BehaviorSubject.swift; sourceTree = ""; }; + 8A95956A18890D406F52B50CE636C417 /* ConcurrentDispatchQueueScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConcurrentDispatchQueueScheduler.swift; path = RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift; sourceTree = ""; }; + 8CA8E405CD1F1D51078388FDE3498848 /* Observable+Concurrency.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Observable+Concurrency.swift"; path = "RxSwift/Observables/Observable+Concurrency.swift"; sourceTree = ""; }; + 8E78A6B0E3334E11FE5615FE4CC506E8 /* Upload.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Upload.swift; path = Source/Upload.swift; sourceTree = ""; }; + 8EFB1B59D84F8B11F82B8DF1A2150846 /* Observable+Time.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Observable+Time.swift"; path = "RxSwift/Observables/Observable+Time.swift"; sourceTree = ""; }; + 8F0266C5AE0B23A436291F6647902086 /* Models.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Models.swift; sourceTree = ""; }; + 8F329D6196F35CB573BEBA0D2379035F /* SkipWhile.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkipWhile.swift; path = RxSwift/Observables/Implementations/SkipWhile.swift; sourceTree = ""; }; + 9144FDC8DC22962DE80692307106EF74 /* Merge.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Merge.swift; path = RxSwift/Observables/Implementations/Merge.swift; sourceTree = ""; }; + 914B1C0C6B1C0BB87F3EB1E7F1060425 /* AnonymousObserver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnonymousObserver.swift; path = RxSwift/Observers/AnonymousObserver.swift; sourceTree = ""; }; + 922907F82CF71DEBAE0585263AEF4518 /* ObserveOnSerialDispatchQueue.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObserveOnSerialDispatchQueue.swift; path = RxSwift/Observables/Implementations/ObserveOnSerialDispatchQueue.swift; sourceTree = ""; }; + 92734297B64DFE0EB0EDE1EA821163DB /* AlamofireImplementations.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AlamofireImplementations.swift; sourceTree = ""; }; + 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + 93ECB6F232D07DFDE4F782C41FFD85FE /* Using.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Using.swift; path = RxSwift/Observables/Implementations/Using.swift; sourceTree = ""; }; + 9610BA4403551C05999CF892D495F516 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.3.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + 969C2AF48F4307163B301A92E78AFCF2 /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = ""; }; + 97C78DB1DE41EDF5A70DBAB37DA9904B /* Queue.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Queue.swift; path = RxSwift/DataStructures/Queue.swift; sourceTree = ""; }; + 983586C602A5C7D5B4FD91982F3711D0 /* DisposeBase.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DisposeBase.swift; path = RxSwift/Disposables/DisposeBase.swift; sourceTree = ""; }; + 99A31BA1E446FA35628A7DED964EF04F /* Skip.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Skip.swift; path = RxSwift/Observables/Implementations/Skip.swift; sourceTree = ""; }; + 9B0F57917A904327F2D141C7E2E8623F /* Observable+Multiple.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Observable+Multiple.swift"; path = "RxSwift/Observables/Observable+Multiple.swift"; sourceTree = ""; }; + 9B3FF9A09AF9E0D7751789D55FDDDCA2 /* CompositeDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CompositeDisposable.swift; path = RxSwift/Disposables/CompositeDisposable.swift; sourceTree = ""; }; + 9B5BDA8EA0E40E1A09E34DD0FF21BAD9 /* Filter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Filter.swift; path = RxSwift/Observables/Implementations/Filter.swift; sourceTree = ""; }; + 9D510BAAE86BD9AA107EBEE6C81330BB /* RxSwift-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxSwift-prefix.pch"; sourceTree = ""; }; + 9E9064EE8CEF10A602EFC90A26D1DC39 /* HistoricalSchedulerTimeConverter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HistoricalSchedulerTimeConverter.swift; path = RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift; sourceTree = ""; }; + 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-umbrella.h"; sourceTree = ""; }; + A03FE8BD209B0504BE052CBD44BD277A /* Timer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timer.swift; path = RxSwift/Observables/Implementations/Timer.swift; sourceTree = ""; }; + A272A3BAB4634A80251132C7FB980D8A /* Observable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Observable.swift; path = RxSwift/Observable.swift; sourceTree = ""; }; + A2CEC38D6994E89F7BD53BCE73AB7F89 /* AnonymousObservable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnonymousObservable.swift; path = RxSwift/Observables/Implementations/AnonymousObservable.swift; sourceTree = ""; }; + A371B67E1A1BC9D198E470D4B54FEE87 /* ObservableType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObservableType.swift; path = RxSwift/ObservableType.swift; sourceTree = ""; }; + A38E6FD240ADA8F1BCE82B9426E6EF8F /* OperationQueueScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = OperationQueueScheduler.swift; path = RxSwift/Schedulers/OperationQueueScheduler.swift; sourceTree = ""; }; + A4D4B50A66CA7EB372C9BCE21D117CEC /* SynchronizedSubscribeType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SynchronizedSubscribeType.swift; path = RxSwift/Concurrency/SynchronizedSubscribeType.swift; sourceTree = ""; }; + A56FED751BA06FF779D945B5D478065C /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; + A5D1009B6CD1857E5025278FDFACF63C /* Do.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Do.swift; path = RxSwift/Observables/Implementations/Do.swift; sourceTree = ""; }; + A6E7F9EA5FCA01B648E37743D97B9D57 /* Deferred.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Deferred.swift; path = RxSwift/Observables/Implementations/Deferred.swift; sourceTree = ""; }; + A7D21C15998D42252EF80A55181C7D18 /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; + A98250195E2C07F9A7DB5E4BB333ACE9 /* Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Rx.swift; path = RxSwift/Rx.swift; sourceTree = ""; }; + AA9C5856BEAE5090A7D1EB450A10C04F /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + ACF6B90536554BCC5A32E2DC7731D9FD /* Zip+arity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Zip+arity.swift"; path = "RxSwift/Observables/Implementations/Zip+arity.swift"; sourceTree = ""; }; + AD65E96303458AB841FAD17494E26AAD /* Disposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Disposable.swift; path = RxSwift/Disposable.swift; sourceTree = ""; }; + AEC4CF736B6956856103762EC255EEA2 /* AsyncLock.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AsyncLock.swift; path = RxSwift/Concurrency/AsyncLock.swift; sourceTree = ""; }; + B2B14E7D38A4727796ABDFA4079BD210 /* Repeat.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Repeat.swift; path = RxSwift/Observables/Implementations/Repeat.swift; sourceTree = ""; }; + B3A144887C8B13FD888B76AB096B0CA1 /* PetstoreClient-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-prefix.pch"; sourceTree = ""; }; + B4D9A8D2D89ACE5DBF27150F182DE34E /* CombineLatest+arity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "CombineLatest+arity.swift"; path = "RxSwift/Observables/Implementations/CombineLatest+arity.swift"; sourceTree = ""; }; + B7B5D80C0F71324ED10DBE73D28402DB /* SynchronizedOnType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SynchronizedOnType.swift; path = RxSwift/Concurrency/SynchronizedOnType.swift; sourceTree = ""; }; + B7FA9B23245D415690FB894178BBF20F /* SerialDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SerialDisposable.swift; path = RxSwift/Disposables/SerialDisposable.swift; sourceTree = ""; }; + BA1AAD8792DE618CDBBF78CA8E642111 /* SingleAsync.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SingleAsync.swift; path = RxSwift/Observables/Implementations/SingleAsync.swift; sourceTree = ""; }; + BABA671A27CF29C8AA31D5C66D34CBA3 /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = ""; }; + BC813A2800E1E5B7D9C9A9A095B0D51E /* StableCompositeDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = StableCompositeDisposable.swift; path = RxSwift/Disposables/StableCompositeDisposable.swift; sourceTree = ""; }; + BCF2D4DFF08D2A18E8C8FE4C4B4633FB /* Pods-SwaggerClient-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-frameworks.sh"; sourceTree = ""; }; + BDA5F3724FE84CF94299E36A8DF89017 /* RxSwift-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxSwift-umbrella.h"; sourceTree = ""; }; + BE69C5E6F8BF09D066522463F69EB8A6 /* Empty.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Empty.swift; path = RxSwift/Observables/Implementations/Empty.swift; sourceTree = ""; }; + C239D292236A2F59F0F6F5F1DB31795E /* SynchronizedDisposeType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SynchronizedDisposeType.swift; path = RxSwift/Concurrency/SynchronizedDisposeType.swift; sourceTree = ""; }; + C4B474BD9070828C0F786071EEF46CD0 /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + D02FE9C7BBEB944DACB0B057F631B40C /* TailRecursiveSink.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TailRecursiveSink.swift; path = RxSwift/Observers/TailRecursiveSink.swift; sourceTree = ""; }; + D072A90162699810B672895226A27C43 /* ObservableConvertibleType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObservableConvertibleType.swift; path = RxSwift/ObservableConvertibleType.swift; sourceTree = ""; }; + D0A71420D33D17B1C771C1CC7ADD8258 /* RxSwift.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RxSwift.xcconfig; sourceTree = ""; }; + D2841E5E2183846280B97F6E660DA26C /* Pods-SwaggerClient-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClient-resources.sh"; sourceTree = ""; }; + D2BAD338E56EF3CAA6E54490FE0C5DF9 /* APIHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = APIHelper.swift; sourceTree = ""; }; + D4DF0604EDC1460935E6E445A47023A4 /* Category.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Category.swift; sourceTree = ""; }; + D5438FA602118A769102A572D66E5EDD /* Reduce.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Reduce.swift; path = RxSwift/Observables/Implementations/Reduce.swift; sourceTree = ""; }; + D69A080DF8671D7B4CEB7E706EF4667F /* SkipUntil.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkipUntil.swift; path = RxSwift/Observables/Implementations/SkipUntil.swift; sourceTree = ""; }; + D8072E1108951F272C003553FC8926C7 /* APIs.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = APIs.swift; sourceTree = ""; }; + DABFA04B3B312B12F4703582A14EEE51 /* ElementAt.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ElementAt.swift; path = RxSwift/Observables/Implementations/ElementAt.swift; sourceTree = ""; }; + DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = PetstoreClient.xcconfig; sourceTree = ""; }; + DB5D61F564F3FF7A53825B0EF70E98B4 /* Observable+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Observable+Extensions.swift"; path = "RxSwift/Observable+Extensions.swift"; sourceTree = ""; }; + DBC29FB0F89F4B2B863A122A41D07007 /* Sample.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Sample.swift; path = RxSwift/Observables/Implementations/Sample.swift; sourceTree = ""; }; + DE164497A94DD3215ED4D1AE0D4703B1 /* Pods-SwaggerClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = "Pods-SwaggerClient.modulemap"; sourceTree = ""; }; + DE3076AFBC266A6E88C8171467D6C5A5 /* SingleAssignmentDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SingleAssignmentDisposable.swift; path = RxSwift/Disposables/SingleAssignmentDisposable.swift; sourceTree = ""; }; + DFB51688711C8369A2961F69330DCC99 /* ShareReplay1.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ShareReplay1.swift; path = RxSwift/Observables/Implementations/ShareReplay1.swift; sourceTree = ""; }; + E1E4BCB344D3C100253B24B79421F00A /* Pods-SwaggerClient-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-SwaggerClient-acknowledgements.plist"; sourceTree = ""; }; + E3D1141B63DF38660CD6F3AC588A782B /* PetstoreClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = PetstoreClient.modulemap; sourceTree = ""; }; + E4E6F4A58FE7868CA2177D3AC79AD2FA /* Pods-SwaggerClientTests-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-SwaggerClientTests-resources.sh"; sourceTree = ""; }; + E64D15D1795EA999578C393A507A882F /* SubjectType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SubjectType.swift; path = RxSwift/Subjects/SubjectType.swift; sourceTree = ""; }; + E8B5CE5592D5B0BD393B7D599B053BFA /* Concat.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Concat.swift; path = RxSwift/Observables/Implementations/Concat.swift; sourceTree = ""; }; + E97A3908B642D476F00987B50894F4C9 /* InvocableType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = InvocableType.swift; path = RxSwift/Schedulers/Internal/InvocableType.swift; sourceTree = ""; }; + E9CBBB398E7A62950FA8BC091CBE0359 /* PetstoreClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = PetstoreClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + EBED49C45F40708D9355E7D2CFFE4602 /* Observable+Creation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Observable+Creation.swift"; path = "RxSwift/Observables/Observable+Creation.swift"; sourceTree = ""; }; + EC88FCE0410EAE3C16E64A8A8108D142 /* SchedulerType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SchedulerType.swift; path = RxSwift/SchedulerType.swift; sourceTree = ""; }; + ED580EA15AD5B2541B7EBE483BEE21EE /* LockOwnerType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LockOwnerType.swift; path = RxSwift/Concurrency/LockOwnerType.swift; sourceTree = ""; }; + EDC79FC8F9A849970B716868E7F51D2C /* Timeout.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeout.swift; path = RxSwift/Observables/Implementations/Timeout.swift; sourceTree = ""; }; + F0B81B0D0B0B21977235410AAD4CFECB /* BooleanDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BooleanDisposable.swift; path = RxSwift/Disposables/BooleanDisposable.swift; sourceTree = ""; }; + F0D4E00A8974E74325E9E53D456F9AD4 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + F17B79123C6F61E5E5DBBF14710E6012 /* StartWith.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = StartWith.swift; path = RxSwift/Observables/Implementations/StartWith.swift; sourceTree = ""; }; + F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-SwaggerClientTests-umbrella.h"; sourceTree = ""; }; + F250B545A022C0627A401DF08D2B7339 /* Errors.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Errors.swift; path = RxSwift/Errors.swift; sourceTree = ""; }; + F31DEFD11FF950B319F5E3A97C41178F /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; + FB170EFD14935F121CDE3211DB4C5CA3 /* Pods-SwaggerClientTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-SwaggerClientTests-acknowledgements.markdown"; sourceTree = ""; }; + FC3B7613AC16E246F73123670BAED3F5 /* Platform.Darwin.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Platform.Darwin.swift; path = RxSwift/Platform/Platform.Darwin.swift; sourceTree = ""; }; + FCF668BEB868B23FA177F79EA8B5D5CF /* Never.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Never.swift; path = RxSwift/Observables/Implementations/Never.swift; sourceTree = ""; }; + FD709EBAF5345AC238B7849DE5BCB273 /* Scan.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Scan.swift; path = RxSwift/Observables/Implementations/Scan.swift; sourceTree = ""; }; + FF0E5B19D36827BBE8598B8ACC2EC189 /* AnyObserver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnyObserver.swift; path = RxSwift/AnyObserver.swift; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 05BA91ABD8AC918A49A9D7E0E3722C70 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 14DD51004DF8C27A7D0491AEFEC5F464 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 76130794E62D45206C62CE83429B6CF2 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 9FDB94097AD437CDE44A507037AE4010 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A5AE1D340C4A0691EC28EEA8241C9FCD /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 0BD8B4E55E72312366130E97A1204CD8 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + CB2482011FA929C2BCC3E41A1B6E02E1 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 110E6B43666A729745E9980F080944C4 /* Alamofire.framework in Frameworks */, + 393372CC0F931D0D192179C4B16DF65E /* Foundation.framework in Frameworks */, + 58344FE826FA6ED012A3450ACB0BF93D /* RxSwift.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FE8FC779CF4B0CFCC594E81C0FF86C7E /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + F206C370F63155D3468E0C188498C5DC /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 1322FED69118C64DAD026CAF7F4C38C6 /* Models */ = { + isa = PBXGroup; + children = ( + D4DF0604EDC1460935E6E445A47023A4 /* Category.swift */, + 0A545673F09F49CDD60A13B4B0AF1020 /* Order.swift */, + 284B3DE9B793FCC633E971DB1798AFAF /* Pet.swift */, + 211F73A46D90346F7FC6D0D29640EE4F /* Tag.swift */, + 5B248364ABF60ACD7DB31A17DCFDFD0C /* User.swift */, + ); + path = Models; + sourceTree = ""; + }; + 22F52349E1BE90FC6E064DAAC9EA9612 /* Development Pods */ = { + isa = PBXGroup; + children = ( + E9F8459055B900A58FB97600A53E5D1C /* PetstoreClient */, + ); + name = "Development Pods"; + sourceTree = ""; + }; + 530337216701C70B5DE636BF1B3DB0C5 /* RxSwift */ = { + isa = PBXGroup; + children = ( + 47C4BE1760C078A0188C4A66807F2C29 /* AddRef.swift */, + 1EF617EC4E8045D4B384E618B83B2F6F /* Amb.swift */, + 0DE7F5B430FDC646F58271F85B672788 /* AnonymousDisposable.swift */, + 257C3EC4A4AA8458E5B4BE717014B450 /* AnonymousInvocable.swift */, + A2CEC38D6994E89F7BD53BCE73AB7F89 /* AnonymousObservable.swift */, + 914B1C0C6B1C0BB87F3EB1E7F1060425 /* AnonymousObserver.swift */, + FF0E5B19D36827BBE8598B8ACC2EC189 /* AnyObserver.swift */, + AEC4CF736B6956856103762EC255EEA2 /* AsyncLock.swift */, + 2529676E540C411C575AB0CD27CCEF57 /* Bag.swift */, + 88A83A4C472835F0F6BDC178F2EF51A6 /* BehaviorSubject.swift */, + 5124609C66364357A0450CE5890AB140 /* BinaryDisposable.swift */, + F0B81B0D0B0B21977235410AAD4CFECB /* BooleanDisposable.swift */, + 31889B2EAD6E61A01714C04A70E0DF6F /* Buffer.swift */, + 09414F47E12D9B51147335D651E0D536 /* Cancelable.swift */, + 2FE2208C0198E8412BDD034563E2B1A7 /* Catch.swift */, + 516C671101243A9465AF2A689641D598 /* CombineLatest.swift */, + B4D9A8D2D89ACE5DBF27150F182DE34E /* CombineLatest+arity.swift */, + 5CF9673331C58F7D9396CDEC9CE940A9 /* CombineLatest+CollectionType.swift */, + 9B3FF9A09AF9E0D7751789D55FDDDCA2 /* CompositeDisposable.swift */, + E8B5CE5592D5B0BD393B7D599B053BFA /* Concat.swift */, + 8A95956A18890D406F52B50CE636C417 /* ConcurrentDispatchQueueScheduler.swift */, + 6DBCE4DC8C3C8888BE09F0BC0EFCB3EA /* ConcurrentMainScheduler.swift */, + 76485D1ACD1F13E0E68638CA3D9E175C /* ConnectableObservable.swift */, + 39E5209D93CDC3C851C2F4454601FF04 /* ConnectableObservableType.swift */, + 51171A514198E93AF767FD06958653FA /* CurrentThreadScheduler.swift */, + 0E21F1428A7A2D51A86015D1E4531D87 /* Debug.swift */, + A6E7F9EA5FCA01B648E37743D97B9D57 /* Deferred.swift */, + 3C0CED57E33C91E281A79EE0195FCAC2 /* DelaySubscription.swift */, + 609B0D6771C363A74DDB9B2FFF4A9BAC /* DispatchQueueSchedulerQOS.swift */, + AD65E96303458AB841FAD17494E26AAD /* Disposable.swift */, + 0B72DF27B30B51C1091F485174052F1D /* DisposeBag.swift */, + 983586C602A5C7D5B4FD91982F3711D0 /* DisposeBase.swift */, + 0567A0BF989778CA9FF9575D62613B8E /* DistinctUntilChanged.swift */, + A5D1009B6CD1857E5025278FDFACF63C /* Do.swift */, + DABFA04B3B312B12F4703582A14EEE51 /* ElementAt.swift */, + BE69C5E6F8BF09D066522463F69EB8A6 /* Empty.swift */, + 14EB178F75EE27270C8F21ADA50D9C41 /* Error.swift */, + F250B545A022C0627A401DF08D2B7339 /* Errors.swift */, + 0CAB8BECDF386291E0D615DE5171B181 /* Event.swift */, + 9B5BDA8EA0E40E1A09E34DD0FF21BAD9 /* Filter.swift */, + 48F68420AE4974226AE95592AB01F5C3 /* Generate.swift */, + 52611EC9CCB565A24C2C007F5A2CB6C3 /* HistoricalScheduler.swift */, + 9E9064EE8CEF10A602EFC90A26D1DC39 /* HistoricalSchedulerTimeConverter.swift */, + 7E056012594D80C40AF86E23AAD413A0 /* ImmediateScheduler.swift */, + 09BD8ACFD826D9E6CCCAAB5DDB0132BF /* ImmediateSchedulerType.swift */, + 34DB4ED4653A16819871618F69B3182D /* InfiniteSequence.swift */, + 06C46F9E4863BA39300A28EEBB2FED44 /* InvocableScheduledItem.swift */, + E97A3908B642D476F00987B50894F4C9 /* InvocableType.swift */, + 72AAAA3FE5DDA94BC0636A15F9F4F7EF /* Just.swift */, + 1974F6C69B156C91AE3DD56FAC5A3808 /* Lock.swift */, + ED580EA15AD5B2541B7EBE483BEE21EE /* LockOwnerType.swift */, + 2B77AAD2C4150B81817D5833C2B78B7C /* MainScheduler.swift */, + 4A3658B178A16F05FFD28C46A18EF8E8 /* Map.swift */, + 9144FDC8DC22962DE80692307106EF74 /* Merge.swift */, + 7D488959FBBFCF0351F42E7D150C1942 /* Multicast.swift */, + 5C6944EFCED2081E91C44EEF357D1EA3 /* NAryDisposable.swift */, + FCF668BEB868B23FA177F79EA8B5D5CF /* Never.swift */, + 6156CD5049D33CC68DF29760B398B408 /* NopDisposable.swift */, + A272A3BAB4634A80251132C7FB980D8A /* Observable.swift */, + 3C2489BF8D3C006E1A6E9FA8E1275FC1 /* Observable+Aggregate.swift */, + 7D9E0FD7CAAFFDA1BCA65C0DE4AB27B4 /* Observable+Binding.swift */, + 8CA8E405CD1F1D51078388FDE3498848 /* Observable+Concurrency.swift */, + EBED49C45F40708D9355E7D2CFFE4602 /* Observable+Creation.swift */, + 051BE7827FDD01F32E6822EC2DE1CE1C /* Observable+Debug.swift */, + DB5D61F564F3FF7A53825B0EF70E98B4 /* Observable+Extensions.swift */, + 9B0F57917A904327F2D141C7E2E8623F /* Observable+Multiple.swift */, + 8033FB9B41A3E314A0CC6C50015B835D /* Observable+Single.swift */, + 372C2E8DD6FEE19981359253F88A881F /* Observable+StandardSequenceOperators.swift */, + 8EFB1B59D84F8B11F82B8DF1A2150846 /* Observable+Time.swift */, + D072A90162699810B672895226A27C43 /* ObservableConvertibleType.swift */, + A371B67E1A1BC9D198E470D4B54FEE87 /* ObservableType.swift */, + 315D8F39A79B562AA2268250BED93150 /* ObserveOn.swift */, + 922907F82CF71DEBAE0585263AEF4518 /* ObserveOnSerialDispatchQueue.swift */, + 6F1954F056E7EC88AD642B7E7D937664 /* ObserverBase.swift */, + 0B9FE8B611FD713A03D461C686322726 /* ObserverType.swift */, + A38E6FD240ADA8F1BCE82B9426E6EF8F /* OperationQueueScheduler.swift */, + FC3B7613AC16E246F73123670BAED3F5 /* Platform.Darwin.swift */, + 0668CCF084235C10B605A3F640FB98D8 /* Platform.Linux.swift */, + 1F9095E4F9CC417FB1536F011BCAFACA /* PriorityQueue.swift */, + 7AD0626709B8BF22F5F6B42379D4C1EB /* Producer.swift */, + 84665902C00313BF6D709D279E597AF9 /* PublishSubject.swift */, + 97C78DB1DE41EDF5A70DBAB37DA9904B /* Queue.swift */, + 509773F27764F1FF30E06C5F91E1FF0D /* Range.swift */, + 5DEE36ACBCF70F5F1553D055175D1622 /* RecursiveScheduler.swift */, + D5438FA602118A769102A572D66E5EDD /* Reduce.swift */, + 5ADB3F22CC2D987B4C7E76A7B502DE81 /* RefCount.swift */, + 62EC50E209B29C93EAECE01AD46DBAE7 /* RefCountDisposable.swift */, + B2B14E7D38A4727796ABDFA4079BD210 /* Repeat.swift */, + 19C0FF31F56DFA84FE0CDF777CF56845 /* ReplaySubject.swift */, + 7678CC14BE55592C2250C4C122EADEF3 /* RetryWhen.swift */, + A98250195E2C07F9A7DB5E4BB333ACE9 /* Rx.swift */, + 1F0C939A9E2A83A661C6EA3D4EE8DC54 /* RxMutableBox.swift */, + DBC29FB0F89F4B2B863A122A41D07007 /* Sample.swift */, + FD709EBAF5345AC238B7849DE5BCB273 /* Scan.swift */, + 17881314399342A30A86EF8655AFD35C /* ScheduledDisposable.swift */, + 72DC2CBE50494D6723773E2C3E89C3C1 /* ScheduledItem.swift */, + 07017B36556829104C6CC52B3E0DFDA4 /* ScheduledItemType.swift */, + 10D1C22E4BBFB16E5C966FF77E92F296 /* SchedulerServices+Emulation.swift */, + EC88FCE0410EAE3C16E64A8A8108D142 /* SchedulerType.swift */, + 075BA1FDBF8D0B4B1D383DF8FD3BE509 /* Sequence.swift */, + 1BE009E15582DF43271F4102E7EC30F5 /* SerialDispatchQueueScheduler.swift */, + B7FA9B23245D415690FB894178BBF20F /* SerialDisposable.swift */, + DFB51688711C8369A2961F69330DCC99 /* ShareReplay1.swift */, + 35A3C82BD63330195DE669D3836B7E41 /* ShareReplay1WhileConnected.swift */, + DE3076AFBC266A6E88C8171467D6C5A5 /* SingleAssignmentDisposable.swift */, + BA1AAD8792DE618CDBBF78CA8E642111 /* SingleAsync.swift */, + 37E5E51602A7EC243D3CC5A8B0FBC7E3 /* Sink.swift */, + 99A31BA1E446FA35628A7DED964EF04F /* Skip.swift */, + D69A080DF8671D7B4CEB7E706EF4667F /* SkipUntil.swift */, + 8F329D6196F35CB573BEBA0D2379035F /* SkipWhile.swift */, + BC813A2800E1E5B7D9C9A9A095B0D51E /* StableCompositeDisposable.swift */, + F17B79123C6F61E5E5DBBF14710E6012 /* StartWith.swift */, + 64FED6C504DC2686A1BF8615B1D0213F /* String+Rx.swift */, + E64D15D1795EA999578C393A507A882F /* SubjectType.swift */, + 46BB6E8D195D7B7711B8B0B50213D36B /* SubscribeOn.swift */, + 3F52905F2DED9823E28E154C2CD365A0 /* SubscriptionDisposable.swift */, + 636788473300310D67C31CCE1A571AC4 /* Switch.swift */, + C239D292236A2F59F0F6F5F1DB31795E /* SynchronizedDisposeType.swift */, + B7B5D80C0F71324ED10DBE73D28402DB /* SynchronizedOnType.swift */, + A4D4B50A66CA7EB372C9BCE21D117CEC /* SynchronizedSubscribeType.swift */, + 292B4E8722DE17F6767ABED8D62A4C9E /* SynchronizedUnsubscribeType.swift */, + D02FE9C7BBEB944DACB0B057F631B40C /* TailRecursiveSink.swift */, + 4CAF565A8B834CB6FD86DDFF010D4E4B /* Take.swift */, + 75D5E40EFDE70F2D69310639B473B817 /* TakeLast.swift */, + 2AC78F9679615E991FC6F18D85FCF21C /* TakeUntil.swift */, + 72F5796E9AA6A65EA2149A206ADE4289 /* TakeWhile.swift */, + 31D3B68FA022AAECF54F3CBFB928B666 /* Throttle.swift */, + EDC79FC8F9A849970B716868E7F51D2C /* Timeout.swift */, + A03FE8BD209B0504BE052CBD44BD277A /* Timer.swift */, + 17534D83D8298C9D739F4506816D218F /* ToArray.swift */, + 93ECB6F232D07DFDE4F782C41FFD85FE /* Using.swift */, + 101E84FB1E5F4A753DAF7518FB9BF0A7 /* Variable.swift */, + 3B5E5E7372652C9D351B65002A966365 /* VirtualTimeConverterType.swift */, + 25C6BCDF18A3A22B7FEDE36B0A580C0E /* VirtualTimeScheduler.swift */, + 81BA6471D19E57603D3AF0A0A49939B9 /* Window.swift */, + 7E2F61612759130FD3873E3FBE0E2CC0 /* WithLatestFrom.swift */, + 321E8BEC99166D3ED7E88CDBACBE407A /* Zip.swift */, + ACF6B90536554BCC5A32E2DC7731D9FD /* Zip+arity.swift */, + 6204091F721976FA7C97D74AC93B9637 /* Zip+CollectionType.swift */, + A45143F0CEA87E55D6F93C6DF7BD1446 /* Support Files */, + ); + path = RxSwift; + sourceTree = ""; + }; + 5E2543AE40E062857224EB1DCE80B9E3 /* iOS */ = { + isa = PBXGroup; + children = ( + 9610BA4403551C05999CF892D495F516 /* Foundation.framework */, + ); + name = iOS; + sourceTree = ""; + }; + 69750F9014CEFA9B29584C65B2491D2E /* Frameworks */ = { + isa = PBXGroup; + children = ( + AA9C5856BEAE5090A7D1EB450A10C04F /* Alamofire.framework */, + 19296A8C5E948345E5744A748B1CC720 /* RxSwift.framework */, + 5E2543AE40E062857224EB1DCE80B9E3 /* iOS */, + ); + name = Frameworks; + sourceTree = ""; + }; + 771D190F914310F450FF47756BC0DD0F /* Support Files */ = { + isa = PBXGroup; + children = ( + 6EBAF7A3F8D6D888BC91244485ECD2AA /* Alamofire.modulemap */, + 66429A42B7499250307412ECB7AF627E /* Alamofire.xcconfig */, + 14BA42A836361E4416D38DECBEFE25C0 /* Alamofire-dummy.m */, + 1C7A9744D1553CE8C58822392FE251D8 /* Alamofire-prefix.pch */, + 3341D7B714515136B34354D7D32202DB /* Alamofire-umbrella.h */, + 14F8F74E862AC5CA39F8E5132F1C00B9 /* Info.plist */, + ); + name = "Support Files"; + path = "../Target Support Files/Alamofire"; + sourceTree = ""; + }; + 7DB346D0F39D3F0E887471402A8071AB = { + isa = PBXGroup; + children = ( + 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */, + 22F52349E1BE90FC6E064DAAC9EA9612 /* Development Pods */, + 69750F9014CEFA9B29584C65B2491D2E /* Frameworks */, + 920125D5A6247D4AF2FAB58D0148CAD8 /* Pods */, + C1398CE2D296EEBAA178C160CA6E6AD6 /* Products */, + C1A60D10CED0E61146591438999C7502 /* Targets Support Files */, + ); + sourceTree = ""; + }; + 88CE2B3F08C34DDB098AD8A5DCC1DF1E /* Pods-SwaggerClient */ = { + isa = PBXGroup; + children = ( + 7C8E63660D346FD8ED2A97242E74EA09 /* Info.plist */, + DE164497A94DD3215ED4D1AE0D4703B1 /* Pods-SwaggerClient.modulemap */, + 2FF17440CCD2E1A69791A4AA23325AD5 /* Pods-SwaggerClient-acknowledgements.markdown */, + E1E4BCB344D3C100253B24B79421F00A /* Pods-SwaggerClient-acknowledgements.plist */, + 291054DAA3207AFC1F6B3D7AD6C25E5C /* Pods-SwaggerClient-dummy.m */, + BCF2D4DFF08D2A18E8C8FE4C4B4633FB /* Pods-SwaggerClient-frameworks.sh */, + D2841E5E2183846280B97F6E660DA26C /* Pods-SwaggerClient-resources.sh */, + 3EEBA91980AEC8774CF7EC08035B089A /* Pods-SwaggerClient-umbrella.h */, + 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */, + 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */, + ); + name = "Pods-SwaggerClient"; + path = "Target Support Files/Pods-SwaggerClient"; + sourceTree = ""; + }; + 8F6D133867EE63820DFB7E83F4C51252 /* Support Files */ = { + isa = PBXGroup; + children = ( + F0D4E00A8974E74325E9E53D456F9AD4 /* Info.plist */, + E3D1141B63DF38660CD6F3AC588A782B /* PetstoreClient.modulemap */, + DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */, + 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */, + B3A144887C8B13FD888B76AB096B0CA1 /* PetstoreClient-prefix.pch */, + 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */, + ); + name = "Support Files"; + path = "SwaggerClientTests/Pods/Target Support Files/PetstoreClient"; + sourceTree = ""; + }; + 920125D5A6247D4AF2FAB58D0148CAD8 /* Pods */ = { + isa = PBXGroup; + children = ( + E4310C54179D230C8E716E0BF52E4F90 /* Alamofire */, + 530337216701C70B5DE636BF1B3DB0C5 /* RxSwift */, + ); + name = Pods; + sourceTree = ""; + }; + A45143F0CEA87E55D6F93C6DF7BD1446 /* Support Files */ = { + isa = PBXGroup; + children = ( + 25D1E84FDF56D9C05CACE85F684D9965 /* Info.plist */, + 8611EB072B953093474C20B1B11F76CC /* RxSwift.modulemap */, + D0A71420D33D17B1C771C1CC7ADD8258 /* RxSwift.xcconfig */, + 24D7DE1FFF6AE5D438E4DAC777A8B8F2 /* RxSwift-dummy.m */, + 9D510BAAE86BD9AA107EBEE6C81330BB /* RxSwift-prefix.pch */, + BDA5F3724FE84CF94299E36A8DF89017 /* RxSwift-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/RxSwift"; + sourceTree = ""; + }; + AD94092456F8ABCB18F74CAC75AD85DE /* Classes */ = { + isa = PBXGroup; + children = ( + F64549CFCC17C7AC6479508BE180B18D /* Swaggers */, + ); + path = Classes; + sourceTree = ""; + }; + C1398CE2D296EEBAA178C160CA6E6AD6 /* Products */ = { + isa = PBXGroup; + children = ( + 5B598E168B47485DC60F9DBBCBEEF5BB /* Alamofire.framework */, + E9CBBB398E7A62950FA8BC091CBE0359 /* PetstoreClient.framework */, + 057FC3E5DE19EA8F4DD600557D771032 /* Pods_SwaggerClient.framework */, + C4B474BD9070828C0F786071EEF46CD0 /* Pods_SwaggerClientTests.framework */, + 84A09D760BA2EA13D5BE269086BAD34C /* RxSwift.framework */, + ); + name = Products; + sourceTree = ""; + }; + C1A60D10CED0E61146591438999C7502 /* Targets Support Files */ = { + isa = PBXGroup; + children = ( + 88CE2B3F08C34DDB098AD8A5DCC1DF1E /* Pods-SwaggerClient */, + D6D0CD30E3EAF2ED10AE0CBC07506C5A /* Pods-SwaggerClientTests */, + ); + name = "Targets Support Files"; + sourceTree = ""; + }; + D6D0CD30E3EAF2ED10AE0CBC07506C5A /* Pods-SwaggerClientTests */ = { + isa = PBXGroup; + children = ( + 3F16B43ABD2C8CD4A311AA1AB3B6C02F /* Info.plist */, + 00ACB4396DD1B4E4539E4E81C1D7A14E /* Pods-SwaggerClientTests.modulemap */, + FB170EFD14935F121CDE3211DB4C5CA3 /* Pods-SwaggerClientTests-acknowledgements.markdown */, + 02F28E719AA874BE9213D6CF8CE7E36B /* Pods-SwaggerClientTests-acknowledgements.plist */, + 687B19CB3E722272B41D60B485C29EE7 /* Pods-SwaggerClientTests-dummy.m */, + 43FC49AA70D3E2A84CAED9C37BE9C4B5 /* Pods-SwaggerClientTests-frameworks.sh */, + E4E6F4A58FE7868CA2177D3AC79AD2FA /* Pods-SwaggerClientTests-resources.sh */, + F22FE315AC1C04A8749BD18281EE9028 /* Pods-SwaggerClientTests-umbrella.h */, + 969C2AF48F4307163B301A92E78AFCF2 /* Pods-SwaggerClientTests.debug.xcconfig */, + 849FECBC6CC67F2B6800F982927E3A9E /* Pods-SwaggerClientTests.release.xcconfig */, + ); + name = "Pods-SwaggerClientTests"; + path = "Target Support Files/Pods-SwaggerClientTests"; + sourceTree = ""; + }; + E4310C54179D230C8E716E0BF52E4F90 /* Alamofire */ = { + isa = PBXGroup; + children = ( + 621056D7E34F3276D7ECDB147918DBEC /* Alamofire.swift */, + 64491633490DB74E1E8D2CED2021C746 /* Download.swift */, + 526E73E2F71E0EC1442DFF1E6C3D7626 /* Error.swift */, + 25A12681F026446EDBE1C55D22872F9D /* Manager.swift */, + A7D21C15998D42252EF80A55181C7D18 /* MultipartFormData.swift */, + 3107BC52C0E01198FAE330F1ADC0BF3C /* ParameterEncoding.swift */, + 86C5082D39612A1F1FD675C33932AEC9 /* Request.swift */, + 3EB61DA897ED3DE273EC2B5824A42DF0 /* Response.swift */, + A56FED751BA06FF779D945B5D478065C /* ResponseSerialization.swift */, + BABA671A27CF29C8AA31D5C66D34CBA3 /* Result.swift */, + 6C4F5E9ABF91F6B2FF369456D3804258 /* ServerTrustPolicy.swift */, + 6EF1F005F839FD46AD74F13986274F1B /* Stream.swift */, + 8E78A6B0E3334E11FE5615FE4CC506E8 /* Upload.swift */, + F31DEFD11FF950B319F5E3A97C41178F /* Validation.swift */, + 771D190F914310F450FF47756BC0DD0F /* Support Files */, + ); + path = Alamofire; + sourceTree = ""; + }; + E73D9BF152C59F341559DE62A3143721 /* PetstoreClient */ = { + isa = PBXGroup; + children = ( + AD94092456F8ABCB18F74CAC75AD85DE /* Classes */, + ); + path = PetstoreClient; + sourceTree = ""; + }; + E9F8459055B900A58FB97600A53E5D1C /* PetstoreClient */ = { + isa = PBXGroup; + children = ( + E73D9BF152C59F341559DE62A3143721 /* PetstoreClient */, + 8F6D133867EE63820DFB7E83F4C51252 /* Support Files */, + ); + name = PetstoreClient; + path = ../..; + sourceTree = ""; + }; + F64549CFCC17C7AC6479508BE180B18D /* Swaggers */ = { + isa = PBXGroup; + children = ( + 92734297B64DFE0EB0EDE1EA821163DB /* AlamofireImplementations.swift */, + D2BAD338E56EF3CAA6E54490FE0C5DF9 /* APIHelper.swift */, + D8072E1108951F272C003553FC8926C7 /* APIs.swift */, + 5412898DEB10F1983487A10453C6B9CB /* Extensions.swift */, + 8F0266C5AE0B23A436291F6647902086 /* Models.swift */, + F92EFB558CBA923AB1CFA22F708E315A /* APIs */, + 1322FED69118C64DAD026CAF7F4C38C6 /* Models */, + ); + path = Swaggers; + sourceTree = ""; + }; + F92EFB558CBA923AB1CFA22F708E315A /* APIs */ = { + isa = PBXGroup; + children = ( + 261F03A3C73374FD19333EEA59CCD59F /* PetAPI.swift */, + 1A3E5E3CD673B025FD8AC260E67AB47E /* StoreAPI.swift */, + 552D15E0340BF58CC1922B82E864AEC9 /* UserAPI.swift */, + ); + path = APIs; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 0B076F0166D87A519E5251C471131E44 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 69AC467220269CE474E1C1156912C9DD /* RxSwift-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5F7B61281F714E2A64A51E80A2C9C062 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 2C5450AC69398958CF6F7539EF7D99E5 /* Alamofire-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 99AE2032DA4A773DFF2E835A8D453117 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + DFF7D509E6FC70067A71C1CF0441AD48 /* PetstoreClient-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 9C8BBB69FE8BD651A7BBC07E32AED31A /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 725EED04ED27CA8159CB2683F1EFD45A /* Pods-SwaggerClient-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FF84DA06E91FBBAA756A7832375803CE /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 897283A0B7F5299913327CC8FD6CC997 /* Pods-SwaggerClientTests-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 432ECC54282C84882B482CCB4CF227FC /* Alamofire */ = { + isa = PBXNativeTarget; + buildConfigurationList = 8B2B2DA2F7F80D41B1FDB5FACFA4B3DE /* Build configuration list for PBXNativeTarget "Alamofire" */; + buildPhases = ( + EF659EFF40D426A3A32A82CDB98CC6EE /* Sources */, + A5AE1D340C4A0691EC28EEA8241C9FCD /* Frameworks */, + 5F7B61281F714E2A64A51E80A2C9C062 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Alamofire; + productName = Alamofire; + productReference = 5B598E168B47485DC60F9DBBCBEEF5BB /* Alamofire.framework */; + productType = "com.apple.product-type.framework"; + }; + 462B200BD111D7F438E47B7C42B6772F /* Pods-SwaggerClientTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 245A935A321D16F418F4D34C5D17D2B6 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClientTests" */; + buildPhases = ( + 0529825EC79AED06C77091DC0F061854 /* Sources */, + FE8FC779CF4B0CFCC594E81C0FF86C7E /* Frameworks */, + FF84DA06E91FBBAA756A7832375803CE /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "Pods-SwaggerClientTests"; + productName = "Pods-SwaggerClientTests"; + productReference = C4B474BD9070828C0F786071EEF46CD0 /* Pods_SwaggerClientTests.framework */; + productType = "com.apple.product-type.framework"; + }; + 7E04F4E0C9D1C499E7C5C2E0653893A5 /* Pods-SwaggerClient */ = { + isa = PBXNativeTarget; + buildConfigurationList = C17E886D20DFCEDEFC84423D6652F7EE /* Build configuration list for PBXNativeTarget "Pods-SwaggerClient" */; + buildPhases = ( + EDDE9277BF55CC0EE317B81A0DB026A1 /* Sources */, + 05BA91ABD8AC918A49A9D7E0E3722C70 /* Frameworks */, + 9C8BBB69FE8BD651A7BBC07E32AED31A /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + C9B7EA4A29DBD0225CC347E19EBAC59F /* PBXTargetDependency */, + 31D9C92344926342E3D2800111C05269 /* PBXTargetDependency */, + 57DC5B1E798B66E24E2BEC74CDB6BDF2 /* PBXTargetDependency */, + ); + name = "Pods-SwaggerClient"; + productName = "Pods-SwaggerClient"; + productReference = 057FC3E5DE19EA8F4DD600557D771032 /* Pods_SwaggerClient.framework */; + productType = "com.apple.product-type.framework"; + }; + B3F4219972B712BDBD25392781A43848 /* PetstoreClient */ = { + isa = PBXNativeTarget; + buildConfigurationList = F609276975EA85CEC0F2AA47BE77CDBD /* Build configuration list for PBXNativeTarget "PetstoreClient" */; + buildPhases = ( + CABD7A5E996838E97D6AE9D1E4A47DE6 /* Sources */, + CB2482011FA929C2BCC3E41A1B6E02E1 /* Frameworks */, + 99AE2032DA4A773DFF2E835A8D453117 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + 9351A33C64C743193D9663213D4582BD /* PBXTargetDependency */, + F461599241C7FC6B0184BF7BAAEF658C /* PBXTargetDependency */, + ); + name = PetstoreClient; + productName = PetstoreClient; + productReference = E9CBBB398E7A62950FA8BC091CBE0359 /* PetstoreClient.framework */; + productType = "com.apple.product-type.framework"; + }; + F316854D76F084E9539BFEF85DCBCF9D /* RxSwift */ = { + isa = PBXNativeTarget; + buildConfigurationList = 7335F4AA774EFBDED5B7673EF35FCF11 /* Build configuration list for PBXNativeTarget "RxSwift" */; + buildPhases = ( + 26ED5385D63D1F6761BEF3EA5FAE7165 /* Sources */, + 76130794E62D45206C62CE83429B6CF2 /* Frameworks */, + 0B076F0166D87A519E5251C471131E44 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = RxSwift; + productName = RxSwift; + productReference = 84A09D760BA2EA13D5BE269086BAD34C /* RxSwift.framework */; + productType = "com.apple.product-type.framework"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + D41D8CD98F00B204E9800998ECF8427E /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0730; + LastUpgradeCheck = 0700; + }; + buildConfigurationList = 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + ); + mainGroup = 7DB346D0F39D3F0E887471402A8071AB; + productRefGroup = C1398CE2D296EEBAA178C160CA6E6AD6 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 432ECC54282C84882B482CCB4CF227FC /* Alamofire */, + B3F4219972B712BDBD25392781A43848 /* PetstoreClient */, + 7E04F4E0C9D1C499E7C5C2E0653893A5 /* Pods-SwaggerClient */, + 462B200BD111D7F438E47B7C42B6772F /* Pods-SwaggerClientTests */, + F316854D76F084E9539BFEF85DCBCF9D /* RxSwift */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXSourcesBuildPhase section */ + 0529825EC79AED06C77091DC0F061854 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + C546890220177F840E8AFC829D0E3FEB /* Pods-SwaggerClientTests-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 26ED5385D63D1F6761BEF3EA5FAE7165 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 22C91CF507223CEE1A7E1302E912DC8B /* AddRef.swift in Sources */, + CD00FDDA48E9BC390530672F9F09D8CF /* Amb.swift in Sources */, + B22405A127912A4943AEFBDD57E7A267 /* AnonymousDisposable.swift in Sources */, + 84B93CFEFA6412E49988C92153998357 /* AnonymousInvocable.swift in Sources */, + 4F8D754FA3405C5B692B644166A0F02A /* AnonymousObservable.swift in Sources */, + 77D1DB57FAA744C6ECBA7242836D6479 /* AnonymousObserver.swift in Sources */, + 751E794A58F9FCB7738D4ED30D10DD19 /* AnyObserver.swift in Sources */, + ADC582F488BC636CC4292513053F6992 /* AsyncLock.swift in Sources */, + D190592C39D806474770AF30FCC4EF4E /* Bag.swift in Sources */, + 9543E1505CCD2189D86456DAA0D55A22 /* BehaviorSubject.swift in Sources */, + 4DB1B23F5FAF7C5E02520AFE08646AF2 /* BinaryDisposable.swift in Sources */, + 96A03A2C4325A59DE2B02913FE351815 /* BooleanDisposable.swift in Sources */, + A606E44DA4B92B1FFBA177125D55F6AA /* Buffer.swift in Sources */, + 8BDC4F0F424CA9A8190F28E7A02417A8 /* Cancelable.swift in Sources */, + 39F4B474510DFC1711DD2EF809EA101B /* Catch.swift in Sources */, + B0F20FEA2B9A800D016EF5B46EFDECE9 /* CombineLatest+arity.swift in Sources */, + 04509FBE687E186C45C9E2F78E6F6946 /* CombineLatest+CollectionType.swift in Sources */, + 99F6DFF51E7C238DF99CA788144C732A /* CombineLatest.swift in Sources */, + 00A528BBED5B1D5DF26B8ADE64C5B3F2 /* CompositeDisposable.swift in Sources */, + 3DAFF4DA4C977B85B5C5B35728001AF2 /* Concat.swift in Sources */, + 028C4C90CAA75222DAA6CA7B37F16A84 /* ConcurrentDispatchQueueScheduler.swift in Sources */, + FEDA6187E5CC1CFB1781F8F4947E160C /* ConcurrentMainScheduler.swift in Sources */, + 030667BEF4154402A2317126A893E459 /* ConnectableObservable.swift in Sources */, + 1CBCB4FF2C9CDB144871C2A0856EB44D /* ConnectableObservableType.swift in Sources */, + ECFCC7B806126EF7788D0DE094711905 /* CurrentThreadScheduler.swift in Sources */, + F460F46DBA5EE0D4FABB3CD0BEFE6CE3 /* Debug.swift in Sources */, + 434C2C5108A8B9EEA916566F7DB0EDF6 /* Deferred.swift in Sources */, + 5997C0F97BD6687648224D5C6442B862 /* DelaySubscription.swift in Sources */, + 956216483BCB853794F52B0292831E9C /* DispatchQueueSchedulerQOS.swift in Sources */, + E51F4BE281ADBC629708A4D131E9190C /* Disposable.swift in Sources */, + 98FA1CFF63A5E74A7DB3255DA60C1843 /* DisposeBag.swift in Sources */, + 58023FA401993154E36E604471265263 /* DisposeBase.swift in Sources */, + 3AAB4B14DB0A02456F909B482400C142 /* DistinctUntilChanged.swift in Sources */, + AF3E5D2CE5E3448DB881E0F40F2F334F /* Do.swift in Sources */, + 4A216C127342712EDE589085CBB58962 /* ElementAt.swift in Sources */, + 5BD263D28F10A84969A6521CA166957C /* Empty.swift in Sources */, + 92450B928E8001F2B28A80072611F4C1 /* Error.swift in Sources */, + 498A556404BCE59DD962113CD29165A0 /* Errors.swift in Sources */, + BB3A568E8ED6C1792B43708A36A66F3D /* Event.swift in Sources */, + D180CF545583D5DCDF770FBAA36F5DB0 /* Filter.swift in Sources */, + A67CCBFC004EF58E785FA7ED4A1B69B6 /* Generate.swift in Sources */, + 22C9E40BB4DFB30DAAFD8555EF69BC08 /* HistoricalScheduler.swift in Sources */, + 5C8C1A80AB947F293430868D52A910C2 /* HistoricalSchedulerTimeConverter.swift in Sources */, + A4FBC2BD1A93FA52B5C97E79CDB9302F /* ImmediateScheduler.swift in Sources */, + 55D355CC26824B52E1A7420802FB5DC5 /* ImmediateSchedulerType.swift in Sources */, + C3739BDF471B57AECC84085608EC9CE6 /* InfiniteSequence.swift in Sources */, + 207AB9AAE48F202AF774554ED7545D98 /* InvocableScheduledItem.swift in Sources */, + 26E95A382D3F6848E571EF506D91B1C1 /* InvocableType.swift in Sources */, + 0487B12B08D927162A20CB2A56A2D077 /* Just.swift in Sources */, + 72CF8071AF37B85C1DE763805C39A3AB /* Lock.swift in Sources */, + F2246690EA6DEBF52D4CACA089B7FFC0 /* LockOwnerType.swift in Sources */, + B590B3C59D3A327452D2532766F2F630 /* MainScheduler.swift in Sources */, + 0D6AD3708152BB59E38D5839A0B0377F /* Map.swift in Sources */, + 4266AE0D8F9A4FA69F408AAC9118320A /* Merge.swift in Sources */, + 5BDF0811AEFBD49A7DE4AF35DA3BD34F /* Multicast.swift in Sources */, + E16A421C7269D0E81CB5E59344E63391 /* NAryDisposable.swift in Sources */, + 2023E24B94C04CC05DDFB499ECA760FB /* Never.swift in Sources */, + 00D1D0E4C3E6F9EA952C2EDEF2C13DE9 /* NopDisposable.swift in Sources */, + 7A6597623E723E6F8350D2CA30A2CD9C /* Observable+Aggregate.swift in Sources */, + D99C59116FC2BC799C9C9DE4D0282EB9 /* Observable+Binding.swift in Sources */, + A0A18CB5F889D7C2F80D6024EA568BEA /* Observable+Concurrency.swift in Sources */, + 618251D2C3027F214154D2CDFE1900AB /* Observable+Creation.swift in Sources */, + 501A111A5AE07BC13E3265DB49EE0A1B /* Observable+Debug.swift in Sources */, + EE42701AD3887754AF7695978852957E /* Observable+Extensions.swift in Sources */, + 68614EDB167FFFA6FBEC851368044FB3 /* Observable+Multiple.swift in Sources */, + 731E6ACE4939DCE8F6AF47FA1A00D595 /* Observable+Single.swift in Sources */, + E61B26D220A1A27E3BE7AD3F9BE35C76 /* Observable+StandardSequenceOperators.swift in Sources */, + 165531B0C3FF4D343825C3DB0B79FD68 /* Observable+Time.swift in Sources */, + DA18B15A9632B7282CF91FE4771C0B60 /* Observable.swift in Sources */, + E315A5FF56451DF73C7FE3140D5E2C6C /* ObservableConvertibleType.swift in Sources */, + 2BEA24EE395DA16EFEBC08B8D450F00A /* ObservableType.swift in Sources */, + 6414AAC9ED1AD7417B005D50D04341F5 /* ObserveOn.swift in Sources */, + CF13D1D873436D3890EC7392DEDE0B3E /* ObserveOnSerialDispatchQueue.swift in Sources */, + 88CCC2ADA43F75CB4708A701F5031643 /* ObserverBase.swift in Sources */, + 8D3CD54E3BACC9DB116DDA2DC30420CF /* ObserverType.swift in Sources */, + CA4A98FD2226B57E5F59E0BA2E1A97EC /* OperationQueueScheduler.swift in Sources */, + 6007585CC5912D979404BDB047CD36C4 /* Platform.Darwin.swift in Sources */, + D4789D8318C97E380412D03C1C321A88 /* Platform.Linux.swift in Sources */, + AC265ECE8E2AF91D58A755022E7DF802 /* PriorityQueue.swift in Sources */, + 4CA85A5CF8897D7D46BC6D0D76C8189A /* Producer.swift in Sources */, + DB5B0A5C01527330DCD4CEF9740C7140 /* PublishSubject.swift in Sources */, + B754E33E17893DF35DECA754DE819A66 /* Queue.swift in Sources */, + D0F5068C6F5C0489E8A41A9912A09016 /* Range.swift in Sources */, + AD9D268210ED449C3BE591513FD0CFB8 /* RecursiveScheduler.swift in Sources */, + 07E83400AACF1430C5B3DF482167A0F1 /* Reduce.swift in Sources */, + 3ADB6687421BF63BCC8A8C8D62E0C4F2 /* RefCount.swift in Sources */, + 66D9046FEDE40E6732F8B3E090007268 /* RefCountDisposable.swift in Sources */, + 5B721FAF55FEDB8046F23843565833A2 /* Repeat.swift in Sources */, + B28CA824CA5CD903042D8A07E9C5950E /* ReplaySubject.swift in Sources */, + 0A5F6F590DCE147853B2E21487ABA4AA /* RetryWhen.swift in Sources */, + 437C3354F611D5412125ADF24F4FDEE1 /* Rx.swift in Sources */, + 1A11209BABC1DE84187BFAEA3E91602D /* RxMutableBox.swift in Sources */, + B33369A55E29C11FA5F5977B5A47F1D4 /* RxSwift-dummy.m in Sources */, + 0607BCCDD781FF7FFD3629BF4A8BAD23 /* Sample.swift in Sources */, + 107E73472222CFD28A8C640F332DA52A /* Scan.swift in Sources */, + 0268E70939A7BFBC91C0557D16DDD027 /* ScheduledDisposable.swift in Sources */, + 4EF8849290BCC9D36D8D75969F6753E7 /* ScheduledItem.swift in Sources */, + BC10CEE813861D2F71E501E2F06532AB /* ScheduledItemType.swift in Sources */, + 0AEB6185484DD9137068A40CE70D4B85 /* SchedulerServices+Emulation.swift in Sources */, + 23CA1BD96C4742DE71082211C8DBFF5F /* SchedulerType.swift in Sources */, + 7E6DD4CEE210B03B7E3A0F01A36A7624 /* Sequence.swift in Sources */, + A23E9C4262ED3ED9FF20A9E6E1FA2121 /* SerialDispatchQueueScheduler.swift in Sources */, + 4AE52A909A95E3E4A6DC2F48BD8FC758 /* SerialDisposable.swift in Sources */, + 85E0465919F9DC7C97DD593CB49BB5E0 /* ShareReplay1.swift in Sources */, + 7F8297BE677C9A67B915F044DB16C0BE /* ShareReplay1WhileConnected.swift in Sources */, + 12999CCB3E22F57CB230F85534EF6930 /* SingleAssignmentDisposable.swift in Sources */, + 3EE9F1D7EB9C05CB5821E18136EF812E /* SingleAsync.swift in Sources */, + 4C5244B7F2D69F1DFC083E31070E3B0F /* Sink.swift in Sources */, + 33393FE8FB3933A22617E02FA3FFA780 /* Skip.swift in Sources */, + 79F6454BBF28D094A211494E22A07327 /* SkipUntil.swift in Sources */, + B7DCF4199B0EEF4CB2FE0DFF23F99049 /* SkipWhile.swift in Sources */, + B45CADB404E006E0EA39D7239C81C64F /* StableCompositeDisposable.swift in Sources */, + E8CAB3FA190277C8E609F992A51EA9D2 /* StartWith.swift in Sources */, + 9C824A364077ED1458CEF9776F2FB44A /* String+Rx.swift in Sources */, + 04923B3851BD1F857A9B207EE9EC8CDB /* SubjectType.swift in Sources */, + DC9EF51CEA903F88D43F7B3A96923DFD /* SubscribeOn.swift in Sources */, + CDF08B0C84BE839E79DF99C271453406 /* SubscriptionDisposable.swift in Sources */, + 3200EF8FA76EE92E0108DF928FB39CCB /* Switch.swift in Sources */, + C5099A3F4D955165F503506F2D10065D /* SynchronizedDisposeType.swift in Sources */, + 717576C9ABD8ABE8163D441ABE1C4A8D /* SynchronizedOnType.swift in Sources */, + 159C262BD23A08981D11D3B94340848B /* SynchronizedSubscribeType.swift in Sources */, + 313FCC5057970674AB6016DEF7A05902 /* SynchronizedUnsubscribeType.swift in Sources */, + 527C7425A5831BFC30CC9EC216506393 /* TailRecursiveSink.swift in Sources */, + 7F82F4EE1BA91C32CE75312176ACD4F0 /* Take.swift in Sources */, + 480B2F9937EF953E12DE12FCB177C32A /* TakeLast.swift in Sources */, + D932A3F3727B26175B547BA865A76B81 /* TakeUntil.swift in Sources */, + 5CF87E88489D3832C46FAFCE191F78F9 /* TakeWhile.swift in Sources */, + 9C3C83B09DE882AA526C40FDA31B69C8 /* Throttle.swift in Sources */, + 7574EBA19BA114D77C76D2CC1B58E73C /* Timeout.swift in Sources */, + C6EFFFF6D9947B99945FE08559733EF6 /* Timer.swift in Sources */, + 82DB09296E2BC713C6D363528657A3FD /* ToArray.swift in Sources */, + D5ECB1C860D3F53280EE2C5E54D470BD /* Using.swift in Sources */, + 2DF21CC164C25ED6947C67198879DE12 /* Variable.swift in Sources */, + 7E11CAC09AC72BD412078441E2F7BC21 /* VirtualTimeConverterType.swift in Sources */, + FFDD18622776D270EAFE1CF94726C96D /* VirtualTimeScheduler.swift in Sources */, + 84B43422CBE09278E477D1BFF27B07A1 /* Window.swift in Sources */, + 252E1D07E589566E0B8F49C2B9131976 /* WithLatestFrom.swift in Sources */, + BB5C8DC43B5072BBC05F56BF4DFD8CC5 /* Zip+arity.swift in Sources */, + 402BB7DBAC4D93AD381A0075D7BDDDBA /* Zip+CollectionType.swift in Sources */, + B0EAF63B91ABFD39C96353392D157D19 /* Zip.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + CABD7A5E996838E97D6AE9D1E4A47DE6 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 983C8A7CA7087B8FD905B6392B05B790 /* AlamofireImplementations.swift in Sources */, + 54325B7F87498350C604C429751BEC97 /* APIHelper.swift in Sources */, + 08D2C4B252A264F837733A22CBFB2481 /* APIs.swift in Sources */, + 569684CF06CEDCEA569BEC7910FC6E5B /* Category.swift in Sources */, + 75D86B4420906282E6B3393E98837360 /* Extensions.swift in Sources */, + BB03FC085AE6A19821878DE92116DDD5 /* Models.swift in Sources */, + A1B963DD34D20B255430C99DD78A1D43 /* Order.swift in Sources */, + DA202CAFA730E897B4D302C8C603A7E1 /* Pet.swift in Sources */, + AFF9AA31B242BF7F011D018D1B2A12FC /* PetAPI.swift in Sources */, + 4E1394BCD39E2E3470805196E884B68B /* PetstoreClient-dummy.m in Sources */, + 8634F37209E5506667C604C1973F630D /* StoreAPI.swift in Sources */, + 4B059D5D108F9D2A4E51A6D1B477A2F5 /* Tag.swift in Sources */, + 0A9698AC9DD60FC3721809C6AB9BCE81 /* User.swift in Sources */, + 97AB8959ABA0C9B8D4F400FD814BBB65 /* UserAPI.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + EDDE9277BF55CC0EE317B81A0DB026A1 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 8B68A752ED9CC80E5478E4FEC5A5F721 /* Pods-SwaggerClient-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + EF659EFF40D426A3A32A82CDB98CC6EE /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + B6D2DC3E3DA44CD382B9B425F40E11C1 /* Alamofire-dummy.m in Sources */, + B0FB4B01682814B9E3D32F9DC4A5E762 /* Alamofire.swift in Sources */, + A3505FA2FB3067D53847AD288AC04F03 /* Download.swift in Sources */, + D75CA395D510E08C404E55F5BDAE55CE /* Error.swift in Sources */, + A2C172FE407C0BC3478ADCA91A6C9CEC /* Manager.swift in Sources */, + 8399DBEE3E2D98EB1F466132E476F4D9 /* MultipartFormData.swift in Sources */, + 4DE5FCC41D100B113B6645EA64410F16 /* ParameterEncoding.swift in Sources */, + FC14480CECE872865A9C6E584F886DA3 /* Request.swift in Sources */, + 03F494989CC1A8857B68A317D5D6860F /* Response.swift in Sources */, + D21B7325B3642887BFBE977E021F2D26 /* ResponseSerialization.swift in Sources */, + 82971968CBDAB224212EEB4607C9FB8D /* Result.swift in Sources */, + 80F496237530D382A045A29654D8C11C /* ServerTrustPolicy.swift in Sources */, + FEF0D7653948988B804226129471C1EC /* Stream.swift in Sources */, + 0681ADC8BAE2C3185F13487BAAB4D9DD /* Upload.swift in Sources */, + C75519F0450166A6F28126ECC7664E9C /* Validation.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 31D9C92344926342E3D2800111C05269 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = PetstoreClient; + target = B3F4219972B712BDBD25392781A43848 /* PetstoreClient */; + targetProxy = D6508A8A1DB5D04976ECA9641101DB50 /* PBXContainerItemProxy */; + }; + 57DC5B1E798B66E24E2BEC74CDB6BDF2 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxSwift; + target = F316854D76F084E9539BFEF85DCBCF9D /* RxSwift */; + targetProxy = 1E7EDC9660FD64A123EAC6BDA4C055AC /* PBXContainerItemProxy */; + }; + 9351A33C64C743193D9663213D4582BD /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = 432ECC54282C84882B482CCB4CF227FC /* Alamofire */; + targetProxy = 1B1D2D2B5F790067C63584DC46E8DEED /* PBXContainerItemProxy */; + }; + C9B7EA4A29DBD0225CC347E19EBAC59F /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = 432ECC54282C84882B482CCB4CF227FC /* Alamofire */; + targetProxy = 80996B8BB3446668F158E7817336A6E4 /* PBXContainerItemProxy */; + }; + F461599241C7FC6B0184BF7BAAEF658C /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxSwift; + target = F316854D76F084E9539BFEF85DCBCF9D /* RxSwift */; + targetProxy = C11AB97FC44865EAFD37FD7629B96B72 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 00BCE7A03AB3EB1357203501EA6FCC84 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = D0A71420D33D17B1C771C1CC7ADD8258 /* RxSwift.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/RxSwift/RxSwift-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/RxSwift/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/RxSwift/RxSwift.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = RxSwift; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 2B14898A0D927578A91AF17061B0704F /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 86B1DDCB9E27DF43C2C35D9E7B2E84DA /* Pods-SwaggerClient.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClient/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.3; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_SwaggerClient; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 3FA451D268613890FA8A5A03801E11D5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = YES; + ENABLE_NS_ASSERTIONS = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_RELEASE=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.3; + STRIP_INSTALLED_PRODUCT = NO; + SYMROOT = "${SRCROOT}/../build"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 5E62115DE8C09934BF8D2FE5D15FED1E /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_DEBUG=1", + "DEBUG=1", + "$(inherited)", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.3; + ONLY_ACTIVE_ARCH = YES; + STRIP_INSTALLED_PRODUCT = NO; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Debug; + }; + 8710426EC015A0183026219312A2B17E /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/PetstoreClient/PetstoreClient-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/PetstoreClient/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/PetstoreClient/PetstoreClient.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = PetstoreClient; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 99EA0FE8990CDA4F2B5110D22698851E /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 849FECBC6CC67F2B6800F982927E3A9E /* Pods-SwaggerClientTests.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClientTests/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.3; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_SwaggerClientTests; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 9B259A01C5DDE12EA25530F7D005A3D2 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 969C2AF48F4307163B301A92E78AFCF2 /* Pods-SwaggerClientTests.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClientTests/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.3; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_SwaggerClientTests; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 9B26D3A39011247999C097562A550399 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 66429A42B7499250307412ECB7AF627E /* Alamofire.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + AD723F120D0CDC6265BA516FE35A9BEB /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 549C6527D10094289B101749047807C5 /* Pods-SwaggerClient.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-SwaggerClient/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.3; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_SwaggerClient; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + B0B4110B60B5F7F6D72CFA5E690CEF32 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = D0A71420D33D17B1C771C1CC7ADD8258 /* RxSwift.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/RxSwift/RxSwift-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/RxSwift/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/RxSwift/RxSwift.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = RxSwift; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + BE1BF3E5FC53BAFA505AB342C35E1F50 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 66429A42B7499250307412ECB7AF627E /* Alamofire.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + F0817112233556AF9CA538F326C20567 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/PetstoreClient/PetstoreClient-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/PetstoreClient/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/PetstoreClient/PetstoreClient.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = PetstoreClient; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 245A935A321D16F418F4D34C5D17D2B6 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClientTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 9B259A01C5DDE12EA25530F7D005A3D2 /* Debug */, + 99EA0FE8990CDA4F2B5110D22698851E /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 5E62115DE8C09934BF8D2FE5D15FED1E /* Debug */, + 3FA451D268613890FA8A5A03801E11D5 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 7335F4AA774EFBDED5B7673EF35FCF11 /* Build configuration list for PBXNativeTarget "RxSwift" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 00BCE7A03AB3EB1357203501EA6FCC84 /* Debug */, + B0B4110B60B5F7F6D72CFA5E690CEF32 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 8B2B2DA2F7F80D41B1FDB5FACFA4B3DE /* Build configuration list for PBXNativeTarget "Alamofire" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + BE1BF3E5FC53BAFA505AB342C35E1F50 /* Debug */, + 9B26D3A39011247999C097562A550399 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + C17E886D20DFCEDEFC84423D6652F7EE /* Build configuration list for PBXNativeTarget "Pods-SwaggerClient" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + AD723F120D0CDC6265BA516FE35A9BEB /* Debug */, + 2B14898A0D927578A91AF17061B0704F /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + F609276975EA85CEC0F2AA47BE77CDBD /* Build configuration list for PBXNativeTarget "PetstoreClient" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + F0817112233556AF9CA538F326C20567 /* Debug */, + 8710426EC015A0183026219312A2B17E /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = D41D8CD98F00B204E9800998ECF8427E /* Project object */; +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/LICENSE.md b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/LICENSE.md new file mode 100644 index 00000000000..d6765d9c9b9 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/LICENSE.md @@ -0,0 +1,9 @@ +**The MIT License** +**Copyright © 2015 Krunoslav Zaher** +**All rights reserved.** + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/README.md b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/README.md new file mode 100644 index 00000000000..c024273281e --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/README.md @@ -0,0 +1,180 @@ +Miss Electric Eel 2016 RxSwift: ReactiveX for Swift +====================================== + +[![Travis CI](https://travis-ci.org/ReactiveX/RxSwift.svg?branch=master)](https://travis-ci.org/ReactiveX/RxSwift) ![platforms](https://img.shields.io/badge/platforms-iOS%20%7C%20OSX%20%7C%20tvOS%20%7C%20watchOS%20%7C%20Linux%28experimental%29-333333.svg) ![pod](https://img.shields.io/cocoapods/v/RxSwift.svg) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) + +Xcode 7.3 Swift 2.2 required + +## About Rx + +Rx is a [generic abstraction of computation](https://youtu.be/looJcaeboBY) expressed through `Observable` interface. + +This is a Swift version of [Rx](https://github.com/Reactive-Extensions/Rx.NET). + +It tries to port as many concepts from the original version as possible, but some concepts were adapted for more pleasant and performant integration with iOS/OSX environment. + +Cross platform documentation can be found on [ReactiveX.io](http://reactivex.io/). + +Like the original Rx, its intention is to enable easy composition of asynchronous operations and event/data streams. + +KVO observing, async operations and streams are all unified under [abstraction of sequence](Documentation/GettingStarted.md#observables-aka-sequences). This is the reason why Rx is so simple, elegant and powerful. + +## I came here because I want to ... + +###### ... understand + +* [why use rx?](Documentation/Why.md) +* [the basics, getting started with RxSwift](Documentation/GettingStarted.md) +* [units](Documentation/Units.md) - what is `Driver`, `ControlProperty`, and `Variable` ... and why do they exist? +* [testing](Documentation/UnitTests.md) +* [tips and common errors](Documentation/Tips.md) +* [debugging](Documentation/GettingStarted.md#debugging) +* [the math behind Rx](Documentation/MathBehindRx.md) +* [what are hot and cold observable sequences?](Documentation/HotAndColdObservables.md) +* [what does the the public API look like?](Documentation/API.md) + +###### ... install + +* Integrate RxSwift/RxCocoa with my app. [Installation Guide](Documentation/Installation.md) + +###### ... hack around + +* with the example app. [Running Example App](Documentation/ExampleApp.md) +* with operators in playgrounds. [Playgrounds](Documentation/Playgrounds.md) + +###### ... interact + +* All of this is great, but it would be nice to talk with other people using RxSwift and exchange experiences.
[![Slack channel](http://slack.rxswift.org/badge.svg)](http://slack.rxswift.org) [Join Slack Channel](http://slack.rxswift.org/) +* Report a problem using the library. [Open an Issue With Bug Template](ISSUE_TEMPLATE.md) +* Request a new feature. [Open an Issue With Feature Request Template](Documentation/NewFeatureRequestTemplate.md) + + +###### ... compare + +* [with other libraries](Documentation/ComparisonWithOtherLibraries.md). + + +###### ... find compatible + +* libraries from [RxSwiftCommunity](https://github.com/RxSwiftCommunity). +* [Pods using RxSwift](https://cocoapods.org/?q=uses%3Arxswift). + +###### ... see the broader vision + +* Does this exist for Android? [RxJava](https://github.com/ReactiveX/RxJava) +* Where is all of this going, what is the future, what about reactive architectures, how do you design entire apps this way? [Cycle.js](https://github.com/cyclejs/cycle-core) - this is javascript, but [RxJS](https://github.com/Reactive-Extensions/RxJS) is javascript version of Rx. + +## Usage + + + + + + + + + + + + + + + + + + + +
Here's an exampleIn Action
Define search for GitHub repositories ...
+let searchResults = searchBar.rx_text
+    .throttle(0.3, scheduler: MainScheduler.instance)
+    .distinctUntilChanged()
+    .flatMapLatest { query -> Observable<[Repository]> in
+        if query.isEmpty {
+            return Observable.just([])
+        }
+
+        return searchGitHub(query)
+            .catchErrorJustReturn([])
+    }
+    .observeOn(MainScheduler.instance)
... then bind the results to your tableview
+searchResults
+    .bindTo(tableView.rx_itemsWithCellIdentifier("Cell")) {
+        (index, repository: Repository, cell) in
+        cell.textLabel?.text = repository.name
+        cell.detailTextLabel?.text = repository.url
+    }
+    .addDisposableTo(disposeBag)
+ + +## Installation + +Rx doesn't contain any external dependencies. + +These are currently the supported options: + +### Manual + +Open Rx.xcworkspace, choose `RxExample` and hit run. This method will build everything and run the sample app + +### [CocoaPods](https://guides.cocoapods.org/using/using-cocoapods.html) + +**:warning: IMPORTANT! For tvOS support, CocoaPods `0.39` is required. :warning:** + +``` +# Podfile +use_frameworks! + +target 'YOUR_TARGET_NAME' do + pod 'RxSwift', '~> 2.0' + pod 'RxCocoa', '~> 2.0' +end + +# RxTests and RxBlocking make the most sense in the context of unit/integration tests +target 'YOUR_TESTING_TARGET' do + pod 'RxBlocking', '~> 2.0' + pod 'RxTests', '~> 2.0' +end +``` + +Replace `YOUR_TARGET_NAME` and then, in the `Podfile` directory, type: + +``` +$ pod install +``` + +### [Carthage](https://github.com/Carthage/Carthage) + +**Xcode 7.1 required** + +Add this to `Cartfile` + +``` +github "ReactiveX/RxSwift" ~> 2.0 +``` + +``` +$ carthage update +``` + +### Manually using git submodules + +* Add RxSwift as a submodule + +``` +$ git submodule add git@github.com:ReactiveX/RxSwift.git +``` + +* Drag `Rx.xcodeproj` into Project Navigator +* Go to `Project > Targets > Build Phases > Link Binary With Libraries`, click `+` and select `RxSwift-[Platform]` and `RxCocoa-[Platform]` targets + + +## References + +* [http://reactivex.io/](http://reactivex.io/) +* [Reactive Extensions GitHub (GitHub)](https://github.com/Reactive-Extensions) +* [Erik Meijer (Wikipedia)](http://en.wikipedia.org/wiki/Erik_Meijer_%28computer_scientist%29) +* [Expert to Expert: Brian Beckman and Erik Meijer - Inside the .NET Reactive Framework (Rx) (video)](https://youtu.be/looJcaeboBY) +* [Reactive Programming Overview (Jafar Husain from Netflix)](https://www.youtube.com/watch?v=dwP1TNXE6fc) +* [Subject/Observer is Dual to Iterator (paper)](http://csl.stanford.edu/~christos/pldi2010.fit/meijer.duality.pdf) +* [Rx standard sequence operators visualized (visualization tool)](http://rxmarbles.com/) +* [Haskell](https://www.haskell.org/) diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/AnyObserver.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/AnyObserver.swift new file mode 100644 index 00000000000..530142e4e68 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/AnyObserver.swift @@ -0,0 +1,75 @@ +// +// AnyObserver.swift +// Rx +// +// Created by Krunoslav Zaher on 2/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +A type-erased `ObserverType`. + +Forwards operations to an arbitrary underlying observer with the same `Element` type, hiding the specifics of the underlying observer type. +*/ +public struct AnyObserver : ObserverType { + /** + The type of elements in sequence that observer can observe. + */ + public typealias E = Element + + /** + Anonymous event handler type. + */ + public typealias EventHandler = (Event) -> Void + + public let observer: EventHandler + + /** + Construct an instance whose `on(event)` calls `eventHandler(event)` + + - parameter eventHandler: Event handler that observes sequences events. + */ + public init(eventHandler: EventHandler) { + self.observer = eventHandler + } + + /** + Construct an instance whose `on(event)` calls `observer.on(event)` + + - parameter observer: Observer that receives sequence events. + */ + public init(_ observer: O) { + self.observer = observer.on + } + + /** + Send `event` to this observer. + + - parameter event: Event instance. + */ + public func on(event: Event) { + return self.observer(event) + } + + /** + Erases type of observer and returns canonical observer. + + - returns: type erased observer. + */ + public func asObserver() -> AnyObserver { + return self + } +} + +extension ObserverType { + /** + Erases type of observer and returns canonical observer. + + - returns: type erased observer. + */ + public func asObserver() -> AnyObserver { + return AnyObserver(self) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Cancelable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Cancelable.swift new file mode 100644 index 00000000000..1a6c5911d0b --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Cancelable.swift @@ -0,0 +1,19 @@ +// +// Cancelable.swift +// Rx +// +// Created by Krunoslav Zaher on 3/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Represents disposable resource with state tracking. +*/ +public protocol Cancelable : Disposable { + /** + - returns: Was resource disposed. + */ + var disposed: Bool { get } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift new file mode 100644 index 00000000000..0d1ab168c24 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift @@ -0,0 +1,104 @@ +// +// AsyncLock.swift +// Rx +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +In case nobody holds this lock, the work will be queued and executed immediately +on thread that is requesting lock. + +In case there is somebody currently holding that lock, action will be enqueued. +When owned of the lock finishes with it's processing, it will also execute +and pending work. + +That means that enqueued work could possibly be executed later on a different thread. +*/ +class AsyncLock + : Disposable + , Lock + , SynchronizedDisposeType { + typealias Action = () -> Void + + var _lock = SpinLock() + + private var _queue: Queue = Queue(capacity: 0) + + private var _isExecuting: Bool = false + private var _hasFaulted: Bool = false + + // lock { + func lock() { + _lock.lock() + } + + func unlock() { + _lock.unlock() + } + // } + + private func enqueue(action: I) -> I? { + _lock.lock(); defer { _lock.unlock() } // { + if _hasFaulted { + return nil + } + + if _isExecuting { + _queue.enqueue(action) + return nil + } + + _isExecuting = true + + return action + // } + } + + private func dequeue() -> I? { + _lock.lock(); defer { _lock.unlock() } // { + if _queue.count > 0 { + return _queue.dequeue() + } + else { + _isExecuting = false + return nil + } + // } + } + + func invoke(action: I) { + let firstEnqueuedAction = enqueue(action) + + if let firstEnqueuedAction = firstEnqueuedAction { + firstEnqueuedAction.invoke() + } + else { + // action is enqueued, it's somebody else's concern now + return + } + + while true { + let nextAction = dequeue() + + if let nextAction = nextAction { + nextAction.invoke() + } + else { + return + } + } + } + + func dispose() { + synchronizedDispose() + } + + func _synchronized_dispose() { + _queue = Queue(capacity: 0) + _hasFaulted = true + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/Lock.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/Lock.swift new file mode 100644 index 00000000000..d1632f1cebf --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/Lock.swift @@ -0,0 +1,107 @@ +// +// Lock.swift +// Rx +// +// Created by Krunoslav Zaher on 3/31/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +protocol Lock { + func lock() + func unlock() +} + +#if os(Linux) + import Glibc + + /** + Simple wrapper for spin lock. + */ + class SpinLock { + private var _lock: pthread_spinlock_t = 0 + + init() { + if (pthread_spin_init(&_lock, 0) != 0) { + fatalError("Spin lock initialization failed") + } + } + + func lock() { + pthread_spin_lock(&_lock) + } + + func unlock() { + pthread_spin_unlock(&_lock) + } + + func performLocked(@noescape action: () -> Void) { + lock(); defer { unlock() } + action() + } + + func calculateLocked(@noescape action: () -> T) -> T { + lock(); defer { unlock() } + return action() + } + + func calculateLockedOrFail(@noescape action: () throws -> T) throws -> T { + lock(); defer { unlock() } + let result = try action() + return result + } + + deinit { + pthread_spin_destroy(&_lock) + } + } +#else + + // https://lists.swift.org/pipermail/swift-dev/Week-of-Mon-20151214/000321.html + typealias SpinLock = NSRecursiveLock +#endif + +extension NSRecursiveLock : Lock { + func performLocked(@noescape action: () -> Void) { + lock(); defer { unlock() } + action() + } + + func calculateLocked(@noescape action: () -> T) -> T { + lock(); defer { unlock() } + return action() + } + + func calculateLockedOrFail(@noescape action: () throws -> T) throws -> T { + lock(); defer { unlock() } + let result = try action() + return result + } +} + +/* +let RECURSIVE_MUTEX = _initializeRecursiveMutex() + +func _initializeRecursiveMutex() -> pthread_mutex_t { + var mutex: pthread_mutex_t = pthread_mutex_t() + var mta: pthread_mutexattr_t = pthread_mutexattr_t() + + pthread_mutex_init(&mutex, nil) + pthread_mutexattr_init(&mta) + pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_RECURSIVE) + pthread_mutex_init(&mutex, &mta) + + return mutex +} + +extension pthread_mutex_t { + mutating func lock() { + pthread_mutex_lock(&self) + } + + mutating func unlock() { + pthread_mutex_unlock(&self) + } +} +*/ diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift new file mode 100644 index 00000000000..b11fcaa87df --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift @@ -0,0 +1,23 @@ +// +// LockOwnerType.swift +// Rx +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +protocol LockOwnerType : class, Lock { + var _lock: NSRecursiveLock { get } +} + +extension LockOwnerType { + func lock() { + _lock.lock() + } + + func unlock() { + _lock.unlock() + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift new file mode 100644 index 00000000000..5764575e899 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift @@ -0,0 +1,20 @@ +// +// SynchronizedDisposeType.swift +// Rx +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +protocol SynchronizedDisposeType : class, Disposable, Lock { + func _synchronized_dispose() +} + +extension SynchronizedDisposeType { + func synchronizedDispose() { + lock(); defer { unlock() } + _synchronized_dispose() + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift new file mode 100644 index 00000000000..84a3df5d104 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift @@ -0,0 +1,20 @@ +// +// SynchronizedOnType.swift +// Rx +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +protocol SynchronizedOnType : class, ObserverType, Lock { + func _synchronized_on(event: Event) +} + +extension SynchronizedOnType { + func synchronizedOn(event: Event) { + lock(); defer { unlock() } + _synchronized_on(event) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedSubscribeType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedSubscribeType.swift new file mode 100644 index 00000000000..a4903157511 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedSubscribeType.swift @@ -0,0 +1,20 @@ +// +// SynchronizedSubscribeType.swift +// Rx +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +protocol SynchronizedSubscribeType : class, ObservableType, Lock { + func _synchronized_subscribe(observer: O) -> Disposable +} + +extension SynchronizedSubscribeType { + func synchronizedSubscribe(observer: O) -> Disposable { + lock(); defer { unlock() } + return _synchronized_subscribe(observer) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift new file mode 100644 index 00000000000..4f41cb89a66 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift @@ -0,0 +1,15 @@ +// +// SynchronizedUnsubscribeType.swift +// Rx +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +protocol SynchronizedUnsubscribeType : class { + associatedtype DisposeKey + + func synchronizedUnsubscribe(disposeKey: DisposeKey) +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ConnectableObservableType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ConnectableObservableType.swift new file mode 100644 index 00000000000..2ba55dc60f7 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ConnectableObservableType.swift @@ -0,0 +1,21 @@ +// +// ConnectableObservableType.swift +// Rx +// +// Created by Krunoslav Zaher on 3/1/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Represents an observable sequence wrapper that can be connected and disconnected from its underlying observable sequence. +*/ +public protocol ConnectableObservableType : ObservableType { + /** + Connects the observable wrapper to its source. All subscribed observers will receive values from the underlying observable sequence as long as the connection is established. + + - returns: Disposable used to disconnect the observable wrapper from its source, causing subscribed observer to stop receiving values from the underlying observable sequence. + */ + func connect() -> Disposable +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/DataStructures/Bag.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/DataStructures/Bag.swift new file mode 100644 index 00000000000..f886f249f36 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/DataStructures/Bag.swift @@ -0,0 +1,328 @@ +// +// Bag.swift +// Rx +// +// Created by Krunoslav Zaher on 2/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation +import Swift + +let arrayDictionaryMaxSize = 30 + +/** +Class that enables using memory allocations as a means to uniquely identify objects. +*/ +class Identity { + // weird things have known to happen with Swift + var _forceAllocation: Int32 = 0 +} + +func hash(_x: Int) -> Int { + var x = _x + x = ((x >> 16) ^ x) &* 0x45d9f3b + x = ((x >> 16) ^ x) &* 0x45d9f3b + x = ((x >> 16) ^ x) + return x; +} + +/** +Unique identifier for object added to `Bag`. +*/ +public struct BagKey : Hashable { + let uniqueIdentity: Identity? + let key: Int + + public var hashValue: Int { + if let uniqueIdentity = uniqueIdentity { + return hash(key) ^ (unsafeAddressOf(uniqueIdentity).hashValue) + } + else { + return hash(key) + } + } +} + +/** +Compares two `BagKey`s. +*/ +public func == (lhs: BagKey, rhs: BagKey) -> Bool { + return lhs.key == rhs.key && lhs.uniqueIdentity === rhs.uniqueIdentity +} + +/** +Data structure that represents a bag of elements typed `T`. + +Single element can be stored multiple times. + +Time and space complexity of insertion an deletion is O(n). + +It is suitable for storing small number of elements. +*/ +public struct Bag : CustomDebugStringConvertible { + /** + Type of identifier for inserted elements. + */ + public typealias KeyType = BagKey + + private typealias ScopeUniqueTokenType = Int + + typealias Entry = (key: BagKey, value: T) + + private var _uniqueIdentity: Identity? + private var _nextKey: ScopeUniqueTokenType = 0 + + // data + + // first fill inline variables + private var _key0: BagKey? = nil + private var _value0: T? = nil + + private var _key1: BagKey? = nil + private var _value1: T? = nil + + // then fill "array dictionary" + private var _pairs = ContiguousArray() + + // last is sparse dictionary + private var _dictionary: [BagKey : T]? = nil + + private var _onlyFastPath = true + + /** + Creates new empty `Bag`. + */ + public init() { + } + + /** + Inserts `value` into bag. + + - parameter element: Element to insert. + - returns: Key that can be used to remove element from bag. + */ + public mutating func insert(element: T) -> BagKey { + _nextKey = _nextKey &+ 1 + +#if DEBUG + _nextKey = _nextKey % 20 +#endif + + if _nextKey == 0 { + _uniqueIdentity = Identity() + } + + let key = BagKey(uniqueIdentity: _uniqueIdentity, key: _nextKey) + + if _key0 == nil { + _key0 = key + _value0 = element + return key + } + + _onlyFastPath = false + + if _key1 == nil { + _key1 = key + _value1 = element + return key + } + + if _dictionary != nil { + _dictionary![key] = element + return key + } + + if _pairs.count < arrayDictionaryMaxSize { + _pairs.append(key: key, value: element) + return key + } + + if _dictionary == nil { + _dictionary = [:] + } + + _dictionary![key] = element + + return key + } + + /** + - returns: Number of elements in bag. + */ + public var count: Int { + let dictionaryCount: Int = _dictionary?.count ?? 0 + return _pairs.count + (_value0 != nil ? 1 : 0) + (_value1 != nil ? 1 : 0) + dictionaryCount + } + + /** + Removes all elements from bag and clears capacity. + */ + public mutating func removeAll() { + _key0 = nil + _value0 = nil + _key1 = nil + _value1 = nil + + _pairs.removeAll(keepCapacity: false) + _dictionary?.removeAll(keepCapacity: false) + } + + /** + Removes element with a specific `key` from bag. + + - parameter key: Key that identifies element to remove from bag. + - returns: Element that bag contained, or nil in case element was already removed. + */ + public mutating func removeKey(key: BagKey) -> T? { + if _key0 == key { + _key0 = nil + let value = _value0! + _value0 = nil + return value + } + + if _key1 == key { + _key1 = nil + let value = _value1! + _value1 = nil + return value + } + + if let existingObject = _dictionary?.removeValueForKey(key) { + return existingObject + } + + for i in 0 ..< _pairs.count { + if _pairs[i].key == key { + let value = _pairs[i].value + _pairs.removeAtIndex(i) + return value + } + } + + return nil + } +} + +extension Bag { + /** + A textual representation of `self`, suitable for debugging. + */ + public var debugDescription : String { + return "\(self.count) elements in Bag" + } +} + + +// MARK: forEach + +extension Bag { + /** + Enumerates elements inside the bag. + + - parameter action: Enumeration closure. + */ + public func forEach(@noescape action: (T) -> Void) { + if _onlyFastPath { + if let value0 = _value0 { + action(value0) + } + return + } + + let pairs = _pairs + let value0 = _value0 + let value1 = _value1 + let dictionary = _dictionary + + if let value0 = value0 { + action(value0) + } + + if let value1 = value1 { + action(value1) + } + + for i in 0 ..< pairs.count { + action(pairs[i].value) + } + + if dictionary?.count ?? 0 > 0 { + for element in dictionary!.values { + action(element) + } + } + } +} + +extension Bag where T: ObserverType { + /** + Dispatches `event` to app observers contained inside bag. + + - parameter action: Enumeration closure. + */ + public func on(event: Event) { + if _onlyFastPath { + _value0?.on(event) + return + } + + let pairs = _pairs + let value0 = _value0 + let value1 = _value1 + let dictionary = _dictionary + + if let value0 = value0 { + value0.on(event) + } + + if let value1 = value1 { + value1.on(event) + } + + for i in 0 ..< pairs.count { + pairs[i].value.on(event) + } + + if dictionary?.count ?? 0 > 0 { + for element in dictionary!.values { + element.on(event) + } + } + } +} + +/** +Dispatches `dispose` to all disposables contained inside bag. +*/ +public func disposeAllIn(bag: Bag) { + if bag._onlyFastPath { + bag._value0?.dispose() + return + } + + let pairs = bag._pairs + let value0 = bag._value0 + let value1 = bag._value1 + let dictionary = bag._dictionary + + if let value0 = value0 { + value0.dispose() + } + + if let value1 = value1 { + value1.dispose() + } + + for i in 0 ..< pairs.count { + pairs[i].value.dispose() + } + + if dictionary?.count ?? 0 > 0 { + for element in dictionary!.values { + element.dispose() + } + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/DataStructures/InfiniteSequence.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/DataStructures/InfiniteSequence.swift new file mode 100644 index 00000000000..33ead5ec09f --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/DataStructures/InfiniteSequence.swift @@ -0,0 +1,30 @@ +// +// InfiniteSequence.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Sequence that repeats `repeatedValue` infinite number of times. +*/ +struct InfiniteSequence : SequenceType { + typealias Element = E + typealias Generator = AnyGenerator + + private let _repeatedValue: E + + init(repeatedValue: E) { + _repeatedValue = repeatedValue + } + + func generate() -> Generator { + let repeatedValue = _repeatedValue + return AnyGenerator { + return repeatedValue + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/DataStructures/PriorityQueue.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/DataStructures/PriorityQueue.swift new file mode 100644 index 00000000000..efbd546a453 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/DataStructures/PriorityQueue.swift @@ -0,0 +1,120 @@ +// +// PriorityQueue.swift +// Rx +// +// Created by Krunoslav Zaher on 12/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +struct PriorityQueue { + private let _hasHigherPriority: (Element, Element) -> Bool + private var _elements = [Element]() + + init(hasHigherPriority: (Element, Element) -> Bool) { + _hasHigherPriority = hasHigherPriority + } + + mutating func enqueue(element: Element) { + _elements.append(element) + bubbleToHigherPriority(_elements.count - 1) + } + + func peek() -> Element? { + return _elements.first + } + + var isEmpty: Bool { + return _elements.count == 0 + } + + mutating func dequeue() -> Element? { + guard let front = peek() else { + return nil + } + + removeAt(0) + + return front + } + + mutating func remove(element: Element) { + for i in 0 ..< _elements.count { + if _elements[i] === element { + removeAt(i) + return + } + } + } + + private mutating func removeAt(index: Int) { + let removingLast = index == _elements.count - 1 + if !removingLast { + swap(&_elements[index], &_elements[_elements.count - 1]) + } + + _elements.popLast() + + if !removingLast { + bubbleToHigherPriority(index) + bubbleToLowerPriority(index) + } + } + + private mutating func bubbleToHigherPriority(initialUnbalancedIndex: Int) { + precondition(initialUnbalancedIndex >= 0) + precondition(initialUnbalancedIndex < _elements.count) + + var unbalancedIndex = initialUnbalancedIndex + + while unbalancedIndex > 0 { + let parentIndex = (unbalancedIndex - 1) / 2 + + if _hasHigherPriority(_elements[unbalancedIndex], _elements[parentIndex]) { + swap(&_elements[unbalancedIndex], &_elements[parentIndex]) + + unbalancedIndex = parentIndex + } + else { + break + } + } + } + + private mutating func bubbleToLowerPriority(initialUnbalancedIndex: Int) { + precondition(initialUnbalancedIndex >= 0) + precondition(initialUnbalancedIndex < _elements.count) + + var unbalancedIndex = initialUnbalancedIndex + repeat { + let leftChildIndex = unbalancedIndex * 2 + 1 + let rightChildIndex = unbalancedIndex * 2 + 2 + + var highestPriorityIndex = unbalancedIndex + + if leftChildIndex < _elements.count && _hasHigherPriority(_elements[leftChildIndex], _elements[highestPriorityIndex]) { + highestPriorityIndex = leftChildIndex + } + + if rightChildIndex < _elements.count && _hasHigherPriority(_elements[rightChildIndex], _elements[highestPriorityIndex]) { + highestPriorityIndex = rightChildIndex + } + + if highestPriorityIndex != unbalancedIndex { + swap(&_elements[highestPriorityIndex], &_elements[unbalancedIndex]) + + unbalancedIndex = highestPriorityIndex + } + else { + break + } + } while true + } +} + +extension PriorityQueue : CustomDebugStringConvertible { + var debugDescription: String { + return _elements.debugDescription + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/DataStructures/Queue.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/DataStructures/Queue.swift new file mode 100644 index 00000000000..4bf95889861 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/DataStructures/Queue.swift @@ -0,0 +1,168 @@ +// +// Queue.swift +// Rx +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Data structure that represents queue. + +Complexity of `enqueue`, `dequeue` is O(1) when number of operations is +averaged over N operations. + +Complexity of `peek` is O(1). +*/ +public struct Queue: SequenceType { + /** + Type of generator. + */ + public typealias Generator = AnyGenerator + + private let _resizeFactor = 2 + + private var _storage: ContiguousArray + private var _count = 0 + private var _pushNextIndex = 0 + private var _initialCapacity: Int + + /** + Creates new queue. + + - parameter capacity: Capacity of newly created queue. + */ + public init(capacity: Int) { + _initialCapacity = capacity + + _storage = ContiguousArray(count: capacity, repeatedValue: nil) + } + + private var dequeueIndex: Int { + let index = _pushNextIndex - count + return index < 0 ? index + _storage.count : index + } + + /** + - returns: Is queue empty. + */ + public var isEmpty: Bool { + return count == 0 + } + + /** + - returns: Number of elements inside queue. + */ + public var count: Int { + return _count + } + + /** + - returns: Element in front of a list of elements to `dequeue`. + */ + public func peek() -> T { + precondition(count > 0) + + return _storage[dequeueIndex]! + } + + mutating private func resizeTo(size: Int) { + var newStorage = ContiguousArray(count: size, repeatedValue: nil) + + let count = _count + + let dequeueIndex = self.dequeueIndex + let spaceToEndOfQueue = _storage.count - dequeueIndex + + // first batch is from dequeue index to end of array + let countElementsInFirstBatch = min(count, spaceToEndOfQueue) + // second batch is wrapped from start of array to end of queue + let numberOfElementsInSecondBatch = count - countElementsInFirstBatch + + newStorage[0 ..< countElementsInFirstBatch] = _storage[dequeueIndex ..< (dequeueIndex + countElementsInFirstBatch)] + newStorage[countElementsInFirstBatch ..< (countElementsInFirstBatch + numberOfElementsInSecondBatch)] = _storage[0 ..< numberOfElementsInSecondBatch] + + _count = count + _pushNextIndex = count + _storage = newStorage + } + + /** + Enqueues `element`. + + - parameter element: Element to enqueue. + */ + public mutating func enqueue(element: T) { + if count == _storage.count { + resizeTo(max(_storage.count, 1) * _resizeFactor) + } + + _storage[_pushNextIndex] = element + _pushNextIndex += 1 + _count += 1 + + if _pushNextIndex >= _storage.count { + _pushNextIndex -= _storage.count + } + } + + private mutating func dequeueElementOnly() -> T { + precondition(count > 0) + + let index = dequeueIndex + + defer { + _storage[index] = nil + _count -= 1 + } + + return _storage[index]! + } + + /** + Dequeues element or throws an exception in case queue is empty. + + - returns: Dequeued element. + */ + public mutating func dequeue() -> T? { + if self.count == 0 { + return nil + } + + defer { + let downsizeLimit = _storage.count / (_resizeFactor * _resizeFactor) + if _count < downsizeLimit && downsizeLimit >= _initialCapacity { + resizeTo(_storage.count / _resizeFactor) + } + } + + return dequeueElementOnly() + } + + /** + - returns: Generator of contained elements. + */ + public func generate() -> Generator { + var i = dequeueIndex + var count = _count + + return AnyGenerator { + if count == 0 { + return nil + } + + defer { + count -= 1 + i += 1 + } + + if i >= self._storage.count { + i -= self._storage.count + } + + return self._storage[i] + } + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposable.swift new file mode 100644 index 00000000000..da760fff763 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposable.swift @@ -0,0 +1,15 @@ +// +// Disposable.swift +// Rx +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/// Respresents a disposable resource. +public protocol Disposable { + /// Dispose resource. + func dispose() +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift new file mode 100644 index 00000000000..17a40910be0 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift @@ -0,0 +1,54 @@ +// +// AnonymousDisposable.swift +// Rx +// +// Created by Krunoslav Zaher on 2/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Represents an Action-based disposable. + +When dispose method is called, disposal action will be dereferenced. +*/ +public final class AnonymousDisposable : DisposeBase, Cancelable { + public typealias DisposeAction = () -> Void + + private var _disposed: AtomicInt = 0 + private var _disposeAction: DisposeAction? + + /** + - returns: Was resource disposed. + */ + public var disposed: Bool { + return _disposed == 1 + } + + /** + Constructs a new disposable with the given action used for disposal. + + - parameter disposeAction: Disposal action which will be run upon calling `dispose`. + */ + public init(_ disposeAction: DisposeAction) { + _disposeAction = disposeAction + super.init() + } + + /** + Calls the disposal action if and only if the current instance hasn't been disposed yet. + + After invoking disposal action, disposal action will be dereferenced. + */ + public func dispose() { + if AtomicCompareAndSwap(0, 1, &_disposed) { + assert(_disposed == 1) + + if let action = _disposeAction { + _disposeAction = nil + action() + } + } + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift new file mode 100644 index 00000000000..b6176592fdc --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift @@ -0,0 +1,54 @@ +// +// BinaryDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Represents two disposable resources that are disposed together. +*/ +public final class BinaryDisposable : DisposeBase, Cancelable { + + private var _disposed: AtomicInt = 0 + + // state + private var _disposable1: Disposable? + private var _disposable2: Disposable? + + /** + - returns: Was resource disposed. + */ + public var disposed: Bool { + return _disposed > 0 + } + + /** + Constructs new binary disposable from two disposables. + + - parameter disposable1: First disposable + - parameter disposable2: Second disposable + */ + init(_ disposable1: Disposable, _ disposable2: Disposable) { + _disposable1 = disposable1 + _disposable2 = disposable2 + super.init() + } + + /** + Calls the disposal action if and only if the current instance hasn't been disposed yet. + + After invoking disposal action, disposal action will be dereferenced. + */ + public func dispose() { + if AtomicCompareAndSwap(0, 1, &_disposed) { + _disposable1?.dispose() + _disposable2?.dispose() + _disposable1 = nil + _disposable2 = nil + } + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift new file mode 100644 index 00000000000..28db627b14a --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift @@ -0,0 +1,45 @@ +// +// BooleanDisposable.swift +// Rx +// +// Created by Junior B. on 10/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Represents a disposable resource that can be checked for disposal status. +*/ +public class BooleanDisposable : Disposable, Cancelable { + + internal static let BooleanDisposableTrue = BooleanDisposable(disposed: true) + private var _disposed = false + + /** + Initializes a new instance of the `BooleanDisposable` class + */ + public init() { + } + + /** + Initializes a new instance of the `BooleanDisposable` class with given value + */ + public init(disposed: Bool) { + self._disposed = disposed + } + + /** + - returns: Was resource disposed. + */ + public var disposed: Bool { + return _disposed + } + + /** + Sets the status to disposed, which can be observer through the `disposed` property. + */ + public func dispose() { + _disposed = true + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift new file mode 100644 index 00000000000..a787f3625fd --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift @@ -0,0 +1,135 @@ +// +// CompositeDisposable.swift +// Rx +// +// Created by Krunoslav Zaher on 2/20/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Represents a group of disposable resources that are disposed together. +*/ +public class CompositeDisposable : DisposeBase, Disposable, Cancelable { + public typealias DisposeKey = Bag.KeyType + + private var _lock = SpinLock() + + // state + private var _disposables: Bag? = Bag() + + public var disposed: Bool { + _lock.lock(); defer { _lock.unlock() } + return _disposables == nil + } + + public override init() { + } + + /** + Initializes a new instance of composite disposable with the specified number of disposables. + */ + public init(_ disposable1: Disposable, _ disposable2: Disposable) { + // This overload is here to make sure we are using optimized version up to 4 arguments. + _disposables!.insert(disposable1) + _disposables!.insert(disposable2) + } + + /** + Initializes a new instance of composite disposable with the specified number of disposables. + */ + public init(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable) { + // This overload is here to make sure we are using optimized version up to 4 arguments. + _disposables!.insert(disposable1) + _disposables!.insert(disposable2) + _disposables!.insert(disposable3) + } + + /** + Initializes a new instance of composite disposable with the specified number of disposables. + */ + public init(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable, _ disposable4: Disposable, _ disposables: Disposable...) { + // This overload is here to make sure we are using optimized version up to 4 arguments. + _disposables!.insert(disposable1) + _disposables!.insert(disposable2) + _disposables!.insert(disposable3) + _disposables!.insert(disposable4) + + for disposable in disposables { + _disposables!.insert(disposable) + } + } + + /** + Initializes a new instance of composite disposable with the specified number of disposables. + */ + public init(disposables: [Disposable]) { + for disposable in disposables { + _disposables!.insert(disposable) + } + } + + /** + Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. + + - parameter disposable: Disposable to add. + - returns: Key that can be used to remove disposable from composite disposable. In case dispose bag was already + disposed `nil` will be returned. + */ + public func addDisposable(disposable: Disposable) -> DisposeKey? { + let key = _addDisposable(disposable) + + if key == nil { + disposable.dispose() + } + + return key + } + + private func _addDisposable(disposable: Disposable) -> DisposeKey? { + _lock.lock(); defer { _lock.unlock() } + + return _disposables?.insert(disposable) + } + + /** + - returns: Gets the number of disposables contained in the `CompositeDisposable`. + */ + public var count: Int { + _lock.lock(); defer { _lock.unlock() } + return _disposables?.count ?? 0 + } + + /** + Removes and disposes the disposable identified by `disposeKey` from the CompositeDisposable. + + - parameter disposeKey: Key used to identify disposable to be removed. + */ + public func removeDisposable(disposeKey: DisposeKey) { + _removeDisposable(disposeKey)?.dispose() + } + + private func _removeDisposable(disposeKey: DisposeKey) -> Disposable? { + _lock.lock(); defer { _lock.unlock() } + return _disposables?.removeKey(disposeKey) + } + + /** + Disposes all disposables in the group and removes them from the group. + */ + public func dispose() { + if let disposables = _dispose() { + disposeAllIn(disposables) + } + } + + private func _dispose() -> Bag? { + _lock.lock(); defer { _lock.unlock() } + + let disposeBag = _disposables + _disposables = nil + + return disposeBag + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift new file mode 100644 index 00000000000..ce1f0b7fce7 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift @@ -0,0 +1,94 @@ +// +// DisposeBag.swift +// Rx +// +// Created by Krunoslav Zaher on 3/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +extension Disposable { + /** + Adds `self` to `bag`. + + - parameter bag: `DisposeBag` to add `self` to. + */ + public func addDisposableTo(bag: DisposeBag) { + bag.addDisposable(self) + } +} + +/** +Thread safe bag that disposes added disposables on `deinit`. + +This returns ARC (RAII) like resource management to `RxSwift`. + +In case contained disposables need to be disposed, just put a different dispose bag +or create a new one in its place. + + self.existingDisposeBag = DisposeBag() + +In case explicit disposal is necessary, there is also `CompositeDisposable`. +*/ +public class DisposeBag: DisposeBase { + + private var _lock = SpinLock() + + // state + private var _disposables = [Disposable]() + private var _disposed = false + + /** + Constructs new empty dispose bag. + */ + public override init() { + super.init() + } + + /** + Adds `disposable` to be disposed when dispose bag is being deinited. + + - parameter disposable: Disposable to add. + */ + public func addDisposable(disposable: Disposable) { + _addDisposable(disposable)?.dispose() + } + + private func _addDisposable(disposable: Disposable) -> Disposable? { + _lock.lock(); defer { _lock.unlock() } + if _disposed { + return disposable + } + + _disposables.append(disposable) + + return nil + } + + /** + This is internal on purpose, take a look at `CompositeDisposable` instead. + */ + private func dispose() { + let oldDisposables = _dispose() + + for disposable in oldDisposables { + disposable.dispose() + } + } + + private func _dispose() -> [Disposable] { + _lock.lock(); defer { _lock.unlock() } + + let disposables = _disposables + + _disposables.removeAll(keepCapacity: false) + _disposed = true + + return disposables + } + + deinit { + dispose() + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift new file mode 100644 index 00000000000..86ecf4198f9 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift @@ -0,0 +1,26 @@ +// +// DisposeBase.swift +// Rx +// +// Created by Krunoslav Zaher on 4/4/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Base class for all disposables. +*/ +public class DisposeBase { + init() { +#if TRACE_RESOURCES + AtomicIncrement(&resourceCount) +#endif + } + + deinit { +#if TRACE_RESOURCES + AtomicDecrement(&resourceCount) +#endif + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/NAryDisposable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/NAryDisposable.swift new file mode 100644 index 00000000000..548a1c3a5c2 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/NAryDisposable.swift @@ -0,0 +1,10 @@ +// This file is autogenerated. Take a look at `Preprocessor` target in RxSwift project +// +// NAryDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/20/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift new file mode 100644 index 00000000000..05048bcea92 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift @@ -0,0 +1,32 @@ +// +// NopDisposable.swift +// Rx +// +// Created by Krunoslav Zaher on 2/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Represents a disposable that does nothing on disposal. + +Nop = No Operation +*/ +public struct NopDisposable : Disposable { + + /** + Singleton instance of `NopDisposable`. + */ + public static let instance: Disposable = NopDisposable() + + init() { + + } + + /** + Does nothing. + */ + public func dispose() { + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift new file mode 100644 index 00000000000..2d29d74a33f --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift @@ -0,0 +1,127 @@ +// +// RefCountDisposable.swift +// Rx +// +// Created by Junior B. on 10/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** + Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. + */ +public class RefCountDisposable : DisposeBase, Cancelable { + private var _lock = SpinLock() + private var _disposable = nil as Disposable? + private var _primaryDisposed = false + private var _count = 0 + + /** + - returns: Was resource disposed. + */ + public var disposed: Bool { + _lock.lock(); defer { _lock.unlock() } + return _disposable == nil + } + + /** + Initializes a new instance of the `RefCountDisposable`. + */ + public init(disposable: Disposable) { + _disposable = disposable + super.init() + } + + /** + Holds a dependent disposable that when disposed decreases the refcount on the underlying disposable. + + When getter is called, a dependent disposable contributing to the reference count that manages the underlying disposable's lifetime is returned. + */ + public func retain() -> Disposable { + return _lock.calculateLocked { + if let _ = _disposable { + + do { + try incrementChecked(&_count) + } catch (_) { + rxFatalError("RefCountDisposable increment failed") + } + + return RefCountInnerDisposable(self) + } else { + return NopDisposable.instance + } + } + } + + /** + Disposes the underlying disposable only when all dependent disposables have been disposed. + */ + public func dispose() { + let oldDisposable: Disposable? = _lock.calculateLocked { + if let oldDisposable = _disposable where !_primaryDisposed + { + _primaryDisposed = true + + if (_count == 0) + { + _disposable = nil + return oldDisposable + } + } + + return nil + } + + if let disposable = oldDisposable { + disposable.dispose() + } + } + + private func release() { + let oldDisposable: Disposable? = _lock.calculateLocked { + if let oldDisposable = _disposable { + do { + try decrementChecked(&_count) + } catch (_) { + rxFatalError("RefCountDisposable decrement on release failed") + } + + guard _count >= 0 else { + rxFatalError("RefCountDisposable counter is lower than 0") + } + + if _primaryDisposed && _count == 0 { + _disposable = nil + return oldDisposable + } + } + + return nil + } + + if let disposable = oldDisposable { + disposable.dispose() + } + } +} + +internal final class RefCountInnerDisposable: DisposeBase, Disposable +{ + private let _parent: RefCountDisposable + private var _disposed: AtomicInt = 0 + + init(_ parent: RefCountDisposable) + { + _parent = parent + super.init() + } + + internal func dispose() + { + if AtomicCompareAndSwap(0, 1, &_disposed) { + _parent.release() + } + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift new file mode 100644 index 00000000000..ac734996c46 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift @@ -0,0 +1,58 @@ +// +// ScheduledDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +private let disposeScheduledDisposable: ScheduledDisposable -> Disposable = { sd in + sd.disposeInner() + return NopDisposable.instance +} + +/** +Represents a disposable resource whose disposal invocation will be scheduled on the specified scheduler. +*/ +public class ScheduledDisposable : Cancelable { + public let scheduler: ImmediateSchedulerType + + private var _disposed: AtomicInt = 0 + + // state + private var _disposable: Disposable? + + /** + - returns: Was resource disposed. + */ + public var disposed: Bool { + return _disposed == 1 + } + + /** + Initializes a new instance of the `ScheduledDisposable` that uses a `scheduler` on which to dispose the `disposable`. + + - parameter scheduler: Scheduler where the disposable resource will be disposed on. + - parameter disposable: Disposable resource to dispose on the given scheduler. + */ + public init(scheduler: ImmediateSchedulerType, disposable: Disposable) { + self.scheduler = scheduler + _disposable = disposable + } + + /** + Disposes the wrapped disposable on the provided scheduler. + */ + public func dispose() { + scheduler.schedule(self, action: disposeScheduledDisposable) + } + + func disposeInner() { + if AtomicCompareAndSwap(0, 1, &_disposed) { + _disposable!.dispose() + _disposable = nil + } + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift new file mode 100644 index 00000000000..07eebcc1cb5 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift @@ -0,0 +1,85 @@ +// +// SerialDisposable.swift +// Rx +// +// Created by Krunoslav Zaher on 3/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. +*/ +public class SerialDisposable : DisposeBase, Cancelable { + private var _lock = SpinLock() + + // state + private var _current = nil as Disposable? + private var _disposed = false + + /** + - returns: Was resource disposed. + */ + public var disposed: Bool { + return _disposed + } + + /** + Initializes a new instance of the `SerialDisposable`. + */ + override public init() { + super.init() + } + + /** + Gets or sets the underlying disposable. + + Assigning this property disposes the previous disposable object. + + If the `SerialDisposable` has already been disposed, assignment to this property causes immediate disposal of the given disposable object. + */ + public var disposable: Disposable { + get { + return _lock.calculateLocked { + return self.disposable + } + } + set (newDisposable) { + let disposable: Disposable? = _lock.calculateLocked { + if _disposed { + return newDisposable + } + else { + let toDispose = _current + _current = newDisposable + return toDispose + } + } + + if let disposable = disposable { + disposable.dispose() + } + } + } + + /** + Disposes the underlying disposable as well as all future replacements. + */ + public func dispose() { + _dispose()?.dispose() + } + + private func _dispose() -> Disposable? { + _lock.lock(); defer { _lock.unlock() } + if _disposed { + return nil + } + else { + _disposed = true + let current = _current + _current = nil + return current + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift new file mode 100644 index 00000000000..2b192bac869 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift @@ -0,0 +1,89 @@ +// +// SingleAssignmentDisposable.swift +// Rx +// +// Created by Krunoslav Zaher on 2/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Represents a disposable resource which only allows a single assignment of its underlying disposable resource. + +If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an exception. +*/ +public class SingleAssignmentDisposable : DisposeBase, Disposable, Cancelable { + private var _lock = SpinLock() + + // state + private var _disposed = false + private var _disposableSet = false + private var _disposable = nil as Disposable? + + /** + - returns: A value that indicates whether the object is disposed. + */ + public var disposed: Bool { + return _disposed + } + + /** + Initializes a new instance of the `SingleAssignmentDisposable`. + */ + public override init() { + super.init() + } + + /** + Gets or sets the underlying disposable. After disposal, the result of getting this property is undefined. + + **Throws exception if the `SingleAssignmentDisposable` has already been assigned to.** + */ + public var disposable: Disposable { + get { + _lock.lock(); defer { _lock.unlock() } + return _disposable ?? NopDisposable.instance + } + set { + _setDisposable(newValue)?.dispose() + } + } + + private func _setDisposable(newValue: Disposable) -> Disposable? { + _lock.lock(); defer { _lock.unlock() } + if _disposableSet { + rxFatalError("oldState.disposable != nil") + } + + _disposableSet = true + + if _disposed { + return newValue + } + + _disposable = newValue + + return nil + } + + /** + Disposes the underlying disposable. + */ + public func dispose() { + if _disposed { + return + } + _dispose()?.dispose() + } + + private func _dispose() -> Disposable? { + _lock.lock(); defer { _lock.unlock() } + + _disposed = true + let disposable = _disposable + _disposable = nil + + return disposable + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/StableCompositeDisposable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/StableCompositeDisposable.swift new file mode 100644 index 00000000000..54162d2ee63 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/StableCompositeDisposable.swift @@ -0,0 +1,15 @@ +// +// StableCompositeDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +public final class StableCompositeDisposable { + public static func create(disposable1: Disposable, _ disposable2: Disposable) -> Disposable { + return BinaryDisposable(disposable1, disposable2) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift new file mode 100644 index 00000000000..7a3e1e97053 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift @@ -0,0 +1,23 @@ +// +// SubscriptionDisposable.swift +// Rx +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +struct SubscriptionDisposable : Disposable { + private let _key: T.DisposeKey + private weak var _owner: T? + + init(owner: T, key: T.DisposeKey) { + _owner = owner + _key = key + } + + func dispose() { + _owner?.synchronizedUnsubscribe(_key) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Errors.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Errors.swift new file mode 100644 index 00000000000..ccb71c198a8 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Errors.swift @@ -0,0 +1,72 @@ +// +// Errors.swift +// Rx +// +// Created by Krunoslav Zaher on 3/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +let RxErrorDomain = "RxErrorDomain" +let RxCompositeFailures = "RxCompositeFailures" + +/** +Generic Rx error codes. +*/ +public enum RxError + : ErrorType + , CustomDebugStringConvertible { + /** + Unknown error occured. + */ + case Unknown + /** + Performing an action on disposed object. + */ + case Disposed(object: AnyObject) + /** + Aritmetic overflow error. + */ + case Overflow + /** + Argument out of range error. + */ + case ArgumentOutOfRange + /** + Sequence doesn't contain any elements. + */ + case NoElements + /** + Sequence contains more than one element. + */ + case MoreThanOneElement + /** + Timeout error. + */ + case Timeout +} + +public extension RxError { + /** + A textual representation of `self`, suitable for debugging. + */ + public var debugDescription: String { + switch self { + case .Unknown: + return "Unknown error occured." + case .Disposed(let object): + return "Object `\(object)` was already disposed." + case .Overflow: + return "Arithmetic overflow occured." + case .ArgumentOutOfRange: + return "Argument out of range." + case .NoElements: + return "Sequence doesn't contain any elements." + case .MoreThanOneElement: + return "Sequence contains more than one element." + case .Timeout: + return "Sequence timeout." + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Event.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Event.swift new file mode 100644 index 00000000000..46e5f1b13d8 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Event.swift @@ -0,0 +1,66 @@ +// +// Event.swift +// Rx +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Represents a sequence event. + +Sequence grammar: +Next\* (Error | Completed) +*/ +public enum Event { + /// Next element is produced. + case Next(Element) + + /// Sequence terminated with an error. + case Error(ErrorType) + + /// Sequence completed successfully. + case Completed +} + +extension Event : CustomDebugStringConvertible { + /// - returns: Description of event. + public var debugDescription: String { + switch self { + case .Next(let value): + return "Next(\(value))" + case .Error(let error): + return "Error(\(error))" + case .Completed: + return "Completed" + } + } +} + +extension Event { + /// - returns: Is `Completed` or `Error` event. + public var isStopEvent: Bool { + switch self { + case .Next: return false + case .Error, .Completed: return true + } + } + + /// - returns: If `Next` event, returns element value. + public var element: Element? { + if case .Next(let value) = self { + return value + } + return nil + } + + /// - returns: If `Error` event, returns error. + public var error: ErrorType? { + if case .Error(let error) = self { + return error + } + return nil + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Extensions/String+Rx.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Extensions/String+Rx.swift new file mode 100644 index 00000000000..430fc3a3fec --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Extensions/String+Rx.swift @@ -0,0 +1,26 @@ +// +// String+Rx.swift +// Rx +// +// Created by Krunoslav Zaher on 12/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +extension String { + /** + This is needed because on Linux Swift doesn't have `rangeOfString(..., options: .BackwardsSearch)` + */ + func lastIndexOf(character: Character) -> Index? { + var index = endIndex + while index > startIndex { + index = index.predecessor() + if self[index] == character { + return index + } + } + + return nil + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift new file mode 100644 index 00000000000..b14b9abdaee --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift @@ -0,0 +1,40 @@ +// +// ImmediateSchedulerType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/31/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Represents an object that immediately schedules units of work. +*/ +public protocol ImmediateSchedulerType { + /** + Schedules an action to be executed immediatelly. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + func schedule(state: StateType, action: (StateType) -> Disposable) -> Disposable +} + +extension ImmediateSchedulerType { + /** + Schedules an action to be executed recursively. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func scheduleRecursive(state: State, action: (state: State, recurse: (State) -> ()) -> ()) -> Disposable { + let recursiveScheduler = RecursiveImmediateScheduler(action: action, scheduler: self) + + recursiveScheduler.schedule(state) + + return AnonymousDisposable(recursiveScheduler.dispose) + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observable+Extensions.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observable+Extensions.swift new file mode 100644 index 00000000000..c44b9b05125 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observable+Extensions.swift @@ -0,0 +1,128 @@ +// +// Observable+Extensions.swift +// Rx +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +extension ObservableType { + /** + Subscribes an event handler to an observable sequence. + + - parameter on: Action to invoke for each event in the observable sequence. + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + @warn_unused_result(message="http://git.io/rxs.ud") + public func subscribe(on: (event: Event) -> Void) + -> Disposable { + let observer = AnonymousObserver { e in + on(event: e) + } + return self.subscribeSafe(observer) + } + + /** + Subscribes an element handler, an error handler, a completion handler and disposed handler to an observable sequence. + + - parameter onNext: Action to invoke for each element in the observable sequence. + - parameter onError: Action to invoke upon errored termination of the observable sequence. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has + gracefully completed, errored, or if the generation is cancelled by disposing subscription). + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + @warn_unused_result(message="http://git.io/rxs.ud") + public func subscribe(onNext onNext: (E -> Void)? = nil, onError: (ErrorType -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil) + -> Disposable { + + let disposable: Disposable + + if let disposed = onDisposed { + disposable = AnonymousDisposable(disposed) + } + else { + disposable = NopDisposable.instance + } + + let observer = AnonymousObserver { e in + switch e { + case .Next(let value): + onNext?(value) + case .Error(let e): + onError?(e) + disposable.dispose() + case .Completed: + onCompleted?() + disposable.dispose() + } + } + return BinaryDisposable( + self.subscribeSafe(observer), + disposable + ) + } + + /** + Subscribes an element handler to an observable sequence. + + - parameter onNext: Action to invoke for each element in the observable sequence. + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + @warn_unused_result(message="http://git.io/rxs.ud") + public func subscribeNext(onNext: (E) -> Void) + -> Disposable { + let observer = AnonymousObserver { e in + if case .Next(let value) = e { + onNext(value) + } + } + return self.subscribeSafe(observer) + } + + /** + Subscribes an error handler to an observable sequence. + + - parameter onError: Action to invoke upon errored termination of the observable sequence. + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + @warn_unused_result(message="http://git.io/rxs.ud") + public func subscribeError(onError: (ErrorType) -> Void) + -> Disposable { + let observer = AnonymousObserver { e in + if case .Error(let error) = e { + onError(error) + } + } + return self.subscribeSafe(observer) + } + + /** + Subscribes a completion handler to an observable sequence. + + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + @warn_unused_result(message="http://git.io/rxs.ud") + public func subscribeCompleted(onCompleted: () -> Void) + -> Disposable { + let observer = AnonymousObserver { e in + if case .Completed = e { + onCompleted() + } + } + return self.subscribeSafe(observer) + } +} + +public extension ObservableType { + /** + All internal subscribe calls go through this method. + */ + @warn_unused_result(message="http://git.io/rxs.ud") + func subscribeSafe(observer: O) -> Disposable { + return self.asObservable().subscribe(observer) + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observable.swift new file mode 100644 index 00000000000..cc472a0c9b7 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observable.swift @@ -0,0 +1,51 @@ +// +// Observable.swift +// Rx +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +A type-erased `ObservableType`. + +It represents a push style sequence. +*/ +public class Observable : ObservableType { + /** + Type of elements in sequence. + */ + public typealias E = Element + + init() { +#if TRACE_RESOURCES + OSAtomicIncrement32(&resourceCount) +#endif + } + + public func subscribe(observer: O) -> Disposable { + abstractMethod() + } + + public func asObservable() -> Observable { + return self + } + + deinit { +#if TRACE_RESOURCES + AtomicDecrement(&resourceCount) +#endif + } + + // this is kind of ugly I know :( + // Swift compiler reports "Not supported yet" when trying to override protocol extensions, so ¯\_(ツ)_/¯ + + /** + Optimizations for map operator + */ + internal func composeMap(selector: Element throws -> R) -> Observable { + return Map(source: self, selector: selector) + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift new file mode 100644 index 00000000000..802cc472fd4 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift @@ -0,0 +1,26 @@ +// +// ObservableConvertibleType.swift +// Rx +// +// Created by Krunoslav Zaher on 9/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Type that can be converted to observable sequence (`Observer`). +*/ +public protocol ObservableConvertibleType { + /** + Type of elements in sequence. + */ + associatedtype E + + /** + Converts `self` to `Observable` sequence. + + - returns: Observable sequence that represents `self`. + */ + func asObservable() -> Observable +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObservableType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObservableType.swift new file mode 100644 index 00000000000..5608ac03fd5 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObservableType.swift @@ -0,0 +1,57 @@ +// +// ObservableType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Represents a push style sequence. +*/ +public protocol ObservableType : ObservableConvertibleType { + /** + Type of elements in sequence. + */ + associatedtype E + + /** + Subscribes `observer` to receive events for this sequence. + + ### Grammar + + **Next\* (Error | Completed)?** + + * sequences can produce zero or more elements so zero or more `Next` events can be sent to `observer` + * once an `Error` or `Completed` event is sent, the sequence terminates and can't produce any other elements + + It is possible that events are sent from different threads, but no two events can be sent concurrently to + `observer`. + + ### Resource Management + + When sequence sends `Complete` or `Error` event all internal resources that compute sequence elements + will be freed. + + To cancel production of sequence elements and free resources immediatelly, call `dispose` on returned + subscription. + + - returns: Subscription for `observer` that can be used to cancel production of sequence elements and free resources. + */ + @warn_unused_result(message="http://git.io/rxs.ud") + func subscribe(observer: O) -> Disposable + +} + +extension ObservableType { + + /** + Default implementation of converting `ObservableType` to `Observable`. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func asObservable() -> Observable { + return Observable.create(self.subscribe) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/AddRef.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/AddRef.swift new file mode 100644 index 00000000000..211a9d41f34 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/AddRef.swift @@ -0,0 +1,47 @@ +// +// AddRef.swift +// Rx +// +// Created by Junior B. on 30/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class AddRefSink : Sink, ObserverType { + typealias Element = O.E + + override init(observer: O) { + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(_): + forwardOn(event) + case .Completed, .Error(_): + forwardOn(event) + dispose() + } + } +} + +class AddRef : Producer { + typealias EventHandler = Event throws -> Void + + private let _source: Observable + private let _refCount: RefCountDisposable + + init(source: Observable, refCount: RefCountDisposable) { + _source = source + _refCount = refCount + } + + override func run(observer: O) -> Disposable { + let releaseDisposable = _refCount.retain() + let sink = AddRefSink(observer: observer) + sink.disposable = StableCompositeDisposable.create(releaseDisposable, _source.subscribeSafe(sink)) + + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Amb.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Amb.swift new file mode 100644 index 00000000000..7e9b5452294 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Amb.swift @@ -0,0 +1,122 @@ +// +// Amb.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +enum AmbState { + case Neither + case Left + case Right +} + +class AmbObserver : ObserverType { + typealias Element = ElementType + typealias Parent = AmbSink + typealias This = AmbObserver + typealias Sink = (This, Event) -> Void + + private let _parent: Parent + private var _sink: Sink + private var _cancel: Disposable + + init(parent: Parent, cancel: Disposable, sink: Sink) { +#if TRACE_RESOURCES + AtomicIncrement(&resourceCount) +#endif + + _parent = parent + _sink = sink + _cancel = cancel + } + + func on(event: Event) { + _sink(self, event) + if event.isStopEvent { + _cancel.dispose() + } + } + + deinit { +#if TRACE_RESOURCES + AtomicDecrement(&resourceCount) +#endif + } +} + +class AmbSink : Sink { + typealias Parent = Amb + typealias AmbObserverType = AmbObserver + + private let _parent: Parent + + private let _lock = NSRecursiveLock() + // state + private var _choice = AmbState.Neither + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let disposeAll = StableCompositeDisposable.create(subscription1, subscription2) + + let forwardEvent = { (o: AmbObserverType, event: Event) -> Void in + self.forwardOn(event) + } + + let decide = { (o: AmbObserverType, event: Event, me: AmbState, otherSubscription: Disposable) in + self._lock.performLocked { + if self._choice == .Neither { + self._choice = me + o._sink = forwardEvent + o._cancel = disposeAll + otherSubscription.dispose() + } + + if self._choice == me { + self.forwardOn(event) + if event.isStopEvent { + self.dispose() + } + } + } + } + + let sink1 = AmbObserver(parent: self, cancel: subscription1) { o, e in + decide(o, e, .Left, subscription2) + } + + let sink2 = AmbObserver(parent: self, cancel: subscription1) { o, e in + decide(o, e, .Right, subscription1) + } + + subscription1.disposable = _parent._left.subscribe(sink1) + subscription2.disposable = _parent._right.subscribe(sink2) + + return disposeAll + } +} + +class Amb: Producer { + private let _left: Observable + private let _right: Observable + + init(left: Observable, right: Observable) { + _left = left + _right = right + } + + override func run(observer: O) -> Disposable { + let sink = AmbSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/AnonymousObservable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/AnonymousObservable.swift new file mode 100644 index 00000000000..11346a9ff66 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/AnonymousObservable.swift @@ -0,0 +1,56 @@ +// +// AnonymousObservable.swift +// Rx +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class AnonymousObservableSink : Sink, ObserverType { + typealias E = O.E + typealias Parent = AnonymousObservable + + // state + private var _isStopped: AtomicInt = 0 + + override init(observer: O) { + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next: + if _isStopped == 1 { + return + } + forwardOn(event) + case .Error, .Completed: + if AtomicCompareAndSwap(0, 1, &_isStopped) { + forwardOn(event) + dispose() + } + } + } + + func run(parent: Parent) -> Disposable { + return parent._subscribeHandler(AnyObserver(self)) + } +} + +class AnonymousObservable : Producer { + typealias SubscribeHandler = (AnyObserver) -> Disposable + + let _subscribeHandler: SubscribeHandler + + init(_ subscribeHandler: SubscribeHandler) { + _subscribeHandler = subscribeHandler + } + + override func run(observer: O) -> Disposable { + let sink = AnonymousObservableSink(observer: observer) + sink.disposable = sink.run(self) + return sink + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Buffer.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Buffer.swift new file mode 100644 index 00000000000..0fa4714f2a3 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Buffer.swift @@ -0,0 +1,119 @@ +// +// Buffer.swift +// Rx +// +// Created by Krunoslav Zaher on 9/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class BufferTimeCount : Producer<[Element]> { + + private let _timeSpan: RxTimeInterval + private let _count: Int + private let _scheduler: SchedulerType + private let _source: Observable + + init(source: Observable, timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) { + _source = source + _timeSpan = timeSpan + _count = count + _scheduler = scheduler + } + + override func run(observer: O) -> Disposable { + let sink = BufferTimeCountSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} + +class BufferTimeCountSink + : Sink + , LockOwnerType + , ObserverType + , SynchronizedOnType { + typealias Parent = BufferTimeCount + typealias E = Element + + private let _parent: Parent + + let _lock = NSRecursiveLock() + + // state + private let _timerD = SerialDisposable() + private var _buffer = [Element]() + private var _windowID = 0 + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func run() -> Disposable { + createTimer(_windowID) + return StableCompositeDisposable.create(_timerD, _parent._source.subscribe(self)) + } + + func startNewWindowAndSendCurrentOne() { + _windowID = _windowID &+ 1 + let windowID = _windowID + + let buffer = _buffer + _buffer = [] + forwardOn(.Next(buffer)) + + createTimer(windowID) + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + switch event { + case .Next(let element): + _buffer.append(element) + + if _buffer.count == _parent._count { + startNewWindowAndSendCurrentOne() + } + + case .Error(let error): + _buffer = [] + forwardOn(.Error(error)) + dispose() + case .Completed: + forwardOn(.Next(_buffer)) + forwardOn(.Completed) + dispose() + } + } + + func createTimer(windowID: Int) { + if _timerD.disposed { + return + } + + if _windowID != windowID { + return + } + + let nextTimer = SingleAssignmentDisposable() + + _timerD.disposable = nextTimer + + nextTimer.disposable = _parent._scheduler.scheduleRelative(windowID, dueTime: _parent._timeSpan) { previousWindowID in + self._lock.performLocked { + if previousWindowID != self._windowID { + return + } + + self.startNewWindowAndSendCurrentOne() + } + + return NopDisposable.instance + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Catch.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Catch.swift new file mode 100644 index 00000000000..5f73d40538f --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Catch.swift @@ -0,0 +1,162 @@ +// +// Catch.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +// catch with callback + +class CatchSinkProxy : ObserverType { + typealias E = O.E + typealias Parent = CatchSink + + private let _parent: Parent + + init(parent: Parent) { + _parent = parent + } + + func on(event: Event) { + _parent.forwardOn(event) + + switch event { + case .Next: + break + case .Error, .Completed: + _parent.dispose() + } + } +} + +class CatchSink : Sink, ObserverType { + typealias E = O.E + typealias Parent = Catch + + private let _parent: Parent + private let _subscription = SerialDisposable() + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func run() -> Disposable { + let d1 = SingleAssignmentDisposable() + _subscription.disposable = d1 + d1.disposable = _parent._source.subscribe(self) + + return _subscription + } + + func on(event: Event) { + switch event { + case .Next: + forwardOn(event) + case .Completed: + forwardOn(event) + dispose() + case .Error(let error): + do { + let catchSequence = try _parent._handler(error) + + let observer = CatchSinkProxy(parent: self) + + _subscription.disposable = catchSequence.subscribe(observer) + } + catch let e { + forwardOn(.Error(e)) + dispose() + } + } + } +} + +class Catch : Producer { + typealias Handler = (ErrorType) throws -> Observable + + private let _source: Observable + private let _handler: Handler + + init(source: Observable, handler: Handler) { + _source = source + _handler = handler + } + + override func run(observer: O) -> Disposable { + let sink = CatchSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} + +// catch enumerable + +class CatchSequenceSink + : TailRecursiveSink + , ObserverType { + typealias Element = O.E + typealias Parent = CatchSequence + + private var _lastError: ErrorType? + + override init(observer: O) { + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next: + forwardOn(event) + case .Error(let error): + _lastError = error + schedule(.MoveNext) + case .Completed: + forwardOn(event) + dispose() + } + } + + override func subscribeToNext(source: Observable) -> Disposable { + return source.subscribe(self) + } + + override func done() { + if let lastError = _lastError { + forwardOn(.Error(lastError)) + } + else { + forwardOn(.Completed) + } + + self.dispose() + } + + override func extract(observable: Observable) -> SequenceGenerator? { + if let onError = observable as? CatchSequence { + return (onError.sources.generate(), nil) + } + else { + return nil + } + } +} + +class CatchSequence : Producer { + typealias Element = S.Generator.Element.E + + let sources: S + + init(sources: S) { + self.sources = sources + } + + override func run(observer: O) -> Disposable { + let sink = CatchSequenceSink(observer: observer) + sink.disposable = sink.run((self.sources.generate(), nil)) + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/CombineLatest+CollectionType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/CombineLatest+CollectionType.swift new file mode 100644 index 00000000000..7164815d7ab --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/CombineLatest+CollectionType.swift @@ -0,0 +1,125 @@ +// +// CombineLatest+CollectionType.swift +// Rx +// +// Created by Krunoslav Zaher on 8/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class CombineLatestCollectionTypeSink + : Sink { + typealias Parent = CombineLatestCollectionType + typealias SourceElement = C.Generator.Element.E + + let _parent: Parent + + let _lock = NSRecursiveLock() + + // state + var _numberOfValues = 0 + var _values: [SourceElement?] + var _isDone: [Bool] + var _numberOfDone = 0 + var _subscriptions: [SingleAssignmentDisposable] + + init(parent: Parent, observer: O) { + _parent = parent + _values = [SourceElement?](count: parent._count, repeatedValue: nil) + _isDone = [Bool](count: parent._count, repeatedValue: false) + _subscriptions = Array() + _subscriptions.reserveCapacity(parent._count) + + for _ in 0 ..< parent._count { + _subscriptions.append(SingleAssignmentDisposable()) + } + + super.init(observer: observer) + } + + func on(event: Event, atIndex: Int) { + _lock.lock(); defer { _lock.unlock() } // { + switch event { + case .Next(let element): + if _values[atIndex] == nil { + _numberOfValues += 1 + } + + _values[atIndex] = element + + if _numberOfValues < _parent._count { + let numberOfOthersThatAreDone = self._numberOfDone - (_isDone[atIndex] ? 1 : 0) + if numberOfOthersThatAreDone == self._parent._count - 1 { + forwardOn(.Completed) + dispose() + } + return + } + + do { + let result = try _parent._resultSelector(_values.map { $0! }) + forwardOn(.Next(result)) + } + catch let error { + forwardOn(.Error(error)) + dispose() + } + + case .Error(let error): + forwardOn(.Error(error)) + dispose() + case .Completed: + if _isDone[atIndex] { + return + } + + _isDone[atIndex] = true + _numberOfDone += 1 + + if _numberOfDone == self._parent._count { + forwardOn(.Completed) + dispose() + } + else { + _subscriptions[atIndex].dispose() + } + } + // } + } + + func run() -> Disposable { + var j = 0 + for i in _parent._sources.startIndex ..< _parent._sources.endIndex { + let index = j + let source = _parent._sources[i].asObservable() + _subscriptions[j].disposable = source.subscribe(AnyObserver { event in + self.on(event, atIndex: index) + }) + + j += 1 + } + + return CompositeDisposable(disposables: _subscriptions.map { $0 }) + } +} + +class CombineLatestCollectionType : Producer { + typealias ResultSelector = [C.Generator.Element.E] throws -> R + + let _sources: C + let _resultSelector: ResultSelector + let _count: Int + + init(sources: C, resultSelector: ResultSelector) { + _sources = sources + _resultSelector = resultSelector + _count = Int(self._sources.count.toIntMax()) + } + + override func run(observer: O) -> Disposable { + let sink = CombineLatestCollectionTypeSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/CombineLatest+arity.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/CombineLatest+arity.swift new file mode 100644 index 00000000000..5d5ea47aafc --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/CombineLatest+arity.swift @@ -0,0 +1,724 @@ +// This file is autogenerated. Take a look at `Preprocessor` target in RxSwift project +// +// CombineLatest+arity.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/22/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + + + +// 2 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func combineLatest + (source1: O1, _ source2: O2, resultSelector: (O1.E, O2.E) throws -> E) + -> Observable { + return CombineLatest2( + source1: source1.asObservable(), source2: source2.asObservable(), + resultSelector: resultSelector + ) + } +} + +class CombineLatestSink2_ : CombineLatestSink { + typealias R = O.E + typealias Parent = CombineLatest2 + + let _parent: Parent + + var _latestElement1: E1! = nil + var _latestElement2: E2! = nil + + init(parent: Parent, observer: O) { + _parent = parent + super.init(arity: 2, observer: observer) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: _lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self._latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: _lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self._latestElement2 = e }, this: subscription2) + + subscription1.disposable = _parent._source1.subscribe(observer1) + subscription2.disposable = _parent._source2.subscribe(observer2) + + return CompositeDisposable(disposables: [ + subscription1, + subscription2 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_latestElement1, _latestElement2) + } +} + +class CombineLatest2 : Producer { + typealias ResultSelector = (E1, E2) throws -> R + + let _source1: Observable + let _source2: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, resultSelector: ResultSelector) { + _source1 = source1 + _source2 = source2 + + _resultSelector = resultSelector + } + + override func run(observer: O) -> Disposable { + let sink = CombineLatestSink2_(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} + + + +// 3 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func combineLatest + (source1: O1, _ source2: O2, _ source3: O3, resultSelector: (O1.E, O2.E, O3.E) throws -> E) + -> Observable { + return CombineLatest3( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), + resultSelector: resultSelector + ) + } +} + +class CombineLatestSink3_ : CombineLatestSink { + typealias R = O.E + typealias Parent = CombineLatest3 + + let _parent: Parent + + var _latestElement1: E1! = nil + var _latestElement2: E2! = nil + var _latestElement3: E3! = nil + + init(parent: Parent, observer: O) { + _parent = parent + super.init(arity: 3, observer: observer) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: _lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self._latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: _lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self._latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: _lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self._latestElement3 = e }, this: subscription3) + + subscription1.disposable = _parent._source1.subscribe(observer1) + subscription2.disposable = _parent._source2.subscribe(observer2) + subscription3.disposable = _parent._source3.subscribe(observer3) + + return CompositeDisposable(disposables: [ + subscription1, + subscription2, + subscription3 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_latestElement1, _latestElement2, _latestElement3) + } +} + +class CombineLatest3 : Producer { + typealias ResultSelector = (E1, E2, E3) throws -> R + + let _source1: Observable + let _source2: Observable + let _source3: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, resultSelector: ResultSelector) { + _source1 = source1 + _source2 = source2 + _source3 = source3 + + _resultSelector = resultSelector + } + + override func run(observer: O) -> Disposable { + let sink = CombineLatestSink3_(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} + + + +// 4 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func combineLatest + (source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, resultSelector: (O1.E, O2.E, O3.E, O4.E) throws -> E) + -> Observable { + return CombineLatest4( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), + resultSelector: resultSelector + ) + } +} + +class CombineLatestSink4_ : CombineLatestSink { + typealias R = O.E + typealias Parent = CombineLatest4 + + let _parent: Parent + + var _latestElement1: E1! = nil + var _latestElement2: E2! = nil + var _latestElement3: E3! = nil + var _latestElement4: E4! = nil + + init(parent: Parent, observer: O) { + _parent = parent + super.init(arity: 4, observer: observer) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: _lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self._latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: _lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self._latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: _lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self._latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: _lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self._latestElement4 = e }, this: subscription4) + + subscription1.disposable = _parent._source1.subscribe(observer1) + subscription2.disposable = _parent._source2.subscribe(observer2) + subscription3.disposable = _parent._source3.subscribe(observer3) + subscription4.disposable = _parent._source4.subscribe(observer4) + + return CompositeDisposable(disposables: [ + subscription1, + subscription2, + subscription3, + subscription4 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_latestElement1, _latestElement2, _latestElement3, _latestElement4) + } +} + +class CombineLatest4 : Producer { + typealias ResultSelector = (E1, E2, E3, E4) throws -> R + + let _source1: Observable + let _source2: Observable + let _source3: Observable + let _source4: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, resultSelector: ResultSelector) { + _source1 = source1 + _source2 = source2 + _source3 = source3 + _source4 = source4 + + _resultSelector = resultSelector + } + + override func run(observer: O) -> Disposable { + let sink = CombineLatestSink4_(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} + + + +// 5 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func combineLatest + (source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, resultSelector: (O1.E, O2.E, O3.E, O4.E, O5.E) throws -> E) + -> Observable { + return CombineLatest5( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), + resultSelector: resultSelector + ) + } +} + +class CombineLatestSink5_ : CombineLatestSink { + typealias R = O.E + typealias Parent = CombineLatest5 + + let _parent: Parent + + var _latestElement1: E1! = nil + var _latestElement2: E2! = nil + var _latestElement3: E3! = nil + var _latestElement4: E4! = nil + var _latestElement5: E5! = nil + + init(parent: Parent, observer: O) { + _parent = parent + super.init(arity: 5, observer: observer) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: _lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self._latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: _lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self._latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: _lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self._latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: _lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self._latestElement4 = e }, this: subscription4) + let observer5 = CombineLatestObserver(lock: _lock, parent: self, index: 4, setLatestValue: { (e: E5) -> Void in self._latestElement5 = e }, this: subscription5) + + subscription1.disposable = _parent._source1.subscribe(observer1) + subscription2.disposable = _parent._source2.subscribe(observer2) + subscription3.disposable = _parent._source3.subscribe(observer3) + subscription4.disposable = _parent._source4.subscribe(observer4) + subscription5.disposable = _parent._source5.subscribe(observer5) + + return CompositeDisposable(disposables: [ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_latestElement1, _latestElement2, _latestElement3, _latestElement4, _latestElement5) + } +} + +class CombineLatest5 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5) throws -> R + + let _source1: Observable + let _source2: Observable + let _source3: Observable + let _source4: Observable + let _source5: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, resultSelector: ResultSelector) { + _source1 = source1 + _source2 = source2 + _source3 = source3 + _source4 = source4 + _source5 = source5 + + _resultSelector = resultSelector + } + + override func run(observer: O) -> Disposable { + let sink = CombineLatestSink5_(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} + + + +// 6 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func combineLatest + (source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, resultSelector: (O1.E, O2.E, O3.E, O4.E, O5.E, O6.E) throws -> E) + -> Observable { + return CombineLatest6( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), + resultSelector: resultSelector + ) + } +} + +class CombineLatestSink6_ : CombineLatestSink { + typealias R = O.E + typealias Parent = CombineLatest6 + + let _parent: Parent + + var _latestElement1: E1! = nil + var _latestElement2: E2! = nil + var _latestElement3: E3! = nil + var _latestElement4: E4! = nil + var _latestElement5: E5! = nil + var _latestElement6: E6! = nil + + init(parent: Parent, observer: O) { + _parent = parent + super.init(arity: 6, observer: observer) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: _lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self._latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: _lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self._latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: _lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self._latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: _lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self._latestElement4 = e }, this: subscription4) + let observer5 = CombineLatestObserver(lock: _lock, parent: self, index: 4, setLatestValue: { (e: E5) -> Void in self._latestElement5 = e }, this: subscription5) + let observer6 = CombineLatestObserver(lock: _lock, parent: self, index: 5, setLatestValue: { (e: E6) -> Void in self._latestElement6 = e }, this: subscription6) + + subscription1.disposable = _parent._source1.subscribe(observer1) + subscription2.disposable = _parent._source2.subscribe(observer2) + subscription3.disposable = _parent._source3.subscribe(observer3) + subscription4.disposable = _parent._source4.subscribe(observer4) + subscription5.disposable = _parent._source5.subscribe(observer5) + subscription6.disposable = _parent._source6.subscribe(observer6) + + return CompositeDisposable(disposables: [ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_latestElement1, _latestElement2, _latestElement3, _latestElement4, _latestElement5, _latestElement6) + } +} + +class CombineLatest6 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6) throws -> R + + let _source1: Observable + let _source2: Observable + let _source3: Observable + let _source4: Observable + let _source5: Observable + let _source6: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, resultSelector: ResultSelector) { + _source1 = source1 + _source2 = source2 + _source3 = source3 + _source4 = source4 + _source5 = source5 + _source6 = source6 + + _resultSelector = resultSelector + } + + override func run(observer: O) -> Disposable { + let sink = CombineLatestSink6_(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} + + + +// 7 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func combineLatest + (source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, resultSelector: (O1.E, O2.E, O3.E, O4.E, O5.E, O6.E, O7.E) throws -> E) + -> Observable { + return CombineLatest7( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), + resultSelector: resultSelector + ) + } +} + +class CombineLatestSink7_ : CombineLatestSink { + typealias R = O.E + typealias Parent = CombineLatest7 + + let _parent: Parent + + var _latestElement1: E1! = nil + var _latestElement2: E2! = nil + var _latestElement3: E3! = nil + var _latestElement4: E4! = nil + var _latestElement5: E5! = nil + var _latestElement6: E6! = nil + var _latestElement7: E7! = nil + + init(parent: Parent, observer: O) { + _parent = parent + super.init(arity: 7, observer: observer) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + let subscription7 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: _lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self._latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: _lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self._latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: _lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self._latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: _lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self._latestElement4 = e }, this: subscription4) + let observer5 = CombineLatestObserver(lock: _lock, parent: self, index: 4, setLatestValue: { (e: E5) -> Void in self._latestElement5 = e }, this: subscription5) + let observer6 = CombineLatestObserver(lock: _lock, parent: self, index: 5, setLatestValue: { (e: E6) -> Void in self._latestElement6 = e }, this: subscription6) + let observer7 = CombineLatestObserver(lock: _lock, parent: self, index: 6, setLatestValue: { (e: E7) -> Void in self._latestElement7 = e }, this: subscription7) + + subscription1.disposable = _parent._source1.subscribe(observer1) + subscription2.disposable = _parent._source2.subscribe(observer2) + subscription3.disposable = _parent._source3.subscribe(observer3) + subscription4.disposable = _parent._source4.subscribe(observer4) + subscription5.disposable = _parent._source5.subscribe(observer5) + subscription6.disposable = _parent._source6.subscribe(observer6) + subscription7.disposable = _parent._source7.subscribe(observer7) + + return CompositeDisposable(disposables: [ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6, + subscription7 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_latestElement1, _latestElement2, _latestElement3, _latestElement4, _latestElement5, _latestElement6, _latestElement7) + } +} + +class CombineLatest7 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7) throws -> R + + let _source1: Observable + let _source2: Observable + let _source3: Observable + let _source4: Observable + let _source5: Observable + let _source6: Observable + let _source7: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, source7: Observable, resultSelector: ResultSelector) { + _source1 = source1 + _source2 = source2 + _source3 = source3 + _source4 = source4 + _source5 = source5 + _source6 = source6 + _source7 = source7 + + _resultSelector = resultSelector + } + + override func run(observer: O) -> Disposable { + let sink = CombineLatestSink7_(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} + + + +// 8 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func combineLatest + (source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8, resultSelector: (O1.E, O2.E, O3.E, O4.E, O5.E, O6.E, O7.E, O8.E) throws -> E) + -> Observable { + return CombineLatest8( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), source8: source8.asObservable(), + resultSelector: resultSelector + ) + } +} + +class CombineLatestSink8_ : CombineLatestSink { + typealias R = O.E + typealias Parent = CombineLatest8 + + let _parent: Parent + + var _latestElement1: E1! = nil + var _latestElement2: E2! = nil + var _latestElement3: E3! = nil + var _latestElement4: E4! = nil + var _latestElement5: E5! = nil + var _latestElement6: E6! = nil + var _latestElement7: E7! = nil + var _latestElement8: E8! = nil + + init(parent: Parent, observer: O) { + _parent = parent + super.init(arity: 8, observer: observer) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + let subscription7 = SingleAssignmentDisposable() + let subscription8 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: _lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self._latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: _lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self._latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: _lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self._latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: _lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self._latestElement4 = e }, this: subscription4) + let observer5 = CombineLatestObserver(lock: _lock, parent: self, index: 4, setLatestValue: { (e: E5) -> Void in self._latestElement5 = e }, this: subscription5) + let observer6 = CombineLatestObserver(lock: _lock, parent: self, index: 5, setLatestValue: { (e: E6) -> Void in self._latestElement6 = e }, this: subscription6) + let observer7 = CombineLatestObserver(lock: _lock, parent: self, index: 6, setLatestValue: { (e: E7) -> Void in self._latestElement7 = e }, this: subscription7) + let observer8 = CombineLatestObserver(lock: _lock, parent: self, index: 7, setLatestValue: { (e: E8) -> Void in self._latestElement8 = e }, this: subscription8) + + subscription1.disposable = _parent._source1.subscribe(observer1) + subscription2.disposable = _parent._source2.subscribe(observer2) + subscription3.disposable = _parent._source3.subscribe(observer3) + subscription4.disposable = _parent._source4.subscribe(observer4) + subscription5.disposable = _parent._source5.subscribe(observer5) + subscription6.disposable = _parent._source6.subscribe(observer6) + subscription7.disposable = _parent._source7.subscribe(observer7) + subscription8.disposable = _parent._source8.subscribe(observer8) + + return CompositeDisposable(disposables: [ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6, + subscription7, + subscription8 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_latestElement1, _latestElement2, _latestElement3, _latestElement4, _latestElement5, _latestElement6, _latestElement7, _latestElement8) + } +} + +class CombineLatest8 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7, E8) throws -> R + + let _source1: Observable + let _source2: Observable + let _source3: Observable + let _source4: Observable + let _source5: Observable + let _source6: Observable + let _source7: Observable + let _source8: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, source7: Observable, source8: Observable, resultSelector: ResultSelector) { + _source1 = source1 + _source2 = source2 + _source3 = source3 + _source4 = source4 + _source5 = source5 + _source6 = source6 + _source7 = source7 + _source8 = source8 + + _resultSelector = resultSelector + } + + override func run(observer: O) -> Disposable { + let sink = CombineLatestSink8_(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/CombineLatest.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/CombineLatest.swift new file mode 100644 index 00000000000..6662edb8dcc --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/CombineLatest.swift @@ -0,0 +1,134 @@ +// +// CombineLatest.swift +// Rx +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +protocol CombineLatestProtocol : class { + func next(index: Int) + func fail(error: ErrorType) + func done(index: Int) +} + +class CombineLatestSink + : Sink + , CombineLatestProtocol { + typealias Element = O.E + + let _lock = NSRecursiveLock() + + private let _arity: Int + private var _numberOfValues = 0 + private var _numberOfDone = 0 + private var _hasValue: [Bool] + private var _isDone: [Bool] + + init(arity: Int, observer: O) { + _arity = arity + _hasValue = [Bool](count: arity, repeatedValue: false) + _isDone = [Bool](count: arity, repeatedValue: false) + + super.init(observer: observer) + } + + func getResult() throws -> Element { + abstractMethod() + } + + func next(index: Int) { + if !_hasValue[index] { + _hasValue[index] = true + _numberOfValues += 1 + } + + if _numberOfValues == _arity { + do { + let result = try getResult() + forwardOn(.Next(result)) + } + catch let e { + forwardOn(.Error(e)) + dispose() + } + } + else { + var allOthersDone = true + + for i in 0 ..< _arity { + if i != index && !_isDone[i] { + allOthersDone = false + break + } + } + + if allOthersDone { + forwardOn(.Completed) + dispose() + } + } + } + + func fail(error: ErrorType) { + forwardOn(.Error(error)) + dispose() + } + + func done(index: Int) { + if _isDone[index] { + return + } + + _isDone[index] = true + _numberOfDone += 1 + + if _numberOfDone == _arity { + forwardOn(.Completed) + dispose() + } + } +} + +class CombineLatestObserver + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = ElementType + typealias ValueSetter = (Element) -> Void + + private let _parent: CombineLatestProtocol + + let _lock: NSRecursiveLock + private let _index: Int + private let _this: Disposable + private let _setLatestValue: ValueSetter + + init(lock: NSRecursiveLock, parent: CombineLatestProtocol, index: Int, setLatestValue: ValueSetter, this: Disposable) { + _lock = lock + _parent = parent + _index = index + _this = this + _setLatestValue = setLatestValue + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + switch event { + case .Next(let value): + _setLatestValue(value) + _parent.next(_index) + case .Error(let error): + _this.dispose() + _parent.fail(error) + case .Completed: + _this.dispose() + _parent.done(_index) + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Concat.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Concat.swift new file mode 100644 index 00000000000..85feff2e871 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Concat.swift @@ -0,0 +1,63 @@ +// +// Concat.swift +// Rx +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + + +class ConcatSink + : TailRecursiveSink + , ObserverType { + typealias Element = O.E + + override init(observer: O) { + super.init(observer: observer) + } + + func on(event: Event){ + switch event { + case .Next: + forwardOn(event) + case .Error: + forwardOn(event) + dispose() + case .Completed: + schedule(.MoveNext) + } + } + + override func subscribeToNext(source: Observable) -> Disposable { + return source.subscribe(self) + } + + override func extract(observable: Observable) -> SequenceGenerator? { + if let source = observable as? Concat { + return (source._sources.generate(), source._count) + } + else { + return nil + } + } +} + +class Concat : Producer { + typealias Element = S.Generator.Element.E + + private let _sources: S + private let _count: IntMax? + + init(sources: S, count: IntMax?) { + _sources = sources + _count = count + } + + override func run(observer: O) -> Disposable { + let sink = ConcatSink(observer: observer) + sink.disposable = sink.run((_sources.generate(), _count)) + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ConnectableObservable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ConnectableObservable.swift new file mode 100644 index 00000000000..72d4ed29cc4 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ConnectableObservable.swift @@ -0,0 +1,96 @@ +// +// ConnectableObservable.swift +// Rx +// +// Created by Krunoslav Zaher on 3/1/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** + Represents an observable wrapper that can be connected and disconnected from its underlying observable sequence. +*/ +public class ConnectableObservable + : Observable + , ConnectableObservableType { + + /** + Connects the observable wrapper to its source. All subscribed observers will receive values from the underlying observable sequence as long as the connection is established. + + - returns: Disposable used to disconnect the observable wrapper from its source, causing subscribed observer to stop receiving values from the underlying observable sequence. + */ + public func connect() -> Disposable { + abstractMethod() + } +} + +class Connection : Disposable { + + private var _lock: NSRecursiveLock + // state + private var _parent: ConnectableObservableAdapter? + private var _subscription : Disposable? + + init(parent: ConnectableObservableAdapter, lock: NSRecursiveLock, subscription: Disposable) { + _parent = parent + _subscription = subscription + _lock = lock + } + + func dispose() { + _lock.lock(); defer { _lock.unlock() } // { + guard let parent = _parent else { + return + } + + guard let oldSubscription = _subscription else { + return + } + + _subscription = nil + if parent._connection === self { + parent._connection = nil + } + _parent = nil + + oldSubscription.dispose() + // } + } +} + +class ConnectableObservableAdapter + : ConnectableObservable { + typealias ConnectionType = Connection + + private let _subject: S + private let _source: Observable + + private let _lock = NSRecursiveLock() + + // state + private var _connection: ConnectionType? + + init(source: Observable, subject: S) { + _source = source + _subject = subject + _connection = nil + } + + override func connect() -> Disposable { + return _lock.calculateLocked { + if let connection = _connection { + return connection + } + + let disposable = _source.subscribe(_subject.asObserver()) + let connection = Connection(parent: self, lock: _lock, subscription: disposable) + _connection = connection + return connection + } + } + + override func subscribe(observer: O) -> Disposable { + return _subject.subscribe(observer) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Debug.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Debug.swift new file mode 100644 index 00000000000..66b65f25b38 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Debug.swift @@ -0,0 +1,77 @@ +// +// Debug.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +let dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" + +func logEvent(identifier: String, dateFormat: NSDateFormatter, content: String) { + print("\(dateFormat.stringFromDate(NSDate())): \(identifier) -> \(content)") +} + +class Debug_ : Sink, ObserverType { + typealias Element = O.E + typealias Parent = Debug + + private let _parent: Parent + private let _timestampFormatter = NSDateFormatter() + + init(parent: Parent, observer: O) { + _parent = parent + _timestampFormatter.dateFormat = dateFormat + + logEvent(_parent._identifier, dateFormat: _timestampFormatter, content: "subscribed") + + super.init(observer: observer) + } + + func on(event: Event) { + let maxEventTextLength = 40 + let eventText = "\(event)" + let eventNormalized = eventText.characters.count > maxEventTextLength + ? String(eventText.characters.prefix(maxEventTextLength / 2)) + "..." + String(eventText.characters.suffix(maxEventTextLength / 2)) + : eventText + + logEvent(_parent._identifier, dateFormat: _timestampFormatter, content: "Event \(eventNormalized)") + forwardOn(event) + } + + override func dispose() { + logEvent(_parent._identifier, dateFormat: _timestampFormatter, content: "disposed") + super.dispose() + } +} + +class Debug : Producer { + private let _identifier: String + + private let _source: Observable + + init(source: Observable, identifier: String?, file: String, line: UInt, function: String) { + if let identifier = identifier { + _identifier = identifier + } + else { + let trimmedFile: String + if let lastIndex = file.lastIndexOf("/") { + trimmedFile = file[lastIndex.successor() ..< file.endIndex] + } + else { + trimmedFile = file + } + _identifier = "\(trimmedFile):\(line) (\(function))" + } + _source = source + } + + override func run(observer: O) -> Disposable { + let sink = Debug_(parent: self, observer: observer) + sink.disposable = _source.subscribe(sink) + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Deferred.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Deferred.swift new file mode 100644 index 00000000000..900082c4d93 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Deferred.swift @@ -0,0 +1,61 @@ +// +// Deferred.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class DeferredSink : Sink, ObserverType { + typealias E = O.E + + private let _observableFactory: () throws -> S + + init(observableFactory: () throws -> S, observer: O) { + _observableFactory = observableFactory + super.init(observer: observer) + } + + func run() -> Disposable { + do { + let result = try _observableFactory() + return result.subscribe(self) + } + catch let e { + forwardOn(.Error(e)) + dispose() + return NopDisposable.instance + } + } + + func on(event: Event) { + forwardOn(event) + + switch event { + case .Next: + break + case .Error: + dispose() + case .Completed: + dispose() + } + } +} + +class Deferred : Producer { + typealias Factory = () throws -> S + + private let _observableFactory : Factory + + init(observableFactory: Factory) { + _observableFactory = observableFactory + } + + override func run(observer: O) -> Disposable { + let sink = DeferredSink(observableFactory: _observableFactory, observer: observer) + sink.disposable = sink.run() + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/DelaySubscription.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/DelaySubscription.swift new file mode 100644 index 00000000000..31d7c7c7a0a --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/DelaySubscription.swift @@ -0,0 +1,52 @@ +// +// DelaySubscription.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class DelaySubscriptionSink + : Sink + , ObserverType { + typealias Parent = DelaySubscription + typealias E = O.E + + private let _parent: Parent + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func on(event: Event) { + forwardOn(event) + if event.isStopEvent { + dispose() + } + } + +} + +class DelaySubscription: Producer { + private let _source: Observable + private let _dueTime: RxTimeInterval + private let _scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, scheduler: SchedulerType) { + _source = source + _dueTime = dueTime + _scheduler = scheduler + } + + override func run(observer: O) -> Disposable { + let sink = DelaySubscriptionSink(parent: self, observer: observer) + sink.disposable = _scheduler.scheduleRelative((), dueTime: _dueTime) { _ in + return self._source.subscribe(sink) + } + + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/DistinctUntilChanged.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/DistinctUntilChanged.swift new file mode 100644 index 00000000000..cff09a898e8 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/DistinctUntilChanged.swift @@ -0,0 +1,70 @@ +// +// DistinctUntilChanged.swift +// Rx +// +// Created by Krunoslav Zaher on 3/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class DistinctUntilChangedSink: Sink, ObserverType { + typealias E = O.E + + private let _parent: DistinctUntilChanged + private var _currentKey: Key? = nil + + init(parent: DistinctUntilChanged, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(let value): + do { + let key = try _parent._selector(value) + var areEqual = false + if let currentKey = _currentKey { + areEqual = try _parent._comparer(currentKey, key) + } + + if areEqual { + return + } + + _currentKey = key + + forwardOn(event) + } + catch let error { + forwardOn(.Error(error)) + dispose() + } + case .Error, .Completed: + forwardOn(event) + dispose() + } + } +} + +class DistinctUntilChanged: Producer { + typealias KeySelector = (Element) throws -> Key + typealias EqualityComparer = (Key, Key) throws -> Bool + + private let _source: Observable + private let _selector: KeySelector + private let _comparer: EqualityComparer + + init(source: Observable, selector: KeySelector, comparer: EqualityComparer) { + _source = source + _selector = selector + _comparer = comparer + } + + override func run(observer: O) -> Disposable { + let sink = DistinctUntilChangedSink(parent: self, observer: observer) + sink.disposable = _source.subscribe(sink) + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Do.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Do.swift new file mode 100644 index 00000000000..7fc07dcb706 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Do.swift @@ -0,0 +1,53 @@ +// +// Do.swift +// Rx +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class DoSink : Sink, ObserverType { + typealias Element = O.E + typealias Parent = Do + + private let _parent: Parent + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func on(event: Event) { + do { + try _parent._eventHandler(event) + forwardOn(event) + if event.isStopEvent { + dispose() + } + } + catch let error { + forwardOn(.Error(error)) + dispose() + } + } +} + +class Do : Producer { + typealias EventHandler = Event throws -> Void + + private let _source: Observable + private let _eventHandler: EventHandler + + init(source: Observable, eventHandler: EventHandler) { + _source = source + _eventHandler = eventHandler + } + + override func run(observer: O) -> Disposable { + let sink = DoSink(parent: self, observer: observer) + sink.disposable = _source.subscribe(sink) + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ElementAt.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ElementAt.swift new file mode 100644 index 00000000000..158e471572d --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ElementAt.swift @@ -0,0 +1,79 @@ +// +// ElementAt.swift +// Rx +// +// Created by Junior B. on 21/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + + +class ElementAtSink : Sink, ObserverType { + typealias Parent = ElementAt + + let _parent: Parent + var _i: Int + + init(parent: Parent, observer: O) { + _parent = parent + _i = parent._index + + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(_): + + if (_i == 0) { + forwardOn(event) + forwardOn(.Completed) + self.dispose() + } + + do { + try decrementChecked(&_i) + } catch(let e) { + forwardOn(.Error(e)) + dispose() + return + } + + case .Error(let e): + forwardOn(.Error(e)) + self.dispose() + case .Completed: + if (_parent._throwOnEmpty) { + forwardOn(.Error(RxError.ArgumentOutOfRange)) + } else { + forwardOn(.Completed) + } + + self.dispose() + } + } +} + +class ElementAt : Producer { + + let _source: Observable + let _throwOnEmpty: Bool + let _index: Int + + init(source: Observable, index: Int, throwOnEmpty: Bool) { + if index < 0 { + rxFatalError("index can't be negative") + } + + self._source = source + self._index = index + self._throwOnEmpty = throwOnEmpty + } + + override func run(observer: O) -> Disposable { + let sink = ElementAtSink(parent: self, observer: observer) + sink.disposable = _source.subscribeSafe(sink) + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Empty.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Empty.swift new file mode 100644 index 00000000000..d2ebb1886a6 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Empty.swift @@ -0,0 +1,16 @@ +// +// Empty.swift +// Rx +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class Empty : Producer { + override func subscribe(observer: O) -> Disposable { + observer.on(.Completed) + return NopDisposable.instance + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Error.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Error.swift new file mode 100644 index 00000000000..ba0abf940a3 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Error.swift @@ -0,0 +1,22 @@ +// +// Error.swift +// Rx +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class Error : Producer { + private let _error: ErrorType + + init(error: ErrorType) { + _error = error + } + + override func subscribe(observer: O) -> Disposable { + observer.on(.Error(_error)) + return NopDisposable.instance + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Filter.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Filter.swift new file mode 100644 index 00000000000..43d7a18f6c6 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Filter.swift @@ -0,0 +1,60 @@ +// +// Filter.swift +// Rx +// +// Created by Krunoslav Zaher on 2/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class FilterSink: Sink, ObserverType { + typealias Predicate = (Element) throws -> Bool + typealias Element = O.E + + typealias Parent = Filter + + private let _predicate: Predicate + + init(predicate: Predicate, observer: O) { + _predicate = predicate + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(let value): + do { + let satisfies = try _predicate(value) + if satisfies { + forwardOn(.Next(value)) + } + } + catch let e { + forwardOn(.Error(e)) + dispose() + } + case .Completed, .Error: + forwardOn(event) + dispose() + } + } +} + +class Filter : Producer { + typealias Predicate = (Element) throws -> Bool + + private let _source: Observable + private let _predicate: Predicate + + init(source: Observable, predicate: Predicate) { + _source = source + _predicate = predicate + } + + override func run(observer: O) -> Disposable { + let sink = FilterSink(predicate: _predicate, observer: observer) + sink.disposable = _source.subscribe(sink) + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Generate.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Generate.swift new file mode 100644 index 00000000000..d60a9b7431c --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Generate.swift @@ -0,0 +1,71 @@ +// +// Generate.swift +// Rx +// +// Created by Krunoslav Zaher on 9/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class GenerateSink : Sink { + typealias Parent = Generate + + private let _parent: Parent + + private var _state: S + + init(parent: Parent, observer: O) { + _parent = parent + _state = parent._initialState + super.init(observer: observer) + } + + func run() -> Disposable { + return _parent._scheduler.scheduleRecursive(true) { (isFirst, recurse) -> Void in + do { + if !isFirst { + self._state = try self._parent._iterate(self._state) + } + + if try self._parent._condition(self._state) { + let result = try self._parent._resultSelector(self._state) + self.forwardOn(.Next(result)) + + recurse(false) + } + else { + self.forwardOn(.Completed) + self.dispose() + } + } + catch let error { + self.forwardOn(.Error(error)) + self.dispose() + } + } + } +} + +class Generate : Producer { + private let _initialState: S + private let _condition: S throws -> Bool + private let _iterate: S throws -> S + private let _resultSelector: S throws -> E + private let _scheduler: ImmediateSchedulerType + + init(initialState: S, condition: S throws -> Bool, iterate: S throws -> S, resultSelector: S throws -> E, scheduler: ImmediateSchedulerType) { + _initialState = initialState + _condition = condition + _iterate = iterate + _resultSelector = resultSelector + _scheduler = scheduler + super.init() + } + + override func run(observer: O) -> Disposable { + let sink = GenerateSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Just.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Just.swift new file mode 100644 index 00000000000..d116d641582 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Just.swift @@ -0,0 +1,61 @@ +// +// Just.swift +// Rx +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class JustScheduledSink : Sink { + typealias Parent = JustScheduled + + private let _parent: Parent + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func run() -> Disposable { + let scheduler = _parent._scheduler + return scheduler.schedule(_parent._element) { element in + self.forwardOn(.Next(element)) + return scheduler.schedule(()) { _ in + self.forwardOn(.Completed) + return NopDisposable.instance + } + } + } +} + +class JustScheduled : Producer { + private let _scheduler: ImmediateSchedulerType + private let _element: Element + + init(element: Element, scheduler: ImmediateSchedulerType) { + _scheduler = scheduler + _element = element + } + + override func subscribe(observer: O) -> Disposable { + let sink = JustScheduledSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} + +class Just : Producer { + private let _element: Element + + init(element: Element) { + _element = element + } + + override func subscribe(observer: O) -> Disposable { + observer.on(.Next(_element)) + observer.on(.Completed) + return NopDisposable.instance + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Map.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Map.swift new file mode 100644 index 00000000000..54a3404dc52 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Map.swift @@ -0,0 +1,140 @@ +// +// Map.swift +// Rx +// +// Created by Krunoslav Zaher on 3/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class MapSink : Sink, ObserverType { + typealias Selector = (SourceType) throws -> ResultType + + typealias ResultType = O.E + typealias Element = SourceType + + private let _selector: Selector + + init(selector: Selector, observer: O) { + _selector = selector + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(let element): + do { + let mappedElement = try _selector(element) + forwardOn(.Next(mappedElement)) + } + catch let e { + forwardOn(.Error(e)) + dispose() + } + case .Error(let error): + forwardOn(.Error(error)) + dispose() + case .Completed: + forwardOn(.Completed) + dispose() + } + } +} + +class MapWithIndexSink : Sink, ObserverType { + typealias Selector = (SourceType, Int) throws -> ResultType + + typealias ResultType = O.E + typealias Element = SourceType + typealias Parent = MapWithIndex + + private let _selector: Selector + + private var _index = 0 + + init(selector: Selector, observer: O) { + _selector = selector + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(let element): + do { + let mappedElement = try _selector(element, try incrementChecked(&_index)) + forwardOn(.Next(mappedElement)) + } + catch let e { + forwardOn(.Error(e)) + dispose() + } + case .Error(let error): + forwardOn(.Error(error)) + dispose() + case .Completed: + forwardOn(.Completed) + dispose() + } + } +} + +class MapWithIndex : Producer { + typealias Selector = (SourceType, Int) throws -> ResultType + + private let _source: Observable + + private let _selector: Selector + + init(source: Observable, selector: Selector) { + _source = source + _selector = selector + } + + override func run(observer: O) -> Disposable { + let sink = MapWithIndexSink(selector: _selector, observer: observer) + sink.disposable = _source.subscribe(sink) + return sink + } +} + +#if TRACE_RESOURCES +public var numberOfMapOperators: Int32 = 0 +#endif + +class Map: Producer { + typealias Selector = (SourceType) throws -> ResultType + + private let _source: Observable + + private let _selector: Selector + + init(source: Observable, selector: Selector) { + _source = source + _selector = selector + +#if TRACE_RESOURCES + AtomicIncrement(&numberOfMapOperators) +#endif + } + + override func composeMap(selector: ResultType throws -> R) -> Observable { + let originalSelector = _selector + return Map(source: _source, selector: { (s: SourceType) throws -> R in + let r: ResultType = try originalSelector(s) + return try selector(r) + }) + } + + override func run(observer: O) -> Disposable { + let sink = MapSink(selector: _selector, observer: observer) + sink.disposable = _source.subscribe(sink) + return sink + } + + #if TRACE_RESOURCES + deinit { + AtomicDecrement(&numberOfMapOperators) + } + #endif +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Merge.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Merge.swift new file mode 100644 index 00000000000..0bba8ca7317 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Merge.swift @@ -0,0 +1,423 @@ +// +// Merge.swift +// Rx +// +// Created by Krunoslav Zaher on 3/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +// MARK: Limited concurrency version + +class MergeLimitedSinkIter + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias E = O.E + typealias DisposeKey = Bag.KeyType + typealias Parent = MergeLimitedSink + + private let _parent: Parent + private let _disposeKey: DisposeKey + + var _lock: NSRecursiveLock { + return _parent._lock + } + + init(parent: Parent, disposeKey: DisposeKey) { + _parent = parent + _disposeKey = disposeKey + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + switch event { + case .Next: + _parent.forwardOn(event) + case .Error: + _parent.forwardOn(event) + _parent.dispose() + case .Completed: + _parent._group.removeDisposable(_disposeKey) + if let next = _parent._queue.dequeue() { + _parent.subscribe(next, group: _parent._group) + } + else { + _parent._activeCount = _parent._activeCount - 1 + + if _parent._stopped && _parent._activeCount == 0 { + _parent.forwardOn(.Completed) + _parent.dispose() + } + } + } + } +} + +class MergeLimitedSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias E = S + typealias QueueType = Queue + + private let _maxConcurrent: Int + + let _lock = NSRecursiveLock() + + // state + private var _stopped = false + private var _activeCount = 0 + private var _queue = QueueType(capacity: 2) + + private let _sourceSubscription = SingleAssignmentDisposable() + private let _group = CompositeDisposable() + + init(maxConcurrent: Int, observer: O) { + _maxConcurrent = maxConcurrent + + _group.addDisposable(_sourceSubscription) + super.init(observer: observer) + } + + func run(source: Observable) -> Disposable { + _group.addDisposable(_sourceSubscription) + + let disposable = source.subscribe(self) + _sourceSubscription.disposable = disposable + return _group + } + + func subscribe(innerSource: E, group: CompositeDisposable) { + let subscription = SingleAssignmentDisposable() + + let key = group.addDisposable(subscription) + + if let key = key { + let observer = MergeLimitedSinkIter(parent: self, disposeKey: key) + + let disposable = innerSource.asObservable().subscribe(observer) + subscription.disposable = disposable + } + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + switch event { + case .Next(let value): + let subscribe: Bool + if _activeCount < _maxConcurrent { + _activeCount += 1 + subscribe = true + } + else { + _queue.enqueue(value) + subscribe = false + } + + if subscribe { + self.subscribe(value, group: _group) + } + case .Error(let error): + forwardOn(.Error(error)) + dispose() + case .Completed: + if _activeCount == 0 { + forwardOn(.Completed) + dispose() + } + else { + _sourceSubscription.dispose() + } + + _stopped = true + } + } +} + +class MergeLimited : Producer { + private let _source: Observable + private let _maxConcurrent: Int + + init(source: Observable, maxConcurrent: Int) { + _source = source + _maxConcurrent = maxConcurrent + } + + override func run(observer: O) -> Disposable { + let sink = MergeLimitedSink(maxConcurrent: _maxConcurrent, observer: observer) + sink.disposable = sink.run(_source) + return sink + } +} + +// MARK: Merge + +final class MergeBasicSink : MergeSink { + override init(observer: O) { + super.init(observer: observer) + } + + override func performMap(element: S) throws -> S { + return element + } +} + +// MARK: flatMap + +final class FlatMapSink : MergeSink { + typealias Selector = (SourceType) throws -> S + + private let _selector: Selector + + init(selector: Selector, observer: O) { + _selector = selector + super.init(observer: observer) + } + + override func performMap(element: SourceType) throws -> S { + return try _selector(element) + } +} + +final class FlatMapWithIndexSink : MergeSink { + typealias Selector = (SourceType, Int) throws -> S + + private var _index = 0 + private let _selector: Selector + + init(selector: Selector, observer: O) { + _selector = selector + super.init(observer: observer) + } + + override func performMap(element: SourceType) throws -> S { + return try _selector(element, try incrementChecked(&_index)) + } +} + +// MARK: FlatMapFirst + +final class FlatMapFirstSink : MergeSink { + typealias Selector = (SourceType) throws -> S + + private let _selector: Selector + + override var subscribeNext: Bool { + return _group.count == MergeNoIterators + } + + init(selector: Selector, observer: O) { + _selector = selector + super.init(observer: observer) + } + + override func performMap(element: SourceType) throws -> S { + return try _selector(element) + } +} + +// It's value is one because initial source subscription is always in CompositeDisposable +private let MergeNoIterators = 1 + +class MergeSinkIter : ObserverType { + typealias Parent = MergeSink + typealias DisposeKey = CompositeDisposable.DisposeKey + typealias E = O.E + + private let _parent: Parent + private let _disposeKey: DisposeKey + + init(parent: Parent, disposeKey: DisposeKey) { + _parent = parent + _disposeKey = disposeKey + } + + func on(event: Event) { + switch event { + case .Next(let value): + _parent._lock.lock(); defer { _parent._lock.unlock() } // lock { + _parent.forwardOn(.Next(value)) + // } + case .Error(let error): + _parent._lock.lock(); defer { _parent._lock.unlock() } // lock { + _parent.forwardOn(.Error(error)) + _parent.dispose() + // } + case .Completed: + _parent._group.removeDisposable(_disposeKey) + // If this has returned true that means that `Completed` should be sent. + // In case there is a race who will sent first completed, + // lock will sort it out. When first Completed message is sent + // it will set observer to nil, and thus prevent further complete messages + // to be sent, and thus preserving the sequence grammar. + if _parent._stopped && _parent._group.count == MergeNoIterators { + _parent._lock.lock(); defer { _parent._lock.unlock() } // lock { + _parent.forwardOn(.Completed) + _parent.dispose() + // } + } + } + } +} + + +class MergeSink + : Sink + , ObserverType { + typealias ResultType = O.E + typealias Element = SourceType + + private let _lock = NSRecursiveLock() + + private var subscribeNext: Bool { + return true + } + + // state + private let _group = CompositeDisposable() + private let _sourceSubscription = SingleAssignmentDisposable() + + private var _stopped = false + + override init(observer: O) { + super.init(observer: observer) + } + + func performMap(element: SourceType) throws -> S { + abstractMethod() + } + + func on(event: Event) { + switch event { + case .Next(let element): + if !subscribeNext { + return + } + do { + let value = try performMap(element) + subscribeInner(value.asObservable()) + } + catch let e { + forwardOn(.Error(e)) + dispose() + } + case .Error(let error): + _lock.lock(); defer { _lock.unlock() } // lock { + forwardOn(.Error(error)) + dispose() + // } + case .Completed: + _lock.lock(); defer { _lock.unlock() } // lock { + _stopped = true + if _group.count == MergeNoIterators { + forwardOn(.Completed) + dispose() + } + else { + _sourceSubscription.dispose() + } + //} + } + } + + func subscribeInner(source: Observable) { + let iterDisposable = SingleAssignmentDisposable() + if let disposeKey = _group.addDisposable(iterDisposable) { + let iter = MergeSinkIter(parent: self, disposeKey: disposeKey) + let subscription = source.subscribe(iter) + iterDisposable.disposable = subscription + } + } + + func run(source: Observable) -> Disposable { + _group.addDisposable(_sourceSubscription) + + let subscription = source.subscribe(self) + _sourceSubscription.disposable = subscription + + return _group + } +} + +// MARK: Producers + +final class FlatMap: Producer { + typealias Selector = (SourceType) throws -> S + + private let _source: Observable + + private let _selector: Selector + + init(source: Observable, selector: Selector) { + _source = source + _selector = selector + } + + override func run(observer: O) -> Disposable { + let sink = FlatMapSink(selector: _selector, observer: observer) + sink.disposable = sink.run(_source) + return sink + } +} + +final class FlatMapWithIndex: Producer { + typealias Selector = (SourceType, Int) throws -> S + + private let _source: Observable + + private let _selector: Selector + + init(source: Observable, selector: Selector) { + _source = source + _selector = selector + } + + override func run(observer: O) -> Disposable { + let sink = FlatMapWithIndexSink(selector: _selector, observer: observer) + sink.disposable = sink.run(_source) + return sink + } + +} + +final class FlatMapFirst: Producer { + typealias Selector = (SourceType) throws -> S + + private let _source: Observable + + private let _selector: Selector + + init(source: Observable, selector: Selector) { + _source = source + _selector = selector + } + + override func run(observer: O) -> Disposable { + let sink = FlatMapFirstSink(selector: _selector, observer: observer) + sink.disposable = sink.run(_source) + return sink + } +} + +final class Merge : Producer { + private let _source: Observable + + init(source: Observable) { + _source = source + } + + override func run(observer: O) -> Disposable { + let sink = MergeBasicSink(observer: observer) + sink.disposable = sink.run(_source) + return sink + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Multicast.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Multicast.swift new file mode 100644 index 00000000000..f91a3a11e1b --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Multicast.swift @@ -0,0 +1,71 @@ +// +// Multicast.swift +// Rx +// +// Created by Krunoslav Zaher on 2/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class MulticastSink: Sink, ObserverType { + typealias Element = O.E + typealias ResultType = Element + typealias MutlicastType = Multicast + + private let _parent: MutlicastType + + init(parent: MutlicastType, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func run() -> Disposable { + do { + let subject = try _parent._subjectSelector() + let connectable = ConnectableObservableAdapter(source: _parent._source, subject: subject) + + let observable = try _parent._selector(connectable) + + let subscription = observable.subscribe(self) + let connection = connectable.connect() + + return BinaryDisposable(subscription, connection) + } + catch let e { + forwardOn(.Error(e)) + dispose() + return NopDisposable.instance + } + } + + func on(event: Event) { + forwardOn(event) + switch event { + case .Next: break + case .Error, .Completed: + dispose() + } + } +} + +class Multicast: Producer { + typealias SubjectSelectorType = () throws -> S + typealias SelectorType = (Observable) throws -> Observable + + private let _source: Observable + private let _subjectSelector: SubjectSelectorType + private let _selector: SelectorType + + init(source: Observable, subjectSelector: SubjectSelectorType, selector: SelectorType) { + _source = source + _subjectSelector = subjectSelector + _selector = selector + } + + override func run(observer: O) -> Disposable { + let sink = MulticastSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Never.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Never.swift new file mode 100644 index 00000000000..1b20b277877 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Never.swift @@ -0,0 +1,15 @@ +// +// Never.swift +// Rx +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class Never : Producer { + override func subscribe(observer: O) -> Disposable { + return NopDisposable.instance + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ObserveOn.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ObserveOn.swift new file mode 100644 index 00000000000..2c458ff405a --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ObserveOn.swift @@ -0,0 +1,133 @@ +// +// ObserveOn.swift +// RxSwift +// +// Created by Krunoslav Zaher on 7/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class ObserveOn : Producer { + let scheduler: ImmediateSchedulerType + let source: Observable + + init(source: Observable, scheduler: ImmediateSchedulerType) { + self.scheduler = scheduler + self.source = source + +#if TRACE_RESOURCES + AtomicIncrement(&resourceCount) +#endif + } + + override func run(observer: O) -> Disposable { + let sink = ObserveOnSink(scheduler: scheduler, observer: observer) + sink._subscription.disposable = source.subscribe(sink) + return sink + } + +#if TRACE_RESOURCES + deinit { + AtomicDecrement(&resourceCount) + } +#endif +} + +enum ObserveOnState : Int32 { + // pump is not running + case Stopped = 0 + // pump is running + case Running = 1 +} + +class ObserveOnSink : ObserverBase { + typealias E = O.E + + let _scheduler: ImmediateSchedulerType + + var _lock = SpinLock() + + // state + var _state = ObserveOnState.Stopped + var _observer: O? + var _queue = Queue>(capacity: 10) + + let _scheduleDisposable = SerialDisposable() + let _subscription = SingleAssignmentDisposable() + + init(scheduler: ImmediateSchedulerType, observer: O) { + _scheduler = scheduler + _observer = observer + } + + override func onCore(event: Event) { + let shouldStart = _lock.calculateLocked { () -> Bool in + self._queue.enqueue(event) + + switch self._state { + case .Stopped: + self._state = .Running + return true + case .Running: + return false + } + } + + if shouldStart { + _scheduleDisposable.disposable = self._scheduler.scheduleRecursive((), action: self.run) + } + } + + func run(state: Void, recurse: Void -> Void) { + let (nextEvent, observer) = self._lock.calculateLocked { () -> (Event?, O?) in + if self._queue.count > 0 { + return (self._queue.dequeue(), self._observer) + } + else { + self._state = .Stopped + return (nil, self._observer) + } + } + + if let nextEvent = nextEvent { + observer?.on(nextEvent) + if nextEvent.isStopEvent { + dispose() + } + } + else { + return + } + + let shouldContinue = _shouldContinue_synchronized() + + if shouldContinue { + recurse() + } + } + + func _shouldContinue_synchronized() -> Bool { + _lock.lock(); defer { _lock.unlock() } // { + if self._queue.count > 0 { + return true + } + else { + self._state = .Stopped + return false + } + // } + } + + override func dispose() { + super.dispose() + + _subscription.dispose() + _scheduleDisposable.dispose() + + _lock.lock(); defer { _lock.unlock() } // { + _observer = nil + + // } + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ObserveOnSerialDispatchQueue.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ObserveOnSerialDispatchQueue.swift new file mode 100644 index 00000000000..714b1304b26 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ObserveOnSerialDispatchQueue.swift @@ -0,0 +1,81 @@ +// +// ObserveOnSerialDispatchQueue.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/31/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +#if TRACE_RESOURCES +/** +Counts number of `SerialDispatchQueueObservables`. + +Purposed for unit tests. +*/ +public var numberOfSerialDispatchQueueObservables: AtomicInt = 0 +#endif + +class ObserveOnSerialDispatchQueueSink : ObserverBase { + let scheduler: SerialDispatchQueueScheduler + let observer: O + + let subscription = SingleAssignmentDisposable() + + var cachedScheduleLambda: ((ObserveOnSerialDispatchQueueSink, Event) -> Disposable)! + + init(scheduler: SerialDispatchQueueScheduler, observer: O) { + self.scheduler = scheduler + self.observer = observer + super.init() + + cachedScheduleLambda = { sink, event in + sink.observer.on(event) + + if event.isStopEvent { + sink.dispose() + } + + return NopDisposable.instance + } + } + + override func onCore(event: Event) { + self.scheduler.schedule((self, event), action: cachedScheduleLambda) + } + + override func dispose() { + super.dispose() + + subscription.dispose() + } +} + +class ObserveOnSerialDispatchQueue : Producer { + let scheduler: SerialDispatchQueueScheduler + let source: Observable + + init(source: Observable, scheduler: SerialDispatchQueueScheduler) { + self.scheduler = scheduler + self.source = source + +#if TRACE_RESOURCES + AtomicIncrement(&resourceCount) + AtomicIncrement(&numberOfSerialDispatchQueueObservables) +#endif + } + + override func run(observer: O) -> Disposable { + let sink = ObserveOnSerialDispatchQueueSink(scheduler: scheduler, observer: observer) + sink.subscription.disposable = source.subscribe(sink) + return sink + } + +#if TRACE_RESOURCES + deinit { + AtomicDecrement(&resourceCount) + AtomicDecrement(&numberOfSerialDispatchQueueObservables) + } +#endif +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Producer.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Producer.swift new file mode 100644 index 00000000000..84048e4bf53 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Producer.swift @@ -0,0 +1,30 @@ +// +// Producer.swift +// Rx +// +// Created by Krunoslav Zaher on 2/20/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class Producer : Observable { + override init() { + super.init() + } + + override func subscribe(observer: O) -> Disposable { + if !CurrentThreadScheduler.isScheduleRequired { + return run(observer) + } + else { + return CurrentThreadScheduler.instance.schedule(()) { _ in + return self.run(observer) + } + } + } + + func run(observer: O) -> Disposable { + abstractMethod() + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Range.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Range.swift new file mode 100644 index 00000000000..d01da11a2ea --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Range.swift @@ -0,0 +1,59 @@ +// +// Range.swift +// Rx +// +// Created by Krunoslav Zaher on 9/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class RangeProducer : Producer { + private let _start: E + private let _count: E + private let _scheduler: ImmediateSchedulerType + + init(start: E, count: E, scheduler: ImmediateSchedulerType) { + if count < 0 { + rxFatalError("count can't be negative") + } + + if start &+ (count - 1) < start { + rxFatalError("overflow of count") + } + + _start = start + _count = count + _scheduler = scheduler + } + + override func run(observer: O) -> Disposable { + let sink = RangeSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} + +class RangeSink : Sink { + typealias Parent = RangeProducer + + private let _parent: Parent + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func run() -> Disposable { + return _parent._scheduler.scheduleRecursive(0 as O.E) { i, recurse in + if i < self._parent._count { + self.forwardOn(.Next(self._parent._start + i)) + recurse(i + 1) + } + else { + self.forwardOn(.Completed) + self.dispose() + } + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Reduce.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Reduce.swift new file mode 100644 index 00000000000..7709b431a2c --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Reduce.swift @@ -0,0 +1,74 @@ +// +// Reduce.swift +// Rx +// +// Created by Krunoslav Zaher on 4/1/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class ReduceSink : Sink, ObserverType { + typealias ResultType = O.E + typealias Parent = Reduce + + private let _parent: Parent + private var _accumulation: AccumulateType + + init(parent: Parent, observer: O) { + _parent = parent + _accumulation = parent._seed + + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(let value): + do { + _accumulation = try _parent._accumulator(_accumulation, value) + } + catch let e { + forwardOn(.Error(e)) + dispose() + } + case .Error(let e): + forwardOn(.Error(e)) + dispose() + case .Completed: + do { + let result = try _parent._mapResult(_accumulation) + forwardOn(.Next(result)) + forwardOn(.Completed) + dispose() + } + catch let e { + forwardOn(.Error(e)) + dispose() + } + } + } +} + +class Reduce : Producer { + typealias AccumulatorType = (AccumulateType, SourceType) throws -> AccumulateType + typealias ResultSelectorType = (AccumulateType) throws -> ResultType + + private let _source: Observable + private let _seed: AccumulateType + private let _accumulator: AccumulatorType + private let _mapResult: ResultSelectorType + + init(source: Observable, seed: AccumulateType, accumulator: AccumulatorType, mapResult: ResultSelectorType) { + _source = source + _seed = seed + _accumulator = accumulator + _mapResult = mapResult + } + + override func run(observer: O) -> Disposable { + let sink = ReduceSink(parent: self, observer: observer) + sink.disposable = _source.subscribe(sink) + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/RefCount.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/RefCount.swift new file mode 100644 index 00000000000..e1450381dc8 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/RefCount.swift @@ -0,0 +1,84 @@ +// +// RefCount.swift +// Rx +// +// Created by Krunoslav Zaher on 3/5/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class RefCountSink + : Sink + , ObserverType { + typealias Element = O.E + typealias Parent = RefCount + + private let _parent: Parent + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func run() -> Disposable { + let subscription = _parent._source.subscribeSafe(self) + + _parent._lock.lock(); defer { _parent._lock.unlock() } // { + if _parent._count == 0 { + _parent._count = 1 + _parent._connectableSubscription = _parent._source.connect() + } + else { + _parent._count = _parent._count + 1 + } + // } + + return AnonymousDisposable { + subscription.dispose() + self._parent._lock.lock(); defer { self._parent._lock.unlock() } // { + if self._parent._count == 1 { + self._parent._connectableSubscription!.dispose() + self._parent._count = 0 + self._parent._connectableSubscription = nil + } + else if self._parent._count > 1 { + self._parent._count = self._parent._count - 1 + } + else { + rxFatalError("Something went wrong with RefCount disposing mechanism") + } + // } + } + } + + func on(event: Event) { + switch event { + case .Next: + forwardOn(event) + case .Error, .Completed: + forwardOn(event) + dispose() + } + } +} + +class RefCount: Producer { + private let _lock = NSRecursiveLock() + + // state + private var _count = 0 + private var _connectableSubscription = nil as Disposable? + + private let _source: CO + + init(source: CO) { + _source = source + } + + override func run(observer: O) -> Disposable { + let sink = RefCountSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Repeat.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Repeat.swift new file mode 100644 index 00000000000..0b24510c3ef --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Repeat.swift @@ -0,0 +1,44 @@ +// +// Repeat.swift +// RxExample +// +// Created by Krunoslav Zaher on 9/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class RepeatElement : Producer { + private let _element: Element + private let _scheduler: ImmediateSchedulerType + + init(element: Element, scheduler: ImmediateSchedulerType) { + _element = element + _scheduler = scheduler + } + + override func run(observer: O) -> Disposable { + let sink = RepeatElementSink(parent: self, observer: observer) + sink.disposable = sink.run() + + return sink + } +} + +class RepeatElementSink : Sink { + typealias Parent = RepeatElement + + private let _parent: Parent + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func run() -> Disposable { + return _parent._scheduler.scheduleRecursive(_parent._element) { e, recurse in + self.forwardOn(.Next(e)) + recurse(e) + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/RetryWhen.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/RetryWhen.swift new file mode 100644 index 00000000000..0bbb08cf1c5 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/RetryWhen.swift @@ -0,0 +1,150 @@ +// +// RetryWhen.swift +// Rx +// +// Created by Junior B. on 06/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class RetryTriggerSink + : ObserverType { + typealias E = TriggerObservable.E + + typealias Parent = RetryWhenSequenceSinkIter + + private let _parent: Parent + + init(parent: Parent) { + _parent = parent + } + + func on(event: Event) { + switch event { + case .Next: + _parent._parent._lastError = nil + _parent._parent.schedule(.MoveNext) + case .Error(let e): + _parent._parent.forwardOn(.Error(e)) + _parent._parent.dispose() + case .Completed: + _parent._parent.forwardOn(.Completed) + _parent._parent.dispose() + } + } +} + +class RetryWhenSequenceSinkIter + : SingleAssignmentDisposable + , ObserverType { + typealias E = O.E + typealias Parent = RetryWhenSequenceSink + + private let _parent: Parent + private let _errorHandlerSubscription = SingleAssignmentDisposable() + + init(parent: Parent) { + _parent = parent + } + + func on(event: Event) { + switch event { + case .Next: + _parent.forwardOn(event) + case .Error(let error): + _parent._lastError = error + + if let failedWith = error as? Error { + // dispose current subscription + super.dispose() + + let errorHandlerSubscription = _parent._notifier.subscribe(RetryTriggerSink(parent: self)) + _errorHandlerSubscription.disposable = errorHandlerSubscription + _parent._errorSubject.on(.Next(failedWith)) + } + else { + _parent.forwardOn(.Error(error)) + _parent.dispose() + } + case .Completed: + _parent.forwardOn(event) + _parent.dispose() + } + } + + override func dispose() { + super.dispose() + _errorHandlerSubscription.dispose() + } +} + +class RetryWhenSequenceSink + : TailRecursiveSink { + typealias Element = O.E + typealias Parent = RetryWhenSequence + + let _lock = NSRecursiveLock() + + private let _parent: Parent + + private var _lastError: ErrorType? + private let _errorSubject = PublishSubject() + private let _handler: Observable + private let _notifier = PublishSubject() + + init(parent: Parent, observer: O) { + _parent = parent + _handler = parent._notificationHandler(_errorSubject).asObservable() + super.init(observer: observer) + } + + override func done() { + if let lastError = _lastError { + forwardOn(.Error(lastError)) + _lastError = nil + } + else { + forwardOn(.Completed) + } + + dispose() + } + + override func extract(observable: Observable) -> SequenceGenerator? { + // It is important to always return `nil` here because there are sideffects in the `run` method + // that are dependant on particular `retryWhen` operator so single operator stack can't be reused in this + // case. + return nil + } + + override func subscribeToNext(source: Observable) -> Disposable { + let iter = RetryWhenSequenceSinkIter(parent: self) + iter.disposable = source.subscribe(iter) + return iter + } + + override func run(sources: SequenceGenerator) -> Disposable { + let triggerSubscription = _handler.subscribe(_notifier.asObserver()) + let superSubscription = super.run(sources) + return StableCompositeDisposable.create(superSubscription, triggerSubscription) + } +} + +class RetryWhenSequence : Producer { + typealias Element = S.Generator.Element.E + + private let _sources: S + private let _notificationHandler: Observable -> TriggerObservable + + init(sources: S, notificationHandler: Observable -> TriggerObservable) { + _sources = sources + _notificationHandler = notificationHandler + } + + override func run(observer: O) -> Disposable { + let sink = RetryWhenSequenceSink(parent: self, observer: observer) + sink.disposable = sink.run((self._sources.generate(), nil)) + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Sample.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Sample.swift new file mode 100644 index 00000000000..ef13f13ff70 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Sample.swift @@ -0,0 +1,129 @@ +// +// Sample.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/1/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class SamplerSink + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias E = SampleType + + typealias Parent = SampleSequenceSink + + private let _parent: Parent + + var _lock: NSRecursiveLock { + return _parent._lock + } + + init(parent: Parent) { + _parent = parent + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + switch event { + case .Next: + if let element = _parent._element { + if _parent._parent._onlyNew { + _parent._element = nil + } + + _parent.forwardOn(.Next(element)) + } + + if _parent._atEnd { + _parent.forwardOn(.Completed) + _parent.dispose() + } + case .Error(let e): + _parent.forwardOn(.Error(e)) + _parent.dispose() + case .Completed: + if let element = _parent._element { + _parent._element = nil + _parent.forwardOn(.Next(element)) + } + if _parent._atEnd { + _parent.forwardOn(.Completed) + _parent.dispose() + } + } + } +} + +class SampleSequenceSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = O.E + typealias Parent = Sample + + private let _parent: Parent + + let _lock = NSRecursiveLock() + + // state + private var _element = nil as Element? + private var _atEnd = false + + private let _sourceSubscription = SingleAssignmentDisposable() + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func run() -> Disposable { + _sourceSubscription.disposable = _parent._source.subscribe(self) + let samplerSubscription = _parent._sampler.subscribe(SamplerSink(parent: self)) + + return StableCompositeDisposable.create(_sourceSubscription, samplerSubscription) + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + switch event { + case .Next(let element): + _element = element + case .Error: + forwardOn(event) + dispose() + case .Completed: + _atEnd = true + _sourceSubscription.dispose() + } + } + +} + +class Sample : Producer { + private let _source: Observable + private let _sampler: Observable + private let _onlyNew: Bool + + init(source: Observable, sampler: Observable, onlyNew: Bool) { + _source = source + _sampler = sampler + _onlyNew = onlyNew + } + + override func run(observer: O) -> Disposable { + let sink = SampleSequenceSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Scan.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Scan.swift new file mode 100644 index 00000000000..bc0adc87988 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Scan.swift @@ -0,0 +1,64 @@ +// +// Scan.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class ScanSink : Sink, ObserverType { + typealias Parent = Scan + typealias E = ElementType + + private let _parent: Parent + private var _accumulate: Accumulate + + init(parent: Parent, observer: O) { + _parent = parent + _accumulate = parent._seed + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(let element): + do { + _accumulate = try _parent._accumulator(_accumulate, element) + forwardOn(.Next(_accumulate)) + } + catch let error { + forwardOn(.Error(error)) + dispose() + } + case .Error(let error): + forwardOn(.Error(error)) + dispose() + case .Completed: + forwardOn(.Completed) + dispose() + } + } + +} + +class Scan: Producer { + typealias Accumulator = (Accumulate, Element) throws -> Accumulate + + private let _source: Observable + private let _seed: Accumulate + private let _accumulator: Accumulator + + init(source: Observable, seed: Accumulate, accumulator: Accumulator) { + _source = source + _seed = seed + _accumulator = accumulator + } + + override func run(observer: O) -> Disposable { + let sink = ScanSink(parent: self, observer: observer) + sink.disposable = _source.subscribe(sink) + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Sequence.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Sequence.swift new file mode 100644 index 00000000000..0a31d9291da --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Sequence.swift @@ -0,0 +1,58 @@ +// +// Sequence.swift +// Rx +// +// Created by Krunoslav Zaher on 11/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class SequenceSink : Sink { + typealias Parent = Sequence + + private let _parent: Parent + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func run() -> Disposable { + return _parent._scheduler!.scheduleRecursive((0, _parent._elements)) { (state, recurse) in + if state.0 < state.1.count { + self.forwardOn(.Next(state.1[state.0])) + recurse((state.0 + 1, state.1)) + } + else { + self.forwardOn(.Completed) + } + } + } +} + +class Sequence : Producer { + private let _elements: [E] + private let _scheduler: ImmediateSchedulerType? + + init(elements: [E], scheduler: ImmediateSchedulerType?) { + _elements = elements + _scheduler = scheduler + } + + override func subscribe(observer: O) -> Disposable { + // optimized version without scheduler + guard _scheduler != nil else { + for element in _elements { + observer.on(.Next(element)) + } + + observer.on(.Completed) + return NopDisposable.instance + } + + let sink = SequenceSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ShareReplay1.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ShareReplay1.swift new file mode 100644 index 00000000000..52cb5ebe3df --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ShareReplay1.swift @@ -0,0 +1,101 @@ +// +// ShareReplay1.swift +// Rx +// +// Created by Krunoslav Zaher on 10/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +// optimized version of share replay for most common case +final class ShareReplay1 + : Observable + , ObserverType + , SynchronizedUnsubscribeType { + + typealias DisposeKey = Bag>.KeyType + + private let _source: Observable + + private var _lock = NSRecursiveLock() + + private var _connection: SingleAssignmentDisposable? + private var _element: Element? + private var _stopped = false + private var _stopEvent = nil as Event? + private var _observers = Bag>() + + init(source: Observable) { + self._source = source + } + + override func subscribe(observer: O) -> Disposable { + _lock.lock(); defer { _lock.unlock() } + return _synchronized_subscribe(observer) + } + + func _synchronized_subscribe(observer: O) -> Disposable { + if let element = self._element { + observer.on(.Next(element)) + } + + if let stopEvent = self._stopEvent { + observer.on(stopEvent) + return NopDisposable.instance + } + + let initialCount = self._observers.count + + let disposeKey = self._observers.insert(AnyObserver(observer)) + + if initialCount == 0 { + let connection = SingleAssignmentDisposable() + _connection = connection + + connection.disposable = self._source.subscribe(self) + } + + return SubscriptionDisposable(owner: self, key: disposeKey) + } + + func synchronizedUnsubscribe(disposeKey: DisposeKey) { + _lock.lock(); defer { _lock.unlock() } + _synchronized_unsubscribe(disposeKey) + } + + func _synchronized_unsubscribe(disposeKey: DisposeKey) { + // if already unsubscribed, just return + if self._observers.removeKey(disposeKey) == nil { + return + } + + if _observers.count == 0 { + _connection?.dispose() + _connection = nil + } + } + + func on(event: Event) { + _lock.lock(); defer { _lock.unlock() } + _synchronized_on(event) + } + + func _synchronized_on(event: Event) { + if _stopped { + return + } + + switch event { + case .Next(let element): + _element = element + case .Error, .Completed: + _stopEvent = event + _stopped = true + _connection?.dispose() + _connection = nil + } + + _observers.on(event) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ShareReplay1WhileConnected.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ShareReplay1WhileConnected.swift new file mode 100644 index 00000000000..af776b1ce9e --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ShareReplay1WhileConnected.swift @@ -0,0 +1,92 @@ +// +// ShareReplay1WhileConnected.swift +// Rx +// +// Created by Krunoslav Zaher on 12/6/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +// optimized version of share replay for most common case +final class ShareReplay1WhileConnected + : Observable + , ObserverType + , SynchronizedUnsubscribeType { + + typealias DisposeKey = Bag>.KeyType + + private let _source: Observable + + private var _lock = NSRecursiveLock() + + private var _connection: SingleAssignmentDisposable? + private var _element: Element? + private var _observers = Bag>() + + init(source: Observable) { + self._source = source + } + + override func subscribe(observer: O) -> Disposable { + _lock.lock(); defer { _lock.unlock() } + return _synchronized_subscribe(observer) + } + + func _synchronized_subscribe(observer: O) -> Disposable { + if let element = self._element { + observer.on(.Next(element)) + } + + let initialCount = self._observers.count + + let disposeKey = self._observers.insert(AnyObserver(observer)) + + if initialCount == 0 { + let connection = SingleAssignmentDisposable() + _connection = connection + + connection.disposable = self._source.subscribe(self) + } + + return SubscriptionDisposable(owner: self, key: disposeKey) + } + + func synchronizedUnsubscribe(disposeKey: DisposeKey) { + _lock.lock(); defer { _lock.unlock() } + _synchronized_unsubscribe(disposeKey) + } + + func _synchronized_unsubscribe(disposeKey: DisposeKey) { + // if already unsubscribed, just return + if self._observers.removeKey(disposeKey) == nil { + return + } + + if _observers.count == 0 { + _connection?.dispose() + _connection = nil + _element = nil + } + } + + func on(event: Event) { + _lock.lock(); defer { _lock.unlock() } + _synchronized_on(event) + } + + func _synchronized_on(event: Event) { + switch event { + case .Next(let element): + _element = element + _observers.on(event) + case .Error, .Completed: + _element = nil + _connection?.dispose() + _connection = nil + let observers = _observers + _observers = Bag() + observers.on(event) + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/SingleAsync.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/SingleAsync.swift new file mode 100644 index 00000000000..abf40d8d4c1 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/SingleAsync.swift @@ -0,0 +1,76 @@ +// +// SingleAsync.swift +// Rx +// +// Created by Junior B. on 09/11/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class SingleAsyncSink : Sink, ObserverType { + typealias Parent = SingleAsync + typealias E = ElementType + + private let _parent: Parent + private var _seenValue: Bool = false + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(let value): + do { + let forward = try _parent._predicate?(value) ?? true + if !forward { + return + } + } + catch let error { + forwardOn(.Error(error as ErrorType)) + dispose() + return + } + + if _seenValue == false { + _seenValue = true + forwardOn(.Next(value)) + } else { + forwardOn(.Error(RxError.MoreThanOneElement)) + dispose() + } + + case .Error: + forwardOn(event) + dispose() + case .Completed: + if (!_seenValue) { + forwardOn(.Error(RxError.NoElements)) + } else { + forwardOn(.Completed) + } + dispose() + } + } +} + +class SingleAsync: Producer { + typealias Predicate = (Element) throws -> Bool + + private let _source: Observable + private let _predicate: Predicate? + + init(source: Observable, predicate: Predicate? = nil) { + _source = source + _predicate = predicate + } + + override func run(observer: O) -> Disposable { + let sink = SingleAsyncSink(parent: self, observer: observer) + sink.disposable = _source.subscribe(sink) + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Sink.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Sink.swift new file mode 100644 index 00000000000..36b1937f814 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Sink.swift @@ -0,0 +1,57 @@ +// +// Sink.swift +// Rx +// +// Created by Krunoslav Zaher on 2/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class Sink : SingleAssignmentDisposable { + private let _observer: O + + init(observer: O) { +#if TRACE_RESOURCES + AtomicIncrement(&resourceCount) +#endif + _observer = observer + } + + final func forwardOn(event: Event) { + if disposed { + return + } + _observer.on(event) + } + + final func forwarder() -> SinkForward { + return SinkForward(forward: self) + } + + deinit { +#if TRACE_RESOURCES + AtomicDecrement(&resourceCount) +#endif + } +} + +class SinkForward: ObserverType { + typealias E = O.E + + private let _forward: Sink + + init(forward: Sink) { + _forward = forward + } + + func on(event: Event) { + switch event { + case .Next: + _forward._observer.on(event) + case .Error, .Completed: + _forward._observer.on(event) + _forward.dispose() + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Skip.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Skip.swift new file mode 100644 index 00000000000..ea977d396fe --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Skip.swift @@ -0,0 +1,128 @@ +// +// Skip.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +// count version + +class SkipCountSink : Sink, ObserverType { + typealias Parent = SkipCount + typealias Element = ElementType + + let parent: Parent + + var remaining: Int + + init(parent: Parent, observer: O) { + self.parent = parent + self.remaining = parent.count + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(let value): + + if remaining <= 0 { + forwardOn(.Next(value)) + } + else { + remaining -= 1 + } + case .Error: + forwardOn(event) + self.dispose() + case .Completed: + forwardOn(event) + self.dispose() + } + } + +} + +class SkipCount: Producer { + let source: Observable + let count: Int + + init(source: Observable, count: Int) { + self.source = source + self.count = count + } + + override func run(observer: O) -> Disposable { + let sink = SkipCountSink(parent: self, observer: observer) + sink.disposable = source.subscribe(sink) + + return sink + } +} + +// time version + +class SkipTimeSink : Sink, ObserverType { + typealias Parent = SkipTime + typealias Element = ElementType + + let parent: Parent + + // state + var open = false + + init(parent: Parent, observer: O) { + self.parent = parent + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(let value): + if open { + forwardOn(.Next(value)) + } + case .Error: + forwardOn(event) + self.dispose() + case .Completed: + forwardOn(event) + self.dispose() + } + } + + func tick() { + open = true + } + + func run() -> Disposable { + let disposeTimer = parent.scheduler.scheduleRelative((), dueTime: self.parent.duration) { + self.tick() + return NopDisposable.instance + } + + let disposeSubscription = parent.source.subscribe(self) + + return BinaryDisposable(disposeTimer, disposeSubscription) + } +} + +class SkipTime: Producer { + let source: Observable + let duration: RxTimeInterval + let scheduler: SchedulerType + + init(source: Observable, duration: RxTimeInterval, scheduler: SchedulerType) { + self.source = source + self.scheduler = scheduler + self.duration = duration + } + + override func run(observer: O) -> Disposable { + let sink = SkipTimeSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/SkipUntil.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/SkipUntil.swift new file mode 100644 index 00000000000..be3c69373f2 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/SkipUntil.swift @@ -0,0 +1,125 @@ +// +// SkipUntil.swift +// Rx +// +// Created by Yury Korolev on 10/3/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class SkipUntilSinkOther + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Parent = SkipUntilSink + typealias E = Other + + private let _parent: Parent + + var _lock: NSRecursiveLock { + return _parent._lock + } + + let _subscription = SingleAssignmentDisposable() + + init(parent: Parent) { + _parent = parent + #if TRACE_RESOURCES + AtomicIncrement(&resourceCount) + #endif + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + switch event { + case .Next: + _parent._forwardElements = true + _subscription.dispose() + case .Error(let e): + _parent.forwardOn(.Error(e)) + _parent.dispose() + case .Completed: + _subscription.dispose() + } + } + + #if TRACE_RESOURCES + deinit { + AtomicDecrement(&resourceCount) + } + #endif + +} + + +class SkipUntilSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias E = ElementType + typealias Parent = SkipUntil + + let _lock = NSRecursiveLock() + private let _parent: Parent + private var _forwardElements = false + + private let _sourceSubscription = SingleAssignmentDisposable() + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + switch event { + case .Next: + if _forwardElements { + forwardOn(event) + } + case .Error: + forwardOn(event) + dispose() + case .Completed: + if _forwardElements { + forwardOn(event) + } + _sourceSubscription.dispose() + } + } + + func run() -> Disposable { + let sourceSubscription = _parent._source.subscribe(self) + let otherObserver = SkipUntilSinkOther(parent: self) + let otherSubscription = _parent._other.subscribe(otherObserver) + _sourceSubscription.disposable = sourceSubscription + otherObserver._subscription.disposable = otherSubscription + + return StableCompositeDisposable.create(_sourceSubscription, otherObserver._subscription) + } +} + +class SkipUntil: Producer { + + private let _source: Observable + private let _other: Observable + + init(source: Observable, other: Observable) { + _source = source + _other = other + } + + override func run(observer: O) -> Disposable { + let sink = SkipUntilSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/SkipWhile.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/SkipWhile.swift new file mode 100644 index 00000000000..d16304a089e --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/SkipWhile.swift @@ -0,0 +1,115 @@ +// +// SkipWhile.swift +// Rx +// +// Created by Yury Korolev on 10/9/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +class SkipWhileSink : Sink, ObserverType { + + typealias Parent = SkipWhile + typealias Element = ElementType + + private let _parent: Parent + private var _running = false + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(let value): + if !_running { + do { + _running = try !_parent._predicate(value) + } catch let e { + forwardOn(.Error(e)) + dispose() + return + } + } + + if _running { + forwardOn(.Next(value)) + } + case .Error, .Completed: + forwardOn(event) + dispose() + } + } +} + +class SkipWhileSinkWithIndex : Sink, ObserverType { + + typealias Parent = SkipWhile + typealias Element = ElementType + + private let _parent: Parent + private var _index = 0 + private var _running = false + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(let value): + if !_running { + do { + _running = try !_parent._predicateWithIndex(value, _index) + try incrementChecked(&_index) + } catch let e { + forwardOn(.Error(e)) + dispose() + return + } + } + + if _running { + forwardOn(.Next(value)) + } + case .Error, .Completed: + forwardOn(event) + dispose() + } + } +} + +class SkipWhile: Producer { + typealias Predicate = (Element) throws -> Bool + typealias PredicateWithIndex = (Element, Int) throws -> Bool + + private let _source: Observable + private let _predicate: Predicate! + private let _predicateWithIndex: PredicateWithIndex! + + init(source: Observable, predicate: Predicate) { + _source = source + _predicate = predicate + _predicateWithIndex = nil + } + + init(source: Observable, predicate: PredicateWithIndex) { + _source = source + _predicate = nil + _predicateWithIndex = predicate + } + + override func run(observer: O) -> Disposable { + if let _ = _predicate { + let sink = SkipWhileSink(parent: self, observer: observer) + sink.disposable = _source.subscribe(sink) + return sink + } + else { + let sink = SkipWhileSinkWithIndex(parent: self, observer: observer) + sink.disposable = _source.subscribe(sink) + return sink + } + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/StartWith.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/StartWith.swift new file mode 100644 index 00000000000..c60cb367971 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/StartWith.swift @@ -0,0 +1,28 @@ +// +// StartWith.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 4/6/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class StartWith: Producer { + let elements: [Element] + let source: Observable + + init(source: Observable, elements: [Element]) { + self.source = source + self.elements = elements + super.init() + } + + override func run(observer: O) -> Disposable { + for e in elements { + observer.on(.Next(e)) + } + + return source.subscribe(observer) + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/SubscribeOn.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/SubscribeOn.swift new file mode 100644 index 00000000000..1d461a3d620 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/SubscribeOn.swift @@ -0,0 +1,60 @@ +// +// SubscribeOn.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class SubscribeOnSink : Sink, ObserverType { + typealias Element = O.E + typealias Parent = SubscribeOn + + let parent: Parent + + init(parent: Parent, observer: O) { + self.parent = parent + super.init(observer: observer) + } + + func on(event: Event) { + forwardOn(event) + + if event.isStopEvent { + self.dispose() + } + } + + func run() -> Disposable { + let disposeEverything = SerialDisposable() + let cancelSchedule = SingleAssignmentDisposable() + + disposeEverything.disposable = cancelSchedule + + cancelSchedule.disposable = parent.scheduler.schedule(()) { (_) -> Disposable in + let subscription = self.parent.source.subscribe(self) + disposeEverything.disposable = ScheduledDisposable(scheduler: self.parent.scheduler, disposable: subscription) + return NopDisposable.instance + } + + return disposeEverything + } +} + +class SubscribeOn : Producer { + let source: Ob + let scheduler: ImmediateSchedulerType + + init(source: Ob, scheduler: ImmediateSchedulerType) { + self.source = source + self.scheduler = scheduler + } + + override func run(observer: O) -> Disposable { + let sink = SubscribeOnSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Switch.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Switch.swift new file mode 100644 index 00000000000..2051275cc1b --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Switch.swift @@ -0,0 +1,193 @@ +// +// Switch.swift +// Rx +// +// Created by Krunoslav Zaher on 3/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class SwitchSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias E = SourceType + + private let _subscriptions: SingleAssignmentDisposable = SingleAssignmentDisposable() + private let _innerSubscription: SerialDisposable = SerialDisposable() + + let _lock = NSRecursiveLock() + + // state + private var _stopped = false + private var _latest = 0 + private var _hasLatest = false + + override init(observer: O) { + super.init(observer: observer) + } + + func run(source: Observable) -> Disposable { + let subscription = source.subscribe(self) + _subscriptions.disposable = subscription + return StableCompositeDisposable.create(_subscriptions, _innerSubscription) + } + + func on(event: Event) { + synchronizedOn(event) + } + + func performMap(element: SourceType) throws -> S { + abstractMethod() + } + + func _synchronized_on(event: Event) { + switch event { + case .Next(let element): + do { + let observable = try performMap(element).asObservable() + _hasLatest = true + _latest = _latest &+ 1 + let latest = _latest + + let d = SingleAssignmentDisposable() + _innerSubscription.disposable = d + + let observer = SwitchSinkIter(parent: self, id: latest, _self: d) + let disposable = observable.subscribe(observer) + d.disposable = disposable + } + catch let error { + forwardOn(.Error(error)) + dispose() + } + case .Error(let error): + forwardOn(.Error(error)) + dispose() + case .Completed: + _stopped = true + + _subscriptions.dispose() + + if !_hasLatest { + forwardOn(.Completed) + dispose() + } + } + } +} + +class SwitchSinkIter + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias E = S.E + typealias Parent = SwitchSink + + private let _parent: Parent + private let _id: Int + private let _self: Disposable + + var _lock: NSRecursiveLock { + return _parent._lock + } + + init(parent: Parent, id: Int, _self: Disposable) { + _parent = parent + _id = id + self._self = _self + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + switch event { + case .Next: break + case .Error, .Completed: + _self.dispose() + } + + if _parent._latest != _id { + return + } + + switch event { + case .Next: + _parent.forwardOn(event) + case .Error: + _parent.forwardOn(event) + _parent.dispose() + case .Completed: + _parent._hasLatest = false + if _parent._stopped { + _parent.forwardOn(event) + _parent.dispose() + } + } + } +} + +// MARK: Specializations + +final class SwitchIdentitySink : SwitchSink { + override init(observer: O) { + super.init(observer: observer) + } + + override func performMap(element: S) throws -> S { + return element + } +} + +final class MapSwitchSink : SwitchSink { + typealias Selector = SourceType throws -> S + + private let _selector: Selector + + init(selector: Selector, observer: O) { + _selector = selector + super.init(observer: observer) + } + + override func performMap(element: SourceType) throws -> S { + return try _selector(element) + } +} + +// MARK: Producers + +final class Switch : Producer { + private let _source: Observable + + init(source: Observable) { + _source = source + } + + override func run(observer: O) -> Disposable { + let sink = SwitchIdentitySink(observer: observer) + sink.disposable = sink.run(_source) + return sink + } +} + +final class FlatMapLatest : Producer { + typealias Selector = SourceType throws -> S + + private let _source: Observable + private let _selector: Selector + + init(source: Observable, selector: Selector) { + _source = source + _selector = selector + } + + override func run(observer: O) -> Disposable { + let sink = MapSwitchSink(selector: _selector, observer: observer) + sink.disposable = sink.run(_source) + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Take.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Take.swift new file mode 100644 index 00000000000..d551100476c --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Take.swift @@ -0,0 +1,144 @@ +// +// Take.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +// count version + +class TakeCountSink : Sink, ObserverType { + typealias Parent = TakeCount + typealias E = ElementType + + private let _parent: Parent + + private var _remaining: Int + + init(parent: Parent, observer: O) { + _parent = parent + _remaining = parent._count + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(let value): + + if _remaining > 0 { + _remaining -= 1 + + forwardOn(.Next(value)) + + if _remaining == 0 { + forwardOn(.Completed) + dispose() + } + } + case .Error: + forwardOn(event) + dispose() + case .Completed: + forwardOn(event) + dispose() + } + } + +} + +class TakeCount: Producer { + private let _source: Observable + private let _count: Int + + init(source: Observable, count: Int) { + if count < 0 { + rxFatalError("count can't be negative") + } + _source = source + _count = count + } + + override func run(observer: O) -> Disposable { + let sink = TakeCountSink(parent: self, observer: observer) + sink.disposable = _source.subscribe(sink) + return sink + } +} + +// time version + +class TakeTimeSink + : Sink + , LockOwnerType + , ObserverType + , SynchronizedOnType { + typealias Parent = TakeTime + typealias E = ElementType + + private let _parent: Parent + + let _lock = NSRecursiveLock() + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + switch event { + case .Next(let value): + forwardOn(.Next(value)) + case .Error: + forwardOn(event) + dispose() + case .Completed: + forwardOn(event) + dispose() + } + } + + func tick() { + _lock.lock(); defer { _lock.unlock() } + + forwardOn(.Completed) + dispose() + } + + func run() -> Disposable { + let disposeTimer = _parent._scheduler.scheduleRelative((), dueTime: _parent._duration) { + self.tick() + return NopDisposable.instance + } + + let disposeSubscription = _parent._source.subscribe(self) + + return BinaryDisposable(disposeTimer, disposeSubscription) + } +} + +class TakeTime : Producer { + typealias TimeInterval = RxTimeInterval + + private let _source: Observable + private let _duration: TimeInterval + private let _scheduler: SchedulerType + + init(source: Observable, duration: TimeInterval, scheduler: SchedulerType) { + _source = source + _scheduler = scheduler + _duration = duration + } + + override func run(observer: O) -> Disposable { + let sink = TakeTimeSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/TakeLast.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/TakeLast.swift new file mode 100644 index 00000000000..2a479d393f0 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/TakeLast.swift @@ -0,0 +1,63 @@ +// +// TakeLast.swift +// Rx +// +// Created by Tomi Koskinen on 25/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + + +class TakeLastSink : Sink, ObserverType { + typealias Parent = TakeLast + typealias E = ElementType + + private let _parent: Parent + + private var _elements: Queue + + init(parent: Parent, observer: O) { + _parent = parent + _elements = Queue(capacity: parent._count + 1) + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(let value): + _elements.enqueue(value) + if _elements.count > self._parent._count { + _elements.dequeue() + } + case .Error: + forwardOn(event) + dispose() + case .Completed: + for e in _elements { + forwardOn(.Next(e)) + } + forwardOn(.Completed) + dispose() + } + } +} + +class TakeLast: Producer { + private let _source: Observable + private let _count: Int + + init(source: Observable, count: Int) { + if count < 0 { + rxFatalError("count can't be negative") + } + _source = source + _count = count + } + + override func run(observer: O) -> Disposable { + let sink = TakeLastSink(parent: self, observer: observer) + sink.disposable = _source.subscribe(sink) + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/TakeUntil.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/TakeUntil.swift new file mode 100644 index 00000000000..f1e36d9774e --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/TakeUntil.swift @@ -0,0 +1,120 @@ +// +// TakeUntil.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class TakeUntilSinkOther + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Parent = TakeUntilSink + typealias E = Other + + private let _parent: Parent + + var _lock: NSRecursiveLock { + return _parent._lock + } + + private let _subscription = SingleAssignmentDisposable() + + init(parent: Parent) { + _parent = parent +#if TRACE_RESOURCES + AtomicIncrement(&resourceCount) +#endif + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + switch event { + case .Next: + _parent.forwardOn(.Completed) + _parent.dispose() + case .Error(let e): + _parent.forwardOn(.Error(e)) + _parent.dispose() + case .Completed: + _parent._open = true + _subscription.dispose() + } + } + +#if TRACE_RESOURCES + deinit { + AtomicDecrement(&resourceCount) + } +#endif +} + +class TakeUntilSink + : Sink + , LockOwnerType + , ObserverType + , SynchronizedOnType { + typealias E = ElementType + typealias Parent = TakeUntil + + private let _parent: Parent + + let _lock = NSRecursiveLock() + + // state + private var _open = false + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + switch event { + case .Next: + forwardOn(event) + case .Error: + forwardOn(event) + dispose() + case .Completed: + forwardOn(event) + dispose() + } + } + + func run() -> Disposable { + let otherObserver = TakeUntilSinkOther(parent: self) + let otherSubscription = _parent._other.subscribe(otherObserver) + otherObserver._subscription.disposable = otherSubscription + let sourceSubscription = _parent._source.subscribe(self) + + return StableCompositeDisposable.create(sourceSubscription, otherObserver._subscription) + } +} + +class TakeUntil: Producer { + + private let _source: Observable + private let _other: Observable + + init(source: Observable, other: Observable) { + _source = source + _other = other + } + + override func run(observer: O) -> Disposable { + let sink = TakeUntilSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/TakeWhile.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/TakeWhile.swift new file mode 100644 index 00000000000..a660bb813bb --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/TakeWhile.swift @@ -0,0 +1,132 @@ +// +// TakeWhile.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class TakeWhileSink + : Sink + , ObserverType { + typealias Parent = TakeWhile + typealias Element = ElementType + + private let _parent: Parent + + private var _running = true + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(let value): + if !_running { + return + } + + do { + _running = try _parent._predicate(value) + } catch let e { + forwardOn(.Error(e)) + dispose() + return + } + + if _running { + forwardOn(.Next(value)) + } else { + forwardOn(.Completed) + dispose() + } + case .Error, .Completed: + forwardOn(event) + dispose() + } + } + +} + +class TakeWhileSinkWithIndex + : Sink + , ObserverType { + typealias Parent = TakeWhile + typealias Element = ElementType + + private let _parent: Parent + + private var _running = true + private var _index = 0 + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(let value): + if !_running { + return + } + + do { + _running = try _parent._predicateWithIndex(value, _index) + try incrementChecked(&_index) + } catch let e { + forwardOn(.Error(e)) + dispose() + return + } + + if _running { + forwardOn(.Next(value)) + } else { + forwardOn(.Completed) + dispose() + } + case .Error, .Completed: + forwardOn(event) + dispose() + } + } + +} + +class TakeWhile: Producer { + typealias Predicate = (Element) throws -> Bool + typealias PredicateWithIndex = (Element, Int) throws -> Bool + + private let _source: Observable + private let _predicate: Predicate! + private let _predicateWithIndex: PredicateWithIndex! + + init(source: Observable, predicate: Predicate) { + _source = source + _predicate = predicate + _predicateWithIndex = nil + } + + init(source: Observable, predicate: PredicateWithIndex) { + _source = source + _predicate = nil + _predicateWithIndex = predicate + } + + override func run(observer: O) -> Disposable { + if let _ = _predicate { + let sink = TakeWhileSink(parent: self, observer: observer) + sink.disposable = _source.subscribe(sink) + return sink + } else { + let sink = TakeWhileSinkWithIndex(parent: self, observer: observer) + sink.disposable = _source.subscribe(sink) + return sink + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Throttle.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Throttle.swift new file mode 100644 index 00000000000..33e9837dc4b --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Throttle.swift @@ -0,0 +1,104 @@ +// +// Throttle.swift +// Rx +// +// Created by Krunoslav Zaher on 3/22/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class ThrottleSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = O.E + typealias ParentType = Throttle + + private let _parent: ParentType + + let _lock = NSRecursiveLock() + + // state + private var _id = 0 as UInt64 + private var _value: Element? = nil + + let cancellable = SerialDisposable() + + init(parent: ParentType, observer: O) { + _parent = parent + + super.init(observer: observer) + } + + func run() -> Disposable { + let subscription = _parent._source.subscribe(self) + + return StableCompositeDisposable.create(subscription, cancellable) + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + switch event { + case .Next(let element): + _id = _id &+ 1 + let currentId = _id + _value = element + + + let scheduler = _parent._scheduler + let dueTime = _parent._dueTime + + let d = SingleAssignmentDisposable() + self.cancellable.disposable = d + d.disposable = scheduler.scheduleRelative(currentId, dueTime: dueTime, action: self.propagate) + case .Error: + _value = nil + forwardOn(event) + dispose() + case .Completed: + if let value = _value { + _value = nil + forwardOn(.Next(value)) + } + forwardOn(.Completed) + dispose() + } + } + + func propagate(currentId: UInt64) -> Disposable { + _lock.lock(); defer { _lock.unlock() } // { + let originalValue = _value + + if let value = originalValue where _id == currentId { + _value = nil + forwardOn(.Next(value)) + } + // } + return NopDisposable.instance + } +} + +class Throttle : Producer { + + private let _source: Observable + private let _dueTime: RxTimeInterval + private let _scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, scheduler: SchedulerType) { + _source = source + _dueTime = dueTime + _scheduler = scheduler + } + + override func run(observer: O) -> Disposable { + let sink = ThrottleSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } + +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Timeout.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Timeout.swift new file mode 100644 index 00000000000..fe6a1b85396 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Timeout.swift @@ -0,0 +1,120 @@ +// +// Timeout.swift +// Rx +// +// Created by Tomi Koskinen on 13/11/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class TimeoutSink: Sink, LockOwnerType, ObserverType { + typealias E = ElementType + typealias Parent = Timeout + + private let _parent: Parent + + let _lock = NSRecursiveLock() + + private let _timerD = SerialDisposable() + private let _subscription = SerialDisposable() + + private var _id = 0 + private var _switched = false + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func run() -> Disposable { + let original = SingleAssignmentDisposable() + _subscription.disposable = original + + _createTimeoutTimer() + + original.disposable = _parent._source.subscribeSafe(self) + + return StableCompositeDisposable.create(_subscription, _timerD) + } + + func on(event: Event) { + switch event { + case .Next: + var onNextWins = false + + _lock.performLocked() { + onNextWins = !self._switched + if onNextWins { + self._id = self._id &+ 1 + } + } + + if onNextWins { + forwardOn(event) + self._createTimeoutTimer() + } + case .Error, .Completed: + var onEventWins = false + + _lock.performLocked() { + onEventWins = !self._switched + if onEventWins { + self._id = self._id &+ 1 + } + } + + if onEventWins { + forwardOn(event) + self.dispose() + } + } + } + + private func _createTimeoutTimer() { + if _timerD.disposed { + return + } + + let nextTimer = SingleAssignmentDisposable() + _timerD.disposable = nextTimer + + nextTimer.disposable = _parent._scheduler.scheduleRelative(_id, dueTime: _parent._dueTime) { state in + + var timerWins = false + + self._lock.performLocked() { + self._switched = (state == self._id) + timerWins = self._switched + } + + if timerWins { + self._subscription.disposable = self._parent._other.subscribeSafe(self.forwarder()) + } + + return NopDisposable.instance + } + } +} + + +class Timeout : Producer { + + private let _source: Observable + private let _dueTime: RxTimeInterval + private let _other: Observable + private let _scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, other: Observable, scheduler: SchedulerType) { + _source = source + _dueTime = dueTime + _other = other + _scheduler = scheduler + } + + override func run(observer: O) -> Disposable { + let sink = TimeoutSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Timer.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Timer.swift new file mode 100644 index 00000000000..dcbb2bfd260 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Timer.swift @@ -0,0 +1,72 @@ +// +// Timer.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class TimerSink : Sink { + typealias Parent = Timer + + private let _parent: Parent + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func run() -> Disposable { + return _parent._scheduler.schedulePeriodic(0 as O.E, startAfter: _parent._dueTime, period: _parent._period!) { state in + self.forwardOn(.Next(state)) + return state &+ 1 + } + } +} + +class TimerOneOffSink : Sink { + typealias Parent = Timer + + private let _parent: Parent + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func run() -> Disposable { + return _parent._scheduler.scheduleRelative((), dueTime: _parent._dueTime) { (_) -> Disposable in + self.forwardOn(.Next(0)) + self.forwardOn(.Completed) + + return NopDisposable.instance + } + } +} + +class Timer: Producer { + private let _scheduler: SchedulerType + private let _dueTime: RxTimeInterval + private let _period: RxTimeInterval? + + init(dueTime: RxTimeInterval, period: RxTimeInterval?, scheduler: SchedulerType) { + _scheduler = scheduler + _dueTime = dueTime + _period = period + } + + override func run(observer: O) -> Disposable { + if let _ = _period { + let sink = TimerSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } + else { + let sink = TimerOneOffSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ToArray.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ToArray.swift new file mode 100644 index 00000000000..cb5c428143c --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/ToArray.swift @@ -0,0 +1,50 @@ +// +// ToArray.swift +// Rx +// +// Created by Junior B. on 20/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class ToArraySink : Sink, ObserverType { + typealias Parent = ToArray + + let _parent: Parent + var _list = Array() + + init(parent: Parent, observer: O) { + _parent = parent + + super.init(observer: observer) + } + + func on(event: Event) { + switch event { + case .Next(let value): + self._list.append(value) + case .Error(let e): + forwardOn(.Error(e)) + self.dispose() + case .Completed: + forwardOn(.Next(_list)) + forwardOn(.Completed) + self.dispose() + } + } +} + +class ToArray : Producer<[SourceType]> { + let _source: Observable + + init(source: Observable) { + _source = source + } + + override func run(observer: O) -> Disposable { + let sink = ToArraySink(parent: self, observer: observer) + sink.disposable = _source.subscribe(sink) + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Using.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Using.swift new file mode 100644 index 00000000000..6aa229823ca --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Using.swift @@ -0,0 +1,78 @@ +// +// Using.swift +// Rx +// +// Created by Yury Korolev on 10/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class UsingSink : Sink, ObserverType { + + typealias Parent = Using + typealias E = O.E + + private let _parent: Parent + + init(parent: Parent, observer: O) { + _parent = parent + super.init(observer: observer) + } + + func run() -> Disposable { + var disposable = NopDisposable.instance + + do { + let resource = try _parent._resourceFactory() + disposable = resource + let source = try _parent._observableFactory(resource) + + return StableCompositeDisposable.create( + source.subscribe(self), + disposable + ) + } catch let error { + return StableCompositeDisposable.create( + Observable.error(error).subscribe(self), + disposable + ) + } + } + + func on(event: Event) { + switch event { + case let .Next(value): + forwardOn(.Next(value)) + case let .Error(error): + forwardOn(.Error(error)) + dispose() + case .Completed: + forwardOn(.Completed) + dispose() + } + } +} + +class Using: Producer { + + typealias E = SourceType + + typealias ResourceFactory = () throws -> ResourceType + typealias ObservableFactory = ResourceType throws -> Observable + + private let _resourceFactory: ResourceFactory + private let _observableFactory: ObservableFactory + + + init(resourceFactory: ResourceFactory, observableFactory: ObservableFactory) { + _resourceFactory = resourceFactory + _observableFactory = observableFactory + } + + override func run(observer: O) -> Disposable { + let sink = UsingSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Window.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Window.swift new file mode 100644 index 00000000000..24060a8493e --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Window.swift @@ -0,0 +1,152 @@ +// +// Window.swift +// Rx +// +// Created by Junior B. on 29/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class WindowTimeCountSink> + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Parent = WindowTimeCount + typealias E = Element + + private let _parent: Parent + + let _lock = NSRecursiveLock() + + private var _subject = PublishSubject() + private var _count = 0 + private var _windowId = 0 + + private let _timerD = SerialDisposable() + private let _refCountDisposable: RefCountDisposable + private let _groupDisposable = CompositeDisposable() + + init(parent: Parent, observer: O) { + _parent = parent + + _groupDisposable.addDisposable(_timerD) + + _refCountDisposable = RefCountDisposable(disposable: _groupDisposable) + super.init(observer: observer) + } + + func run() -> Disposable { + + forwardOn(.Next(AddRef(source: _subject, refCount: _refCountDisposable).asObservable())) + createTimer(_windowId) + + _groupDisposable.addDisposable(_parent._source.subscribeSafe(self)) + return _refCountDisposable + } + + func startNewWindowAndCompleteCurrentOne() { + _subject.on(.Completed) + _subject = PublishSubject() + + forwardOn(.Next(AddRef(source: _subject, refCount: _refCountDisposable).asObservable())) + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + var newWindow = false + var newId = 0 + + switch event { + case .Next(let element): + _subject.on(.Next(element)) + + do { + try incrementChecked(&_count) + } catch (let e) { + _subject.on(.Error(e as ErrorType)) + dispose() + } + + if (_count == _parent._count) { + newWindow = true + _count = 0 + _windowId += 1 + newId = _windowId + self.startNewWindowAndCompleteCurrentOne() + } + + case .Error(let error): + _subject.on(.Error(error)) + forwardOn(.Error(error)) + dispose() + case .Completed: + _subject.on(.Completed) + forwardOn(.Completed) + dispose() + } + + if newWindow { + createTimer(newId) + } + } + + func createTimer(windowId: Int) { + if _timerD.disposed { + return + } + + if _windowId != windowId { + return + } + + let nextTimer = SingleAssignmentDisposable() + + _timerD.disposable = nextTimer + + nextTimer.disposable = _parent._scheduler.scheduleRelative(windowId, dueTime: _parent._timeSpan) { previousWindowId in + + var newId = 0 + + self._lock.performLocked { + if previousWindowId != self._windowId { + return + } + + self._count = 0 + self._windowId = self._windowId &+ 1 + newId = self._windowId + self.startNewWindowAndCompleteCurrentOne() + } + + self.createTimer(newId) + + return NopDisposable.instance + } + } +} + +class WindowTimeCount : Producer> { + + private let _timeSpan: RxTimeInterval + private let _count: Int + private let _scheduler: SchedulerType + private let _source: Observable + + init(source: Observable, timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) { + _source = source + _timeSpan = timeSpan + _count = count + _scheduler = scheduler + } + + override func run>(observer: O) -> Disposable { + let sink = WindowTimeCountSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/WithLatestFrom.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/WithLatestFrom.swift new file mode 100644 index 00000000000..7d0ab9f615c --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/WithLatestFrom.swift @@ -0,0 +1,122 @@ +// +// WithLatestFrom.swift +// RxExample +// +// Created by Yury Korolev on 10/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class WithLatestFromSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + + typealias Parent = WithLatestFrom + typealias E = FirstType + + private let _parent: Parent + + var _lock = NSRecursiveLock() + private var _latest: SecondType? + + init(parent: Parent, observer: O) { + _parent = parent + + super.init(observer: observer) + } + + func run() -> Disposable { + let sndSubscription = SingleAssignmentDisposable() + let sndO = WithLatestFromSecond(parent: self, disposable: sndSubscription) + + sndSubscription.disposable = _parent._second.subscribe(sndO) + let fstSubscription = _parent._first.subscribe(self) + + return StableCompositeDisposable.create(fstSubscription, sndSubscription) + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + switch event { + case let .Next(value): + guard let latest = _latest else { return } + do { + let res = try _parent._resultSelector(value, latest) + + forwardOn(.Next(res)) + } catch let e { + forwardOn(.Error(e)) + dispose() + } + case .Completed: + forwardOn(.Completed) + dispose() + case let .Error(error): + forwardOn(.Error(error)) + dispose() + } + } +} + +class WithLatestFromSecond + : ObserverType + , LockOwnerType + , SynchronizedOnType { + + typealias Parent = WithLatestFromSink + typealias E = SecondType + + private let _parent: Parent + private let _disposable: Disposable + + var _lock: NSRecursiveLock { + return _parent._lock + } + + init(parent: Parent, disposable: Disposable) { + _parent = parent + _disposable = disposable + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + switch event { + case let .Next(value): + _parent._latest = value + case .Completed: + _disposable.dispose() + case let .Error(error): + _parent.forwardOn(.Error(error)) + _parent.dispose() + } + } +} + +class WithLatestFrom: Producer { + typealias ResultSelector = (FirstType, SecondType) throws -> ResultType + + private let _first: Observable + private let _second: Observable + private let _resultSelector: ResultSelector + + init(first: Observable, second: Observable, resultSelector: ResultSelector) { + _first = first + _second = second + _resultSelector = resultSelector + } + + override func run(observer: O) -> Disposable { + let sink = WithLatestFromSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Zip+CollectionType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Zip+CollectionType.swift new file mode 100644 index 00000000000..d083a30a582 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Zip+CollectionType.swift @@ -0,0 +1,137 @@ +// +// Zip+CollectionType.swift +// Rx +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class ZipCollectionTypeSink + : Sink { + typealias Parent = ZipCollectionType + typealias SourceElement = C.Generator.Element.E + + private let _parent: Parent + + private let _lock = NSRecursiveLock() + + // state + private var _numberOfValues = 0 + private var _values: [Queue] + private var _isDone: [Bool] + private var _numberOfDone = 0 + private var _subscriptions: [SingleAssignmentDisposable] + + init(parent: Parent, observer: O) { + _parent = parent + _values = [Queue](count: parent.count, repeatedValue: Queue(capacity: 4)) + _isDone = [Bool](count: parent.count, repeatedValue: false) + _subscriptions = Array() + _subscriptions.reserveCapacity(parent.count) + + for _ in 0 ..< parent.count { + _subscriptions.append(SingleAssignmentDisposable()) + } + + super.init(observer: observer) + } + + func on(event: Event, atIndex: Int) { + _lock.lock(); defer { _lock.unlock() } // { + switch event { + case .Next(let element): + _values[atIndex].enqueue(element) + + if _values[atIndex].count == 1 { + _numberOfValues += 1 + } + + if _numberOfValues < _parent.count { + let numberOfOthersThatAreDone = _numberOfDone - (_isDone[atIndex] ? 1 : 0) + if numberOfOthersThatAreDone == _parent.count - 1 { + self.forwardOn(.Completed) + self.dispose() + } + return + } + + do { + var arguments = [SourceElement]() + arguments.reserveCapacity(_parent.count) + + // recalculate number of values + _numberOfValues = 0 + + for i in 0 ..< _values.count { + arguments.append(_values[i].dequeue()!) + if _values[i].count > 0 { + _numberOfValues += 1 + } + } + + let result = try _parent.resultSelector(arguments) + self.forwardOn(.Next(result)) + } + catch let error { + self.forwardOn(.Error(error)) + self.dispose() + } + + case .Error(let error): + self.forwardOn(.Error(error)) + self.dispose() + case .Completed: + if _isDone[atIndex] { + return + } + + _isDone[atIndex] = true + _numberOfDone += 1 + + if _numberOfDone == _parent.count { + self.forwardOn(.Completed) + self.dispose() + } + else { + _subscriptions[atIndex].dispose() + } + } + // } + } + + func run() -> Disposable { + var j = 0 + for i in _parent.sources.startIndex ..< _parent.sources.endIndex { + let index = j + let source = _parent.sources[i].asObservable() + _subscriptions[j].disposable = source.subscribe(AnyObserver { event in + self.on(event, atIndex: index) + }) + j += 1 + } + + return CompositeDisposable(disposables: _subscriptions.map { $0 }) + } +} + +class ZipCollectionType : Producer { + typealias ResultSelector = [C.Generator.Element.E] throws -> R + + let sources: C + let resultSelector: ResultSelector + let count: Int + + init(sources: C, resultSelector: ResultSelector) { + self.sources = sources + self.resultSelector = resultSelector + self.count = Int(self.sources.count.toIntMax()) + } + + override func run(observer: O) -> Disposable { + let sink = ZipCollectionTypeSink(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Zip+arity.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Zip+arity.swift new file mode 100644 index 00000000000..891c2c40ca3 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Zip+arity.swift @@ -0,0 +1,829 @@ +// This file is autogenerated. Take a look at `Preprocessor` target in RxSwift project +// +// Zip+arity.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/23/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + + + +// 2 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func zip + (source1: O1, _ source2: O2, resultSelector: (O1.E, O2.E) throws -> E) + -> Observable { + return Zip2( + source1: source1.asObservable(), source2: source2.asObservable(), + resultSelector: resultSelector + ) + } +} + +class ZipSink2_ : ZipSink { + typealias R = O.E + typealias Parent = Zip2 + + let _parent: Parent + + var _values1: Queue = Queue(capacity: 2) + var _values2: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: O) { + _parent = parent + super.init(arity: 2, observer: observer) + } + + override func hasElements(index: Int) -> Bool { + switch (index) { + case 0: return _values1.count > 0 + case 1: return _values2.count > 0 + + default: + rxFatalError("Unhandled case (Function)") + } + + return false + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: _lock, parent: self, index: 0, setNextValue: { self._values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: _lock, parent: self, index: 1, setNextValue: { self._values2.enqueue($0) }, this: subscription2) + + subscription1.disposable = _parent.source1.subscribe(observer1) + subscription2.disposable = _parent.source2.subscribe(observer2) + + return CompositeDisposable(disposables: [ + subscription1, + subscription2 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_values1.dequeue()!, _values2.dequeue()!) + } +} + +class Zip2 : Producer { + typealias ResultSelector = (E1, E2) throws -> R + + let source1: Observable + let source2: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, resultSelector: ResultSelector) { + self.source1 = source1 + self.source2 = source2 + + _resultSelector = resultSelector + } + + override func run(observer: O) -> Disposable { + let sink = ZipSink2_(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} + + + +// 3 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func zip + (source1: O1, _ source2: O2, _ source3: O3, resultSelector: (O1.E, O2.E, O3.E) throws -> E) + -> Observable { + return Zip3( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), + resultSelector: resultSelector + ) + } +} + +class ZipSink3_ : ZipSink { + typealias R = O.E + typealias Parent = Zip3 + + let _parent: Parent + + var _values1: Queue = Queue(capacity: 2) + var _values2: Queue = Queue(capacity: 2) + var _values3: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: O) { + _parent = parent + super.init(arity: 3, observer: observer) + } + + override func hasElements(index: Int) -> Bool { + switch (index) { + case 0: return _values1.count > 0 + case 1: return _values2.count > 0 + case 2: return _values3.count > 0 + + default: + rxFatalError("Unhandled case (Function)") + } + + return false + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: _lock, parent: self, index: 0, setNextValue: { self._values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: _lock, parent: self, index: 1, setNextValue: { self._values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: _lock, parent: self, index: 2, setNextValue: { self._values3.enqueue($0) }, this: subscription3) + + subscription1.disposable = _parent.source1.subscribe(observer1) + subscription2.disposable = _parent.source2.subscribe(observer2) + subscription3.disposable = _parent.source3.subscribe(observer3) + + return CompositeDisposable(disposables: [ + subscription1, + subscription2, + subscription3 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_values1.dequeue()!, _values2.dequeue()!, _values3.dequeue()!) + } +} + +class Zip3 : Producer { + typealias ResultSelector = (E1, E2, E3) throws -> R + + let source1: Observable + let source2: Observable + let source3: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, resultSelector: ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + + _resultSelector = resultSelector + } + + override func run(observer: O) -> Disposable { + let sink = ZipSink3_(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} + + + +// 4 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func zip + (source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, resultSelector: (O1.E, O2.E, O3.E, O4.E) throws -> E) + -> Observable { + return Zip4( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), + resultSelector: resultSelector + ) + } +} + +class ZipSink4_ : ZipSink { + typealias R = O.E + typealias Parent = Zip4 + + let _parent: Parent + + var _values1: Queue = Queue(capacity: 2) + var _values2: Queue = Queue(capacity: 2) + var _values3: Queue = Queue(capacity: 2) + var _values4: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: O) { + _parent = parent + super.init(arity: 4, observer: observer) + } + + override func hasElements(index: Int) -> Bool { + switch (index) { + case 0: return _values1.count > 0 + case 1: return _values2.count > 0 + case 2: return _values3.count > 0 + case 3: return _values4.count > 0 + + default: + rxFatalError("Unhandled case (Function)") + } + + return false + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: _lock, parent: self, index: 0, setNextValue: { self._values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: _lock, parent: self, index: 1, setNextValue: { self._values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: _lock, parent: self, index: 2, setNextValue: { self._values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: _lock, parent: self, index: 3, setNextValue: { self._values4.enqueue($0) }, this: subscription4) + + subscription1.disposable = _parent.source1.subscribe(observer1) + subscription2.disposable = _parent.source2.subscribe(observer2) + subscription3.disposable = _parent.source3.subscribe(observer3) + subscription4.disposable = _parent.source4.subscribe(observer4) + + return CompositeDisposable(disposables: [ + subscription1, + subscription2, + subscription3, + subscription4 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_values1.dequeue()!, _values2.dequeue()!, _values3.dequeue()!, _values4.dequeue()!) + } +} + +class Zip4 : Producer { + typealias ResultSelector = (E1, E2, E3, E4) throws -> R + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, resultSelector: ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + + _resultSelector = resultSelector + } + + override func run(observer: O) -> Disposable { + let sink = ZipSink4_(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} + + + +// 5 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func zip + (source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, resultSelector: (O1.E, O2.E, O3.E, O4.E, O5.E) throws -> E) + -> Observable { + return Zip5( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), + resultSelector: resultSelector + ) + } +} + +class ZipSink5_ : ZipSink { + typealias R = O.E + typealias Parent = Zip5 + + let _parent: Parent + + var _values1: Queue = Queue(capacity: 2) + var _values2: Queue = Queue(capacity: 2) + var _values3: Queue = Queue(capacity: 2) + var _values4: Queue = Queue(capacity: 2) + var _values5: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: O) { + _parent = parent + super.init(arity: 5, observer: observer) + } + + override func hasElements(index: Int) -> Bool { + switch (index) { + case 0: return _values1.count > 0 + case 1: return _values2.count > 0 + case 2: return _values3.count > 0 + case 3: return _values4.count > 0 + case 4: return _values5.count > 0 + + default: + rxFatalError("Unhandled case (Function)") + } + + return false + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: _lock, parent: self, index: 0, setNextValue: { self._values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: _lock, parent: self, index: 1, setNextValue: { self._values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: _lock, parent: self, index: 2, setNextValue: { self._values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: _lock, parent: self, index: 3, setNextValue: { self._values4.enqueue($0) }, this: subscription4) + let observer5 = ZipObserver(lock: _lock, parent: self, index: 4, setNextValue: { self._values5.enqueue($0) }, this: subscription5) + + subscription1.disposable = _parent.source1.subscribe(observer1) + subscription2.disposable = _parent.source2.subscribe(observer2) + subscription3.disposable = _parent.source3.subscribe(observer3) + subscription4.disposable = _parent.source4.subscribe(observer4) + subscription5.disposable = _parent.source5.subscribe(observer5) + + return CompositeDisposable(disposables: [ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_values1.dequeue()!, _values2.dequeue()!, _values3.dequeue()!, _values4.dequeue()!, _values5.dequeue()!) + } +} + +class Zip5 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5) throws -> R + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, resultSelector: ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + + _resultSelector = resultSelector + } + + override func run(observer: O) -> Disposable { + let sink = ZipSink5_(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} + + + +// 6 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func zip + (source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, resultSelector: (O1.E, O2.E, O3.E, O4.E, O5.E, O6.E) throws -> E) + -> Observable { + return Zip6( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), + resultSelector: resultSelector + ) + } +} + +class ZipSink6_ : ZipSink { + typealias R = O.E + typealias Parent = Zip6 + + let _parent: Parent + + var _values1: Queue = Queue(capacity: 2) + var _values2: Queue = Queue(capacity: 2) + var _values3: Queue = Queue(capacity: 2) + var _values4: Queue = Queue(capacity: 2) + var _values5: Queue = Queue(capacity: 2) + var _values6: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: O) { + _parent = parent + super.init(arity: 6, observer: observer) + } + + override func hasElements(index: Int) -> Bool { + switch (index) { + case 0: return _values1.count > 0 + case 1: return _values2.count > 0 + case 2: return _values3.count > 0 + case 3: return _values4.count > 0 + case 4: return _values5.count > 0 + case 5: return _values6.count > 0 + + default: + rxFatalError("Unhandled case (Function)") + } + + return false + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: _lock, parent: self, index: 0, setNextValue: { self._values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: _lock, parent: self, index: 1, setNextValue: { self._values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: _lock, parent: self, index: 2, setNextValue: { self._values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: _lock, parent: self, index: 3, setNextValue: { self._values4.enqueue($0) }, this: subscription4) + let observer5 = ZipObserver(lock: _lock, parent: self, index: 4, setNextValue: { self._values5.enqueue($0) }, this: subscription5) + let observer6 = ZipObserver(lock: _lock, parent: self, index: 5, setNextValue: { self._values6.enqueue($0) }, this: subscription6) + + subscription1.disposable = _parent.source1.subscribe(observer1) + subscription2.disposable = _parent.source2.subscribe(observer2) + subscription3.disposable = _parent.source3.subscribe(observer3) + subscription4.disposable = _parent.source4.subscribe(observer4) + subscription5.disposable = _parent.source5.subscribe(observer5) + subscription6.disposable = _parent.source6.subscribe(observer6) + + return CompositeDisposable(disposables: [ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_values1.dequeue()!, _values2.dequeue()!, _values3.dequeue()!, _values4.dequeue()!, _values5.dequeue()!, _values6.dequeue()!) + } +} + +class Zip6 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6) throws -> R + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, resultSelector: ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + + _resultSelector = resultSelector + } + + override func run(observer: O) -> Disposable { + let sink = ZipSink6_(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} + + + +// 7 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func zip + (source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, resultSelector: (O1.E, O2.E, O3.E, O4.E, O5.E, O6.E, O7.E) throws -> E) + -> Observable { + return Zip7( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), + resultSelector: resultSelector + ) + } +} + +class ZipSink7_ : ZipSink { + typealias R = O.E + typealias Parent = Zip7 + + let _parent: Parent + + var _values1: Queue = Queue(capacity: 2) + var _values2: Queue = Queue(capacity: 2) + var _values3: Queue = Queue(capacity: 2) + var _values4: Queue = Queue(capacity: 2) + var _values5: Queue = Queue(capacity: 2) + var _values6: Queue = Queue(capacity: 2) + var _values7: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: O) { + _parent = parent + super.init(arity: 7, observer: observer) + } + + override func hasElements(index: Int) -> Bool { + switch (index) { + case 0: return _values1.count > 0 + case 1: return _values2.count > 0 + case 2: return _values3.count > 0 + case 3: return _values4.count > 0 + case 4: return _values5.count > 0 + case 5: return _values6.count > 0 + case 6: return _values7.count > 0 + + default: + rxFatalError("Unhandled case (Function)") + } + + return false + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + let subscription7 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: _lock, parent: self, index: 0, setNextValue: { self._values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: _lock, parent: self, index: 1, setNextValue: { self._values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: _lock, parent: self, index: 2, setNextValue: { self._values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: _lock, parent: self, index: 3, setNextValue: { self._values4.enqueue($0) }, this: subscription4) + let observer5 = ZipObserver(lock: _lock, parent: self, index: 4, setNextValue: { self._values5.enqueue($0) }, this: subscription5) + let observer6 = ZipObserver(lock: _lock, parent: self, index: 5, setNextValue: { self._values6.enqueue($0) }, this: subscription6) + let observer7 = ZipObserver(lock: _lock, parent: self, index: 6, setNextValue: { self._values7.enqueue($0) }, this: subscription7) + + subscription1.disposable = _parent.source1.subscribe(observer1) + subscription2.disposable = _parent.source2.subscribe(observer2) + subscription3.disposable = _parent.source3.subscribe(observer3) + subscription4.disposable = _parent.source4.subscribe(observer4) + subscription5.disposable = _parent.source5.subscribe(observer5) + subscription6.disposable = _parent.source6.subscribe(observer6) + subscription7.disposable = _parent.source7.subscribe(observer7) + + return CompositeDisposable(disposables: [ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6, + subscription7 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_values1.dequeue()!, _values2.dequeue()!, _values3.dequeue()!, _values4.dequeue()!, _values5.dequeue()!, _values6.dequeue()!, _values7.dequeue()!) + } +} + +class Zip7 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7) throws -> R + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + let source7: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, source7: Observable, resultSelector: ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + self.source7 = source7 + + _resultSelector = resultSelector + } + + override func run(observer: O) -> Disposable { + let sink = ZipSink7_(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} + + + +// 8 + +extension Observable { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func zip + (source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8, resultSelector: (O1.E, O2.E, O3.E, O4.E, O5.E, O6.E, O7.E, O8.E) throws -> E) + -> Observable { + return Zip8( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), source8: source8.asObservable(), + resultSelector: resultSelector + ) + } +} + +class ZipSink8_ : ZipSink { + typealias R = O.E + typealias Parent = Zip8 + + let _parent: Parent + + var _values1: Queue = Queue(capacity: 2) + var _values2: Queue = Queue(capacity: 2) + var _values3: Queue = Queue(capacity: 2) + var _values4: Queue = Queue(capacity: 2) + var _values5: Queue = Queue(capacity: 2) + var _values6: Queue = Queue(capacity: 2) + var _values7: Queue = Queue(capacity: 2) + var _values8: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: O) { + _parent = parent + super.init(arity: 8, observer: observer) + } + + override func hasElements(index: Int) -> Bool { + switch (index) { + case 0: return _values1.count > 0 + case 1: return _values2.count > 0 + case 2: return _values3.count > 0 + case 3: return _values4.count > 0 + case 4: return _values5.count > 0 + case 5: return _values6.count > 0 + case 6: return _values7.count > 0 + case 7: return _values8.count > 0 + + default: + rxFatalError("Unhandled case (Function)") + } + + return false + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + let subscription7 = SingleAssignmentDisposable() + let subscription8 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: _lock, parent: self, index: 0, setNextValue: { self._values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: _lock, parent: self, index: 1, setNextValue: { self._values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: _lock, parent: self, index: 2, setNextValue: { self._values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: _lock, parent: self, index: 3, setNextValue: { self._values4.enqueue($0) }, this: subscription4) + let observer5 = ZipObserver(lock: _lock, parent: self, index: 4, setNextValue: { self._values5.enqueue($0) }, this: subscription5) + let observer6 = ZipObserver(lock: _lock, parent: self, index: 5, setNextValue: { self._values6.enqueue($0) }, this: subscription6) + let observer7 = ZipObserver(lock: _lock, parent: self, index: 6, setNextValue: { self._values7.enqueue($0) }, this: subscription7) + let observer8 = ZipObserver(lock: _lock, parent: self, index: 7, setNextValue: { self._values8.enqueue($0) }, this: subscription8) + + subscription1.disposable = _parent.source1.subscribe(observer1) + subscription2.disposable = _parent.source2.subscribe(observer2) + subscription3.disposable = _parent.source3.subscribe(observer3) + subscription4.disposable = _parent.source4.subscribe(observer4) + subscription5.disposable = _parent.source5.subscribe(observer5) + subscription6.disposable = _parent.source6.subscribe(observer6) + subscription7.disposable = _parent.source7.subscribe(observer7) + subscription8.disposable = _parent.source8.subscribe(observer8) + + return CompositeDisposable(disposables: [ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6, + subscription7, + subscription8 + ]) + } + + override func getResult() throws -> R { + return try _parent._resultSelector(_values1.dequeue()!, _values2.dequeue()!, _values3.dequeue()!, _values4.dequeue()!, _values5.dequeue()!, _values6.dequeue()!, _values7.dequeue()!, _values8.dequeue()!) + } +} + +class Zip8 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7, E8) throws -> R + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + let source7: Observable + let source8: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, source7: Observable, source8: Observable, resultSelector: ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + self.source7 = source7 + self.source8 = source8 + + _resultSelector = resultSelector + } + + override func run(observer: O) -> Disposable { + let sink = ZipSink8_(parent: self, observer: observer) + sink.disposable = sink.run() + return sink + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Zip.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Zip.swift new file mode 100644 index 00000000000..108326517e9 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Implementations/Zip.swift @@ -0,0 +1,157 @@ +// +// Zip.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/23/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +protocol ZipSinkProtocol : class +{ + func next(index: Int) + func fail(error: ErrorType) + func done(index: Int) +} + +class ZipSink : Sink, ZipSinkProtocol { + typealias Element = O.E + + let _arity: Int + + let _lock = NSRecursiveLock() + + // state + private var _isDone: [Bool] + + init(arity: Int, observer: O) { + _isDone = [Bool](count: arity, repeatedValue: false) + _arity = arity + + super.init(observer: observer) + } + + func getResult() throws -> Element { + abstractMethod() + } + + func hasElements(index: Int) -> Bool { + abstractMethod() + } + + func next(index: Int) { + var hasValueAll = true + + for i in 0 ..< _arity { + if !hasElements(i) { + hasValueAll = false + break + } + } + + if hasValueAll { + do { + let result = try getResult() + self.forwardOn(.Next(result)) + } + catch let e { + self.forwardOn(.Error(e)) + dispose() + } + } + else { + var allOthersDone = true + + let arity = _isDone.count + for i in 0 ..< arity { + if i != index && !_isDone[i] { + allOthersDone = false + break + } + } + + if allOthersDone { + forwardOn(.Completed) + self.dispose() + } + } + } + + func fail(error: ErrorType) { + forwardOn(.Error(error)) + dispose() + } + + func done(index: Int) { + _isDone[index] = true + + var allDone = true + + for done in _isDone { + if !done { + allDone = false + break + } + } + + if allDone { + forwardOn(.Completed) + dispose() + } + } +} + +class ZipObserver + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias E = ElementType + typealias ValueSetter = (ElementType) -> () + + private var _parent: ZipSinkProtocol? + + let _lock: NSRecursiveLock + + // state + private let _index: Int + private let _this: Disposable + private let _setNextValue: ValueSetter + + init(lock: NSRecursiveLock, parent: ZipSinkProtocol, index: Int, setNextValue: ValueSetter, this: Disposable) { + _lock = lock + _parent = parent + _index = index + _this = this + _setNextValue = setNextValue + } + + func on(event: Event) { + synchronizedOn(event) + } + + func _synchronized_on(event: Event) { + if let _ = _parent { + switch event { + case .Next(_): + break + case .Error(_): + _this.dispose() + case .Completed: + _this.dispose() + } + } + + if let parent = _parent { + switch event { + case .Next(let value): + _setNextValue(value) + parent.next(_index) + case .Error(let error): + parent.fail(error) + case .Completed: + parent.done(_index) + } + } + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Aggregate.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Aggregate.swift new file mode 100644 index 00000000000..8613eb5a62f --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Aggregate.swift @@ -0,0 +1,64 @@ +// +// Observable+Aggregate.swift +// Rx +// +// Created by Krunoslav Zaher on 3/22/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +// MARK: reduce + +extension ObservableType { + + /** + Applies an `accumulator` function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified `seed` value is used as the initial accumulator value. + + For aggregation behavior with incremental intermediate results, see `scan`. + + - seealso: [reduce operator on reactivex.io](http://reactivex.io/documentation/operators/reduce.html) + + - parameter seed: The initial accumulator value. + - parameter accumulator: A accumulator function to be invoked on each element. + - parameter mapResult: A function to transform the final accumulator value into the result value. + - returns: An observable sequence containing a single element with the final accumulator value. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func reduce(seed: A, accumulator: (A, E) throws -> A, mapResult: (A) throws -> R) + -> Observable { + return Reduce(source: self.asObservable(), seed: seed, accumulator: accumulator, mapResult: mapResult) + } + + /** + Applies an `accumulator` function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified `seed` value is used as the initial accumulator value. + + For aggregation behavior with incremental intermediate results, see `scan`. + + - seealso: [reduce operator on reactivex.io](http://reactivex.io/documentation/operators/reduce.html) + + - parameter seed: The initial accumulator value. + - parameter accumulator: A accumulator function to be invoked on each element. + - returns: An observable sequence containing a single element with the final accumulator value. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func reduce(seed: A, accumulator: (A, E) throws -> A) + -> Observable { + return Reduce(source: self.asObservable(), seed: seed, accumulator: accumulator, mapResult: { $0 }) + } + + /** + Converts an Observable into another Observable that emits the whole sequence as a single array and then terminates. + + For aggregation behavior see `reduce`. + + - seealso: [toArray operator on reactivex.io](http://reactivex.io/documentation/operators/to.html) + + - returns: An observable sequence containing all the emitted elements as array. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func toArray() + -> Observable<[E]> { + return ToArray(source: self.asObservable()) + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Binding.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Binding.swift new file mode 100644 index 00000000000..8e91eb3c0aa --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Binding.swift @@ -0,0 +1,190 @@ +// +// Observable+Binding.swift +// Rx +// +// Created by Krunoslav Zaher on 3/1/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +// MARK: multicast + +extension ObservableType { + + /** + Multicasts the source sequence notifications through the specified subject to the resulting connectable observable. + + Upon connection of the connectable observable, the subject is subscribed to the source exactly one, and messages are forwarded to the observers registered with the connectable observable. + + For specializations with fixed subject types, see `publish` and `replay`. + + - seealso: [multicast operator on reactivex.io](http://reactivex.io/documentation/operators/publish.html) + + - parameter subject: Subject to push source elements into. + - returns: A connectable observable sequence that upon connection causes the source sequence to push results into the specified subject. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func multicast(subject: S) + -> ConnectableObservable { + return ConnectableObservableAdapter(source: self.asObservable(), subject: subject) + } + + /** + Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. + + Each subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's invocation. + + For specializations with fixed subject types, see `publish` and `replay`. + + - seealso: [multicast operator on reactivex.io](http://reactivex.io/documentation/operators/publish.html) + + - parameter subjectSelector: Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. + - parameter selector: Selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. + - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func multicast(subjectSelector: () throws -> S, selector: (Observable) throws -> Observable) + -> Observable { + return Multicast( + source: self.asObservable(), + subjectSelector: subjectSelector, + selector: selector + ) + } +} + +// MARK: publish + +extension ObservableType { + + /** + Returns a connectable observable sequence that shares a single subscription to the underlying sequence. + + This operator is a specialization of `multicast` using a `PublishSubject`. + + - seealso: [publish operator on reactivex.io](http://reactivex.io/documentation/operators/publish.html) + + - returns: A connectable observable sequence that shares a single subscription to the underlying sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func publish() -> ConnectableObservable { + return self.multicast(PublishSubject()) + } +} + +// MARK: replay + +extension ObservableType { + + /** + Returns a connectable observable sequence that shares a single subscription to the underlying sequence replaying bufferSize elements. + + This operator is a specialization of `multicast` using a `ReplaySubject`. + + - seealso: [replay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) + + - parameter bufferSize: Maximum element count of the replay buffer. + - returns: A connectable observable sequence that shares a single subscription to the underlying sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func replay(bufferSize: Int) + -> ConnectableObservable { + return self.multicast(ReplaySubject.create(bufferSize: bufferSize)) + } + + /** + Returns a connectable observable sequence that shares a single subscription to the underlying sequence replaying all elements. + + This operator is a specialization of `multicast` using a `ReplaySubject`. + + - seealso: [replay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) + + - returns: A connectable observable sequence that shares a single subscription to the underlying sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func replayAll() + -> ConnectableObservable { + return self.multicast(ReplaySubject.createUnbounded()) + } +} + +// MARK: refcount + +extension ConnectableObservableType { + + /** + Returns an observable sequence that stays connected to the source as long as there is at least one subscription to the observable sequence. + + - seealso: [refCount operator on reactivex.io](http://reactivex.io/documentation/operators/refCount.html) + + - returns: An observable sequence that stays connected to the source as long as there is at least one subscription to the observable sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func refCount() -> Observable { + return RefCount(source: self) + } +} + +// MARK: share + +extension ObservableType { + + /** + Returns an observable sequence that shares a single subscription to the underlying sequence. + + This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. + + - seealso: [share operator on reactivex.io](http://reactivex.io/documentation/operators/refcount.html) + + - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func share() -> Observable { + return self.publish().refCount() + } +} + +// MARK: shareReplay + +extension ObservableType { + + /** + Returns an observable sequence that shares a single subscription to the underlying sequence, and immediately upon subscription replays maximum number of elements in buffer. + + This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. + + - seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) + + - parameter bufferSize: Maximum element count of the replay buffer. + - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func shareReplay(bufferSize: Int) + -> Observable { + if bufferSize == 1 { + return ShareReplay1(source: self.asObservable()) + } + else { + return self.replay(bufferSize).refCount() + } + } + + /** + Returns an observable sequence that shares a single subscription to the underlying sequence, and immediately upon subscription replays latest element in buffer. + + This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. + + Unlike `shareReplay(bufferSize: Int)`, this operator will clear latest element from replay buffer in case number of subscribers drops from one to zero. In case sequence + completes or errors out replay buffer is also cleared. + + - seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) + + - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func shareReplayLatestWhileConnected() + -> Observable { + return ShareReplay1WhileConnected(source: self.asObservable()) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Concurrency.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Concurrency.swift new file mode 100644 index 00000000000..f8875a53c50 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Concurrency.swift @@ -0,0 +1,62 @@ +// +// Observable+Concurrency.swift +// Rx +// +// Created by Krunoslav Zaher on 3/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +// MARK: observeOn + +extension ObservableType { + + /** + Wraps the source sequence in order to run its observer callbacks on the specified scheduler. + + This only invokes observer callbacks on a `scheduler`. In case the subscription and/or unsubscription + actions have side-effects that require to be run on a scheduler, use `subscribeOn`. + + - seealso: [observeOn operator on reactivex.io](http://reactivex.io/documentation/operators/observeon.html) + + - parameter scheduler: Scheduler to notify observers on. + - returns: The source sequence whose observations happen on the specified scheduler. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func observeOn(scheduler: ImmediateSchedulerType) + -> Observable { + if let scheduler = scheduler as? SerialDispatchQueueScheduler { + return ObserveOnSerialDispatchQueue(source: self.asObservable(), scheduler: scheduler) + } + else { + return ObserveOn(source: self.asObservable(), scheduler: scheduler) + } + } +} + +// MARK: subscribeOn + +extension ObservableType { + + /** + Wraps the source sequence in order to run its subscription and unsubscription logic on the specified + scheduler. + + This operation is not commonly used. + + This only performs the side-effects of subscription and unsubscription on the specified scheduler. + + In order to invoke observer callbacks on a `scheduler`, use `observeOn`. + + - seealso: [subscribeOn operator on reactivex.io](http://reactivex.io/documentation/operators/subscribeon.html) + + - parameter scheduler: Scheduler to perform subscription and unsubscription actions on. + - returns: The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func subscribeOn(scheduler: ImmediateSchedulerType) + -> Observable { + return SubscribeOn(source: self, scheduler: scheduler) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Creation.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Creation.swift new file mode 100644 index 00000000000..f14f9c285a2 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Creation.swift @@ -0,0 +1,219 @@ +// +// Observable+Creation.swift +// Rx +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +extension Observable { + // MARK: create + + /** + Creates an observable sequence from a specified subscribe method implementation. + + - seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html) + + - parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method. + - returns: The observable sequence with the specified implementation for the `subscribe` method. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func create(subscribe: (AnyObserver) -> Disposable) -> Observable { + return AnonymousObservable(subscribe) + } + + // MARK: empty + + /** + Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message. + + - seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) + + - returns: An observable sequence with no elements. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func empty() -> Observable { + return Empty() + } + + // MARK: never + + /** + Returns a non-terminating observable sequence, which can be used to denote an infinite duration. + + - seealso: [never operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) + + - returns: An observable sequence whose observers will never get called. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func never() -> Observable { + return Never() + } + + // MARK: just + + /** + Returns an observable sequence that contains a single element. + + - seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html) + + - parameter element: Single element in the resulting observable sequence. + - returns: An observable sequence containing the single specified element. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func just(element: E) -> Observable { + return Just(element: element) + } + + /** + Returns an observable sequence that contains a single element. + + - seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html) + + - parameter element: Single element in the resulting observable sequence. + - parameter: Scheduler to send the single element on. + - returns: An observable sequence containing the single specified element. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func just(element: E, scheduler: ImmediateSchedulerType) -> Observable { + return JustScheduled(element: element, scheduler: scheduler) + } + + // MARK: fail + + /** + Returns an observable sequence that terminates with an `error`. + + - seealso: [throw operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) + + - returns: The observable sequence that terminates with specified error. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func error(error: ErrorType) -> Observable { + return Error(error: error) + } + + // MARK: of + + /** + This method creates a new Observable instance with a variable number of elements. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - parameter elements: Elements to generate. + - parameter scheduler: Scheduler to send elements on. If `nil`, elements are sent immediatelly on subscription. + - returns: The observable sequence whose elements are pulled from the given arguments. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func of(elements: E ..., scheduler: ImmediateSchedulerType? = nil) -> Observable { + return Sequence(elements: elements, scheduler: scheduler) + } + + // MARK: defer + + /** + Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. + + - seealso: [defer operator on reactivex.io](http://reactivex.io/documentation/operators/defer.html) + + - parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence. + - returns: An observable sequence whose observers trigger an invocation of the given observable factory function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func deferred(observableFactory: () throws -> Observable) + -> Observable { + return Deferred(observableFactory: observableFactory) + } + + /** + Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler + to run the loop send out observer messages. + + - seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html) + + - parameter initialState: Initial state. + - parameter condition: Condition to terminate generation (upon returning `false`). + - parameter iterate: Iteration step function. + - parameter scheduler: Scheduler on which to run the generator loop. + - returns: The generated sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func generate(initialState initialState: E, condition: E throws -> Bool, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance, iterate: E throws -> E) -> Observable { + return Generate(initialState: initialState, condition: condition, iterate: iterate, resultSelector: { $0 }, scheduler: scheduler) + } + + /** + Generates an observable sequence that repeats the given element infinitely, using the specified scheduler to send out observer messages. + + - seealso: [repeat operator on reactivex.io](http://reactivex.io/documentation/operators/repeat.html) + + - parameter element: Element to repeat. + - parameter scheduler: Scheduler to run the producer loop on. + - returns: An observable sequence that repeats the given element infinitely. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func repeatElement(element: E, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { + return RepeatElement(element: element, scheduler: scheduler) + } + + /** + Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. + + - seealso: [using operator on reactivex.io](http://reactivex.io/documentation/operators/using.html) + + - parameter resourceFactory: Factory function to obtain a resource object. + - parameter observableFactory: Factory function to obtain an observable sequence that depends on the obtained resource. + - returns: An observable sequence whose lifetime controls the lifetime of the dependent resource object. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func using(resourceFactory: () throws -> R, observableFactory: R throws -> Observable) -> Observable { + return Using(resourceFactory: resourceFactory, observableFactory: observableFactory) + } +} + +extension Observable where Element : SignedIntegerType { + /** + Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to generate and send out observer messages. + + - seealso: [range operator on reactivex.io](http://reactivex.io/documentation/operators/range.html) + + - parameter start: The value of the first integer in the sequence. + - parameter count: The number of sequential integers to generate. + - parameter scheduler: Scheduler to run the generator loop on. + - returns: An observable sequence that contains a range of sequential integral numbers. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func range(start start: E, count: E, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { + return RangeProducer(start: start, count: count, scheduler: scheduler) + } +} + +extension SequenceType { + /** + Converts a sequence to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - returns: The observable sequence whose elements are pulled from the given enumerable sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func toObservable(scheduler: ImmediateSchedulerType? = nil) -> Observable { + return Sequence(elements: Array(self), scheduler: scheduler) + } +} + +extension Array { + /** + Converts a sequence to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - returns: The observable sequence whose elements are pulled from the given enumerable sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func toObservable(scheduler: ImmediateSchedulerType? = nil) -> Observable { + return Sequence(elements: self, scheduler: scheduler) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Debug.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Debug.swift new file mode 100644 index 00000000000..5d058789b81 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Debug.swift @@ -0,0 +1,28 @@ +// +// Observable+Debug.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +// MARK: debug + +extension ObservableType { + + /** + Prints received events for all observers on standard output. + + - seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html) + + - parameter identifier: Identifier that is printed together with event description to standard output. + - returns: An observable sequence whose events are printed to standard output. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func debug(identifier: String? = nil, file: String = #file, line: UInt = #line, function: String = #function) + -> Observable { + return Debug(source: self.asObservable(), identifier: identifier, file: file, line: line, function: function) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Multiple.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Multiple.swift new file mode 100644 index 00000000000..ae2bf50be73 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Multiple.swift @@ -0,0 +1,330 @@ +// +// Observable+Multiple.swift +// Rx +// +// Created by Krunoslav Zaher on 3/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +// MARK: combineLatest + +extension CollectionType where Generator.Element : ObservableType { + + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combinelatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func combineLatest(resultSelector: [Generator.Element.E] throws -> R) -> Observable { + return CombineLatestCollectionType(sources: self, resultSelector: resultSelector) + } +} + +// MARK: zip + +extension CollectionType where Generator.Element : ObservableType { + + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func zip(resultSelector: [Generator.Element.E] throws -> R) -> Observable { + return ZipCollectionType(sources: self, resultSelector: resultSelector) + } +} + +// MARK: switch + +extension ObservableType where E : ObservableConvertibleType { + + /** + Transforms an observable sequence of observable sequences into an observable sequence + producing values only from the most recent observable sequence. + + Each time a new inner observable sequence is received, unsubscribe from the + previous inner observable sequence. + + - seealso: [switch operator on reactivex.io](http://reactivex.io/documentation/operators/switch.html) + + - returns: The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func switchLatest() -> Observable { + return Switch(source: asObservable()) + } +} + +// MARK: concat + +extension ObservableType { + + /** + Concatenates the second observable sequence to `self` upon successful termination of `self`. + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - parameter second: Second observable sequence. + - returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func concat(second: O) -> Observable { + return [asObservable(), second.asObservable()].concat() + } +} + +extension SequenceType where Generator.Element : ObservableType { + + /** + Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully. + + This operator has tail recursive optimizations that will prevent stack overflow. + + Optimizations will be performed in cases equivalent to following: + + [1, [2, [3, .....].concat()].concat].concat() + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each given sequence, in sequential order. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func concat() + -> Observable { + return Concat(sources: self, count: nil) + } +} + +extension CollectionType where Generator.Element : ObservableType { + + /** + Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully. + + This operator has tail recursive optimizations that will prevent stack overflow and enable generating + infinite observable sequences while using limited amount of memory during generation. + + Optimizations will be performed in cases equivalent to following: + + [1, [2, [3, .....].concat()].concat].concat() + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each given sequence, in sequential order. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func concat() + -> Observable { + return Concat(sources: self, count: self.count.toIntMax()) + } +} + +extension ObservableType where E : ObservableConvertibleType { + + /** + Concatenates all inner observable sequences, as long as the previous observable sequence terminated successfully. + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each observed inner sequence, in sequential order. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func concat() -> Observable { + return merge(maxConcurrent: 1) + } +} + +// MARK: merge + +extension ObservableType where E : ObservableConvertibleType { + + /** + Merges elements from all observable sequences in the given enumerable sequence into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - returns: The observable sequence that merges the elements of the observable sequences. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func merge() -> Observable { + return Merge(source: asObservable()) + } + + /** + Merges elements from all inner observable sequences into a single observable sequence, limiting the number of concurrent subscriptions to inner sequences. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter maxConcurrent: Maximum number of inner observable sequences being subscribed to concurrently. + - returns: The observable sequence that merges the elements of the inner sequences. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func merge(maxConcurrent maxConcurrent: Int) + -> Observable { + return MergeLimited(source: asObservable(), maxConcurrent: maxConcurrent) + } +} + +// MARK: catch + +extension ObservableType { + + /** + Continues an observable sequence that is terminated by an error with the observable sequence produced by the handler. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - parameter handler: Error handler function, producing another observable sequence. + - returns: An observable sequence containing the source sequence's elements, followed by the elements produced by the handler's resulting observable sequence in case an error occurred. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func catchError(handler: (ErrorType) throws -> Observable) + -> Observable { + return Catch(source: asObservable(), handler: handler) + } + + /** + Continues an observable sequence that is terminated by an error with a single element. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - parameter element: Last element in an observable sequence in case error occurs. + - returns: An observable sequence containing the source sequence's elements, followed by the `element` in case an error occurred. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func catchErrorJustReturn(element: E) + -> Observable { + return Catch(source: asObservable(), handler: { _ in Observable.just(element) }) + } + +} + +extension SequenceType where Generator.Element : ObservableType { + /** + Continues an observable sequence that is terminated by an error with the next observable sequence. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - returns: An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func catchError() + -> Observable { + return CatchSequence(sources: self) + } +} + +// MARK: takeUntil + +extension ObservableType { + + /** + Returns the elements from the source observable sequence until the other observable sequence produces an element. + + - seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html) + + - parameter other: Observable sequence that terminates propagation of elements of the source sequence. + - returns: An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func takeUntil(other: O) + -> Observable { + return TakeUntil(source: asObservable(), other: other.asObservable()) + } +} + +// MARK: skipUntil + +extension ObservableType { + + /** + Returns the elements from the source observable sequence that are emitted after the other observable sequence produces an element. + + - seealso: [skipUntil operator on reactivex.io](http://reactivex.io/documentation/operators/skipuntil.html) + + - parameter other: Observable sequence that starts propagation of elements of the source sequence. + - returns: An observable sequence containing the elements of the source sequence that are emitted after the other sequence emits an item. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func skipUntil(other: O) + -> Observable { + return SkipUntil(source: asObservable(), other: other.asObservable()) + } +} + +// MARK: amb + +extension ObservableType { + + /** + Propagates the observable sequence that reacts first. + + - seealso: [amb operator on reactivex.io](http://reactivex.io/documentation/operators/amb.html) + + - parameter right: Second observable sequence. + - returns: An observable sequence that surfaces either of the given sequences, whichever reacted first. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func amb + (right: O2) + -> Observable { + return Amb(left: asObservable(), right: right.asObservable()) + } +} + +extension SequenceType where Generator.Element : ObservableType { + + /** + Propagates the observable sequence that reacts first. + + - seealso: [amb operator on reactivex.io](http://reactivex.io/documentation/operators/amb.html) + + - returns: An observable sequence that surfaces any of the given sequences, whichever reacted first. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func amb() + -> Observable { + return self.reduce(Observable.never()) { a, o in + return a.amb(o.asObservable()) + } + } +} + +// withLatestFrom + +extension ObservableType { + + /** + Merges two observable sequences into one observable sequence by combining each element from self with the latest element from the second source, if any. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter second: Second observable source. + - parameter resultSelector: Function to invoke for each element from the self combined with the latest element from the second source, if any. + - returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function. + */ + public func withLatestFrom(second: SecondO, resultSelector: (E, SecondO.E) throws -> ResultType) -> Observable { + return WithLatestFrom(first: asObservable(), second: second.asObservable(), resultSelector: resultSelector) + } + + /** + Merges two observable sequences into one observable sequence by using latest element from the second sequence every time when `self` emitts an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter second: Second observable source. + - returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function. + */ + public func withLatestFrom(second: SecondO) -> Observable { + return WithLatestFrom(first: asObservable(), second: second.asObservable(), resultSelector: { $1 }) + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Single.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Single.swift new file mode 100644 index 00000000000..088fb61f183 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Single.swift @@ -0,0 +1,258 @@ +// +// Observable+Single.swift +// Rx +// +// Created by Krunoslav Zaher on 2/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +// MARK: distinct until changed + +extension ObservableType where E: Equatable { + + /** + Returns an observable sequence that contains only distinct contiguous elements according to equality operator. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - returns: An observable sequence only containing the distinct contiguous elements, based on equality operator, from the source sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func distinctUntilChanged() + -> Observable { + return self.distinctUntilChanged({ $0 }, comparer: { ($0 == $1) }) + } +} + +extension ObservableType { + /** + Returns an observable sequence that contains only distinct contiguous elements according to the `keySelector`. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - parameter keySelector: A function to compute the comparison key for each element. + - returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func distinctUntilChanged(keySelector: (E) throws -> K) + -> Observable { + return self.distinctUntilChanged(keySelector, comparer: { $0 == $1 }) + } + + /** + Returns an observable sequence that contains only distinct contiguous elements according to the `comparer`. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - parameter comparer: Equality comparer for computed key values. + - returns: An observable sequence only containing the distinct contiguous elements, based on `comparer`, from the source sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func distinctUntilChanged(comparer: (lhs: E, rhs: E) throws -> Bool) + -> Observable { + return self.distinctUntilChanged({ $0 }, comparer: comparer) + } + + /** + Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - parameter keySelector: A function to compute the comparison key for each element. + - parameter comparer: Equality comparer for computed key values. + - returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value and the comparer, from the source sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func distinctUntilChanged(keySelector: (E) throws -> K, comparer: (lhs: K, rhs: K) throws -> Bool) + -> Observable { + return DistinctUntilChanged(source: self.asObservable(), selector: keySelector, comparer: comparer) + } +} + +// MARK: doOn + +extension ObservableType { + + /** + Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence. + + - seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html) + + - parameter eventHandler: Action to invoke for each event in the observable sequence. + - returns: The source sequence with the side-effecting behavior applied. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func doOn(eventHandler: (Event) throws -> Void) + -> Observable { + return Do(source: self.asObservable(), eventHandler: eventHandler) + } + + /** + Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence. + + - seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html) + + - parameter onNext: Action to invoke for each element in the observable sequence. + - parameter onError: Action to invoke upon errored termination of the observable sequence. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + - returns: The source sequence with the side-effecting behavior applied. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func doOn(onNext onNext: (E throws -> Void)? = nil, onError: (ErrorType throws -> Void)? = nil, onCompleted: (() throws -> Void)? = nil) + -> Observable { + return Do(source: self.asObservable()) { e in + switch e { + case .Next(let element): + try onNext?(element) + case .Error(let e): + try onError?(e) + case .Completed: + try onCompleted?() + } + } + } + + /** + Invokes an action for each Next event in the observable sequence, and propagates all observer messages through the result sequence. + + - parameter onNext: Action to invoke for each element in the observable sequence. + - returns: The source sequence with the side-effecting behavior applied. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func doOnNext(onNext: (E throws -> Void)) + -> Observable { + return self.doOn(onNext: onNext) + } + + /** + Invokes an action for the Error event in the observable sequence, and propagates all observer messages through the result sequence. + + - parameter onError: Action to invoke upon errored termination of the observable sequence. + - returns: The source sequence with the side-effecting behavior applied. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func doOnError(onError: (ErrorType throws -> Void)) + -> Observable { + return self.doOn(onError: onError) + } + + /** + Invokes an action for the Completed event in the observable sequence, and propagates all observer messages through the result sequence. + + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + - returns: The source sequence with the side-effecting behavior applied. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func doOnCompleted(onCompleted: (() throws -> Void)) + -> Observable { + return self.doOn(onCompleted: onCompleted) + } +} + +// MARK: startWith + +extension ObservableType { + + /** + Prepends a sequence of values to an observable sequence. + + - seealso: [startWith operator on reactivex.io](http://reactivex.io/documentation/operators/startwith.html) + + - parameter elements: Elements to prepend to the specified sequence. + - returns: The source sequence prepended with the specified values. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func startWith(elements: E ...) + -> Observable { + return StartWith(source: self.asObservable(), elements: elements) + } +} + +// MARK: retry + +extension ObservableType { + + /** + Repeats the source observable sequence until it successfully terminates. + + **This could potentially create an infinite sequence.** + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - returns: Observable sequence to repeat until it successfully terminates. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func retry() -> Observable { + return CatchSequence(sources: InfiniteSequence(repeatedValue: self.asObservable())) + } + + /** + Repeats the source observable sequence the specified number of times in case of an error or until it successfully terminates. + + If you encounter an error and want it to retry once, then you must use `retry(2)` + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - parameter maxAttemptCount: Maximum number of times to repeat the sequence. + - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func retry(maxAttemptCount: Int) + -> Observable { + return CatchSequence(sources: Repeat(count: maxAttemptCount, repeatedValue: self.asObservable())) + } + + /** + Repeats the source observable sequence on error when the notifier emits a next value. + If the source observable errors and the notifier completes, it will complete the source sequence. + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable. + - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func retryWhen(notificationHandler: Observable -> TriggerObservable) + -> Observable { + return RetryWhenSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()), notificationHandler: notificationHandler) + } + + /** + Repeats the source observable sequence on error when the notifier emits a next value. + If the source observable errors and the notifier completes, it will complete the source sequence. + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable. + - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func retryWhen(notificationHandler: Observable -> TriggerObservable) + -> Observable { + return RetryWhenSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()), notificationHandler: notificationHandler) + } +} + +// MARK: scan + +extension ObservableType { + + /** + Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value. + + For aggregation behavior with no intermediate results, see `reduce`. + + - seealso: [scan operator on reactivex.io](http://reactivex.io/documentation/operators/scan.html) + + - parameter seed: The initial accumulator value. + - parameter accumulator: An accumulator function to be invoked on each element. + - returns: An observable sequence containing the accumulated values. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func scan(seed: A, accumulator: (A, E) throws -> A) + -> Observable { + return Scan(source: self.asObservable(), seed: seed, accumulator: accumulator) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+StandardSequenceOperators.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+StandardSequenceOperators.swift new file mode 100644 index 00000000000..96fe5fe24ec --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+StandardSequenceOperators.swift @@ -0,0 +1,323 @@ +// +// Observable+StandardSequenceOperators.swift +// Rx +// +// Created by Krunoslav Zaher on 2/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +// MARK: filter aka where + +extension ObservableType { + + /** + Filters the elements of an observable sequence based on a predicate. + + - seealso: [filter operator on reactivex.io](http://reactivex.io/documentation/operators/filter.html) + + - parameter predicate: A function to test each source element for a condition. + - returns: An observable sequence that contains elements from the input sequence that satisfy the condition. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func filter(predicate: (E) throws -> Bool) + -> Observable { + return Filter(source: asObservable(), predicate: predicate) + } +} + +// MARK: takeWhile + +extension ObservableType { + + /** + Returns elements from an observable sequence as long as a specified condition is true. + + - seealso: [takeWhile operator on reactivex.io](http://reactivex.io/documentation/operators/takewhile.html) + + - parameter predicate: A function to test each element for a condition. + - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func takeWhile(predicate: (E) throws -> Bool) + -> Observable { + return TakeWhile(source: asObservable(), predicate: predicate) + } + + /** + Returns elements from an observable sequence as long as a specified condition is true. + + The element's index is used in the logic of the predicate function. + + - seealso: [takeWhile operator on reactivex.io](http://reactivex.io/documentation/operators/takewhile.html) + + - parameter predicate: A function to test each element for a condition; the second parameter of the function represents the index of the source element. + - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func takeWhileWithIndex(predicate: (E, Int) throws -> Bool) + -> Observable { + return TakeWhile(source: asObservable(), predicate: predicate) + } +} + +// MARK: take + +extension ObservableType { + + /** + Returns a specified number of contiguous elements from the start of an observable sequence. + + - seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html) + + - parameter count: The number of elements to return. + - returns: An observable sequence that contains the specified number of elements from the start of the input sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func take(count: Int) + -> Observable { + if count == 0 { + return Observable.empty() + } + else { + return TakeCount(source: asObservable(), count: count) + } + } +} + +// MARK: takeLast + +extension ObservableType { + + /** + Returns a specified number of contiguous elements from the end of an observable sequence. + + This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. + + - seealso: [takeLast operator on reactivex.io](http://reactivex.io/documentation/operators/takelast.html) + + - parameter count: Number of elements to take from the end of the source sequence. + - returns: An observable sequence containing the specified number of elements from the end of the source sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func takeLast(count: Int) + -> Observable { + return TakeLast(source: asObservable(), count: count) + } +} + + +// MARK: skip + +extension ObservableType { + + /** + Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. + + - seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html) + + - parameter count: The number of elements to skip before returning the remaining elements. + - returns: An observable sequence that contains the elements that occur after the specified index in the input sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func skip(count: Int) + -> Observable { + return SkipCount(source: asObservable(), count: count) + } +} + +// MARK: SkipWhile + +extension ObservableType { + + /** + Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. + + - seealso: [skipWhile operator on reactivex.io](http://reactivex.io/documentation/operators/skipwhile.html) + + - parameter predicate: A function to test each element for a condition. + - returns: An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func skipWhile(predicate: (E) throws -> Bool) -> Observable { + return SkipWhile(source: asObservable(), predicate: predicate) + } + + /** + Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. + The element's index is used in the logic of the predicate function. + + - seealso: [skipWhile operator on reactivex.io](http://reactivex.io/documentation/operators/skipwhile.html) + + - parameter predicate: A function to test each element for a condition; the second parameter of the function represents the index of the source element. + - returns: An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func skipWhileWithIndex(predicate: (E, Int) throws -> Bool) -> Observable { + return SkipWhile(source: asObservable(), predicate: predicate) + } +} + +// MARK: map aka select + +extension ObservableType { + + /** + Projects each element of an observable sequence into a new form. + + - seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html) + + - parameter selector: A transform function to apply to each source element. + - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source. + + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func map(selector: E throws -> R) + -> Observable { + return self.asObservable().composeMap(selector) + } + + /** + Projects each element of an observable sequence into a new form by incorporating the element's index. + + - seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html) + + - parameter selector: A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func mapWithIndex(selector: (E, Int) throws -> R) + -> Observable { + return MapWithIndex(source: asObservable(), selector: selector) + } +} + +// MARK: flatMap + +extension ObservableType { + + /** + Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + + - seealso: [flatMap operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) + + - parameter selector: A transform function to apply to each element. + - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func flatMap(selector: (E) throws -> O) + -> Observable { + return FlatMap(source: asObservable(), selector: selector) + } + + /** + Projects each element of an observable sequence to an observable sequence by incorporating the element's index and merges the resulting observable sequences into one observable sequence. + + - seealso: [flatMap operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) + + - parameter selector: A transform function to apply to each element; the second parameter of the function represents the index of the source element. + - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func flatMapWithIndex(selector: (E, Int) throws -> O) + -> Observable { + return FlatMapWithIndex(source: asObservable(), selector: selector) + } +} + +// MARK: flatMapFirst + +extension ObservableType { + + /** + Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + If element is received while there is some projected observable sequence being merged it will simply be ignored. + + - seealso: [flatMapFirst operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) + + - parameter selector: A transform function to apply to element that was observed while no observable is executing in parallel. + - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence that was received while no other sequence was being calculated. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func flatMapFirst(selector: (E) throws -> O) + -> Observable { + return FlatMapFirst(source: asObservable(), selector: selector) + } +} + +// MARK: flatMapLatest + +extension ObservableType { + /** + Projects each element of an observable sequence into a new sequence of observable sequences and then + transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + + It is a combination of `map` + `switchLatest` operator + + - seealso: [flatMapLatest operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) + + - parameter selector: A transform function to apply to each element. + - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source producing an + Observable of Observable sequences and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func flatMapLatest(selector: (E) throws -> O) + -> Observable { + return FlatMapLatest(source: asObservable(), selector: selector) + } +} + +// MARK: elementAt + +extension ObservableType { + + /** + Returns a sequence emitting only item _n_ emitted by an Observable + + - seealso: [elementAt operator on reactivex.io](http://reactivex.io/documentation/operators/elementat.html) + + - parameter index: The index of the required item (starting from 0). + - returns: An observable sequence that emits the desired item as its own sole emission. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func elementAt(index: Int) + -> Observable { + return ElementAt(source: asObservable(), index: index, throwOnEmpty: true) + } +} + +// MARK: single + +extension ObservableType { + + /** + The single operator is similar to first, but throws a `RxError.NoElements` or `RxError.MoreThanOneElement` + if the source Observable does not emit exactly one item before successfully completing. + + - seealso: [single operator on reactivex.io](http://reactivex.io/documentation/operators/first.html) + + - returns: An observable sequence that emits a single item or throws an exception if more (or none) of them are emitted. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func single() + -> Observable { + return SingleAsync(source: asObservable()) + } + + /** + The single operator is similar to first, but throws a `RxError.NoElements` or `RxError.MoreThanOneElement` + if the source Observable does not emit exactly one item before successfully completing. + + - seealso: [single operator on reactivex.io](http://reactivex.io/documentation/operators/first.html) + + - parameter predicate: A function to test each source element for a condition. + - returns: An observable sequence that emits a single item or throws an exception if more (or none) of them are emitted. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func single(predicate: (E) throws -> Bool) + -> Observable { + return SingleAsync(source: asObservable(), predicate: predicate) + } + +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Time.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Time.swift new file mode 100644 index 00000000000..d1c93be0eb2 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Time.swift @@ -0,0 +1,274 @@ +// +// Observable+Time.swift +// Rx +// +// Created by Krunoslav Zaher on 3/22/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +// MARK: throttle +extension ObservableType { + + /** + Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers. + + `throttle` and `debounce` are synonyms. + + - seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html) + + - parameter dueTime: Throttling duration for each element. + - parameter scheduler: Scheduler to run the throttle timers and send events on. + - returns: The throttled sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func throttle(dueTime: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return Throttle(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler) + } + + /** + Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers. + + `throttle` and `debounce` are synonyms. + + - seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html) + + - parameter dueTime: Throttling duration for each element. + - parameter scheduler: Scheduler to run the throttle timers and send events on. + - returns: The throttled sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func debounce(dueTime: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return Throttle(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler) + } +} + +// MARK: sample + +extension ObservableType { + + /** + Samples the source observable sequence using a samper observable sequence producing sampling ticks. + + Upon each sampling tick, the latest element (if any) in the source sequence during the last sampling interval is sent to the resulting sequence. + + **In case there were no new elements between sampler ticks, no element is sent to the resulting sequence.** + + - seealso: [sample operator on reactivex.io](http://reactivex.io/documentation/operators/sample.html) + + - parameter sampler: Sampling tick sequence. + - returns: Sampled observable sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func sample(sampler: O) + -> Observable { + return Sample(source: self.asObservable(), sampler: sampler.asObservable(), onlyNew: true) + } +} + +extension Observable where Element : SignedIntegerType { + /** + Returns an observable sequence that produces a value after each period, using the specified scheduler to run timers and to send out observer messages. + + - seealso: [interval operator on reactivex.io](http://reactivex.io/documentation/operators/interval.html) + + - parameter period: Period for producing the values in the resulting sequence. + - parameter scheduler: Scheduler to run the timer on. + - returns: An observable sequence that produces a value after each period. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func interval(period: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return Timer(dueTime: period, + period: period, + scheduler: scheduler + ) + } +} + +// MARK: timer + +extension Observable where Element: SignedIntegerType { + /** + Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers. + + - seealso: [timer operator on reactivex.io](http://reactivex.io/documentation/operators/timer.html) + + - parameter dueTime: Relative time at which to produce the first value. + - parameter period: Period to produce subsequent values. + - parameter scheduler: Scheduler to run timers on. + - returns: An observable sequence that produces a value after due time has elapsed and then each period. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public static func timer(dueTime: RxTimeInterval, period: RxTimeInterval? = nil, scheduler: SchedulerType) + -> Observable { + return Timer( + dueTime: dueTime, + period: period, + scheduler: scheduler + ) + } +} + +// MARK: take + +extension ObservableType { + + /** + Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + + - seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html) + + - parameter duration: Duration for taking elements from the start of the sequence. + - parameter scheduler: Scheduler to run the timer on. + - returns: An observable sequence with the elements taken during the specified duration from the start of the source sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func take(duration: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return TakeTime(source: self.asObservable(), duration: duration, scheduler: scheduler) + } +} + +// MARK: skip + +extension ObservableType { + + /** + Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + + - seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html) + + - parameter duration: Duration for skipping elements from the start of the sequence. + - parameter scheduler: Scheduler to run the timer on. + - returns: An observable sequence with the elements skipped during the specified duration from the start of the source sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func skip(duration: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return SkipTime(source: self.asObservable(), duration: duration, scheduler: scheduler) + } +} + +// MARK: ignoreElements + +extension ObservableType { + + /** + Skips elements and completes (or errors) when the receiver completes (or errors). Equivalent to filter that always returns false. + + - seealso: [ignoreElements operator on reactivex.io](http://reactivex.io/documentation/operators/ignoreelements.html) + + - returns: An observable sequence that skips all elements of the source sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func ignoreElements() + -> Observable { + return filter { _ -> Bool in + return false + } + } +} + +// MARK: delaySubscription + +extension ObservableType { + + /** + Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers. + + - seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html) + + - parameter dueTime: Relative time shift of the subscription. + - parameter scheduler: Scheduler to run the subscription delay timer on. + - returns: Time-shifted sequence. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func delaySubscription(dueTime: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return DelaySubscription(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler) + } +} + +// MARK: buffer + +extension ObservableType { + + /** + Projects each element of an observable sequence into a buffer that's sent out when either it's full or a given amount of time has elapsed, using the specified scheduler to run timers. + + A useful real-world analogy of this overload is the behavior of a ferry leaving the dock when all seats are taken, or at the scheduled time of departure, whichever event occurs first. + + - seealso: [buffer operator on reactivex.io](http://reactivex.io/documentation/operators/buffer.html) + + - parameter timeSpan: Maximum time length of a buffer. + - parameter count: Maximum element count of a buffer. + - parameter scheduler: Scheduler to run buffering timers on. + - returns: An observable sequence of buffers. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func buffer(timeSpan timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) + -> Observable<[E]> { + return BufferTimeCount(source: self.asObservable(), timeSpan: timeSpan, count: count, scheduler: scheduler) + } +} + +// MARK: window + +extension ObservableType { + + /** + Projects each element of an observable sequence into a window that is completed when either it’s full or a given amount of time has elapsed. + + - seealso: [window operator on reactivex.io](http://reactivex.io/documentation/operators/window.html) + + - parameter timeSpan: Maximum time length of a window. + - parameter count: Maximum element count of a window. + - parameter scheduler: Scheduler to run windowing timers on. + - returns: An observable sequence of windows (instances of `Observable`). + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func window(timeSpan timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) + -> Observable> { + return WindowTimeCount(source: self.asObservable(), timeSpan: timeSpan, count: count, scheduler: scheduler) + } +} + +// MARK: timeout + +extension ObservableType { + + /** + Applies a timeout policy for each element in the observable sequence. If the next element isn't received within the specified timeout duration starting from its predecessor, a TimeoutError is propagated to the observer. + + - seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html) + + - parameter dueTime: Maximum duration between values before a timeout occurs. + - parameter scheduler: Scheduler to run the timeout timer on. + - returns: An observable sequence with a TimeoutError in case of a timeout. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func timeout(dueTime: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return Timeout(source: self.asObservable(), dueTime: dueTime, other: Observable.error(RxError.Timeout), scheduler: scheduler) + } + + /** + Applies a timeout policy for each element in the observable sequence, using the specified scheduler to run timeout timers. If the next element isn't received within the specified timeout duration starting from its predecessor, the other observable sequence is used to produce future messages from that point on. + + - seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html) + + - parameter dueTime: Maximum duration between values before a timeout occurs. + - parameter other: Sequence to return in case of a timeout. + - parameter scheduler: Scheduler to run the timeout timer on. + - returns: The source sequence switching to the other sequence in case of a timeout. + */ + @warn_unused_result(message="http://git.io/rxs.uo") + public func timeout(dueTime: RxTimeInterval, other: O, scheduler: SchedulerType) + -> Observable { + return Timeout(source: self.asObservable(), dueTime: dueTime, other: other.asObservable(), scheduler: scheduler) + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObserverType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObserverType.swift new file mode 100644 index 00000000000..0cd46e3967a --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObserverType.swift @@ -0,0 +1,56 @@ +// +// ObserverType.swift +// Rx +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Supports push-style iteration over an observable sequence. +*/ +public protocol ObserverType { + /** + The type of elements in sequence that observer can observe. + */ + associatedtype E + + /** + Notify observer about sequence event. + + - parameter event: Event that occured. + */ + func on(event: Event) +} + +/** +Convenience API extensions to provide alternate next, error, completed events +*/ +public extension ObserverType { + + /** + Convenience method equivalent to `on(.Next(element: E))` + + - parameter element: Next element to send to observer(s) + */ + final func onNext(element: E) { + on(.Next(element)) + } + + /** + Convenience method equivalent to `on(.Completed)` + */ + final func onCompleted() { + on(.Completed) + } + + /** + Convenience method equivalent to `on(.Error(error: ErrorType))` + - parameter error: ErrorType to send to observer(s) + */ + final func onError(error: ErrorType) { + on(.Error(error)) + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift new file mode 100644 index 00000000000..2bb8f0a4891 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift @@ -0,0 +1,34 @@ +// +// AnonymousObserver.swift +// Rx +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class AnonymousObserver : ObserverBase { + typealias Element = ElementType + + typealias EventHandler = Event -> Void + + private let _eventHandler : EventHandler + + init(_ eventHandler: EventHandler) { +#if TRACE_RESOURCES + AtomicIncrement(&resourceCount) +#endif + _eventHandler = eventHandler + } + + override func onCore(event: Event) { + return _eventHandler(event) + } + +#if TRACE_RESOURCES + deinit { + AtomicDecrement(&resourceCount) + } +#endif +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift new file mode 100644 index 00000000000..0795952162e --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift @@ -0,0 +1,39 @@ +// +// ObserverBase.swift +// Rx +// +// Created by Krunoslav Zaher on 2/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +class ObserverBase : Disposable, ObserverType { + typealias E = ElementType + + private var _isStopped: AtomicInt = 0 + + func on(event: Event) { + switch event { + case .Next: + if _isStopped == 0 { + onCore(event) + } + case .Error, .Completed: + + if !AtomicCompareAndSwap(0, 1, &_isStopped) { + return + } + + onCore(event) + } + } + + func onCore(event: Event) { + abstractMethod() + } + + func dispose() { + _isStopped = 1 + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift new file mode 100644 index 00000000000..1afecb46209 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift @@ -0,0 +1,151 @@ +// +// TailRecursiveSink.swift +// Rx +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +enum TailRecursiveSinkCommand { + case MoveNext + case Dispose +} + +#if DEBUG || TRACE_RESOURCES + public var maxTailRecursiveSinkStackSize = 0 +#endif + +/// This class is usually used with `Generator` version of the operators. +class TailRecursiveSink + : Sink + , InvocableWithValueType { + typealias Value = TailRecursiveSinkCommand + typealias E = O.E + typealias SequenceGenerator = (generator: S.Generator, remaining: IntMax?) + + var _generators: [SequenceGenerator] = [] + var _disposed = false + var _subscription = SerialDisposable() + + // this is thread safe object + var _gate = AsyncLock>>() + + override init(observer: O) { + super.init(observer: observer) + } + + func run(sources: SequenceGenerator) -> Disposable { + _generators.append(sources) + + schedule(.MoveNext) + + return _subscription + } + + func invoke(command: TailRecursiveSinkCommand) { + switch command { + case .Dispose: + disposeCommand() + case .MoveNext: + moveNextCommand() + } + } + + // simple implementation for now + func schedule(command: TailRecursiveSinkCommand) { + _gate.invoke(InvocableScheduledItem(invocable: self, state: command)) + } + + func done() { + forwardOn(.Completed) + dispose() + } + + func extract(observable: Observable) -> SequenceGenerator? { + abstractMethod() + } + + // should be done on gate locked + + private func moveNextCommand() { + var next: Observable? = nil + + repeat { + guard let (g, left) = _generators.last else { + break + } + + if _disposed { + return + } + + _generators.removeLast() + + var e = g + + guard let nextCandidate = e.next()?.asObservable() else { + continue + } + + // `left` is a hint of how many elements are left in generator. + // In case this is the last element, then there is no need to push + // that generator on stack. + // + // This is an optimization used to make sure in tail recursive case + // there is no memory leak in case this operator is used to generate non terminating + // sequence. + + if let knownOriginalLeft = left { + // `- 1` because generator.next() has just been called + if knownOriginalLeft - 1 >= 1 { + _generators.append((e, knownOriginalLeft - 1)) + } + } + else { + _generators.append((e, nil)) + } + + let nextGenerator = extract(nextCandidate) + + if let nextGenerator = nextGenerator { + _generators.append(nextGenerator) + #if DEBUG || TRACE_RESOURCES + if maxTailRecursiveSinkStackSize < _generators.count { + maxTailRecursiveSinkStackSize = _generators.count + } + #endif + } + else { + next = nextCandidate + } + } while next == nil + + if next == nil { + done() + return + } + + let disposable = SingleAssignmentDisposable() + _subscription.disposable = disposable + disposable.disposable = subscribeToNext(next!) + } + + func subscribeToNext(source: Observable) -> Disposable { + abstractMethod() + } + + func disposeCommand() { + _disposed = true + _generators.removeAll(keepCapacity: false) + } + + override func dispose() { + super.dispose() + + _subscription.dispose() + + schedule(.Dispose) + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Platform/Platform.Darwin.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Platform/Platform.Darwin.swift new file mode 100644 index 00000000000..418c9b163b2 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Platform/Platform.Darwin.swift @@ -0,0 +1,45 @@ +// +// Platform.Darwin.swift +// Rx +// +// Created by Krunoslav Zaher on 12/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(OSX) || os(iOS) || os(tvOS) || os(watchOS) + + import Darwin + import Foundation + + #if TRACE_RESOURCES + public typealias AtomicInt = Int32 + #else + typealias AtomicInt = Int32 + #endif + + let AtomicCompareAndSwap = OSAtomicCompareAndSwap32 + let AtomicIncrement = OSAtomicIncrement32 + let AtomicDecrement = OSAtomicDecrement32 + + extension NSThread { + static func setThreadLocalStorageValue(value: T?, forKey key: protocol) { + let currentThread = NSThread.currentThread() + let threadDictionary = currentThread.threadDictionary + + if let newValue = value { + threadDictionary.setObject(newValue, forKey: key) + } + else { + threadDictionary.removeObjectForKey(key) + } + + } + static func getThreadLocalStorageValueForKey(key: protocol) -> T? { + let currentThread = NSThread.currentThread() + let threadDictionary = currentThread.threadDictionary + + return threadDictionary[key] as? T + } + } + +#endif diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Platform/Platform.Linux.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Platform/Platform.Linux.swift new file mode 100644 index 00000000000..f5b93681cd0 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Platform/Platform.Linux.swift @@ -0,0 +1,222 @@ +// +// Platform.Linux.swift +// Rx +// +// Created by Krunoslav Zaher on 12/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(Linux) + //////////////////////////////////////////////////////////////////////////////// + // This is not the greatest API in the world, this is just a tribute. + // !!! Proof of concept until libdispatch becomes operational. !!! + //////////////////////////////////////////////////////////////////////////////// + + import Foundation + import XCTest + import Glibc + import SwiftShims + + // MARK: CoreFoundation run loop mock + + public typealias CFRunLoopRef = Int + public let kCFRunLoopDefaultMode = "CFRunLoopDefaultMode" + + typealias Action = () -> () + + var queue = Queue(capacity: 100) + + var runLoopCounter = 0 + + extension NSThread { + public var isMainThread: Bool { + return true + } + } + + public func CFRunLoopWakeUp(runLoop: CFRunLoopRef) { + } + + public func CFRunLoopStop(runLoop: CFRunLoopRef) { + runLoopCounter -= 1 + } + + public func CFRunLoopPerformBlock(runLoop: CFRunLoopRef, _ mode: String, _ action: () -> ()) { + queue.enqueue(action) + } + + public func CFRunLoopRun() { + runLoopCounter += 1 + let currentValueOfCounter = runLoopCounter + while let front = queue.dequeue() { + front() + if runLoopCounter < currentValueOfCounter - 1 { + fatalError("called stop twice") + } + + if runLoopCounter == currentValueOfCounter - 1 { + break + } + } + } + + public func CFRunLoopGetCurrent() -> CFRunLoopRef { + return 0 + } + + // MARK: Atomic, just something that works for single thread case + + #if TRACE_RESOURCES + public typealias AtomicInt = Int64 + #else + typealias AtomicInt = Int64 + #endif + + func AtomicIncrement(increment: UnsafeMutablePointer) -> AtomicInt { + increment.memory = increment.memory + 1 + return increment.memory + } + + func AtomicDecrement(increment: UnsafeMutablePointer) -> AtomicInt { + increment.memory = increment.memory - 1 + return increment.memory + } + + func AtomicCompareAndSwap(l: AtomicInt, _ r: AtomicInt, _ target: UnsafeMutablePointer) -> Bool { + //return __sync_val_compare_and_swap(target, l, r) + if target.memory == l { + target.memory = r + return true + } + + return false + } + + extension NSThread { + static func setThreadLocalStorageValue(value: T?, forKey key: String) { + let currentThread = NSThread.currentThread() + var threadDictionary = currentThread.threadDictionary + + if let newValue = value { + threadDictionary[key] = newValue + } + else { + threadDictionary[key] = nil + } + + currentThread.threadDictionary = threadDictionary + } + + static func getThreadLocalStorageValueForKey(key: String) -> T? { + let currentThread = NSThread.currentThread() + let threadDictionary = currentThread.threadDictionary + + return threadDictionary[key] as? T + } + } + + // + + // MARK: objc mock + + public func objc_sync_enter(lock: AnyObject) { + } + + public func objc_sync_exit(lock: AnyObject) { + + } + + + // MARK: libdispatch + + public typealias dispatch_time_t = Int + public typealias dispatch_source_t = Int + public typealias dispatch_source_type_t = Int + public typealias dispatch_queue_t = Int + public typealias dispatch_object_t = Int + public typealias dispatch_block_t = () -> () + public typealias dispatch_queue_attr_t = Int + public typealias qos_class_t = Int + + public let DISPATCH_QUEUE_SERIAL = 0 + + public let DISPATCH_QUEUE_PRIORITY_HIGH = 1 + public let DISPATCH_QUEUE_PRIORITY_DEFAULT = 2 + public let DISPATCH_QUEUE_PRIORITY_LOW = 3 + + public let QOS_CLASS_USER_INTERACTIVE = 0 + public let QOS_CLASS_USER_INITIATED = 1 + public let QOS_CLASS_DEFAULT = 2 + public let QOS_CLASS_UTILITY = 3 + public let QOS_CLASS_BACKGROUND = 4 + + public let DISPATCH_SOURCE_TYPE_TIMER = 0 + public let DISPATCH_TIME_FOREVER = 1 as UInt64 + public let NSEC_PER_SEC = 1 + + public let DISPATCH_TIME_NOW = -1 + + public func dispatch_time(when: dispatch_time_t, _ delta: Int64) -> dispatch_time_t { + return when + Int(delta) + } + + public func dispatch_queue_create(label: UnsafePointer, _ attr: dispatch_queue_attr_t!) -> dispatch_queue_t! { + return 0 + } + + public func dispatch_set_target_queue(object: dispatch_object_t!, _ queue: dispatch_queue_t!) { + } + + public func dispatch_async(queue2: dispatch_queue_t, _ block: dispatch_block_t) { + queue.enqueue(block) + } + + public func dispatch_source_create(type: dispatch_source_type_t, _ handle: UInt, _ mask: UInt, _ queue: dispatch_queue_t!) -> dispatch_source_t! { + return 0 + } + + public func dispatch_source_set_timer(source: dispatch_source_t, _ start: dispatch_time_t, _ interval: UInt64, _ leeway: UInt64) { + + } + + public func dispatch_source_set_event_handler(source: dispatch_source_t, _ handler: dispatch_block_t!) { + queue.enqueue(handler) + } + + public func dispatch_resume(object: dispatch_object_t) { + } + + public func dispatch_source_cancel(source: dispatch_source_t) { + } + + public func dispatch_get_global_queue(identifier: Int, _ flags: UInt) -> dispatch_queue_t! { + return 0 + } + + public func dispatch_get_main_queue() -> dispatch_queue_t! { + return 0 + } + + // MARK: XCTest + + public class Expectation { + public func fulfill() { + } + } + + extension XCTestCase { + public func setUp() { + } + + public func tearDown() { + } + + public func expectationWithDescription(description: String) -> Expectation { + return Expectation() + } + + public func waitForExpectationsWithTimeout(time: NSTimeInterval, action: ErrorType? -> Void) { + } + } + +#endif diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Rx.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Rx.swift new file mode 100644 index 00000000000..8e33574e976 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Rx.swift @@ -0,0 +1,42 @@ +// +// Rx.swift +// Rx +// +// Created by Krunoslav Zaher on 2/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +#if TRACE_RESOURCES +/// Counts internal Rx resource allocations (Observables, Observers, Disposables, etc.). This provides a simple way to detect leaks during development. +public var resourceCount: AtomicInt = 0 +#endif + +/// Swift does not implement abstract methods. This method is used as a runtime check to ensure that methods which intended to be abstract (i.e., they should be implemented in subclasses) are not called directly on the superclass. +@noreturn func abstractMethod() -> Void { + rxFatalError("Abstract method") +} + +@noreturn func rxFatalError(lastMessage: String) { + // The temptation to comment this line is great, but please don't, it's for your own good. The choice is yours. + fatalError(lastMessage) +} + +func incrementChecked(inout i: Int) throws -> Int { + if i == Int.max { + throw RxError.Overflow + } + let result = i + i += 1 + return result +} + +func decrementChecked(inout i: Int) throws -> Int { + if i == Int.min { + throw RxError.Overflow + } + let result = i + i -= 1 + return result +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/RxMutableBox.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/RxMutableBox.swift new file mode 100644 index 00000000000..6f5e5c3e648 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/RxMutableBox.swift @@ -0,0 +1,37 @@ +// +// RxMutableBox.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/22/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Creates mutable reference wrapper for any type. +*/ +class RxMutableBox : CustomDebugStringConvertible { + /** + Wrapped value + */ + var value : T + + /** + Creates reference wrapper for `value`. + + - parameter value: Value to wrap. + */ + init (_ value: T) { + self.value = value + } +} + +extension RxMutableBox { + /** + - returns: Box description. + */ + var debugDescription: String { + return "MutatingBox(\(self.value))" + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/SchedulerType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/SchedulerType.swift new file mode 100644 index 00000000000..b88d9cd0701 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/SchedulerType.swift @@ -0,0 +1,78 @@ +// +// SchedulerType.swift +// Rx +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Type that represents time interval in the context of RxSwift. +*/ +public typealias RxTimeInterval = NSTimeInterval + +/** +Type that represents absolute time in the context of RxSwift. +*/ +public typealias RxTime = NSDate + +/** +Represents an object that schedules units of work. +*/ +public protocol SchedulerType: ImmediateSchedulerType { + + /** + - returns: Current time. + */ + var now : RxTime { + get + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + func scheduleRelative(state: StateType, dueTime: RxTimeInterval, action: (StateType) -> Disposable) -> Disposable + + /** + Schedules a periodic piece of work. + + - parameter state: State passed to the action to be executed. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + func schedulePeriodic(state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: (StateType) -> StateType) -> Disposable +} + +extension SchedulerType { + + /** + Periodic task will be emulated using recursive scheduling. + + - parameter state: Initial state passed to the action upon the first iteration. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - returns: The disposable object used to cancel the scheduled recurring action (best effort). + */ + public func schedulePeriodic(state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: (StateType) -> StateType) -> Disposable { + let schedule = SchedulePeriodicRecursive(scheduler: self, startAfter: startAfter, period: period, action: action, state: state) + + return schedule.start() + } + + func scheduleRecursive(state: State, dueTime: RxTimeInterval, action: (state: State, scheduler: AnyRecursiveScheduler) -> ()) -> Disposable { + let scheduler = AnyRecursiveScheduler(scheduler: self, action: action) + + scheduler.schedule(state, dueTime: dueTime) + + return AnonymousDisposable(scheduler.dispose) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift new file mode 100644 index 00000000000..3f8207aa6a1 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift @@ -0,0 +1,147 @@ +// +// ConcurrentDispatchQueueScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 7/5/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Abstracts the work that needs to be performed on a specific `dispatch_queue_t`. You can also pass a serial dispatch queue, it shouldn't cause any problems. + +This scheduler is suitable when some work needs to be performed in background. +*/ +public class ConcurrentDispatchQueueScheduler: SchedulerType { + public typealias TimeInterval = NSTimeInterval + public typealias Time = NSDate + + private let _queue : dispatch_queue_t + + public var now : NSDate { + return NSDate() + } + + // leeway for scheduling timers + private var _leeway: Int64 = 0 + + /** + Constructs new `ConcurrentDispatchQueueScheduler` that wraps `queue`. + + - parameter queue: Target dispatch queue. + */ + public init(queue: dispatch_queue_t) { + _queue = queue + } + + /** + Convenience init for scheduler that wraps one of the global concurrent dispatch queues. + + - parameter globalConcurrentQueueQOS: Target global dispatch queue, by quality of service class. + */ + @available(iOS 8, OSX 10.10, *) + public convenience init(globalConcurrentQueueQOS: DispatchQueueSchedulerQOS) { + let priority = globalConcurrentQueueQOS.QOSClass + self.init(queue: dispatch_get_global_queue(priority, UInt(0))) + } + + + class func convertTimeIntervalToDispatchInterval(timeInterval: NSTimeInterval) -> Int64 { + return Int64(timeInterval * Double(NSEC_PER_SEC)) + } + + class func convertTimeIntervalToDispatchTime(timeInterval: NSTimeInterval) -> dispatch_time_t { + return dispatch_time(DISPATCH_TIME_NOW, convertTimeIntervalToDispatchInterval(timeInterval)) + } + + /** + Schedules an action to be executed immediatelly. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func schedule(state: StateType, action: StateType -> Disposable) -> Disposable { + return self.scheduleInternal(state, action: action) + } + + func scheduleInternal(state: StateType, action: StateType -> Disposable) -> Disposable { + let cancel = SingleAssignmentDisposable() + + dispatch_async(_queue) { + if cancel.disposed { + return + } + + cancel.disposable = action(state) + } + + return cancel + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func scheduleRelative(state: StateType, dueTime: NSTimeInterval, action: (StateType) -> Disposable) -> Disposable { + let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, _queue) + + let dispatchInterval = MainScheduler.convertTimeIntervalToDispatchTime(dueTime) + + let compositeDisposable = CompositeDisposable() + + dispatch_source_set_timer(timer, dispatchInterval, DISPATCH_TIME_FOREVER, 0) + dispatch_source_set_event_handler(timer, { + if compositeDisposable.disposed { + return + } + compositeDisposable.addDisposable(action(state)) + }) + dispatch_resume(timer) + + compositeDisposable.addDisposable(AnonymousDisposable { + dispatch_source_cancel(timer) + }) + + return compositeDisposable + } + + /** + Schedules a periodic piece of work. + + - parameter state: State passed to the action to be executed. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedulePeriodic(state: StateType, startAfter: TimeInterval, period: TimeInterval, action: (StateType) -> StateType) -> Disposable { + let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, _queue) + + let initial = MainScheduler.convertTimeIntervalToDispatchTime(startAfter) + let dispatchInterval = MainScheduler.convertTimeIntervalToDispatchInterval(period) + + var timerState = state + + let validDispatchInterval = dispatchInterval < 0 ? 0 : UInt64(dispatchInterval) + + dispatch_source_set_timer(timer, initial, validDispatchInterval, 0) + let cancel = AnonymousDisposable { + dispatch_source_cancel(timer) + } + dispatch_source_set_event_handler(timer, { + if cancel.disposed { + return + } + timerState = action(timerState) + }) + dispatch_resume(timer) + + return cancel + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift new file mode 100644 index 00000000000..c26be800cf5 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift @@ -0,0 +1,90 @@ +// +// ConcurrentMainScheduler.swift +// Rx +// +// Created by Krunoslav Zaher on 10/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Abstracts work that needs to be performed on `MainThread`. In case `schedule` methods are called from main thread, it will perform action immediately without scheduling. + +This scheduler is optimized for `subscribeOn` operator. If you want to observe observable sequence elements on main thread using `observeOn` operator, +`MainScheduler` is more suitable for that purpose. +*/ +public final class ConcurrentMainScheduler : SchedulerType { + public typealias TimeInterval = NSTimeInterval + public typealias Time = NSDate + + private let _mainScheduler: MainScheduler + private let _mainQueue: dispatch_queue_t + + /** + - returns: Current time. + */ + public var now : NSDate { + return _mainScheduler.now + } + + private init(mainScheduler: MainScheduler) { + _mainQueue = dispatch_get_main_queue() + _mainScheduler = mainScheduler + } + + /** + Singleton instance of `ConcurrentMainScheduler` + */ + public static let instance = ConcurrentMainScheduler(mainScheduler: MainScheduler.instance) + + /** + Schedules an action to be executed immediatelly. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedule(state: StateType, action: (StateType) -> Disposable) -> Disposable { + if NSThread.currentThread().isMainThread { + return action(state) + } + + let cancel = SingleAssignmentDisposable() + + dispatch_async(_mainQueue) { + if cancel.disposed { + return + } + + cancel.disposable = action(state) + } + + return cancel + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func scheduleRelative(state: StateType, dueTime: NSTimeInterval, action: (StateType) -> Disposable) -> Disposable { + return _mainScheduler.scheduleRelative(state, dueTime: dueTime, action: action) + } + + /** + Schedules a periodic piece of work. + + - parameter state: State passed to the action to be executed. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedulePeriodic(state: StateType, startAfter: TimeInterval, period: TimeInterval, action: (StateType) -> StateType) -> Disposable { + return _mainScheduler.schedulePeriodic(state, startAfter: startAfter, period: period, action: action) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift new file mode 100644 index 00000000000..b1c638847a1 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift @@ -0,0 +1,147 @@ +// +// CurrentThreadScheduler.swift +// Rx +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +#if os(Linux) + let CurrentThreadSchedulerKeyInstance = "RxSwift.CurrentThreadScheduler.SchedulerKey" + let CurrentThreadSchedulerQueueKeyInstance = "RxSwift.CurrentThreadScheduler.Queue" + + typealias CurrentThreadSchedulerValue = NSString + let CurrentThreadSchedulerValueInstance = "RxSwift.CurrentThreadScheduler.SchedulerKey" as NSString +#else + let CurrentThreadSchedulerKeyInstance = CurrentThreadSchedulerKey() + let CurrentThreadSchedulerQueueKeyInstance = CurrentThreadSchedulerQueueKey() + + typealias CurrentThreadSchedulerValue = CurrentThreadSchedulerKey + let CurrentThreadSchedulerValueInstance = CurrentThreadSchedulerKeyInstance + + class CurrentThreadSchedulerKey : NSObject, NSCopying { + override func isEqual(object: AnyObject?) -> Bool { + return object === CurrentThreadSchedulerKeyInstance + } + + override var hash: Int { return -904739208 } + + override func copy() -> AnyObject { + return CurrentThreadSchedulerKeyInstance + } + + func copyWithZone(zone: NSZone) -> AnyObject { + return CurrentThreadSchedulerKeyInstance + } + } + + class CurrentThreadSchedulerQueueKey : NSObject, NSCopying { + override func isEqual(object: AnyObject?) -> Bool { + return object === CurrentThreadSchedulerQueueKeyInstance + } + + override var hash: Int { return -904739207 } + + override func copy() -> AnyObject { + return CurrentThreadSchedulerQueueKeyInstance + } + + func copyWithZone(zone: NSZone) -> AnyObject { + return CurrentThreadSchedulerQueueKeyInstance + } + } +#endif + +/** +Represents an object that schedules units of work on the current thread. + +This is the default scheduler for operators that generate elements. + +This scheduler is also sometimes called `trampoline scheduler`. +*/ +public class CurrentThreadScheduler : ImmediateSchedulerType { + typealias ScheduleQueue = RxMutableBox> + + /** + The singleton instance of the current thread scheduler. + */ + public static let instance = CurrentThreadScheduler() + + static var queue : ScheduleQueue? { + get { + return NSThread.getThreadLocalStorageValueForKey(CurrentThreadSchedulerQueueKeyInstance) + } + set { + NSThread.setThreadLocalStorageValue(newValue, forKey: CurrentThreadSchedulerQueueKeyInstance) + } + } + + /** + Gets a value that indicates whether the caller must call a `schedule` method. + */ + public static private(set) var isScheduleRequired: Bool { + get { + let value: CurrentThreadSchedulerValue? = NSThread.getThreadLocalStorageValueForKey(CurrentThreadSchedulerKeyInstance) + return value == nil + } + set(isScheduleRequired) { + NSThread.setThreadLocalStorageValue(isScheduleRequired ? nil : CurrentThreadSchedulerValueInstance, forKey: CurrentThreadSchedulerKeyInstance) + } + } + + /** + Schedules an action to be executed as soon as possible on current thread. + + If this method is called on some thread that doesn't have `CurrentThreadScheduler` installed, scheduler will be + automatically installed and uninstalled after all work is performed. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedule(state: StateType, action: (StateType) -> Disposable) -> Disposable { + if CurrentThreadScheduler.isScheduleRequired { + CurrentThreadScheduler.isScheduleRequired = false + + let disposable = action(state) + + defer { + CurrentThreadScheduler.isScheduleRequired = true + CurrentThreadScheduler.queue = nil + } + + guard let queue = CurrentThreadScheduler.queue else { + return disposable + } + + while let latest = queue.value.dequeue() { + if latest.disposed { + continue + } + latest.invoke() + } + + return disposable + } + + let existingQueue = CurrentThreadScheduler.queue + + let queue: RxMutableBox> + if let existingQueue = existingQueue { + queue = existingQueue + } + else { + queue = RxMutableBox(Queue(capacity: 1)) + CurrentThreadScheduler.queue = queue + } + + let scheduledItem = ScheduledItem(action: action, state: state) + queue.value.enqueue(scheduledItem) + + // In Xcode 7.3, `return scheduledItem` causes segmentation fault 11 on release build. + // To workaround this compiler issue, returns AnonymousDisposable that disposes scheduledItem. + return AnonymousDisposable(scheduledItem.dispose) + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/DispatchQueueSchedulerQOS.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/DispatchQueueSchedulerQOS.swift new file mode 100644 index 00000000000..96154807d75 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/DispatchQueueSchedulerQOS.swift @@ -0,0 +1,54 @@ +// +// DispatchQueueSchedulerQOS.swift +// RxSwift +// +// Created by John C. "Hsoi" Daub on 12/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Identifies one of the global concurrent dispatch queues with specified quality of service class. +*/ +public enum DispatchQueueSchedulerQOS { + + /** + Identifies global dispatch queue with `QOS_CLASS_USER_INTERACTIVE` + */ + case UserInteractive + + /** + Identifies global dispatch queue with `QOS_CLASS_USER_INITIATED` + */ + case UserInitiated + + /** + Identifies global dispatch queue with `QOS_CLASS_DEFAULT` + */ + case Default + + /** + Identifies global dispatch queue with `QOS_CLASS_UTILITY` + */ + case Utility + + /** + Identifies global dispatch queue with `QOS_CLASS_BACKGROUND` + */ + case Background +} + + +@available(iOS 8, OSX 10.10, *) +extension DispatchQueueSchedulerQOS { + var QOSClass: qos_class_t { + switch self { + case .UserInteractive: return QOS_CLASS_USER_INTERACTIVE + case .UserInitiated: return QOS_CLASS_USER_INITIATED + case .Default: return QOS_CLASS_DEFAULT + case .Utility: return QOS_CLASS_UTILITY + case .Background: return QOS_CLASS_BACKGROUND + } + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift new file mode 100644 index 00000000000..949748e15ed --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift @@ -0,0 +1,25 @@ +// +// HistoricalScheduler.swift +// Rx +// +// Created by Krunoslav Zaher on 12/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** + Provides a virtual time scheduler that uses `NSDate` for absolute time and `NSTimeInterval` for relative time. +*/ +public class HistoricalScheduler : VirtualTimeScheduler { + + /** + Creates a new historical scheduler with initial clock value. + + - parameter initialClock: Initial value for virtual clock. + */ + public init(initialClock: RxTime = NSDate(timeIntervalSince1970: 0)) { + super.init(initialClock: initialClock, converter: HistoricalSchedulerTimeConverter()) + } + +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift new file mode 100644 index 00000000000..8384beb4319 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift @@ -0,0 +1,83 @@ +// +// HistoricalSchedulerTimeConverter.swift +// Rx +// +// Created by Krunoslav Zaher on 12/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** + Converts historial virtual time into real time. + + Since historical virtual time is also measured in `NSDate`, this converter is identity function. + */ +public struct HistoricalSchedulerTimeConverter : VirtualTimeConverterType { + /** + Virtual time unit used that represents ticks of virtual clock. + */ + public typealias VirtualTimeUnit = RxTime + + /** + Virtual time unit used to represent differences of virtual times. + */ + public typealias VirtualTimeIntervalUnit = RxTimeInterval + + /** + Returns identical value of argument passed because historical virtual time is equal to real time, just + decoupled from local machine clock. + */ + public func convertFromVirtualTime(virtualTime: VirtualTimeUnit) -> RxTime { + return virtualTime + } + + /** + Returns identical value of argument passed because historical virtual time is equal to real time, just + decoupled from local machine clock. + */ + public func convertToVirtualTime(time: RxTime) -> VirtualTimeUnit { + return time + } + + /** + Returns identical value of argument passed because historical virtual time is equal to real time, just + decoupled from local machine clock. + */ + public func convertFromVirtualTimeInterval(virtualTimeInterval: VirtualTimeIntervalUnit) -> RxTimeInterval { + return virtualTimeInterval + } + + /** + Returns identical value of argument passed because historical virtual time is equal to real time, just + decoupled from local machine clock. + */ + public func convertToVirtualTimeInterval(timeInterval: RxTimeInterval) -> VirtualTimeIntervalUnit { + return timeInterval + } + + /** + Offsets `NSDate` by time interval. + + - parameter time: Time. + - parameter timeInterval: Time interval offset. + - returns: Time offsetted by time interval. + */ + public func offsetVirtualTime(time time: VirtualTimeUnit, offset: VirtualTimeIntervalUnit) -> VirtualTimeUnit { + return time.dateByAddingTimeInterval(offset) + } + + /** + Compares two `NSDate`s. + */ + public func compareVirtualTime(lhs: VirtualTimeUnit, _ rhs: VirtualTimeUnit) -> VirtualTimeComparison { + switch lhs.compare(rhs) { + case .OrderedAscending: + return .LessThan + case .OrderedSame: + return .Equal + case .OrderedDescending: + return .GreaterThan + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ImmediateScheduler.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ImmediateScheduler.swift new file mode 100644 index 00000000000..fc54fd5120a --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ImmediateScheduler.swift @@ -0,0 +1,39 @@ +// +// ImmediateScheduler.swift +// Rx +// +// Created by Krunoslav Zaher on 10/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Represents an object that schedules units of work to run immediately on the current thread. +*/ +private class ImmediateScheduler : ImmediateSchedulerType { + + private let _asyncLock = AsyncLock() + + /** + Schedules an action to be executed immediatelly. + + In case `schedule` is called recursively from inside of `action` callback, scheduled `action` will be enqueued + and executed after current `action`. (`AsyncLock` behavior) + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + func schedule(state: StateType, action: (StateType) -> Disposable) -> Disposable { + let disposable = SingleAssignmentDisposable() + _asyncLock.invoke(AnonymousInvocable { + if disposable.disposed { + return + } + disposable.disposable = action(state) + }) + + return disposable + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/AnonymousInvocable.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/AnonymousInvocable.swift new file mode 100644 index 00000000000..8525db45845 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/AnonymousInvocable.swift @@ -0,0 +1,21 @@ +// +// AnonymousInvocable.swift +// Rx +// +// Created by Krunoslav Zaher on 11/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +struct AnonymousInvocable : InvocableType { + private let _action: () -> () + + init(_ action: () -> ()) { + _action = action + } + + func invoke() { + _action() + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift new file mode 100644 index 00000000000..1a4e3aa44e0 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift @@ -0,0 +1,24 @@ +// +// InvocableScheduledItem.swift +// Rx +// +// Created by Krunoslav Zaher on 11/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +struct InvocableScheduledItem : InvocableType { + + let _invocable: I + let _state: I.Value + + init(invocable: I, state: I.Value) { + _invocable = invocable + _state = state + } + + func invoke() { + _invocable.invoke(_state) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift new file mode 100644 index 00000000000..1632e71dada --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift @@ -0,0 +1,19 @@ +// +// InvocableType.swift +// Rx +// +// Created by Krunoslav Zaher on 11/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +protocol InvocableType { + func invoke() +} + +protocol InvocableWithValueType { + associatedtype Value + + func invoke(value: Value) +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift new file mode 100644 index 00000000000..d4c9a2c65b5 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift @@ -0,0 +1,37 @@ +// +// ScheduledItem.swift +// Rx +// +// Created by Krunoslav Zaher on 9/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +struct ScheduledItem + : ScheduledItemType + , InvocableType { + typealias Action = T -> Disposable + + private let _action: Action + private let _state: T + + private let _disposable = SingleAssignmentDisposable() + + var disposed: Bool { + return _disposable.disposed + } + + init(action: Action, state: T) { + _action = action + _state = state + } + + func invoke() { + _disposable.disposable = _action(_state) + } + + func dispose() { + _disposable.dispose() + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift new file mode 100644 index 00000000000..2a1eca272da --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift @@ -0,0 +1,15 @@ +// +// ScheduledItemType.swift +// Rx +// +// Created by Krunoslav Zaher on 11/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +protocol ScheduledItemType + : Cancelable + , InvocableType { + func invoke() +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift new file mode 100644 index 00000000000..ed109df7447 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift @@ -0,0 +1,73 @@ +// +// MainScheduler.swift +// Rx +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Abstracts work that needs to be performed on `MainThread`. In case `schedule` methods are called from main thread, it will perform action immediately without scheduling. + +This scheduler is usually used to perform UI work. + +Main scheduler is a specialization of `SerialDispatchQueueScheduler`. + +This scheduler is optimized for `observeOn` operator. To ensure observable sequence is subscribed on main thread using `subscribeOn` +operator please use `ConcurrentMainScheduler` because it is more optimized for that purpose. +*/ +public final class MainScheduler : SerialDispatchQueueScheduler { + + private let _mainQueue: dispatch_queue_t + + var numberEnqueued: AtomicInt = 0 + + private init() { + _mainQueue = dispatch_get_main_queue() + super.init(serialQueue: _mainQueue) + } + + /** + Singleton instance of `MainScheduler` + */ + public static let instance = MainScheduler() + + /** + Singleton instance of `MainScheduler` that always schedules work asynchronously + and doesn't perform optimizations for calls scheduled from main thread. + */ + public static let asyncInstance = SerialDispatchQueueScheduler(serialQueue: dispatch_get_main_queue()) + + /** + In case this method is called on a background thread it will throw an exception. + */ + public class func ensureExecutingOnScheduler(errorMessage: String? = nil) { + if !NSThread.currentThread().isMainThread { + rxFatalError(errorMessage ?? "Executing on backgound thread. Please use `MainScheduler.instance.schedule` to schedule work on main thread.") + } + } + + override func scheduleInternal(state: StateType, action: StateType -> Disposable) -> Disposable { + let currentNumberEnqueued = AtomicIncrement(&numberEnqueued) + + if NSThread.currentThread().isMainThread && currentNumberEnqueued == 1 { + let disposable = action(state) + AtomicDecrement(&numberEnqueued) + return disposable + } + + let cancel = SingleAssignmentDisposable() + + dispatch_async(_mainQueue) { + if !cancel.disposed { + action(state) + } + + AtomicDecrement(&self.numberEnqueued) + } + + return cancel + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift new file mode 100644 index 00000000000..8cfba8cafb5 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift @@ -0,0 +1,57 @@ +// +// OperationQueueScheduler.swift +// Rx +// +// Created by Krunoslav Zaher on 4/4/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Abstracts the work that needs to be performed on a specific `NSOperationQueue`. + +This scheduler is suitable for cases when there is some bigger chunk of work that needs to be performed in background and you want to fine tune concurrent processing using `maxConcurrentOperationCount`. +*/ +public class OperationQueueScheduler: ImmediateSchedulerType { + public let operationQueue: NSOperationQueue + + /** + Constructs new instance of `OperationQueueScheduler` that performs work on `operationQueue`. + + - parameter operationQueue: Operation queue targeted to perform work on. + */ + public init(operationQueue: NSOperationQueue) { + self.operationQueue = operationQueue + } + + /** + Schedules an action to be executed recursively. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedule(state: StateType, action: (StateType) -> Disposable) -> Disposable { + + let compositeDisposable = CompositeDisposable() + + weak var compositeDisposableWeak = compositeDisposable + + let operation = NSBlockOperation { + if compositeDisposableWeak?.disposed ?? false { + return + } + + let disposable = action(state) + compositeDisposableWeak?.addDisposable(disposable) + } + + self.operationQueue.addOperation(operation) + + compositeDisposable.addDisposable(AnonymousDisposable(operation.cancel)) + + return compositeDisposable + } + +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift new file mode 100644 index 00000000000..dac4360cc81 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift @@ -0,0 +1,193 @@ +// +// RecursiveScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Type erased recursive scheduler. +*/ +class AnyRecursiveScheduler { + typealias Action = (state: State, scheduler: AnyRecursiveScheduler) -> Void + + private let _lock = NSRecursiveLock() + + // state + private let _group = CompositeDisposable() + + private var _scheduler: SchedulerType + private var _action: Action? + + init(scheduler: SchedulerType, action: Action) { + _action = action + _scheduler = scheduler + } + + /** + Schedules an action to be executed recursively. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the recursive action. + */ + func schedule(state: State, dueTime: RxTimeInterval) { + + var isAdded = false + var isDone = false + + var removeKey: CompositeDisposable.DisposeKey? = nil + let d = _scheduler.scheduleRelative(state, dueTime: dueTime) { (state) -> Disposable in + // best effort + if self._group.disposed { + return NopDisposable.instance + } + + let action = self._lock.calculateLocked { () -> Action? in + if isAdded { + self._group.removeDisposable(removeKey!) + } + else { + isDone = true + } + + return self._action + } + + if let action = action { + action(state: state, scheduler: self) + } + + return NopDisposable.instance + } + + _lock.performLocked { + if !isDone { + removeKey = _group.addDisposable(d) + isAdded = true + } + } + } + + /** + Schedules an action to be executed recursively. + + - parameter state: State passed to the action to be executed. + */ + func schedule(state: State) { + + var isAdded = false + var isDone = false + + var removeKey: CompositeDisposable.DisposeKey? = nil + let d = _scheduler.schedule(state) { (state) -> Disposable in + // best effort + if self._group.disposed { + return NopDisposable.instance + } + + let action = self._lock.calculateLocked { () -> Action? in + if isAdded { + self._group.removeDisposable(removeKey!) + } + else { + isDone = true + } + + return self._action + } + + if let action = action { + action(state: state, scheduler: self) + } + + return NopDisposable.instance + } + + _lock.performLocked { + if !isDone { + removeKey = _group.addDisposable(d) + isAdded = true + } + } + } + + func dispose() { + _lock.performLocked { + _action = nil + } + _group.dispose() + } +} + +/** +Type erased recursive scheduler. +*/ +class RecursiveImmediateScheduler { + typealias Action = (state: State, recurse: State -> Void) -> Void + + private var _lock = SpinLock() + private let _group = CompositeDisposable() + + private var _action: Action? + private let _scheduler: ImmediateSchedulerType + + init(action: Action, scheduler: ImmediateSchedulerType) { + _action = action + _scheduler = scheduler + } + + // immediate scheduling + + /** + Schedules an action to be executed recursively. + + - parameter state: State passed to the action to be executed. + */ + func schedule(state: State) { + + var isAdded = false + var isDone = false + + var removeKey: CompositeDisposable.DisposeKey? = nil + let d = _scheduler.schedule(state) { (state) -> Disposable in + // best effort + if self._group.disposed { + return NopDisposable.instance + } + + let action = self._lock.calculateLocked { () -> Action? in + if isAdded { + self._group.removeDisposable(removeKey!) + } + else { + isDone = true + } + + return self._action + } + + if let action = action { + action(state: state, recurse: self.schedule) + } + + return NopDisposable.instance + } + + _lock.performLocked { + if !isDone { + removeKey = _group.addDisposable(d) + isAdded = true + } + } + } + + func dispose() { + _lock.performLocked { + _action = nil + } + _group.dispose() + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift new file mode 100644 index 00000000000..3906d7a708b --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift @@ -0,0 +1,63 @@ +// +// SchedulerServices+Emulation.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/6/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +enum SchedulePeriodicRecursiveCommand { + case Tick + case DispatchStart +} + +class SchedulePeriodicRecursive { + typealias RecursiveAction = State -> State + typealias RecursiveScheduler = AnyRecursiveScheduler + + private let _scheduler: SchedulerType + private let _startAfter: RxTimeInterval + private let _period: RxTimeInterval + private let _action: RecursiveAction + + private var _state: State + private var _pendingTickCount: AtomicInt = 0 + + init(scheduler: SchedulerType, startAfter: RxTimeInterval, period: RxTimeInterval, action: RecursiveAction, state: State) { + _scheduler = scheduler + _startAfter = startAfter + _period = period + _action = action + _state = state + } + + func start() -> Disposable { + return _scheduler.scheduleRecursive(SchedulePeriodicRecursiveCommand.Tick, dueTime: _startAfter, action: self.tick) + } + + func tick(command: SchedulePeriodicRecursiveCommand, scheduler: RecursiveScheduler) -> Void { + // Tries to emulate periodic scheduling as best as possible. + // The problem that could arise is if handling periodic ticks take too long, or + // tick interval is short. + switch command { + case .Tick: + scheduler.schedule(.Tick, dueTime: _period) + + // The idea is that if on tick there wasn't any item enqueued, schedule to perform work immediatelly. + // Else work will be scheduled after previous enqueued work completes. + if AtomicIncrement(&_pendingTickCount) == 1 { + self.tick(.DispatchStart, scheduler: scheduler) + } + + case .DispatchStart: + _state = _action(_state) + // Start work and schedule check is this last batch of work + if AtomicDecrement(&_pendingTickCount) > 0 { + // This gives priority to scheduler emulation, it's not perfect, but helps + scheduler.schedule(SchedulePeriodicRecursiveCommand.DispatchStart) + } + } + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift new file mode 100644 index 00000000000..8376f9a4326 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift @@ -0,0 +1,184 @@ +// +// SerialDispatchQueueScheduler.swift +// Rx +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Abstracts the work that needs to be performed on a specific `dispatch_queue_t`. It will make sure +that even if concurrent dispatch queue is passed, it's transformed into a serial one. + +It is extremely important that this scheduler is serial, because +certain operator perform optimizations that rely on that property. + +Because there is no way of detecting is passed dispatch queue serial or +concurrent, for every queue that is being passed, worst case (concurrent) +will be assumed, and internal serial proxy dispatch queue will be created. + +This scheduler can also be used with internal serial queue alone. + +In case some customization need to be made on it before usage, +internal serial queue can be customized using `serialQueueConfiguration` +callback. +*/ +public class SerialDispatchQueueScheduler: SchedulerType { + public typealias TimeInterval = NSTimeInterval + public typealias Time = NSDate + + private let _serialQueue : dispatch_queue_t + + /** + - returns: Current time. + */ + public var now : NSDate { + return NSDate() + } + + // leeway for scheduling timers + private var _leeway: Int64 = 0 + + init(serialQueue: dispatch_queue_t) { + _serialQueue = serialQueue + } + + /** + Constructs new `SerialDispatchQueueScheduler` with internal serial queue named `internalSerialQueueName`. + + Additional dispatch queue properties can be set after dispatch queue is created using `serialQueueConfiguration`. + + - parameter internalSerialQueueName: Name of internal serial dispatch queue. + - parameter serialQueueConfiguration: Additional configuration of internal serial dispatch queue. + */ + public convenience init(internalSerialQueueName: String, serialQueueConfiguration: ((dispatch_queue_t) -> Void)? = nil) { + let queue = dispatch_queue_create(internalSerialQueueName, DISPATCH_QUEUE_SERIAL) + serialQueueConfiguration?(queue) + self.init(serialQueue: queue) + } + + /** + Constructs new `SerialDispatchQueueScheduler` named `internalSerialQueueName` that wraps `queue`. + + - parameter queue: Possibly concurrent dispatch queue used to perform work. + - parameter internalSerialQueueName: Name of internal serial dispatch queue proxy. + */ + public convenience init(queue: dispatch_queue_t, internalSerialQueueName: String) { + let serialQueue = dispatch_queue_create(internalSerialQueueName, DISPATCH_QUEUE_SERIAL) + dispatch_set_target_queue(serialQueue, queue) + self.init(serialQueue: serialQueue) + } + + /** + Constructs new `SerialDispatchQueueScheduler` that wraps on of the global concurrent dispatch queues. + + - parameter globalConcurrentQueueQOS: Identifier for global dispatch queue with specified quality of service class. + - parameter internalSerialQueueName: Custom name for internal serial dispatch queue proxy. + */ + @available(iOS 8, OSX 10.10, *) + public convenience init(globalConcurrentQueueQOS: DispatchQueueSchedulerQOS, internalSerialQueueName: String = "rx.global_dispatch_queue.serial") { + let priority = globalConcurrentQueueQOS.QOSClass + self.init(queue: dispatch_get_global_queue(priority, UInt(0)), internalSerialQueueName: internalSerialQueueName) + } + + class func convertTimeIntervalToDispatchInterval(timeInterval: NSTimeInterval) -> Int64 { + return Int64(timeInterval * Double(NSEC_PER_SEC)) + } + + class func convertTimeIntervalToDispatchTime(timeInterval: NSTimeInterval) -> dispatch_time_t { + return dispatch_time(DISPATCH_TIME_NOW, convertTimeIntervalToDispatchInterval(timeInterval)) + } + + /** + Schedules an action to be executed immediatelly. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func schedule(state: StateType, action: (StateType) -> Disposable) -> Disposable { + return self.scheduleInternal(state, action: action) + } + + func scheduleInternal(state: StateType, action: (StateType) -> Disposable) -> Disposable { + let cancel = SingleAssignmentDisposable() + + dispatch_async(_serialQueue) { + if cancel.disposed { + return + } + + + cancel.disposable = action(state) + } + + return cancel + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func scheduleRelative(state: StateType, dueTime: NSTimeInterval, action: (StateType) -> Disposable) -> Disposable { + let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, _serialQueue) + + let dispatchInterval = MainScheduler.convertTimeIntervalToDispatchTime(dueTime) + + let compositeDisposable = CompositeDisposable() + + dispatch_source_set_timer(timer, dispatchInterval, DISPATCH_TIME_FOREVER, 0) + dispatch_source_set_event_handler(timer, { + if compositeDisposable.disposed { + return + } + compositeDisposable.addDisposable(action(state)) + }) + dispatch_resume(timer) + + compositeDisposable.addDisposable(AnonymousDisposable { + dispatch_source_cancel(timer) + }) + + return compositeDisposable + } + + /** + Schedules a periodic piece of work. + + - parameter state: State passed to the action to be executed. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedulePeriodic(state: StateType, startAfter: TimeInterval, period: TimeInterval, action: (StateType) -> StateType) -> Disposable { + let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, _serialQueue) + + let initial = MainScheduler.convertTimeIntervalToDispatchTime(startAfter) + let dispatchInterval = MainScheduler.convertTimeIntervalToDispatchInterval(period) + + var timerState = state + + let validDispatchInterval = dispatchInterval < 0 ? 0 : UInt64(dispatchInterval) + + dispatch_source_set_timer(timer, initial, validDispatchInterval, 0) + let cancel = AnonymousDisposable { + dispatch_source_cancel(timer) + } + dispatch_source_set_event_handler(timer, { + if cancel.disposed { + return + } + timerState = action(timerState) + }) + dispatch_resume(timer) + + return cancel + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift new file mode 100644 index 00000000000..61a58ca62f7 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift @@ -0,0 +1,115 @@ +// +// VirtualTimeConverterType.swift +// Rx +// +// Created by Krunoslav Zaher on 12/23/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Parametrization for virtual time used by `VirtualTimeScheduler`s. +*/ +public protocol VirtualTimeConverterType { + /** + Virtual time unit used that represents ticks of virtual clock. + */ + associatedtype VirtualTimeUnit + + /** + Virtual time unit used to represent differences of virtual times. + */ + associatedtype VirtualTimeIntervalUnit + + /** + Converts virtual time to real time. + + - parameter virtualTime: Virtual time to convert to `NSDate`. + - returns: `NSDate` corresponding to virtual time. + */ + func convertFromVirtualTime(virtualTime: VirtualTimeUnit) -> RxTime + + /** + Converts real time to virtual time. + + - parameter time: `NSDate` to convert to virtual time. + - returns: Virtual time corresponding to `NSDate`. + */ + func convertToVirtualTime(time: RxTime) -> VirtualTimeUnit + + /** + Converts from virtual time interval to `NSTimeInterval`. + + - parameter virtualTimeInterval: Virtual time interval to convert to `NSTimeInterval`. + - returns: `NSTimeInterval` corresponding to virtual time interval. + */ + func convertFromVirtualTimeInterval(virtualTimeInterval: VirtualTimeIntervalUnit) -> RxTimeInterval + + /** + Converts from virtual time interval to `NSTimeInterval`. + + - parameter timeInterval: `NSTimeInterval` to convert to virtual time interval. + - returns: Virtual time interval corresponding to time interval. + */ + func convertToVirtualTimeInterval(timeInterval: RxTimeInterval) -> VirtualTimeIntervalUnit + + /** + Offsets virtual time by virtual time interval. + + - parameter time: Virtual time. + - parameter offset: Virtual time interval. + - returns: Time corresponding to time offsetted by virtual time interval. + */ + func offsetVirtualTime(time time: VirtualTimeUnit, offset: VirtualTimeIntervalUnit) -> VirtualTimeUnit + + /** + This is aditional abstraction because `NSDate` is unfortunately not comparable. + Extending `NSDate` with `Comparable` would be too risky because of possible collisions with other libraries. + */ + func compareVirtualTime(lhs: VirtualTimeUnit, _ rhs: VirtualTimeUnit) -> VirtualTimeComparison +} + +/** + Virtual time comparison result. + + This is aditional abstraction because `NSDate` is unfortunately not comparable. + Extending `NSDate` with `Comparable` would be too risky because of possible collisions with other libraries. +*/ +public enum VirtualTimeComparison { + /** + lhs < rhs. + */ + case LessThan + /** + lhs == rhs. + */ + case Equal + /** + lhs > rhs. + */ + case GreaterThan +} + +extension VirtualTimeComparison { + /** + lhs < rhs. + */ + var lessThen: Bool { + return self == .LessThan + } + + /** + lhs > rhs + */ + var greaterThan: Bool { + return self == .GreaterThan + } + + /** + lhs == rhs + */ + var equal: Bool { + return self == .Equal + } +} diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift new file mode 100644 index 00000000000..9c480619e24 --- /dev/null +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift @@ -0,0 +1,292 @@ +// +// VirtualTimeScheduler.swift +// Rx +// +// Created by Krunoslav Zaher on 2/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/** +Base class for virtual time schedulers using a priority queue for scheduled items. +*/ +public class VirtualTimeScheduler + : SchedulerType + , CustomDebugStringConvertible { + + public typealias VirtualTime = Converter.VirtualTimeUnit + public typealias VirtualTimeInterval = Converter.VirtualTimeIntervalUnit + + private var _running : Bool + + private var _clock: VirtualTime + + private var _schedulerQueue : PriorityQueue> + private var _converter: Converter + + private var _nextId = 0 + + /** + - returns: Current time. + */ + public var now: RxTime { + return _converter.convertFromVirtualTime(clock) + } + + /** + - returns: Scheduler's absolute time clock value. + */ + public var clock: VirtualTime { + return _clock + } + + /** + Creates a new virtual time scheduler. + + - parameter initialClock: Initial value for the clock. + */ + public init(initialClock: VirtualTime, converter: Converter) { + _clock = initialClock + _running = false + _converter = converter + _schedulerQueue = PriorityQueue(hasHigherPriority: { + switch converter.compareVirtualTime($0.time, $1.time) { + case .LessThan: + return true + case .Equal: + return $0.id < $1.id + case .GreaterThan: + return false + } + }) + #if TRACE_RESOURCES + AtomicIncrement(&resourceCount) + #endif + } + + /** + Schedules an action to be executed immediatelly. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedule(state: StateType, action: StateType -> Disposable) -> Disposable { + return self.scheduleRelative(state, dueTime: 0.0) { a in + return action(a) + } + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func scheduleRelative(state: StateType, dueTime: RxTimeInterval, action: StateType -> Disposable) -> Disposable { + let time = self.now.dateByAddingTimeInterval(dueTime) + let absoluteTime = _converter.convertToVirtualTime(time) + let adjustedTime = self.adjustScheduledTime(absoluteTime) + return scheduleAbsoluteVirtual(state, time: adjustedTime, action: action) + } + + /** + Schedules an action to be executed after relative time has passed. + + - parameter state: State passed to the action to be executed. + - parameter time: Absolute time when to execute the action. If this is less or equal then `now`, `now + 1` will be used. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func scheduleRelativeVirtual(state: StateType, dueTime: VirtualTimeInterval, action: StateType -> Disposable) -> Disposable { + let time = _converter.offsetVirtualTime(time: self.clock, offset: dueTime) + return scheduleAbsoluteVirtual(state, time: time, action: action) + } + + /** + Schedules an action to be executed at absolute virtual time. + + - parameter state: State passed to the action to be executed. + - parameter time: Absolute time when to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func scheduleAbsoluteVirtual(state: StateType, time: Converter.VirtualTimeUnit, action: StateType -> Disposable) -> Disposable { + MainScheduler.ensureExecutingOnScheduler() + + let compositeDisposable = CompositeDisposable() + + let item = VirtualSchedulerItem(action: { + let dispose = action(state) + return dispose + }, time: time, id: _nextId) + + _nextId += 1 + + _schedulerQueue.enqueue(item) + + compositeDisposable.addDisposable(item) + + return compositeDisposable + } + + /** + Adjusts time of scheduling before adding item to schedule queue. + */ + public func adjustScheduledTime(time: Converter.VirtualTimeUnit) -> Converter.VirtualTimeUnit { + return time + } + + /** + Starts the virtual time scheduler. + */ + public func start() { + MainScheduler.ensureExecutingOnScheduler() + + if _running { + return + } + + _running = true + repeat { + guard let next = findNext() else { + break + } + + if _converter.compareVirtualTime(next.time, self.clock).greaterThan { + _clock = next.time + } + + next.invoke() + _schedulerQueue.remove(next) + } while _running + + _running = false + } + + func findNext() -> VirtualSchedulerItem? { + while let front = _schedulerQueue.peek() { + if front.disposed { + _schedulerQueue.remove(front) + continue + } + + return front + } + + return nil + } + + /** + Advances the scheduler's clock to the specified time, running all work till that point. + + - parameter virtualTime: Absolute time to advance the scheduler's clock to. + */ + public func advanceTo(virtualTime: VirtualTime) { + MainScheduler.ensureExecutingOnScheduler() + + if _running { + fatalError("Scheduler is already running") + } + + _running = true + repeat { + guard let next = findNext() else { + break + } + + if _converter.compareVirtualTime(next.time, virtualTime).greaterThan { + break + } + + if _converter.compareVirtualTime(next.time, self.clock).greaterThan { + _clock = next.time + } + + next.invoke() + _schedulerQueue.remove(next) + } while _running + + _clock = virtualTime + _running = false + } + + /** + Advances the scheduler's clock by the specified relative time. + */ + public func sleep(virtualInterval: VirtualTimeInterval) { + MainScheduler.ensureExecutingOnScheduler() + + let sleepTo = _converter.offsetVirtualTime(time: clock, offset: virtualInterval) + if _converter.compareVirtualTime(sleepTo, clock).lessThen { + fatalError("Can't sleep to past.") + } + + _clock = sleepTo + } + + /** + Stops the virtual time scheduler. + */ + public func stop() { + MainScheduler.ensureExecutingOnScheduler() + + _running = false + } + + #if TRACE_RESOURCES + deinit { + AtomicDecrement(&resourceCount) + } + #endif +} + +// MARK: description + +extension VirtualTimeScheduler { + /** + A textual representation of `self`, suitable for debugging. + */ + public var debugDescription: String { + return self._schedulerQueue.debugDescription + } +} + +class VirtualSchedulerItemhttp://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client; public class ApiException extends Exception { @@ -14,16 +38,16 @@ public ApiException(int code, String message) { public int getCode() { return code; } - + public void setCode(int code) { this.code = code; } - + public String getMessage() { return message; } - + public void setMessage(String message) { this.message = message; } -} \ No newline at end of file +} diff --git a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/ApiInvoker.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/ApiInvoker.java index ecb787006dd..24f5a129780 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/ApiInvoker.java +++ b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/ApiInvoker.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client; import org.apache.http.*; diff --git a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/HttpPatch.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/HttpPatch.java index cb97056dbc9..e880e64070b 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/HttpPatch.java +++ b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/HttpPatch.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client; import org.apache.http.client.methods.*; @@ -13,4 +37,4 @@ public HttpPatch(final String url) { public String getMethod() { return METHOD_PATCH; } -} \ No newline at end of file +} diff --git a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/Pair.java index 2710fb5a99b..d9c600b04c9 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/Pair.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client; public class Pair { diff --git a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/PetApi.java index 52e84575ad3..3960e910f6c 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/PetApi.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.api; import io.swagger.client.ApiException; diff --git a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/StoreApi.java index d20c70ad997..0672d5c8d5c 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/StoreApi.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.api; import io.swagger.client.ApiException; diff --git a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/UserApi.java index 5f61ba724ae..8a2c64ba9c4 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/UserApi.java @@ -1,3 +1,27 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package io.swagger.client.api; import io.swagger.client.ApiException; diff --git a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Category.java index f5d5ea86b63..eb8367eb21b 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Category.java @@ -43,11 +43,11 @@ public boolean equals(Object o) { return false; } Category category = (Category) o; - return (id == null ? category.id == null : id.equals(category.id)) && - (name == null ? category.name == null : name.equals(category.name)); + return (this.id == null ? category.id == null : this.id.equals(category.id)) && + (this.name == null ? category.name == null : this.name.equals(category.name)); } - @Override + @Override public int hashCode() { int result = 17; result = 31 * result + (id == null ? 0: id.hashCode()); diff --git a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Order.java index f184238f717..bd92826b56b 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Order.java @@ -96,15 +96,15 @@ public boolean equals(Object o) { return false; } Order order = (Order) o; - return (id == null ? order.id == null : id.equals(order.id)) && - (petId == null ? order.petId == null : petId.equals(order.petId)) && - (quantity == null ? order.quantity == null : quantity.equals(order.quantity)) && - (shipDate == null ? order.shipDate == null : shipDate.equals(order.shipDate)) && - (status == null ? order.status == null : status.equals(order.status)) && - (complete == null ? order.complete == null : complete.equals(order.complete)); + return (this.id == null ? order.id == null : this.id.equals(order.id)) && + (this.petId == null ? order.petId == null : this.petId.equals(order.petId)) && + (this.quantity == null ? order.quantity == null : this.quantity.equals(order.quantity)) && + (this.shipDate == null ? order.shipDate == null : this.shipDate.equals(order.shipDate)) && + (this.status == null ? order.status == null : this.status.equals(order.status)) && + (this.complete == null ? order.complete == null : this.complete.equals(order.complete)); } - @Override + @Override public int hashCode() { int result = 17; result = 31 * result + (id == null ? 0: id.hashCode()); diff --git a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Pet.java index e471a300a31..26662c6cfd6 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Pet.java @@ -98,15 +98,15 @@ public boolean equals(Object o) { return false; } Pet pet = (Pet) o; - return (id == null ? pet.id == null : id.equals(pet.id)) && - (category == null ? pet.category == null : category.equals(pet.category)) && - (name == null ? pet.name == null : name.equals(pet.name)) && - (photoUrls == null ? pet.photoUrls == null : photoUrls.equals(pet.photoUrls)) && - (tags == null ? pet.tags == null : tags.equals(pet.tags)) && - (status == null ? pet.status == null : status.equals(pet.status)); + return (this.id == null ? pet.id == null : this.id.equals(pet.id)) && + (this.category == null ? pet.category == null : this.category.equals(pet.category)) && + (this.name == null ? pet.name == null : this.name.equals(pet.name)) && + (this.photoUrls == null ? pet.photoUrls == null : this.photoUrls.equals(pet.photoUrls)) && + (this.tags == null ? pet.tags == null : this.tags.equals(pet.tags)) && + (this.status == null ? pet.status == null : this.status.equals(pet.status)); } - @Override + @Override public int hashCode() { int result = 17; result = 31 * result + (id == null ? 0: id.hashCode()); diff --git a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Tag.java index 722e9194eb2..d6c78a74629 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Tag.java @@ -43,11 +43,11 @@ public boolean equals(Object o) { return false; } Tag tag = (Tag) o; - return (id == null ? tag.id == null : id.equals(tag.id)) && - (name == null ? tag.name == null : name.equals(tag.name)); + return (this.id == null ? tag.id == null : this.id.equals(tag.id)) && + (this.name == null ? tag.name == null : this.name.equals(tag.name)); } - @Override + @Override public int hashCode() { int result = 17; result = 31 * result + (id == null ? 0: id.hashCode()); diff --git a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/User.java index 4f0a64671e2..ea7018078dd 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/User.java @@ -116,17 +116,17 @@ public boolean equals(Object o) { return false; } User user = (User) o; - return (id == null ? user.id == null : id.equals(user.id)) && - (username == null ? user.username == null : username.equals(user.username)) && - (firstName == null ? user.firstName == null : firstName.equals(user.firstName)) && - (lastName == null ? user.lastName == null : lastName.equals(user.lastName)) && - (email == null ? user.email == null : email.equals(user.email)) && - (password == null ? user.password == null : password.equals(user.password)) && - (phone == null ? user.phone == null : phone.equals(user.phone)) && - (userStatus == null ? user.userStatus == null : userStatus.equals(user.userStatus)); + return (this.id == null ? user.id == null : this.id.equals(user.id)) && + (this.username == null ? user.username == null : this.username.equals(user.username)) && + (this.firstName == null ? user.firstName == null : this.firstName.equals(user.firstName)) && + (this.lastName == null ? user.lastName == null : this.lastName.equals(user.lastName)) && + (this.email == null ? user.email == null : this.email.equals(user.email)) && + (this.password == null ? user.password == null : this.password.equals(user.password)) && + (this.phone == null ? user.phone == null : this.phone.equals(user.phone)) && + (this.userStatus == null ? user.userStatus == null : this.userStatus.equals(user.userStatus)); } - @Override + @Override public int hashCode() { int result = 17; result = 31 * result + (id == null ? 0: id.hashCode()); diff --git a/samples/client/petstore/android/volley/docs/PetApi.md b/samples/client/petstore/android/volley/docs/PetApi.md index f0f8ad40fbe..7b5585e3f58 100644 --- a/samples/client/petstore/android/volley/docs/PetApi.md +++ b/samples/client/petstore/android/volley/docs/PetApi.md @@ -128,7 +128,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | [optional] [default to available] + **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | [optional] [default to available] [enum: available, pending, sold] ### Return type diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Category.java index 58f427e5554..70342c4d4fd 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Category.java @@ -67,8 +67,8 @@ public boolean equals(Object o) { return false; } Category category = (Category) o; - return (id == null ? category.id == null : id.equals(category.id)) && - (name == null ? category.name == null : name.equals(category.name)); + return (this.id == null ? category.id == null : this.id.equals(category.id)) && + (this.name == null ? category.name == null : this.name.equals(category.name)); } @Override diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Order.java index 07d0902d548..dae063be65a 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Order.java @@ -120,12 +120,12 @@ public boolean equals(Object o) { return false; } Order order = (Order) o; - return (id == null ? order.id == null : id.equals(order.id)) && - (petId == null ? order.petId == null : petId.equals(order.petId)) && - (quantity == null ? order.quantity == null : quantity.equals(order.quantity)) && - (shipDate == null ? order.shipDate == null : shipDate.equals(order.shipDate)) && - (status == null ? order.status == null : status.equals(order.status)) && - (complete == null ? order.complete == null : complete.equals(order.complete)); + return (this.id == null ? order.id == null : this.id.equals(order.id)) && + (this.petId == null ? order.petId == null : this.petId.equals(order.petId)) && + (this.quantity == null ? order.quantity == null : this.quantity.equals(order.quantity)) && + (this.shipDate == null ? order.shipDate == null : this.shipDate.equals(order.shipDate)) && + (this.status == null ? order.status == null : this.status.equals(order.status)) && + (this.complete == null ? order.complete == null : this.complete.equals(order.complete)); } @Override diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Pet.java index 2d3fc76f483..dd9db9ae4c0 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Pet.java @@ -122,12 +122,12 @@ public boolean equals(Object o) { return false; } Pet pet = (Pet) o; - return (id == null ? pet.id == null : id.equals(pet.id)) && - (category == null ? pet.category == null : category.equals(pet.category)) && - (name == null ? pet.name == null : name.equals(pet.name)) && - (photoUrls == null ? pet.photoUrls == null : photoUrls.equals(pet.photoUrls)) && - (tags == null ? pet.tags == null : tags.equals(pet.tags)) && - (status == null ? pet.status == null : status.equals(pet.status)); + return (this.id == null ? pet.id == null : this.id.equals(pet.id)) && + (this.category == null ? pet.category == null : this.category.equals(pet.category)) && + (this.name == null ? pet.name == null : this.name.equals(pet.name)) && + (this.photoUrls == null ? pet.photoUrls == null : this.photoUrls.equals(pet.photoUrls)) && + (this.tags == null ? pet.tags == null : this.tags.equals(pet.tags)) && + (this.status == null ? pet.status == null : this.status.equals(pet.status)); } @Override diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Tag.java index a65f1968f63..92401c61c39 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Tag.java @@ -67,8 +67,8 @@ public boolean equals(Object o) { return false; } Tag tag = (Tag) o; - return (id == null ? tag.id == null : id.equals(tag.id)) && - (name == null ? tag.name == null : name.equals(tag.name)); + return (this.id == null ? tag.id == null : this.id.equals(tag.id)) && + (this.name == null ? tag.name == null : this.name.equals(tag.name)); } @Override diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/User.java index 5b3ad5c44c4..2e24880b456 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/User.java @@ -140,14 +140,14 @@ public boolean equals(Object o) { return false; } User user = (User) o; - return (id == null ? user.id == null : id.equals(user.id)) && - (username == null ? user.username == null : username.equals(user.username)) && - (firstName == null ? user.firstName == null : firstName.equals(user.firstName)) && - (lastName == null ? user.lastName == null : lastName.equals(user.lastName)) && - (email == null ? user.email == null : email.equals(user.email)) && - (password == null ? user.password == null : password.equals(user.password)) && - (phone == null ? user.phone == null : phone.equals(user.phone)) && - (userStatus == null ? user.userStatus == null : userStatus.equals(user.userStatus)); + return (this.id == null ? user.id == null : this.id.equals(user.id)) && + (this.username == null ? user.username == null : this.username.equals(user.username)) && + (this.firstName == null ? user.firstName == null : this.firstName.equals(user.firstName)) && + (this.lastName == null ? user.lastName == null : this.lastName.equals(user.lastName)) && + (this.email == null ? user.email == null : this.email.equals(user.email)) && + (this.password == null ? user.password == null : this.password.equals(user.password)) && + (this.phone == null ? user.phone == null : this.phone.equals(user.phone)) && + (this.userStatus == null ? user.userStatus == null : this.userStatus.equals(user.userStatus)); } @Override From 2a77dbdd4c9ed61f8541eed7750c6bd191c261c4 Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 26 Aug 2016 00:10:10 +0800 Subject: [PATCH 279/470] add emc --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 70bbcef5275..ecc5ab07da6 100644 --- a/README.md +++ b/README.md @@ -758,6 +758,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [DecentFoX](http://decentfox.com/) - [DocuSign](https://www.docusign.com) - [Ergon](http://www.ergon.ch/) +- [EMC](https://www.emc.com/) - [eureka](http://eure.jp/) - [everystory.us](http://everystory.us) - [Expected Behavior](http://www.expectedbehavior.com/) From c0a72fdcd638612a9b760f336ebeec0518cceaa2 Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 26 Aug 2016 10:46:18 +0800 Subject: [PATCH 280/470] add QuantiModo --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index ecc5ab07da6..46bb7adb4fa 100644 --- a/README.md +++ b/README.md @@ -785,6 +785,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [Plexxi](http://www.plexxi.com) - [Pixoneye](http://www.pixoneye.com/) - [PostAffiliatePro](https://www.postaffiliatepro.com/) +- [QuantiModo](https://quantimo.do/) - [Rapid7](https://rapid7.com/) - [Reload! A/S](https://reload.dk/) - [REstore](https://www.restore.eu) From be0233c609e6b3355567fe7909bbb6b5e0c08023 Mon Sep 17 00:00:00 2001 From: Guo Huang Date: Thu, 25 Aug 2016 21:44:57 -0700 Subject: [PATCH 281/470] [Go] fixing code gen not recognizing 'object' type issue --- .../main/java/io/swagger/codegen/languages/GoClientCodegen.java | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java index 93eecd03251..3a2c0435b49 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java @@ -100,6 +100,7 @@ public GoClientCodegen() { // the correct solution is to use []byte typeMapping.put("binary", "string"); typeMapping.put("ByteArray", "string"); + typeMapping.put("object", "interface{}"); importMapping = new HashMap(); importMapping.put("time.Time", "time"); From b4c139f19ba73e7e0cacae2fa030df7215647d87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Sat, 27 Aug 2016 02:34:33 +0300 Subject: [PATCH 282/470] Spelling fixes --- README.md | 2 +- .../examples/swagger.yaml | 4 ++-- .../java/io/swagger/codegen/DefaultCodegen.java | 10 +++++----- .../codegen/languages/AbstractJavaCodegen.java | 2 +- .../codegen/languages/GoClientCodegen.java | 4 ++-- .../codegen/languages/Qt5CPPGenerator.java | 2 +- .../Java/libraries/okhttp-gson/JSON.mustache | 2 +- .../main/resources/JavaInflector/api.mustache | 2 +- .../main/resources/TypeScript-Fetch/README.md | 2 +- .../src/main/resources/flash/Response.as | 2 +- .../src/main/resources/flash/build.properties | 2 +- .../src/main/resources/flash/build.xml | 2 +- .../resources/objc/ApiClient-header.mustache | 2 +- .../objc/ResponseDeserializer-body.mustache | 2 +- .../main/resources/perl/Configuration.mustache | 2 +- .../src/main/resources/ruby/api_client.mustache | 2 +- ...ular2AdditionalPropertiesIntegrationTest.java | 10 +++++----- .../TypescriptAngular2ArrayAndObjectTest.java | 10 +++++----- .../TypescriptNodeES5IntegrationTest.java | 12 ++++++------ .../src/test/resources/1_2/petstore-1.2/pet | 4 ++-- .../src/test/resources/2_0/globalSecurity.json | 4 ++-- .../src/test/resources/2_0/petstore-orig.json | 4 ++-- .../src/test/resources/2_0/petstore.json | 4 ++-- .../.swagger-codegen-ignore | 2 +- .../.swagger-codegen-ignore | 2 +- .../node-es5-expected/.swagger-codegen-ignore | 2 +- .../src/test/resources/petstore.json | 4 ++-- .../src/test/resources/petstore.json | 4 ++-- .../src/main/java/io/swagger/client/JSON.java | 2 +- .../objc/SwaggerClient/Core/SWGApiClient.h | 2 +- .../SwaggerClient/Core/SWGResponseDeserializer.m | 2 +- .../lib/Something/Deep/Configuration.pm | 2 +- .../perl/lib/WWW/SwaggerClient/Configuration.pm | 2 +- .../ruby/lib/petstore/api_client.rb | 2 +- .../typescript-fetch/README.md | 2 +- .../petstore/android/httpclient/docs/PetApi.md | 4 ++-- .../main/java/io/swagger/client/api/PetApi.java | 4 ++-- .../android/volley/.swagger-codegen-ignore | 2 +- .../petstore/android/volley/docs/PetApi.md | 4 ++-- .../main/java/io/swagger/client/api/PetApi.java | 8 ++++---- .../clojure/src/swagger_petstore/api/pet.clj | 4 ++-- .../petstore/cpprest/.swagger-codegen-ignore | 2 +- .../csharp/SwaggerClient/.swagger-codegen-ignore | 2 +- .../client/petstore/flash/flash/build.properties | 2 +- samples/client/petstore/flash/flash/build.xml | 2 +- .../flash/flash/src/io/swagger/event/Response.as | 2 +- .../flash/src/main/flex/build.properties | 2 +- .../petstore/flash/src/main/flex/build.xml | 2 +- .../flex/io/swagger/swagger/event/Response.as | 2 +- .../go/go-petstore/.swagger-codegen-ignore | 2 +- .../petstore/groovy/.swagger-codegen-ignore | 2 +- .../src/main/java/io/swagger/client/JSON.java | 2 +- .../javascript-closure-angular/lib/goog/base.js | 2 +- .../javascript-promise/.swagger-codegen-ignore | 2 +- .../petstore/javascript/.swagger-codegen-ignore | 2 +- .../objc/core-data/.swagger-codegen-ignore | 2 +- .../objc/core-data/SwaggerClient/Api/SWGPetApi.h | 4 ++-- .../objc/core-data/SwaggerClient/Api/SWGPetApi.m | 4 ++-- .../core-data/SwaggerClient/Core/SWGApiClient.h | 2 +- .../SwaggerClient/Core/SWGResponseDeserializer.m | 2 +- .../objc/default/.swagger-codegen-ignore | 2 +- .../objc/default/SwaggerClient/Api/SWGPetApi.h | 4 ++-- .../objc/default/SwaggerClient/Api/SWGPetApi.m | 4 ++-- .../default/SwaggerClient/Core/SWGApiClient.h | 2 +- .../SwaggerClient/Core/SWGResponseDeserializer.m | 2 +- .../petstore/objc/default/docs/SWGPetApi.md | 4 ++-- .../client/petstore/perl/.swagger-codegen-ignore | 2 +- .../perl/lib/WWW/SwaggerClient/Configuration.pm | 2 +- .../client/petstore/php/.swagger-codegen-ignore | 2 +- .../petstore/python/.swagger-codegen-ignore | 2 +- .../client/petstore/ruby/.swagger-codegen-ignore | 2 +- .../petstore/ruby/lib/petstore/api_client.rb | 2 +- .../petstore/scala/.swagger-codegen-ignore | 2 +- .../spring-stubs/.swagger-codegen-ignore | 2 +- .../swift-promisekit/.swagger-codegen-ignore | 2 +- .../petstore/swift/.swagger-codegen-ignore | 2 +- .../Classes/Swaggers/APIs/PetAPI.swift | 4 ++-- .../SwaggerClientTests/Pods/Alamofire/README.md | 2 +- .../swift/promisekit/.swagger-codegen-ignore | 2 +- .../Classes/Swaggers/APIs/PetAPI.swift | 4 ++-- .../SwaggerClientTests/Pods/Alamofire/README.md | 2 +- .../Categories/Foundation/afterlife.swift | 2 +- .../UIKit/UIViewController+AnyPromise.h | 2 +- .../Pods/PromiseKit/README.markdown | 4 ++-- .../Pods/PromiseKit/Sources/AnyPromise.h | 4 ++-- .../Pods/PromiseKit/Sources/Promise.swift | 4 ++-- .../Classes/Swaggers/APIs/PetAPI.swift | 4 ++-- .../Pods/RxSwift/RxSwift/Errors.swift | 6 +++--- .../RxSwift/RxSwift/ImmediateSchedulerType.swift | 2 +- .../Pods/RxSwift/RxSwift/ObservableType.swift | 2 +- .../Observables/Observable+Creation.swift | 2 +- .../Pods/RxSwift/RxSwift/ObserverType.swift | 2 +- .../ConcurrentDispatchQueueScheduler.swift | 2 +- .../Schedulers/ConcurrentMainScheduler.swift | 2 +- .../RxSwift/Schedulers/ImmediateScheduler.swift | 2 +- .../Schedulers/SchedulerServices+Emulation.swift | 2 +- .../SerialDispatchQueueScheduler.swift | 2 +- .../Schedulers/VirtualTimeScheduler.swift | 2 +- .../typescript-angular/API/Client/PetApi.ts | 4 ++-- .../typescript-angular2/default/api/PetApi.ts | 4 ++-- .../typescript-angular2/npm/api/PetApi.ts | 4 ++-- .../builds/default/.swagger-codegen-ignore | 2 +- .../typescript-fetch/builds/default/README.md | 2 +- .../typescript-fetch/builds/default/api.ts | 16 ++++++++-------- .../builds/es6-target/.swagger-codegen-ignore | 2 +- .../typescript-fetch/builds/es6-target/README.md | 2 +- .../typescript-fetch/builds/es6-target/api.ts | 16 ++++++++-------- .../with-npm-version/.swagger-codegen-ignore | 2 +- .../builds/with-npm-version/README.md | 2 +- .../builds/with-npm-version/api.ts | 16 ++++++++-------- .../default/.swagger-codegen-ignore | 2 +- .../petstore/typescript-node/default/api.js | 4 ++-- .../petstore/typescript-node/default/api.ts | 4 ++-- .../client/petstore/typescript-node/npm/api.ts | 4 ++-- .../container-interop/docs/ContainerInterface.md | 2 +- .../container-interop/docs/Delegate-lookup.md | 2 +- .../vendor/pimple/pimple/ext/pimple/pimple.c | 2 +- .../slim/vendor/slim/slim/Slim/App.php | 2 +- .../go-api-server/.swagger-codegen-ignore | 2 +- .../java/io/swagger/handler/FakeController.java | 2 +- .../java/io/swagger/handler/PetController.java | 2 +- .../java/io/swagger/handler/StoreController.java | 2 +- .../java/io/swagger/handler/UserController.java | 2 +- .../com/ibm/ws/petstoresample/api/PetsApi.java | 4 ++-- samples/server/petstore/jaxrs-spec/swagger.json | 4 ++-- .../petstore/rails5/.swagger-codegen-ignore | 2 +- .../petstore/scalatra/.swagger-codegen-ignore | 2 +- .../petstore/sinatra/.swagger-codegen-ignore | 2 +- .../server/petstore/slim/.swagger-codegen-ignore | 2 +- .../container-interop/docs/ContainerInterface.md | 2 +- .../container-interop/docs/Delegate-lookup.md | 2 +- .../vendor/pimple/pimple/ext/pimple/pimple.c | 2 +- .../petstore/slim/vendor/slim/slim/Slim/App.php | 2 +- .../spring-mvc-j8-async/.swagger-codegen-ignore | 2 +- .../petstore/spring-mvc/.swagger-codegen-ignore | 2 +- samples/yaml/pet.yml | 4 ++-- 136 files changed, 211 insertions(+), 211 deletions(-) diff --git a/README.md b/README.md index 46bb7adb4fa..0dac8820469 100644 --- a/README.md +++ b/README.md @@ -806,7 +806,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you # Swagger Codegen Core Team -Swaagger Codegen core team members are contributors who have been making signficiant contributions (review issues, fix bugs, make enhancements, etc) to the project on a regular basis. +Swaagger Codegen core team members are contributors who have been making significant contributions (review issues, fix bugs, make enhancements, etc) to the project on a regular basis. ## API Clients | Languages | Core Team (join date) | diff --git a/modules/swagger-codegen-maven-plugin/examples/swagger.yaml b/modules/swagger-codegen-maven-plugin/examples/swagger.yaml index c6eeffab7d7..c6d37b25750 100644 --- a/modules/swagger-codegen-maven-plugin/examples/swagger.yaml +++ b/modules/swagger-codegen-maven-plugin/examples/swagger.yaml @@ -93,7 +93,7 @@ paths: tags: - "pet" summary: "Finds Pets by status" - description: "Multiple status values can be provided with comma seperated strings" + description: "Multiple status values can be provided with comma separated strings" operationId: "findPetsByStatus" produces: - "application/xml" @@ -130,7 +130,7 @@ paths: tags: - "pet" summary: "Finds Pets by tags" - description: "Muliple tags can be provided with comma seperated strings. Use\ + description: "Multiple tags can be provided with comma separated strings. Use\ \ tag1, tag2, tag3 for testing." operationId: "findPetsByTags" produces: 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 3ddba67f0d8..aaa49ea79f6 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 @@ -256,7 +256,7 @@ public String findCommonPrefixOfVars(List vars) { } /** - * Return the enum default value in the language specifed format + * Return the enum default value in the language specified format * * @param value enum variable name * @param datatype data type @@ -267,7 +267,7 @@ public String toEnumDefaultValue(String value, String datatype) { } /** - * Return the enum value in the language specifed format + * Return the enum value in the language specified format * e.g. status becomes "status" * * @param value enum variable name @@ -358,7 +358,7 @@ public String escapeText(String input) { * @return string with unsafe characters removed or escaped */ public String escapeUnsafeCharacters(String input) { - LOGGER.warn("escapeUnsafeCharacters should be overriden in the code generator with proper logic to escape unsafe characters"); + LOGGER.warn("escapeUnsafeCharacters should be overridden in the code generator with proper logic to escape unsafe characters"); // doing nothing by default and code generator should implement // the logic to prevent code injection // later we'll make this method abstract to make sure @@ -372,7 +372,7 @@ public String escapeUnsafeCharacters(String input) { * @return string with quotation mark removed or escaped */ public String escapeQuotationMark(String input) { - LOGGER.warn("escapeQuotationMark should be overriden in the code generator with proper logic to escape single/double quote"); + LOGGER.warn("escapeQuotationMark should be overridden in the code generator with proper logic to escape single/double quote"); return input.replace("\"", "\\\""); } @@ -3171,7 +3171,7 @@ public void writeOptional(String outputFolder, SupportingFile supportingFile) { */ public void setParameterBooleanFlagWithCodegenProperty(CodegenParameter parameter, CodegenProperty property) { if (parameter == null) { - LOGGER.error("Codegen Parameter cannnot be null."); + LOGGER.error("Codegen Parameter cannot be null."); return; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java index ee1061d8a74..5078328554a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java @@ -643,7 +643,7 @@ public void postProcessParameter(CodegenParameter parameter) { } @Override public Map postProcessModels(Map objs) { - // recursivly add import for mapping one type to multipe imports + // recursively add import for mapping one type to multiple imports List> recursiveImports = (List>) objs.get("imports"); if (recursiveImports == null) return objs; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java index 68fdb6c9938..4529f126d90 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java @@ -412,7 +412,7 @@ public Map postProcessOperations(Map objs) { } - // recursivly add import for mapping one type to multipe imports + // recursively add import for mapping one type to multiple imports List> recursiveImports = (List>) objs.get("imports"); if (recursiveImports == null) return objs; @@ -442,7 +442,7 @@ public Map postProcessModels(Map objs) { iterator.remove(); } - // recursivly add import for mapping one type to multipe imports + // recursively add import for mapping one type to multiple imports List> recursiveImports = (List>) objs.get("imports"); if (recursiveImports == null) return objs; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java index d922b6aec5a..9cfdc0c143b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java @@ -273,7 +273,7 @@ public String toDefaultValue(Property p) { return "0L"; } else if (p instanceof BaseIntegerProperty) { // catchall for any other format of the swagger specifiction - // integer type not explictly handled above + // integer type not explicitly handled above return "0"; } else if (p instanceof DecimalProperty) { return "0.0"; diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache index bc1176ff8c5..3c199a941bd 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache @@ -89,7 +89,7 @@ public class JSON { * * @param Type * @param body The JSON string - * @param returnType The type to deserialize inot + * @param returnType The type to deserialize into * @return The deserialized Java object */ @SuppressWarnings("unchecked") diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/api.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/api.mustache index 0a5e225306c..71056d37509 100644 --- a/modules/swagger-codegen/src/main/resources/JavaInflector/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/api.mustache @@ -18,7 +18,7 @@ import {{modelPackage}}.*; public class {{classname}} { /** * Uncomment and implement as you see fit. These operations will map - * Direclty to operation calls from the routing logic. Because the inflector + * Directly to operation calls from the routing logic. Because the inflector * Code allows you to implement logic incrementally, they are disabled. **/ diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/README.md b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/README.md index db2dfccec36..664e1755933 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/README.md +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/README.md @@ -26,7 +26,7 @@ CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user #### NPM #### You may publish the module to NPM. In this case, you would be able to install the module as any other NPM module. It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). -You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink everytime you deploy that project. +You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink every time you deploy that project. You can also directly install the module using `npm install file_path`. If you do `npm install file_path --save`, NPM will save relative path to `package.json`. In this case, `npm install` and `npm shrinkwrap` may misbehave. You would need to manually edit `package.json` and replace it with absolute path. diff --git a/modules/swagger-codegen/src/main/resources/flash/Response.as b/modules/swagger-codegen/src/main/resources/flash/Response.as index a43b7980a38..d19dd0ae358 100644 --- a/modules/swagger-codegen/src/main/resources/flash/Response.as +++ b/modules/swagger-codegen/src/main/resources/flash/Response.as @@ -12,7 +12,7 @@ public class Response { public var isSuccess:Boolean; /** - * The payload of the succesful operation eg. a Word in a WordRequest + * The payload of the successful operation eg. a Word in a WordRequest */ public var payload:Object; diff --git a/modules/swagger-codegen/src/main/resources/flash/build.properties b/modules/swagger-codegen/src/main/resources/flash/build.properties index 8e77d88c961..356f112b144 100644 --- a/modules/swagger-codegen/src/main/resources/flash/build.properties +++ b/modules/swagger-codegen/src/main/resources/flash/build.properties @@ -4,7 +4,7 @@ title=Sample app AS3 SDK API Documentation #Path to the source folder where the .as files are located sourcepath = ./src/main/flex -# Class-folders you want to search for classes to be included in the docs, seperated by spaces (for example ../com/ ../net/ ) +# Class-folders you want to search for classes to be included in the docs, separated by spaces (for example ../com/ ../net/ ) # to include every .as and .mxml file within your project, just state ../ domainextensions = ./src/main/flex diff --git a/modules/swagger-codegen/src/main/resources/flash/build.xml b/modules/swagger-codegen/src/main/resources/flash/build.xml index 4f021b0b8b2..9b84a466b76 100644 --- a/modules/swagger-codegen/src/main/resources/flash/build.xml +++ b/modules/swagger-codegen/src/main/resources/flash/build.xml @@ -17,7 +17,7 @@ - + diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache index be5eba32ee0..74ffd6f78c1 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache @@ -128,7 +128,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; /** * Updates header parameters and query parameters for authentication * - * @param headers The header parameter will be udpated, passed by pointer to pointer. + * @param headers The header parameter will be updated, passed by pointer to pointer. * @param querys The query parameters will be updated, passed by pointer to pointer. * @param authSettings The authentication names NSArray. */ diff --git a/modules/swagger-codegen/src/main/resources/objc/ResponseDeserializer-body.mustache b/modules/swagger-codegen/src/main/resources/objc/ResponseDeserializer-body.mustache index 812ed061c04..4d303fc344f 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ResponseDeserializer-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ResponseDeserializer-body.mustache @@ -223,7 +223,7 @@ NSInteger const {{classPrefix}}UnknownResponseObjectErrorCode = 143528; } -(NSError *)unknownResponseErrorWithExpectedType:(NSString *)expected data:(id)data { - NSString * message = [NSString stringWithFormat:NSLocalizedString(@"Unknown response expected type %@ [reponse: %@]",nil),expected,data]; + NSString * message = [NSString stringWithFormat:NSLocalizedString(@"Unknown response expected type %@ [response: %@]",nil),expected,data]; NSDictionary * userInfo = @{NSLocalizedDescriptionKey : message}; return [NSError errorWithDomain:{{classPrefix}}DeserializationErrorDomainKey code:{{classPrefix}}UnknownResponseObjectErrorCode userInfo:userInfo]; } diff --git a/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache b/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache index 500d816b178..8fc7ef1a579 100644 --- a/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache @@ -19,7 +19,7 @@ use constant VERSION => '{{moduleVersion}}'; our $http_timeout = 180; our $http_user_agent = 'Perl-Swagger'; -# authenticaiton setting +# authentication setting our $api_key = {}; our $api_key_prefix = {}; our $api_key_in = {}; 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 3e65c72e932..c845b82f409 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache @@ -118,7 +118,7 @@ module {{moduleName}} # application/json; charset=UTF8 # APPLICATION/JSON # @param [String] mime MIME - # @return [Boolean] True if the MIME is applicaton/json + # @return [Boolean] True if the MIME is application/json def json_mime?(mime) !(mime =~ /\Aapplication\/json(;.*)?\z/i).nil? end diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypescriptAngular2AdditionalPropertiesIntegrationTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypescriptAngular2AdditionalPropertiesIntegrationTest.java index 8b23105f28c..db3121c1dc0 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypescriptAngular2AdditionalPropertiesIntegrationTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypescriptAngular2AdditionalPropertiesIntegrationTest.java @@ -17,12 +17,12 @@ protected CodegenConfig getCodegenConfig() { @Override protected Map configProperties() { - Map propeties = new HashMap<>(); - propeties.put("npmName", "additionalPropertiesTest"); - propeties.put("npmVersion", "1.0.2"); - propeties.put("snapshot", "false"); + Map properties = new HashMap<>(); + properties.put("npmName", "additionalPropertiesTest"); + properties.put("npmVersion", "1.0.2"); + properties.put("snapshot", "false"); - return propeties; + return properties; } @Override diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypescriptAngular2ArrayAndObjectTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypescriptAngular2ArrayAndObjectTest.java index b9a8868a6b8..e60f06ca57d 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypescriptAngular2ArrayAndObjectTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypescriptAngular2ArrayAndObjectTest.java @@ -17,12 +17,12 @@ protected CodegenConfig getCodegenConfig() { @Override protected Map configProperties() { - Map propeties = new HashMap<>(); - propeties.put("npmName", "arrayAndAnyTest"); - propeties.put("npmVersion", "1.0.2"); - propeties.put("snapshot", "false"); + Map properties = new HashMap<>(); + properties.put("npmName", "arrayAndAnyTest"); + properties.put("npmVersion", "1.0.2"); + properties.put("snapshot", "false"); - return propeties; + return properties; } @Override diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypescriptNodeES5IntegrationTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypescriptNodeES5IntegrationTest.java index 22bac4ea316..5bf54ceee85 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypescriptNodeES5IntegrationTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypescriptNodeES5IntegrationTest.java @@ -17,13 +17,13 @@ protected CodegenConfig getCodegenConfig() { @Override protected Map configProperties() { - Map propeties = new HashMap<>(); - propeties.put("npmName", "node-es6-test"); - propeties.put("npmVersion", "1.0.3"); - propeties.put("snapshot", "false"); - propeties.put("supportsES6", "false"); + Map properties = new HashMap<>(); + properties.put("npmName", "node-es6-test"); + properties.put("npmVersion", "1.0.3"); + properties.put("snapshot", "false"); + properties.put("supportsES6", "false"); - return propeties; + return properties; } @Override diff --git a/modules/swagger-codegen/src/test/resources/1_2/petstore-1.2/pet b/modules/swagger-codegen/src/test/resources/1_2/petstore-1.2/pet index 4a8439a4424..9ee8ba2b8e4 100644 --- a/modules/swagger-codegen/src/test/resources/1_2/petstore-1.2/pet +++ b/modules/swagger-codegen/src/test/resources/1_2/petstore-1.2/pet @@ -246,7 +246,7 @@ { "method": "GET", "summary": "Finds Pets by status", - "notes": "Multiple status values can be provided with comma seperated strings", + "notes": "Multiple status values can be provided with comma separated strings", "type": "array", "items": { "$ref": "Pet" @@ -283,7 +283,7 @@ { "method": "GET", "summary": "Finds Pets by tags", - "notes": "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", + "notes": "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", "type": "array", "items": { "$ref": "Pet" diff --git a/modules/swagger-codegen/src/test/resources/2_0/globalSecurity.json b/modules/swagger-codegen/src/test/resources/2_0/globalSecurity.json index 36fa87664ae..cc302bbf5a7 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/globalSecurity.json +++ b/modules/swagger-codegen/src/test/resources/2_0/globalSecurity.json @@ -113,7 +113,7 @@ "pet" ], "summary": "Finds Pets by status", - "description": "Multiple status values can be provided with comma seperated strings", + "description": "Multiple status values can be provided with comma separated strings", "operationId": "findPetsByStatus", "produces": [ "application/json", @@ -163,7 +163,7 @@ "pet" ], "summary": "Finds Pets by tags", - "description": "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", + "description": "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", "operationId": "findPetsByTags", "produces": [ "application/json", diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore-orig.json b/modules/swagger-codegen/src/test/resources/2_0/petstore-orig.json index 7422817fea7..58577dd2f52 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore-orig.json +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore-orig.json @@ -113,7 +113,7 @@ "pet" ], "summary": "Finds Pets by status", - "description": "Multiple status values can be provided with comma seperated strings", + "description": "Multiple status values can be provided with comma separated strings", "operationId": "findPetsByStatus", "produces": [ "application/json", @@ -163,7 +163,7 @@ "pet" ], "summary": "Finds Pets by tags", - "description": "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", + "description": "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", "operationId": "findPetsByTags", "produces": [ "application/json", diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore.json b/modules/swagger-codegen/src/test/resources/2_0/petstore.json index 24fcf4bf768..be0254ec3a2 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore.json +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore.json @@ -114,7 +114,7 @@ "pet" ], "summary": "Finds Pets by status", - "description": "Multiple status values can be provided with comma seperated strings", + "description": "Multiple status values can be provided with comma separated strings", "operationId": "findPetsByStatus", "produces": [ "application/json", @@ -174,7 +174,7 @@ "pet" ], "summary": "Finds Pets by tags", - "description": "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", + "description": "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", "operationId": "findPetsByTags", "produces": [ "application/json", diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/.swagger-codegen-ignore b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/.swagger-codegen-ignore +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/additional-properties-expected/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/.swagger-codegen-ignore b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/.swagger-codegen-ignore +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/array-and-object-expected/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/node-es5-expected/.swagger-codegen-ignore b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/node-es5-expected/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/modules/swagger-codegen/src/test/resources/integrationtests/typescript/node-es5-expected/.swagger-codegen-ignore +++ b/modules/swagger-codegen/src/test/resources/integrationtests/typescript/node-es5-expected/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/modules/swagger-codegen/src/test/resources/petstore.json b/modules/swagger-codegen/src/test/resources/petstore.json index 66762d74b2b..dd9b1f42edf 100644 --- a/modules/swagger-codegen/src/test/resources/petstore.json +++ b/modules/swagger-codegen/src/test/resources/petstore.json @@ -113,7 +113,7 @@ "pet" ], "summary": "Finds Pets by status", - "description": "Multiple status values can be provided with comma seperated strings", + "description": "Multiple status values can be provided with comma separated strings", "operationId": "findPetsByStatus", "produces": [ "application/json", @@ -163,7 +163,7 @@ "pet" ], "summary": "Finds Pets by tags", - "description": "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", + "description": "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", "operationId": "findPetsByTags", "produces": [ "application/json", diff --git a/modules/swagger-generator/src/test/resources/petstore.json b/modules/swagger-generator/src/test/resources/petstore.json index 67c4d47292d..1617f8d0ae6 100644 --- a/modules/swagger-generator/src/test/resources/petstore.json +++ b/modules/swagger-generator/src/test/resources/petstore.json @@ -135,7 +135,7 @@ "pet" ], "summary": "Finds Pets by status", - "description": "Multiple status values can be provided with comma seperated strings", + "description": "Multiple status values can be provided with comma separated strings", "operationId": "findPetsByStatus", "produces": [ "application/xml", @@ -190,7 +190,7 @@ "pet" ], "summary": "Finds Pets by tags", - "description": "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", + "description": "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", "operationId": "findPetsByTags", "produces": [ "application/xml", diff --git a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java index 6053b748e3c..ba757cd0d3d 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java @@ -100,7 +100,7 @@ public String serialize(Object obj) { * * @param Type * @param body The JSON string - * @param returnType The type to deserialize inot + * @param returnType The type to deserialize into * @return The deserialized Java object */ public T deserialize(String body, Type returnType) { diff --git a/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGApiClient.h b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGApiClient.h index 47e66aa1a3b..3421219f37d 100644 --- a/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGApiClient.h +++ b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGApiClient.h @@ -150,7 +150,7 @@ extern NSString *const SWGResponseObjectErrorKey; /** * Updates header parameters and query parameters for authentication * - * @param headers The header parameter will be udpated, passed by pointer to pointer. + * @param headers The header parameter will be updated, passed by pointer to pointer. * @param querys The query parameters will be updated, passed by pointer to pointer. * @param authSettings The authentication names NSArray. */ diff --git a/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGResponseDeserializer.m b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGResponseDeserializer.m index a0efd1d5927..6ac9f75e818 100644 --- a/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGResponseDeserializer.m +++ b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGResponseDeserializer.m @@ -223,7 +223,7 @@ -(NSError *)emptyValueOccurredError { } -(NSError *)unknownResponseErrorWithExpectedType:(NSString *)expected data:(id)data { - NSString * message = [NSString stringWithFormat:NSLocalizedString(@"Unknown response expected type %@ [reponse: %@]",nil),expected,data]; + NSString * message = [NSString stringWithFormat:NSLocalizedString(@"Unknown response expected type %@ [response: %@]",nil),expected,data]; NSDictionary * userInfo = @{NSLocalizedDescriptionKey : message}; return [NSError errorWithDomain:SWGDeserializationErrorDomainKey code:SWGUnknownResponseObjectErrorCode userInfo:userInfo]; } diff --git a/samples/client/petstore-security-test/perl/deep_module_test/lib/Something/Deep/Configuration.pm b/samples/client/petstore-security-test/perl/deep_module_test/lib/Something/Deep/Configuration.pm index c6a1121dcdf..10a61cedce2 100644 --- a/samples/client/petstore-security-test/perl/deep_module_test/lib/Something/Deep/Configuration.pm +++ b/samples/client/petstore-security-test/perl/deep_module_test/lib/Something/Deep/Configuration.pm @@ -44,7 +44,7 @@ use constant VERSION => '1.0.0'; our $http_timeout = 180; our $http_user_agent = 'Perl-Swagger'; -# authenticaiton setting +# authentication setting our $api_key = {}; our $api_key_prefix = {}; our $api_key_in = {}; diff --git a/samples/client/petstore-security-test/perl/lib/WWW/SwaggerClient/Configuration.pm b/samples/client/petstore-security-test/perl/lib/WWW/SwaggerClient/Configuration.pm index 711ffb70d56..fb5d0c6e675 100644 --- a/samples/client/petstore-security-test/perl/lib/WWW/SwaggerClient/Configuration.pm +++ b/samples/client/petstore-security-test/perl/lib/WWW/SwaggerClient/Configuration.pm @@ -44,7 +44,7 @@ use constant VERSION => '1.0.0'; our $http_timeout = 180; our $http_user_agent = 'Perl-Swagger'; -# authenticaiton setting +# authentication setting our $api_key = {}; our $api_key_prefix = {}; our $api_key_in = {}; diff --git a/samples/client/petstore-security-test/ruby/lib/petstore/api_client.rb b/samples/client/petstore-security-test/ruby/lib/petstore/api_client.rb index a198cd74008..9bdf0103a99 100644 --- a/samples/client/petstore-security-test/ruby/lib/petstore/api_client.rb +++ b/samples/client/petstore-security-test/ruby/lib/petstore/api_client.rb @@ -135,7 +135,7 @@ def build_request(http_method, path, opts = {}) # application/json; charset=UTF8 # APPLICATION/JSON # @param [String] mime MIME - # @return [Boolean] True if the MIME is applicaton/json + # @return [Boolean] True if the MIME is application/json def json_mime?(mime) !(mime =~ /\Aapplication\/json(;.*)?\z/i).nil? end diff --git a/samples/client/petstore-security-test/typescript-fetch/README.md b/samples/client/petstore-security-test/typescript-fetch/README.md index db2dfccec36..664e1755933 100644 --- a/samples/client/petstore-security-test/typescript-fetch/README.md +++ b/samples/client/petstore-security-test/typescript-fetch/README.md @@ -26,7 +26,7 @@ CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user #### NPM #### You may publish the module to NPM. In this case, you would be able to install the module as any other NPM module. It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). -You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink everytime you deploy that project. +You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink every time you deploy that project. You can also directly install the module using `npm install file_path`. If you do `npm install file_path --save`, NPM will save relative path to `package.json`. In this case, `npm install` and `npm shrinkwrap` may misbehave. You would need to manually edit `package.json` and replace it with absolute path. diff --git a/samples/client/petstore/android/httpclient/docs/PetApi.md b/samples/client/petstore/android/httpclient/docs/PetApi.md index 7b5585e3f58..e7b393c8ea7 100644 --- a/samples/client/petstore/android/httpclient/docs/PetApi.md +++ b/samples/client/petstore/android/httpclient/docs/PetApi.md @@ -106,7 +106,7 @@ null (empty response body) Finds Pets by status -Multiple status values can be provided with comma seperated strings +Multiple status values can be provided with comma separated strings ### Example ```java @@ -149,7 +149,7 @@ Name | Type | Description | Notes Finds Pets by tags -Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. ### Example ```java diff --git a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/PetApi.java index 3960e910f6c..086378eb0ca 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/PetApi.java @@ -168,7 +168,7 @@ public void deletePet (Long petId, String apiKey) throws ApiException { } /** * Finds Pets by status - * Multiple status values can be provided with comma seperated strings + * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter * @return List */ @@ -218,7 +218,7 @@ public List findPetsByStatus (List status) throws ApiException { } /** * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by * @return List */ diff --git a/samples/client/petstore/android/volley/.swagger-codegen-ignore b/samples/client/petstore/android/volley/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/android/volley/.swagger-codegen-ignore +++ b/samples/client/petstore/android/volley/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/samples/client/petstore/android/volley/docs/PetApi.md b/samples/client/petstore/android/volley/docs/PetApi.md index 7b5585e3f58..e7b393c8ea7 100644 --- a/samples/client/petstore/android/volley/docs/PetApi.md +++ b/samples/client/petstore/android/volley/docs/PetApi.md @@ -106,7 +106,7 @@ null (empty response body) Finds Pets by status -Multiple status values can be provided with comma seperated strings +Multiple status values can be provided with comma separated strings ### Example ```java @@ -149,7 +149,7 @@ Name | Type | Description | Notes Finds Pets by tags -Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. ### Example ```java diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/PetApi.java index 49cd00cd2fd..ae9bcead7c5 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/PetApi.java @@ -327,7 +327,7 @@ public void onErrorResponse(VolleyError error) { } /** * Finds Pets by status - * Multiple status values can be provided with comma seperated strings + * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter * @return List */ @@ -392,7 +392,7 @@ public List findPetsByStatus (List status) throws TimeoutException, /** * Finds Pets by status - * Multiple status values can be provided with comma seperated strings + * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ public void findPetsByStatus (List status, final Response.Listener> responseListener, final Response.ErrorListener errorListener) { @@ -454,7 +454,7 @@ public void onErrorResponse(VolleyError error) { } /** * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by * @return List */ @@ -519,7 +519,7 @@ public List findPetsByTags (List tags) throws TimeoutException, Exe /** * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ public void findPetsByTags (List tags, final Response.Listener> responseListener, final Response.ErrorListener errorListener) { diff --git a/samples/client/petstore/clojure/src/swagger_petstore/api/pet.clj b/samples/client/petstore/clojure/src/swagger_petstore/api/pet.clj index a455838c8fc..96c1cf85fc2 100644 --- a/samples/client/petstore/clojure/src/swagger_petstore/api/pet.clj +++ b/samples/client/petstore/clojure/src/swagger_petstore/api/pet.clj @@ -90,7 +90,7 @@ (defn find-pets-by-tags-with-http-info "Finds Pets by tags - Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing." + Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing." ([] (find-pets-by-tags-with-http-info nil)) ([{:keys [tags ]}] (call-api "/pet/findByTags" :get @@ -104,7 +104,7 @@ (defn find-pets-by-tags "Finds Pets by tags - Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing." + Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing." ([] (find-pets-by-tags nil)) ([optional-params] (:data (find-pets-by-tags-with-http-info optional-params)))) diff --git a/samples/client/petstore/cpprest/.swagger-codegen-ignore b/samples/client/petstore/cpprest/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/cpprest/.swagger-codegen-ignore +++ b/samples/client/petstore/cpprest/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/samples/client/petstore/csharp/SwaggerClient/.swagger-codegen-ignore b/samples/client/petstore/csharp/SwaggerClient/.swagger-codegen-ignore index 61ed08d3455..7a6a67e36cc 100644 --- a/samples/client/petstore/csharp/SwaggerClient/.swagger-codegen-ignore +++ b/samples/client/petstore/csharp/SwaggerClient/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/samples/client/petstore/flash/flash/build.properties b/samples/client/petstore/flash/flash/build.properties index 8e77d88c961..356f112b144 100644 --- a/samples/client/petstore/flash/flash/build.properties +++ b/samples/client/petstore/flash/flash/build.properties @@ -4,7 +4,7 @@ title=Sample app AS3 SDK API Documentation #Path to the source folder where the .as files are located sourcepath = ./src/main/flex -# Class-folders you want to search for classes to be included in the docs, seperated by spaces (for example ../com/ ../net/ ) +# Class-folders you want to search for classes to be included in the docs, separated by spaces (for example ../com/ ../net/ ) # to include every .as and .mxml file within your project, just state ../ domainextensions = ./src/main/flex diff --git a/samples/client/petstore/flash/flash/build.xml b/samples/client/petstore/flash/flash/build.xml index 4f021b0b8b2..9b84a466b76 100644 --- a/samples/client/petstore/flash/flash/build.xml +++ b/samples/client/petstore/flash/flash/build.xml @@ -17,7 +17,7 @@ - + diff --git a/samples/client/petstore/flash/flash/src/io/swagger/event/Response.as b/samples/client/petstore/flash/flash/src/io/swagger/event/Response.as index a43b7980a38..d19dd0ae358 100644 --- a/samples/client/petstore/flash/flash/src/io/swagger/event/Response.as +++ b/samples/client/petstore/flash/flash/src/io/swagger/event/Response.as @@ -12,7 +12,7 @@ public class Response { public var isSuccess:Boolean; /** - * The payload of the succesful operation eg. a Word in a WordRequest + * The payload of the successful operation eg. a Word in a WordRequest */ public var payload:Object; diff --git a/samples/client/petstore/flash/src/main/flex/build.properties b/samples/client/petstore/flash/src/main/flex/build.properties index 8e77d88c961..356f112b144 100644 --- a/samples/client/petstore/flash/src/main/flex/build.properties +++ b/samples/client/petstore/flash/src/main/flex/build.properties @@ -4,7 +4,7 @@ title=Sample app AS3 SDK API Documentation #Path to the source folder where the .as files are located sourcepath = ./src/main/flex -# Class-folders you want to search for classes to be included in the docs, seperated by spaces (for example ../com/ ../net/ ) +# Class-folders you want to search for classes to be included in the docs, separated by spaces (for example ../com/ ../net/ ) # to include every .as and .mxml file within your project, just state ../ domainextensions = ./src/main/flex diff --git a/samples/client/petstore/flash/src/main/flex/build.xml b/samples/client/petstore/flash/src/main/flex/build.xml index 4f021b0b8b2..9b84a466b76 100644 --- a/samples/client/petstore/flash/src/main/flex/build.xml +++ b/samples/client/petstore/flash/src/main/flex/build.xml @@ -17,7 +17,7 @@ - + diff --git a/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/event/Response.as b/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/event/Response.as index a43b7980a38..d19dd0ae358 100644 --- a/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/event/Response.as +++ b/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/event/Response.as @@ -12,7 +12,7 @@ public class Response { public var isSuccess:Boolean; /** - * The payload of the succesful operation eg. a Word in a WordRequest + * The payload of the successful operation eg. a Word in a WordRequest */ public var payload:Object; diff --git a/samples/client/petstore/go/go-petstore/.swagger-codegen-ignore b/samples/client/petstore/go/go-petstore/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/go/go-petstore/.swagger-codegen-ignore +++ b/samples/client/petstore/go/go-petstore/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/samples/client/petstore/groovy/.swagger-codegen-ignore b/samples/client/petstore/groovy/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/groovy/.swagger-codegen-ignore +++ b/samples/client/petstore/groovy/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java index 540611eab9d..99f9bab36ac 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java @@ -100,7 +100,7 @@ public String serialize(Object obj) { * * @param Type * @param body The JSON string - * @param returnType The type to deserialize inot + * @param returnType The type to deserialize into * @return The deserialized Java object */ @SuppressWarnings("unchecked") diff --git a/samples/client/petstore/javascript-closure-angular/lib/goog/base.js b/samples/client/petstore/javascript-closure-angular/lib/goog/base.js index 58674377024..c1f3b579582 100644 --- a/samples/client/petstore/javascript-closure-angular/lib/goog/base.js +++ b/samples/client/petstore/javascript-closure-angular/lib/goog/base.js @@ -284,7 +284,7 @@ goog.addDependency = function(relPath, provides, requires) { // NOTE(nnaze): The debug DOM loader was included in base.js as an orignal // way to do "debug-mode" development. The dependency system can sometimes -// be confusing, as can the debug DOM loader's asyncronous nature. +// be confusing, as can the debug DOM loader's asynchronous nature. // // With the DOM loader, a call to goog.require() is not blocking -- the // script will not load until some point after the current script. If a diff --git a/samples/client/petstore/javascript-promise/.swagger-codegen-ignore b/samples/client/petstore/javascript-promise/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/javascript-promise/.swagger-codegen-ignore +++ b/samples/client/petstore/javascript-promise/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/samples/client/petstore/javascript/.swagger-codegen-ignore b/samples/client/petstore/javascript/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/javascript/.swagger-codegen-ignore +++ b/samples/client/petstore/javascript/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/samples/client/petstore/objc/core-data/.swagger-codegen-ignore b/samples/client/petstore/objc/core-data/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/objc/core-data/.swagger-codegen-ignore +++ b/samples/client/petstore/objc/core-data/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.h b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.h index 97f914a627e..6c3303848f8 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.h +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.h @@ -61,7 +61,7 @@ extern NSInteger kSWGPetApiMissingParamErrorCode; /// Finds Pets by status -/// Multiple status values can be provided with comma seperated strings +/// Multiple status values can be provided with comma separated strings /// /// @param status Status values that need to be considered for filter (optional) (default to available) /// @@ -74,7 +74,7 @@ extern NSInteger kSWGPetApiMissingParamErrorCode; /// Finds Pets by tags -/// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. +/// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. /// /// @param tags Tags to filter by (optional) /// diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.m b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.m index e35421fc520..76d707cdb42 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.m +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.m @@ -208,7 +208,7 @@ -(NSNumber*) deletePetWithPetId: (NSNumber*) petId /// /// Finds Pets by status -/// Multiple status values can be provided with comma seperated strings +/// Multiple status values can be provided with comma separated strings /// @param status Status values that need to be considered for filter (optional, default to available) /// /// @returns NSArray* @@ -270,7 +270,7 @@ -(NSNumber*) findPetsByStatusWithStatus: (NSArray*) status /// /// Finds Pets by tags -/// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. +/// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. /// @param tags Tags to filter by (optional) /// /// @returns NSArray* diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGApiClient.h b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGApiClient.h index 2ec5c9b0fcc..a5f267821d8 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGApiClient.h +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGApiClient.h @@ -154,7 +154,7 @@ extern NSString *const SWGResponseObjectErrorKey; /** * Updates header parameters and query parameters for authentication * - * @param headers The header parameter will be udpated, passed by pointer to pointer. + * @param headers The header parameter will be updated, passed by pointer to pointer. * @param querys The query parameters will be updated, passed by pointer to pointer. * @param authSettings The authentication names NSArray. */ diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGResponseDeserializer.m b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGResponseDeserializer.m index a0efd1d5927..6ac9f75e818 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGResponseDeserializer.m +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGResponseDeserializer.m @@ -223,7 +223,7 @@ -(NSError *)emptyValueOccurredError { } -(NSError *)unknownResponseErrorWithExpectedType:(NSString *)expected data:(id)data { - NSString * message = [NSString stringWithFormat:NSLocalizedString(@"Unknown response expected type %@ [reponse: %@]",nil),expected,data]; + NSString * message = [NSString stringWithFormat:NSLocalizedString(@"Unknown response expected type %@ [response: %@]",nil),expected,data]; NSDictionary * userInfo = @{NSLocalizedDescriptionKey : message}; return [NSError errorWithDomain:SWGDeserializationErrorDomainKey code:SWGUnknownResponseObjectErrorCode userInfo:userInfo]; } diff --git a/samples/client/petstore/objc/default/.swagger-codegen-ignore b/samples/client/petstore/objc/default/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/objc/default/.swagger-codegen-ignore +++ b/samples/client/petstore/objc/default/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.h b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.h index 97f914a627e..6c3303848f8 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.h +++ b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.h @@ -61,7 +61,7 @@ extern NSInteger kSWGPetApiMissingParamErrorCode; /// Finds Pets by status -/// Multiple status values can be provided with comma seperated strings +/// Multiple status values can be provided with comma separated strings /// /// @param status Status values that need to be considered for filter (optional) (default to available) /// @@ -74,7 +74,7 @@ extern NSInteger kSWGPetApiMissingParamErrorCode; /// Finds Pets by tags -/// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. +/// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. /// /// @param tags Tags to filter by (optional) /// diff --git a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.m b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.m index e35421fc520..76d707cdb42 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.m @@ -208,7 +208,7 @@ -(NSNumber*) deletePetWithPetId: (NSNumber*) petId /// /// Finds Pets by status -/// Multiple status values can be provided with comma seperated strings +/// Multiple status values can be provided with comma separated strings /// @param status Status values that need to be considered for filter (optional, default to available) /// /// @returns NSArray* @@ -270,7 +270,7 @@ -(NSNumber*) findPetsByStatusWithStatus: (NSArray*) status /// /// Finds Pets by tags -/// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. +/// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. /// @param tags Tags to filter by (optional) /// /// @returns NSArray* diff --git a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApiClient.h b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApiClient.h index 2ec5c9b0fcc..a5f267821d8 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApiClient.h +++ b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApiClient.h @@ -154,7 +154,7 @@ extern NSString *const SWGResponseObjectErrorKey; /** * Updates header parameters and query parameters for authentication * - * @param headers The header parameter will be udpated, passed by pointer to pointer. + * @param headers The header parameter will be updated, passed by pointer to pointer. * @param querys The query parameters will be updated, passed by pointer to pointer. * @param authSettings The authentication names NSArray. */ diff --git a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGResponseDeserializer.m b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGResponseDeserializer.m index a0efd1d5927..6ac9f75e818 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGResponseDeserializer.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGResponseDeserializer.m @@ -223,7 +223,7 @@ -(NSError *)emptyValueOccurredError { } -(NSError *)unknownResponseErrorWithExpectedType:(NSString *)expected data:(id)data { - NSString * message = [NSString stringWithFormat:NSLocalizedString(@"Unknown response expected type %@ [reponse: %@]",nil),expected,data]; + NSString * message = [NSString stringWithFormat:NSLocalizedString(@"Unknown response expected type %@ [response: %@]",nil),expected,data]; NSDictionary * userInfo = @{NSLocalizedDescriptionKey : message}; return [NSError errorWithDomain:SWGDeserializationErrorDomainKey code:SWGUnknownResponseObjectErrorCode userInfo:userInfo]; } diff --git a/samples/client/petstore/objc/default/docs/SWGPetApi.md b/samples/client/petstore/objc/default/docs/SWGPetApi.md index 92fb2c4de81..9971ffff450 100644 --- a/samples/client/petstore/objc/default/docs/SWGPetApi.md +++ b/samples/client/petstore/objc/default/docs/SWGPetApi.md @@ -130,7 +130,7 @@ void (empty response body) Finds Pets by status -Multiple status values can be provided with comma seperated strings +Multiple status values can be provided with comma separated strings ### Example ```objc @@ -185,7 +185,7 @@ Name | Type | Description | Notes Finds Pets by tags -Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. ### Example ```objc diff --git a/samples/client/petstore/perl/.swagger-codegen-ignore b/samples/client/petstore/perl/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/perl/.swagger-codegen-ignore +++ b/samples/client/petstore/perl/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm index d6f50b46251..fa58024872b 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm @@ -44,7 +44,7 @@ use constant VERSION => '1.0.0'; our $http_timeout = 180; our $http_user_agent = 'Perl-Swagger'; -# authenticaiton setting +# authentication setting our $api_key = {}; our $api_key_prefix = {}; our $api_key_in = {}; diff --git a/samples/client/petstore/php/.swagger-codegen-ignore b/samples/client/petstore/php/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/php/.swagger-codegen-ignore +++ b/samples/client/petstore/php/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/samples/client/petstore/python/.swagger-codegen-ignore b/samples/client/petstore/python/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/python/.swagger-codegen-ignore +++ b/samples/client/petstore/python/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/samples/client/petstore/ruby/.swagger-codegen-ignore b/samples/client/petstore/ruby/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/ruby/.swagger-codegen-ignore +++ b/samples/client/petstore/ruby/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/samples/client/petstore/ruby/lib/petstore/api_client.rb b/samples/client/petstore/ruby/lib/petstore/api_client.rb index 52ba90b2082..c8170709bb6 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_client.rb @@ -135,7 +135,7 @@ def build_request(http_method, path, opts = {}) # application/json; charset=UTF8 # APPLICATION/JSON # @param [String] mime MIME - # @return [Boolean] True if the MIME is applicaton/json + # @return [Boolean] True if the MIME is application/json def json_mime?(mime) !(mime =~ /\Aapplication\/json(;.*)?\z/i).nil? end diff --git a/samples/client/petstore/scala/.swagger-codegen-ignore b/samples/client/petstore/scala/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/scala/.swagger-codegen-ignore +++ b/samples/client/petstore/scala/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/samples/client/petstore/spring-stubs/.swagger-codegen-ignore b/samples/client/petstore/spring-stubs/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/spring-stubs/.swagger-codegen-ignore +++ b/samples/client/petstore/spring-stubs/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/samples/client/petstore/swift-promisekit/.swagger-codegen-ignore b/samples/client/petstore/swift-promisekit/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/swift-promisekit/.swagger-codegen-ignore +++ b/samples/client/petstore/swift-promisekit/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/samples/client/petstore/swift/.swagger-codegen-ignore b/samples/client/petstore/swift/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/swift/.swagger-codegen-ignore +++ b/samples/client/petstore/swift/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index 6e4ddc4227b..a64e2da9b57 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -104,7 +104,7 @@ public class PetAPI: APIBase { /** Finds Pets by status - GET /pet/findByStatus - - Multiple status values can be provided with comma seperated strings + - Multiple status values can be provided with comma separated strings - OAuth: - type: oauth2 - name: petstore_auth @@ -153,7 +153,7 @@ public class PetAPI: APIBase { /** Finds Pets by tags - GET /pet/findByTags - - Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + - Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - OAuth: - type: oauth2 - name: petstore_auth diff --git a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/README.md b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/README.md index 56a6771636c..cce2041d9d9 100644 --- a/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/README.md +++ b/samples/client/petstore/swift/default/SwaggerClientTests/Pods/Alamofire/README.md @@ -1288,7 +1288,7 @@ The [ASF](https://github.com/Alamofire/Foundation#members) is looking to raise m * Potentially fund test servers to make it easier for us to test the edge cases * Potentially fund developers to work on one of our projects full-time -The community adoption of the ASF libraries has been amazing. We are greatly humbled by your enthusiam around the projects, and want to continue to do everything we can to move the needle forward. With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. If you use any of our libraries for work, see if your employers would be interested in donating. Our initial goal is to raise $1000 to get all our legal ducks in a row and kickstart this campaign. Any amount you can donate today to help us reach our goal would be greatly appreciated. +The community adoption of the ASF libraries has been amazing. We are greatly humbled by your enthusiasm around the projects, and want to continue to do everything we can to move the needle forward. With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. If you use any of our libraries for work, see if your employers would be interested in donating. Our initial goal is to raise $1000 to get all our legal ducks in a row and kickstart this campaign. Any amount you can donate today to help us reach our goal would be greatly appreciated. Click here to lend your support to: Alamofire Software Foundation and make a donation at pledgie.com ! diff --git a/samples/client/petstore/swift/promisekit/.swagger-codegen-ignore b/samples/client/petstore/swift/promisekit/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/swift/promisekit/.swagger-codegen-ignore +++ b/samples/client/petstore/swift/promisekit/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index 27000da5417..8388537a83e 100644 --- a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -156,7 +156,7 @@ public class PetAPI: APIBase { /** Finds Pets by status - GET /pet/findByStatus - - Multiple status values can be provided with comma seperated strings + - Multiple status values can be provided with comma separated strings - OAuth: - type: oauth2 - name: petstore_auth @@ -222,7 +222,7 @@ public class PetAPI: APIBase { /** Finds Pets by tags - GET /pet/findByTags - - Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + - Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - OAuth: - type: oauth2 - name: petstore_auth diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/README.md b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/README.md index 56a6771636c..cce2041d9d9 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/README.md +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Alamofire/README.md @@ -1288,7 +1288,7 @@ The [ASF](https://github.com/Alamofire/Foundation#members) is looking to raise m * Potentially fund test servers to make it easier for us to test the edge cases * Potentially fund developers to work on one of our projects full-time -The community adoption of the ASF libraries has been amazing. We are greatly humbled by your enthusiam around the projects, and want to continue to do everything we can to move the needle forward. With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. If you use any of our libraries for work, see if your employers would be interested in donating. Our initial goal is to raise $1000 to get all our legal ducks in a row and kickstart this campaign. Any amount you can donate today to help us reach our goal would be greatly appreciated. +The community adoption of the ASF libraries has been amazing. We are greatly humbled by your enthusiasm around the projects, and want to continue to do everything we can to move the needle forward. With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. If you use any of our libraries for work, see if your employers would be interested in donating. Our initial goal is to raise $1000 to get all our legal ducks in a row and kickstart this campaign. Any amount you can donate today to help us reach our goal would be greatly appreciated. Click here to lend your support to: Alamofire Software Foundation and make a donation at pledgie.com ! diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/afterlife.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/afterlife.swift index 06d5aa5c825..fa52fbf2f25 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/afterlife.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/Foundation/afterlife.swift @@ -6,7 +6,7 @@ import PromiseKit /** @return A promise that resolves when the provided object deallocates - @warning *Important* The promise is not guarenteed to resolve immediately + @warning *Important* The promise is not guaranteed to resolve immediately when the provided object is deallocated. So you cannot write code that depends on exact timing. */ diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIViewController+AnyPromise.h b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIViewController+AnyPromise.h index b131488df70..f36a07658b9 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIViewController+AnyPromise.h +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Categories/UIKit/UIViewController+AnyPromise.h @@ -77,7 +77,7 @@ @interface UIViewController (PMKUnavailable) #define PMKRationale \ - "The promiseViewController system has been rennovated: the fullfil and " \ + "The promiseViewController system has been renovated: the fullfil and " \ "reject category methods have been removed due to runtime safety " \ "concerns and instead you should implement a -promise property on your " \ "view controller subclass. @see promiseViewController:animated:completion:" diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/README.markdown b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/README.markdown index 84aabe138db..8fee72c0d70 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/README.markdown +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/README.markdown @@ -22,7 +22,7 @@ PromiseKit is a thoughtful and complete implementation of promises for iOS and O # Which PromiseKit Should I Use? -If you are writing a library, [**use PromiseKit 1.x**](https://github.com/mxcl/PromiseKit/tree/legacy-1.x). This is because PromiseKit > 2 breaks everytime Swift changes. While Swift is in flux it is not feasible to depend on a library that will break every time Xcode updates. +If you are writing a library, [**use PromiseKit 1.x**](https://github.com/mxcl/PromiseKit/tree/legacy-1.x). This is because PromiseKit > 2 breaks every time Swift changes. While Swift is in flux it is not feasible to depend on a library that will break every time Xcode updates. If you are making an app then PromiseKit 3 is the best PromiseKit, you may have to make some fixes when Xcode updates, but probably you will be OK as long as you update PromiseKit when Xcode updates. @@ -35,7 +35,7 @@ Thus we intend to support PromiseKit 1.x for longer than expected. # PromiseKit 3 -In Swift 2.0 `catch` and `defer` became reserved keywords mandating we rename our functions with these names. This forced a major semantic version change on PromiseKit and thus we took the opportunity to make other minor (source compatability breaking) improvements. +In Swift 2.0 `catch` and `defer` became reserved keywords mandating we rename our functions with these names. This forced a major semantic version change on PromiseKit and thus we took the opportunity to make other minor (source compatibility breaking) improvements. Thus if you cannot afford to adapt to PromiseKit 3 but still want to use Xcode-7.0/Swift-2.0 we provide a [minimal changes branch] where `catch` and `defer` are renamed `catch_` and `defer_` and all other changes are the bare minimum to make PromiseKit 2 compile against Swift 2. diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.h b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.h index 5a76d4d7147..b76075f3f73 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.h +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/AnyPromise.h @@ -75,7 +75,7 @@ typedef NS_ENUM(NSInteger, PMKCatchPolicy) { @warning *Note* Cancellation errors are not caught. - @warning *Note* Since catch is a c++ keyword, this method is not availble in Objective-C++ files. Instead use catchWithPolicy. + @warning *Note* Since catch is a c++ keyword, this method is not available in Objective-C++ files. Instead use catchWithPolicy. @see catchWithPolicy */ @@ -126,7 +126,7 @@ typedef NS_ENUM(NSInteger, PMKCatchPolicy) { /** Creates a resolved promise. - When developing your own promise systems, it is ocassionally useful to be able to return an already resolved promise. + When developing your own promise systems, it is occasionally useful to be able to return an already resolved promise. @param value The value with which to resolve this promise. Passing an `NSError` will cause the promise to be rejected, otherwise the promise will be fulfilled. diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Promise.swift b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Promise.swift index 477d1109bb1..96e2cd3ba79 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Promise.swift +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/PromiseKit/Sources/Promise.swift @@ -47,7 +47,7 @@ public class Promise { } - Parameter resolvers: The provided closure is called immediately. - Inside, execute your asynchronous system, calling fulfill if it suceeds + Inside, execute your asynchronous system, calling fulfill if it succeeds and reject for any errors. - Returns: return A new promise. @@ -532,7 +532,7 @@ public let zalgo: dispatch_queue_t = dispatch_queue_create("Zalgo", nil) then is going to take a while and doesn’t interact with the UI. Please note (again) that generally you should not use zalgo or waldo. The - performance gains are neglible and we provide these functions only out of + performance gains are negligible and we provide these functions only out of a misguided sense that library code should be as optimized as possible. If you use zalgo or waldo without tests proving their correctness you may unwillingly introduce horrendous, near-impossible-to-trace bugs. diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index ee5d73bf4c7..d0df54bebc2 100644 --- a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -162,7 +162,7 @@ public class PetAPI: APIBase { /** Finds Pets by status - GET /pet/findByStatus - - Multiple status values can be provided with comma seperated strings + - Multiple status values can be provided with comma separated strings - OAuth: - type: oauth2 - name: petstore_auth @@ -230,7 +230,7 @@ public class PetAPI: APIBase { /** Finds Pets by tags - GET /pet/findByTags - - Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + - Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - OAuth: - type: oauth2 - name: petstore_auth diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Errors.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Errors.swift index ccb71c198a8..3ac4ac9e92d 100644 --- a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Errors.swift +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Errors.swift @@ -18,7 +18,7 @@ public enum RxError : ErrorType , CustomDebugStringConvertible { /** - Unknown error occured. + Unknown error occurred. */ case Unknown /** @@ -54,11 +54,11 @@ public extension RxError { public var debugDescription: String { switch self { case .Unknown: - return "Unknown error occured." + return "Unknown error occurred." case .Disposed(let object): return "Object `\(object)` was already disposed." case .Overflow: - return "Arithmetic overflow occured." + return "Arithmetic overflow occurred." case .ArgumentOutOfRange: return "Argument out of range." case .NoElements: diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift index b14b9abdaee..c4345e96f50 100644 --- a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift @@ -13,7 +13,7 @@ Represents an object that immediately schedules units of work. */ public protocol ImmediateSchedulerType { /** - Schedules an action to be executed immediatelly. + Schedules an action to be executed immediately. - parameter state: State passed to the action to be executed. - parameter action: Action to be executed. diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObservableType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObservableType.swift index 5608ac03fd5..4f7037845a5 100644 --- a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObservableType.swift +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObservableType.swift @@ -35,7 +35,7 @@ public protocol ObservableType : ObservableConvertibleType { When sequence sends `Complete` or `Error` event all internal resources that compute sequence elements will be freed. - To cancel production of sequence elements and free resources immediatelly, call `dispose` on returned + To cancel production of sequence elements and free resources immediately, call `dispose` on returned subscription. - returns: Subscription for `observer` that can be used to cancel production of sequence elements and free resources. diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Creation.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Creation.swift index f14f9c285a2..acd3b8e5b9f 100644 --- a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Creation.swift +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Observables/Observable+Creation.swift @@ -103,7 +103,7 @@ extension Observable { - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) - parameter elements: Elements to generate. - - parameter scheduler: Scheduler to send elements on. If `nil`, elements are sent immediatelly on subscription. + - parameter scheduler: Scheduler to send elements on. If `nil`, elements are sent immediately on subscription. - returns: The observable sequence whose elements are pulled from the given arguments. */ @warn_unused_result(message="http://git.io/rxs.uo") diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObserverType.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObserverType.swift index 0cd46e3967a..5a7f3341e44 100644 --- a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObserverType.swift +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/ObserverType.swift @@ -20,7 +20,7 @@ public protocol ObserverType { /** Notify observer about sequence event. - - parameter event: Event that occured. + - parameter event: Event that occurred. */ func on(event: Event) } diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift index 3f8207aa6a1..7b8d8fec7a3 100644 --- a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift @@ -56,7 +56,7 @@ public class ConcurrentDispatchQueueScheduler: SchedulerType { } /** - Schedules an action to be executed immediatelly. + Schedules an action to be executed immediately. - parameter state: State passed to the action to be executed. - parameter action: Action to be executed. diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift index c26be800cf5..beac999bf51 100644 --- a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift @@ -39,7 +39,7 @@ public final class ConcurrentMainScheduler : SchedulerType { public static let instance = ConcurrentMainScheduler(mainScheduler: MainScheduler.instance) /** - Schedules an action to be executed immediatelly. + Schedules an action to be executed immediately. - parameter state: State passed to the action to be executed. - parameter action: Action to be executed. diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ImmediateScheduler.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ImmediateScheduler.swift index fc54fd5120a..4371c5ec03b 100644 --- a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ImmediateScheduler.swift +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/ImmediateScheduler.swift @@ -16,7 +16,7 @@ private class ImmediateScheduler : ImmediateSchedulerType { private let _asyncLock = AsyncLock() /** - Schedules an action to be executed immediatelly. + Schedules an action to be executed immediately. In case `schedule` is called recursively from inside of `action` callback, scheduled `action` will be enqueued and executed after current `action`. (`AsyncLock` behavior) diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift index 3906d7a708b..a7523a815d0 100644 --- a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift @@ -45,7 +45,7 @@ class SchedulePeriodicRecursive { case .Tick: scheduler.schedule(.Tick, dueTime: _period) - // The idea is that if on tick there wasn't any item enqueued, schedule to perform work immediatelly. + // The idea is that if on tick there wasn't any item enqueued, schedule to perform work immediately. // Else work will be scheduled after previous enqueued work completes. if AtomicIncrement(&_pendingTickCount) == 1 { self.tick(.DispatchStart, scheduler: scheduler) diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift index 8376f9a4326..ad2e31537fc 100644 --- a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift @@ -92,7 +92,7 @@ public class SerialDispatchQueueScheduler: SchedulerType { } /** - Schedules an action to be executed immediatelly. + Schedules an action to be executed immediately. - parameter state: State passed to the action to be executed. - parameter action: Action to be executed. diff --git a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift index 9c480619e24..d365bd0df0f 100644 --- a/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift +++ b/samples/client/petstore/swift/rxswift/SwaggerClientTests/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift @@ -66,7 +66,7 @@ public class VirtualTimeScheduler } /** - Schedules an action to be executed immediatelly. + Schedules an action to be executed immediately. - parameter state: State passed to the action to be executed. - parameter action: Action to be executed. diff --git a/samples/client/petstore/typescript-angular/API/Client/PetApi.ts b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts index 0cc69189b40..db385440a97 100644 --- a/samples/client/petstore/typescript-angular/API/Client/PetApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts @@ -109,7 +109,7 @@ namespace API.Client { } /** * Finds Pets by status - * Multiple status values can be provided with comma seperated strings + * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ public findPetsByStatus (status?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise> { @@ -137,7 +137,7 @@ namespace API.Client { } /** * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ public findPetsByTags (tags?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise> { diff --git a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts index c030a169cb4..a217fbe8532 100644 --- a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts @@ -106,7 +106,7 @@ export class PetApi { /** * Finds Pets by status - * Multiple status values can be provided with comma seperated strings + * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ public findPetsByStatus (status?: Array, extraHttpRequestParams?: any ) : Observable> { @@ -136,7 +136,7 @@ export class PetApi { /** * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ public findPetsByTags (tags?: Array, extraHttpRequestParams?: any ) : Observable> { diff --git a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts index c030a169cb4..a217fbe8532 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts @@ -106,7 +106,7 @@ export class PetApi { /** * Finds Pets by status - * Multiple status values can be provided with comma seperated strings + * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ public findPetsByStatus (status?: Array, extraHttpRequestParams?: any ) : Observable> { @@ -136,7 +136,7 @@ export class PetApi { /** * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ public findPetsByTags (tags?: Array, extraHttpRequestParams?: any ) : Observable> { diff --git a/samples/client/petstore/typescript-fetch/builds/default/.swagger-codegen-ignore b/samples/client/petstore/typescript-fetch/builds/default/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/typescript-fetch/builds/default/.swagger-codegen-ignore +++ b/samples/client/petstore/typescript-fetch/builds/default/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/samples/client/petstore/typescript-fetch/builds/default/README.md b/samples/client/petstore/typescript-fetch/builds/default/README.md index db2dfccec36..664e1755933 100644 --- a/samples/client/petstore/typescript-fetch/builds/default/README.md +++ b/samples/client/petstore/typescript-fetch/builds/default/README.md @@ -26,7 +26,7 @@ CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user #### NPM #### You may publish the module to NPM. In this case, you would be able to install the module as any other NPM module. It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). -You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink everytime you deploy that project. +You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink every time you deploy that project. You can also directly install the module using `npm install file_path`. If you do `npm install file_path --save`, NPM will save relative path to `package.json`. In this case, `npm install` and `npm shrinkwrap` may misbehave. You would need to manually edit `package.json` and replace it with absolute path. diff --git a/samples/client/petstore/typescript-fetch/builds/default/api.ts b/samples/client/petstore/typescript-fetch/builds/default/api.ts index ee15be389c9..7fb386b373e 100644 --- a/samples/client/petstore/typescript-fetch/builds/default/api.ts +++ b/samples/client/petstore/typescript-fetch/builds/default/api.ts @@ -154,7 +154,7 @@ export const PetApiFetchParamCreactor = { }, /** * Finds Pets by status - * Multiple status values can be provided with comma seperated strings + * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ findPetsByStatus(params: { status?: Array; }): FetchArgs { @@ -176,7 +176,7 @@ export const PetApiFetchParamCreactor = { }, /** * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ findPetsByTags(params: { tags?: Array; }): FetchArgs { @@ -348,7 +348,7 @@ export const PetApiFp = { }, /** * Finds Pets by status - * Multiple status values can be provided with comma seperated strings + * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ findPetsByStatus(params: { status?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise> { @@ -365,7 +365,7 @@ export const PetApiFp = { }, /** * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ findPetsByTags(params: { tags?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise> { @@ -477,7 +477,7 @@ export class PetApi extends BaseAPI { } /** * Finds Pets by status - * Multiple status values can be provided with comma seperated strings + * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ findPetsByStatus(params: { status?: Array; }) { @@ -485,7 +485,7 @@ export class PetApi extends BaseAPI { } /** * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ findPetsByTags(params: { tags?: Array; }) { @@ -553,7 +553,7 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { }, /** * Finds Pets by status - * Multiple status values can be provided with comma seperated strings + * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ findPetsByStatus(params: { status?: Array; }) { @@ -561,7 +561,7 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { }, /** * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ findPetsByTags(params: { tags?: Array; }) { diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/.swagger-codegen-ignore b/samples/client/petstore/typescript-fetch/builds/es6-target/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/typescript-fetch/builds/es6-target/.swagger-codegen-ignore +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/README.md b/samples/client/petstore/typescript-fetch/builds/es6-target/README.md index db2dfccec36..664e1755933 100644 --- a/samples/client/petstore/typescript-fetch/builds/es6-target/README.md +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/README.md @@ -26,7 +26,7 @@ CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user #### NPM #### You may publish the module to NPM. In this case, you would be able to install the module as any other NPM module. It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). -You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink everytime you deploy that project. +You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink every time you deploy that project. You can also directly install the module using `npm install file_path`. If you do `npm install file_path --save`, NPM will save relative path to `package.json`. In this case, `npm install` and `npm shrinkwrap` may misbehave. You would need to manually edit `package.json` and replace it with absolute path. diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts b/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts index 96b912c587f..d27ef74f82e 100644 --- a/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts @@ -153,7 +153,7 @@ export const PetApiFetchParamCreactor = { }, /** * Finds Pets by status - * Multiple status values can be provided with comma seperated strings + * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ findPetsByStatus(params: { status?: Array; }): FetchArgs { @@ -175,7 +175,7 @@ export const PetApiFetchParamCreactor = { }, /** * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ findPetsByTags(params: { tags?: Array; }): FetchArgs { @@ -347,7 +347,7 @@ export const PetApiFp = { }, /** * Finds Pets by status - * Multiple status values can be provided with comma seperated strings + * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ findPetsByStatus(params: { status?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise> { @@ -364,7 +364,7 @@ export const PetApiFp = { }, /** * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ findPetsByTags(params: { tags?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise> { @@ -476,7 +476,7 @@ export class PetApi extends BaseAPI { } /** * Finds Pets by status - * Multiple status values can be provided with comma seperated strings + * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ findPetsByStatus(params: { status?: Array; }) { @@ -484,7 +484,7 @@ export class PetApi extends BaseAPI { } /** * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ findPetsByTags(params: { tags?: Array; }) { @@ -552,7 +552,7 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { }, /** * Finds Pets by status - * Multiple status values can be provided with comma seperated strings + * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ findPetsByStatus(params: { status?: Array; }) { @@ -560,7 +560,7 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { }, /** * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ findPetsByTags(params: { tags?: Array; }) { diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/.swagger-codegen-ignore b/samples/client/petstore/typescript-fetch/builds/with-npm-version/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-npm-version/.swagger-codegen-ignore +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/README.md b/samples/client/petstore/typescript-fetch/builds/with-npm-version/README.md index db2dfccec36..664e1755933 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-npm-version/README.md +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/README.md @@ -26,7 +26,7 @@ CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user #### NPM #### You may publish the module to NPM. In this case, you would be able to install the module as any other NPM module. It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). -You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink everytime you deploy that project. +You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink every time you deploy that project. You can also directly install the module using `npm install file_path`. If you do `npm install file_path --save`, NPM will save relative path to `package.json`. In this case, `npm install` and `npm shrinkwrap` may misbehave. You would need to manually edit `package.json` and replace it with absolute path. diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts b/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts index ee15be389c9..7fb386b373e 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts @@ -154,7 +154,7 @@ export const PetApiFetchParamCreactor = { }, /** * Finds Pets by status - * Multiple status values can be provided with comma seperated strings + * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ findPetsByStatus(params: { status?: Array; }): FetchArgs { @@ -176,7 +176,7 @@ export const PetApiFetchParamCreactor = { }, /** * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ findPetsByTags(params: { tags?: Array; }): FetchArgs { @@ -348,7 +348,7 @@ export const PetApiFp = { }, /** * Finds Pets by status - * Multiple status values can be provided with comma seperated strings + * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ findPetsByStatus(params: { status?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise> { @@ -365,7 +365,7 @@ export const PetApiFp = { }, /** * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ findPetsByTags(params: { tags?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise> { @@ -477,7 +477,7 @@ export class PetApi extends BaseAPI { } /** * Finds Pets by status - * Multiple status values can be provided with comma seperated strings + * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ findPetsByStatus(params: { status?: Array; }) { @@ -485,7 +485,7 @@ export class PetApi extends BaseAPI { } /** * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ findPetsByTags(params: { tags?: Array; }) { @@ -553,7 +553,7 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { }, /** * Finds Pets by status - * Multiple status values can be provided with comma seperated strings + * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ findPetsByStatus(params: { status?: Array; }) { @@ -561,7 +561,7 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { }, /** * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ findPetsByTags(params: { tags?: Array; }) { diff --git a/samples/client/petstore/typescript-node/default/.swagger-codegen-ignore b/samples/client/petstore/typescript-node/default/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/client/petstore/typescript-node/default/.swagger-codegen-ignore +++ b/samples/client/petstore/typescript-node/default/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/samples/client/petstore/typescript-node/default/api.js b/samples/client/petstore/typescript-node/default/api.js index 9a6c0a28ec7..ce78c621a59 100644 --- a/samples/client/petstore/typescript-node/default/api.js +++ b/samples/client/petstore/typescript-node/default/api.js @@ -238,7 +238,7 @@ var PetApi = (function () { }; /** * Finds Pets by status - * Multiple status values can be provided with comma seperated strings + * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ PetApi.prototype.findPetsByStatus = function (status) { @@ -285,7 +285,7 @@ var PetApi = (function () { }; /** * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ PetApi.prototype.findPetsByTags = function (tags) { diff --git a/samples/client/petstore/typescript-node/default/api.ts b/samples/client/petstore/typescript-node/default/api.ts index 02128e1699e..7c61c427008 100644 --- a/samples/client/petstore/typescript-node/default/api.ts +++ b/samples/client/petstore/typescript-node/default/api.ts @@ -300,7 +300,7 @@ export class PetApi { } /** * Finds Pets by status - * Multiple status values can be provided with comma seperated strings + * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ public findPetsByStatus (status?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { @@ -352,7 +352,7 @@ export class PetApi { } /** * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ public findPetsByTags (tags?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { diff --git a/samples/client/petstore/typescript-node/npm/api.ts b/samples/client/petstore/typescript-node/npm/api.ts index 02128e1699e..7c61c427008 100644 --- a/samples/client/petstore/typescript-node/npm/api.ts +++ b/samples/client/petstore/typescript-node/npm/api.ts @@ -300,7 +300,7 @@ export class PetApi { } /** * Finds Pets by status - * Multiple status values can be provided with comma seperated strings + * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ public findPetsByStatus (status?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { @@ -352,7 +352,7 @@ export class PetApi { } /** * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ public findPetsByTags (tags?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { diff --git a/samples/server/petstore-security-test/slim/vendor/container-interop/container-interop/docs/ContainerInterface.md b/samples/server/petstore-security-test/slim/vendor/container-interop/container-interop/docs/ContainerInterface.md index 9f609674c80..b670aa133b4 100644 --- a/samples/server/petstore-security-test/slim/vendor/container-interop/container-interop/docs/ContainerInterface.md +++ b/samples/server/petstore-security-test/slim/vendor/container-interop/container-interop/docs/ContainerInterface.md @@ -12,7 +12,7 @@ interpreted as described in [RFC 2119][]. The word `implementor` in this document is to be interpreted as someone implementing the `ContainerInterface` in a depency injection-related library or framework. -Users of dependency injections containers (DIC) are refered to as `user`. +Users of dependency injections containers (DIC) are referred to as `user`. [RFC 2119]: http://tools.ietf.org/html/rfc2119 diff --git a/samples/server/petstore-security-test/slim/vendor/container-interop/container-interop/docs/Delegate-lookup.md b/samples/server/petstore-security-test/slim/vendor/container-interop/container-interop/docs/Delegate-lookup.md index 04eb3aea023..63cc3fb0f40 100644 --- a/samples/server/petstore-security-test/slim/vendor/container-interop/container-interop/docs/Delegate-lookup.md +++ b/samples/server/petstore-security-test/slim/vendor/container-interop/container-interop/docs/Delegate-lookup.md @@ -15,7 +15,7 @@ interpreted as described in [RFC 2119][]. The word `implementor` in this document is to be interpreted as someone implementing the delegate lookup feature in a dependency injection-related library or framework. -Users of dependency injections containers (DIC) are refered to as `user`. +Users of dependency injections containers (DIC) are referred to as `user`. [RFC 2119]: http://tools.ietf.org/html/rfc2119 diff --git a/samples/server/petstore-security-test/slim/vendor/pimple/pimple/ext/pimple/pimple.c b/samples/server/petstore-security-test/slim/vendor/pimple/pimple/ext/pimple/pimple.c index 239c01d683d..821365bf127 100644 --- a/samples/server/petstore-security-test/slim/vendor/pimple/pimple/ext/pimple/pimple.c +++ b/samples/server/petstore-security-test/slim/vendor/pimple/pimple/ext/pimple/pimple.c @@ -419,7 +419,7 @@ static zval *pimple_object_read_dimension(zval *object, zval *offset, int type T } if (zend_hash_index_exists(&pimple_obj->factories, retval->handle_num)) { - /* Service is a factory, call it everytime and never cache its result */ + /* Service is a factory, call it every time and never cache its result */ PIMPLE_CALL_CB Z_DELREF_P(retval_ptr_ptr); /* fetch dim addr will increment refcount */ return retval_ptr_ptr; diff --git a/samples/server/petstore-security-test/slim/vendor/slim/slim/Slim/App.php b/samples/server/petstore-security-test/slim/vendor/slim/slim/Slim/App.php index 96d82cb81fb..639d9b9b470 100644 --- a/samples/server/petstore-security-test/slim/vendor/slim/slim/Slim/App.php +++ b/samples/server/petstore-security-test/slim/vendor/slim/slim/Slim/App.php @@ -110,7 +110,7 @@ public function add($callable) } /** - * Calling a non-existant method on App checks to see if there's an item + * Calling a non-existent method on App checks to see if there's an item * in the container that is callable and if so, calls it. * * @param string $method diff --git a/samples/server/petstore/go-api-server/.swagger-codegen-ignore b/samples/server/petstore/go-api-server/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/server/petstore/go-api-server/.swagger-codegen-ignore +++ b/samples/server/petstore/go-api-server/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/FakeController.java b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/FakeController.java index e4c99b9eaec..752414ff9ce 100644 --- a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/FakeController.java +++ b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/FakeController.java @@ -18,7 +18,7 @@ public class FakeController { /** * Uncomment and implement as you see fit. These operations will map - * Direclty to operation calls from the routing logic. Because the inflector + * Directly to operation calls from the routing logic. Because the inflector * Code allows you to implement logic incrementally, they are disabled. **/ diff --git a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/PetController.java b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/PetController.java index df14543085c..d1bf6b1b589 100644 --- a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/PetController.java +++ b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/PetController.java @@ -18,7 +18,7 @@ public class PetController { /** * Uncomment and implement as you see fit. These operations will map - * Direclty to operation calls from the routing logic. Because the inflector + * Directly to operation calls from the routing logic. Because the inflector * Code allows you to implement logic incrementally, they are disabled. **/ diff --git a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/StoreController.java b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/StoreController.java index c67931a8461..ee1a74508f0 100644 --- a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/StoreController.java +++ b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/StoreController.java @@ -17,7 +17,7 @@ public class StoreController { /** * Uncomment and implement as you see fit. These operations will map - * Direclty to operation calls from the routing logic. Because the inflector + * Directly to operation calls from the routing logic. Because the inflector * Code allows you to implement logic incrementally, they are disabled. **/ diff --git a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/UserController.java b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/UserController.java index cdb18da0b06..a5ff27d10ba 100644 --- a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/UserController.java +++ b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/UserController.java @@ -17,7 +17,7 @@ public class UserController { /** * Uncomment and implement as you see fit. These operations will map - * Direclty to operation calls from the routing logic. Because the inflector + * Directly to operation calls from the routing logic. Because the inflector * Code allows you to implement logic incrementally, they are disabled. **/ diff --git a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/api/PetsApi.java b/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/api/PetsApi.java index d76844d13a5..bb3beaf9f89 100644 --- a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/api/PetsApi.java +++ b/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/api/PetsApi.java @@ -54,7 +54,7 @@ public Response deletePet(@HeaderParam("api_key") String apiKey,@PathParam("petI @Path("/findByStatus") @Produces({ "application/json", "application/xml" }) - @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma seperated strings", response = Pet.class, responseContainer = "List", authorizations = { + @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { @Authorization(value = "petstore_auth", scopes = { @AuthorizationScope(scope = "write_pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read_pets", description = "read your pets") @@ -71,7 +71,7 @@ public Response findPetsByStatus(@QueryParam("status") List status) { @Path("/findByTags") @Produces({ "application/json", "application/xml" }) - @ApiOperation(value = "Finds Pets by tags", notes = "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { + @ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { @Authorization(value = "petstore_auth", scopes = { @AuthorizationScope(scope = "write_pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read_pets", description = "read your pets") diff --git a/samples/server/petstore/jaxrs-spec/swagger.json b/samples/server/petstore/jaxrs-spec/swagger.json index 5581ce2b405..4524933cd36 100644 --- a/samples/server/petstore/jaxrs-spec/swagger.json +++ b/samples/server/petstore/jaxrs-spec/swagger.json @@ -79,7 +79,7 @@ "get" : { "tags" : [ "pet" ], "summary" : "Finds Pets by status", - "description" : "Multiple status values can be provided with comma seperated strings", + "description" : "Multiple status values can be provided with comma separated strings", "operationId" : "findPetsByStatus", "produces" : [ "application/json", "application/xml" ], "parameters" : [ { @@ -116,7 +116,7 @@ "get" : { "tags" : [ "pet" ], "summary" : "Finds Pets by tags", - "description" : "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", + "description" : "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", "operationId" : "findPetsByTags", "produces" : [ "application/json", "application/xml" ], "parameters" : [ { diff --git a/samples/server/petstore/rails5/.swagger-codegen-ignore b/samples/server/petstore/rails5/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/server/petstore/rails5/.swagger-codegen-ignore +++ b/samples/server/petstore/rails5/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/samples/server/petstore/scalatra/.swagger-codegen-ignore b/samples/server/petstore/scalatra/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/server/petstore/scalatra/.swagger-codegen-ignore +++ b/samples/server/petstore/scalatra/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/samples/server/petstore/sinatra/.swagger-codegen-ignore b/samples/server/petstore/sinatra/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/server/petstore/sinatra/.swagger-codegen-ignore +++ b/samples/server/petstore/sinatra/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/samples/server/petstore/slim/.swagger-codegen-ignore b/samples/server/petstore/slim/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/server/petstore/slim/.swagger-codegen-ignore +++ b/samples/server/petstore/slim/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/samples/server/petstore/slim/vendor/container-interop/container-interop/docs/ContainerInterface.md b/samples/server/petstore/slim/vendor/container-interop/container-interop/docs/ContainerInterface.md index 9f609674c80..b670aa133b4 100644 --- a/samples/server/petstore/slim/vendor/container-interop/container-interop/docs/ContainerInterface.md +++ b/samples/server/petstore/slim/vendor/container-interop/container-interop/docs/ContainerInterface.md @@ -12,7 +12,7 @@ interpreted as described in [RFC 2119][]. The word `implementor` in this document is to be interpreted as someone implementing the `ContainerInterface` in a depency injection-related library or framework. -Users of dependency injections containers (DIC) are refered to as `user`. +Users of dependency injections containers (DIC) are referred to as `user`. [RFC 2119]: http://tools.ietf.org/html/rfc2119 diff --git a/samples/server/petstore/slim/vendor/container-interop/container-interop/docs/Delegate-lookup.md b/samples/server/petstore/slim/vendor/container-interop/container-interop/docs/Delegate-lookup.md index 04eb3aea023..63cc3fb0f40 100644 --- a/samples/server/petstore/slim/vendor/container-interop/container-interop/docs/Delegate-lookup.md +++ b/samples/server/petstore/slim/vendor/container-interop/container-interop/docs/Delegate-lookup.md @@ -15,7 +15,7 @@ interpreted as described in [RFC 2119][]. The word `implementor` in this document is to be interpreted as someone implementing the delegate lookup feature in a dependency injection-related library or framework. -Users of dependency injections containers (DIC) are refered to as `user`. +Users of dependency injections containers (DIC) are referred to as `user`. [RFC 2119]: http://tools.ietf.org/html/rfc2119 diff --git a/samples/server/petstore/slim/vendor/pimple/pimple/ext/pimple/pimple.c b/samples/server/petstore/slim/vendor/pimple/pimple/ext/pimple/pimple.c index 239c01d683d..821365bf127 100644 --- a/samples/server/petstore/slim/vendor/pimple/pimple/ext/pimple/pimple.c +++ b/samples/server/petstore/slim/vendor/pimple/pimple/ext/pimple/pimple.c @@ -419,7 +419,7 @@ static zval *pimple_object_read_dimension(zval *object, zval *offset, int type T } if (zend_hash_index_exists(&pimple_obj->factories, retval->handle_num)) { - /* Service is a factory, call it everytime and never cache its result */ + /* Service is a factory, call it every time and never cache its result */ PIMPLE_CALL_CB Z_DELREF_P(retval_ptr_ptr); /* fetch dim addr will increment refcount */ return retval_ptr_ptr; diff --git a/samples/server/petstore/slim/vendor/slim/slim/Slim/App.php b/samples/server/petstore/slim/vendor/slim/slim/Slim/App.php index 96d82cb81fb..639d9b9b470 100644 --- a/samples/server/petstore/slim/vendor/slim/slim/Slim/App.php +++ b/samples/server/petstore/slim/vendor/slim/slim/Slim/App.php @@ -110,7 +110,7 @@ public function add($callable) } /** - * Calling a non-existant method on App checks to see if there's an item + * Calling a non-existent method on App checks to see if there's an item * in the container that is callable and if so, calls it. * * @param string $method diff --git a/samples/server/petstore/spring-mvc-j8-async/.swagger-codegen-ignore b/samples/server/petstore/spring-mvc-j8-async/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/server/petstore/spring-mvc-j8-async/.swagger-codegen-ignore +++ b/samples/server/petstore/spring-mvc-j8-async/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/samples/server/petstore/spring-mvc/.swagger-codegen-ignore b/samples/server/petstore/spring-mvc/.swagger-codegen-ignore index 19d3377182e..c5fa491b4c5 100644 --- a/samples/server/petstore/spring-mvc/.swagger-codegen-ignore +++ b/samples/server/petstore/spring-mvc/.swagger-codegen-ignore @@ -14,7 +14,7 @@ # You can recursively match patterns against a directory, file or extension with a double asterisk (**): #foo/**/qux -# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # You can also negate patterns with an exclamation (!). # For example, you can ignore all files in a docs folder with the file extension .md: diff --git a/samples/yaml/pet.yml b/samples/yaml/pet.yml index 2d0891d3032..4b3420c99c8 100644 --- a/samples/yaml/pet.yml +++ b/samples/yaml/pet.yml @@ -87,7 +87,7 @@ apis: operations: - method: GET summary: Finds Pets by status - notes: Multiple status values can be provided with comma seperated strings + notes: Multiple status values can be provided with comma separated strings type: array items: $ref: Pet @@ -114,7 +114,7 @@ apis: operations: - method: GET summary: Finds Pets by tags - notes: "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing." + notes: "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing." type: array items: $ref: Pet From 756f7a96f67a514dbbfc85ba722006d2352c0113 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Sun, 28 Aug 2016 01:00:34 +0300 Subject: [PATCH 283/470] java: Fix model package import in example --- modules/swagger-codegen/src/main/resources/Java/README.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/README.mustache b/modules/swagger-codegen/src/main/resources/Java/README.mustache index f3b766a67d8..6849db6f8fe 100644 --- a/modules/swagger-codegen/src/main/resources/Java/README.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/README.mustache @@ -60,7 +60,7 @@ Please follow the [installation](#installation) instruction and execute the foll {{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}} import {{{invokerPackage}}}.*; import {{{invokerPackage}}}.auth.*; -import {{{invokerPackage}}}.model.*; +import {{{modelPackage}}}.*; import {{{package}}}.{{{classname}}}; import java.io.File; From 85c7e7697af6e0524d5f9b148b2e0e28d227b64a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Sun, 28 Aug 2016 10:56:00 +0300 Subject: [PATCH 284/470] Perl example fixes (#3652) * perl: Add configuration and classname imports to examples * perl: Fix list container syntax in examples --- .../swagger-codegen/src/main/resources/perl/README.mustache | 4 +++- .../swagger-codegen/src/main/resources/perl/api_doc.mustache | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/perl/README.mustache b/modules/swagger-codegen/src/main/resources/perl/README.mustache index d47d482742d..60f810eeb30 100644 --- a/modules/swagger-codegen/src/main/resources/perl/README.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/README.mustache @@ -251,6 +251,8 @@ use warnings; {{/model}}{{/models}} # for displaying the API response data use Data::Dumper; +use {{{moduleName}}}::Configuration; +use {{moduleName}}::{{classname}}; {{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}{{#hasAuthMethods}}{{#authMethods}}{{#isBasic}} # Configure HTTP basic authorization: {{{name}}} ${{{moduleName}}}::Configuration::username = 'YOUR_USERNAME'; @@ -264,7 +266,7 @@ ${{{moduleName}}}::Configuration::access_token = 'YOUR_ACCESS_TOKEN';{{/isOAuth} {{/hasAuthMethods}} my $api_instance = {{moduleName}}::{{classname}}->new(); -{{#allParams}}my ${{paramName}} = {{#isListContainer}}({{/isListContainer}}{{#isBodyParam}}{{{moduleName}}}::Object::{{dataType}}->new(){{/isBodyParam}}{{^isBodyParam}}{{{example}}}{{/isBodyParam}}{{#isListContainer}}){{/isListContainer}}; # {{{dataType}}} | {{{description}}} +{{#allParams}}my ${{paramName}} = {{#isListContainer}}[{{/isListContainer}}{{#isBodyParam}}{{{moduleName}}}::Object::{{dataType}}->new(){{/isBodyParam}}{{^isBodyParam}}{{{example}}}{{/isBodyParam}}{{#isListContainer}}]{{/isListContainer}}; # {{{dataType}}} | {{{description}}} {{/allParams}} eval { diff --git a/modules/swagger-codegen/src/main/resources/perl/api_doc.mustache b/modules/swagger-codegen/src/main/resources/perl/api_doc.mustache index 585a67c1ac1..acc6b4a003f 100644 --- a/modules/swagger-codegen/src/main/resources/perl/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/api_doc.mustache @@ -25,6 +25,8 @@ Method | HTTP request | Description ### Example ```perl use Data::Dumper; +use {{{moduleName}}}::Configuration; +use {{moduleName}}::{{classname}}; {{#hasAuthMethods}}{{#authMethods}}{{#isBasic}} # Configure HTTP basic authorization: {{{name}}} ${{{moduleName}}}::Configuration::username = 'YOUR_USERNAME'; @@ -38,7 +40,7 @@ ${{{moduleName}}}::Configuration::access_token = 'YOUR_ACCESS_TOKEN';{{/isOAuth} {{/hasAuthMethods}} my $api_instance = {{moduleName}}::{{classname}}->new(); -{{#allParams}}my ${{paramName}} = {{#isListContainer}}({{/isListContainer}}{{#isBodyParam}}{{{moduleName}}}::Object::{{dataType}}->new(){{/isBodyParam}}{{^isBodyParam}}{{{example}}}{{/isBodyParam}}{{#isListContainer}}){{/isListContainer}}; # {{{dataType}}} | {{{description}}} +{{#allParams}}my ${{paramName}} = {{#isListContainer}}[{{/isListContainer}}{{#isBodyParam}}{{{moduleName}}}::Object::{{dataType}}->new(){{/isBodyParam}}{{^isBodyParam}}{{{example}}}{{/isBodyParam}}{{#isListContainer}}]{{/isListContainer}}; # {{{dataType}}} | {{{description}}} {{/allParams}} eval { From 72d0cd7eb4bb58033d2da18df917732be6dd27d1 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 28 Aug 2016 15:57:50 +0800 Subject: [PATCH 285/470] update petl sample --- samples/client/petstore/perl/README.md | 28 +++- .../client/petstore/perl/docs/ArrayTest.md | 1 - samples/client/petstore/perl/docs/FakeApi.md | 67 +++++--- samples/client/petstore/perl/docs/PetApi.md | 20 ++- samples/client/petstore/perl/docs/StoreApi.md | 8 + samples/client/petstore/perl/docs/UserApi.md | 20 ++- .../perl/lib/WWW/SwaggerClient/ApiClient.pm | 6 + .../perl/lib/WWW/SwaggerClient/FakeApi.pm | 145 +++++++++++++----- .../lib/WWW/SwaggerClient/Object/ArrayTest.pm | 13 +- .../perl/lib/WWW/SwaggerClient/Role.pm | 4 +- 10 files changed, 231 insertions(+), 81 deletions(-) diff --git a/samples/client/petstore/perl/README.md b/samples/client/petstore/perl/README.md index 3c7a28082e6..18df4f126f3 100644 --- a/samples/client/petstore/perl/README.md +++ b/samples/client/petstore/perl/README.md @@ -10,7 +10,7 @@ Automatically generated by the [Swagger Codegen](https://github.com/swagger-api/ - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-06-28T16:35:21.686+08:00 +- Build date: 2016-08-28T15:57:37.016+08:00 - Build package: class io.swagger.codegen.languages.PerlClientCodegen ## A note on Moose @@ -241,11 +241,14 @@ use WWW::SwaggerClient::Object::ArrayOfNumberOnly; use WWW::SwaggerClient::Object::ArrayTest; use WWW::SwaggerClient::Object::Cat; use WWW::SwaggerClient::Object::Category; +use WWW::SwaggerClient::Object::Client; use WWW::SwaggerClient::Object::Dog; +use WWW::SwaggerClient::Object::EnumArrays; use WWW::SwaggerClient::Object::EnumClass; use WWW::SwaggerClient::Object::EnumTest; use WWW::SwaggerClient::Object::FormatTest; use WWW::SwaggerClient::Object::HasOnlyReadOnly; +use WWW::SwaggerClient::Object::List; use WWW::SwaggerClient::Object::MapTest; use WWW::SwaggerClient::Object::MixedPropertiesAndAdditionalPropertiesClass; use WWW::SwaggerClient::Object::Model200Response; @@ -284,11 +287,14 @@ use WWW::SwaggerClient::Object::ArrayOfNumberOnly; use WWW::SwaggerClient::Object::ArrayTest; use WWW::SwaggerClient::Object::Cat; use WWW::SwaggerClient::Object::Category; +use WWW::SwaggerClient::Object::Client; use WWW::SwaggerClient::Object::Dog; +use WWW::SwaggerClient::Object::EnumArrays; use WWW::SwaggerClient::Object::EnumClass; use WWW::SwaggerClient::Object::EnumTest; use WWW::SwaggerClient::Object::FormatTest; use WWW::SwaggerClient::Object::HasOnlyReadOnly; +use WWW::SwaggerClient::Object::List; use WWW::SwaggerClient::Object::MapTest; use WWW::SwaggerClient::Object::MixedPropertiesAndAdditionalPropertiesClass; use WWW::SwaggerClient::Object::Model200Response; @@ -304,15 +310,18 @@ use WWW::SwaggerClient::Object::User; # for displaying the API response data use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::; my $api_instance = WWW::SwaggerClient::FakeApi->new(); -my $test code inject */ =end = 'test code inject */ =end_example'; # string | To test code injection */ +my $body = WWW::SwaggerClient::Object::Client->new(); # Client | client model eval { - $api_instance->test_code_inject__end(test code inject */ =end => $test code inject */ =end); + my $result = $api_instance->test_client_model(body => $body); + print Dumper($result); }; if ($@) { - warn "Exception when calling FakeApi->test_code_inject__end: $@\n"; + warn "Exception when calling FakeApi->test_client_model: $@\n"; } ``` @@ -323,9 +332,9 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*FakeApi* | [**test_code_inject__end**](docs/FakeApi.md#test_code_inject__end) | **PUT** /fake | To test code injection */ +*FakeApi* | [**test_client_model**](docs/FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model *FakeApi* | [**test_endpoint_parameters**](docs/FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -*FakeApi* | [**test_enum_query_parameters**](docs/FakeApi.md#test_enum_query_parameters) | **GET** /fake | To test enum query parameters +*FakeApi* | [**test_enum_parameters**](docs/FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters *PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store *PetApi* | [**delete_pet**](docs/PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet *PetApi* | [**find_pets_by_status**](docs/PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status @@ -358,11 +367,14 @@ Class | Method | HTTP request | Description - [WWW::SwaggerClient::Object::ArrayTest](docs/ArrayTest.md) - [WWW::SwaggerClient::Object::Cat](docs/Cat.md) - [WWW::SwaggerClient::Object::Category](docs/Category.md) + - [WWW::SwaggerClient::Object::Client](docs/Client.md) - [WWW::SwaggerClient::Object::Dog](docs/Dog.md) + - [WWW::SwaggerClient::Object::EnumArrays](docs/EnumArrays.md) - [WWW::SwaggerClient::Object::EnumClass](docs/EnumClass.md) - [WWW::SwaggerClient::Object::EnumTest](docs/EnumTest.md) - [WWW::SwaggerClient::Object::FormatTest](docs/FormatTest.md) - [WWW::SwaggerClient::Object::HasOnlyReadOnly](docs/HasOnlyReadOnly.md) + - [WWW::SwaggerClient::Object::List](docs/List.md) - [WWW::SwaggerClient::Object::MapTest](docs/MapTest.md) - [WWW::SwaggerClient::Object::MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - [WWW::SwaggerClient::Object::Model200Response](docs/Model200Response.md) @@ -394,5 +406,9 @@ Class | Method | HTTP request | Description - **write:pets**: modify pets in your account - **read:pets**: read your pets +## http_basic_test + +- **Type**: HTTP basic authentication + diff --git a/samples/client/petstore/perl/docs/ArrayTest.md b/samples/client/petstore/perl/docs/ArrayTest.md index e6495d4da5e..635c26a893a 100644 --- a/samples/client/petstore/perl/docs/ArrayTest.md +++ b/samples/client/petstore/perl/docs/ArrayTest.md @@ -11,7 +11,6 @@ Name | Type | Description | Notes **array_of_string** | **ARRAY[string]** | | [optional] **array_array_of_integer** | **ARRAY[ARRAY[int]]** | | [optional] **array_array_of_model** | **ARRAY[ARRAY[ReadOnlyFirst]]** | | [optional] -**array_of_enum** | **ARRAY[string]** | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/perl/docs/FakeApi.md b/samples/client/petstore/perl/docs/FakeApi.md index 1207308ca23..985b78596e2 100644 --- a/samples/client/petstore/perl/docs/FakeApi.md +++ b/samples/client/petstore/perl/docs/FakeApi.md @@ -9,28 +9,31 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**test_code_inject__end**](FakeApi.md#test_code_inject__end) | **PUT** /fake | To test code injection */ +[**test_client_model**](FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model [**test_endpoint_parameters**](FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -[**test_enum_query_parameters**](FakeApi.md#test_enum_query_parameters) | **GET** /fake | To test enum query parameters +[**test_enum_parameters**](FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters -# **test_code_inject__end** -> test_code_inject__end(test code inject */ =end => $test code inject */ =end) +# **test_client_model** +> Client test_client_model(body => $body) -To test code injection */ +To test \"client\" model ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::FakeApi; my $api_instance = WWW::SwaggerClient::FakeApi->new(); -my $test code inject */ =end = 'test code inject */ =end_example'; # string | To test code injection */ +my $body = WWW::SwaggerClient::Object::Client->new(); # Client | client model eval { - $api_instance->test_code_inject__end(test code inject */ =end => $test code inject */ =end); + my $result = $api_instance->test_client_model(body => $body); + print Dumper($result); }; if ($@) { - warn "Exception when calling FakeApi->test_code_inject__end: $@\n"; + warn "Exception when calling FakeApi->test_client_model: $@\n"; } ``` @@ -38,11 +41,11 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **test code inject */ =end** | **string**| To test code injection */ | [optional] + **body** | [**Client**](Client.md)| client model | ### Return type -void (empty response body) +[**Client**](Client.md) ### Authorization @@ -50,13 +53,13 @@ No authorization required ### HTTP request headers - - **Content-Type**: application/json, */ =end));(phpinfo( - - **Accept**: application/json, */ end + - **Content-Type**: application/json + - **Accept**: application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **test_endpoint_parameters** -> test_endpoint_parameters(number => $number, double => $double, string => $string, byte => $byte, integer => $integer, int32 => $int32, int64 => $int64, float => $float, binary => $binary, date => $date, date_time => $date_time, password => $password) +> test_endpoint_parameters(number => $number, double => $double, pattern_without_delimiter => $pattern_without_delimiter, byte => $byte, integer => $integer, int32 => $int32, int64 => $int64, float => $float, string => $string, binary => $binary, date => $date, date_time => $date_time, password => $password) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -65,23 +68,30 @@ Fake endpoint for testing various parameters 假端點 偽のエンドポイン ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::FakeApi; + +# Configure HTTP basic authorization: http_basic_test +$WWW::SwaggerClient::Configuration::username = 'YOUR_USERNAME'; +$WWW::SwaggerClient::Configuration::password = 'YOUR_PASSWORD'; my $api_instance = WWW::SwaggerClient::FakeApi->new(); my $number = 3.4; # Number | None my $double = 1.2; # double | None -my $string = 'string_example'; # string | None +my $pattern_without_delimiter = 'pattern_without_delimiter_example'; # string | None my $byte = 'B'; # string | None my $integer = 56; # int | None my $int32 = 56; # int | None my $int64 = 789; # int | None my $float = 3.4; # double | None +my $string = 'string_example'; # string | None my $binary = 'B'; # string | None my $date = DateTime->from_epoch(epoch => str2time('2013-10-20')); # DateTime | None my $date_time = DateTime->from_epoch(epoch => str2time('2013-10-20T19:20:30+01:00')); # DateTime | None my $password = 'password_example'; # string | None eval { - $api_instance->test_endpoint_parameters(number => $number, double => $double, string => $string, byte => $byte, integer => $integer, int32 => $int32, int64 => $int64, float => $float, binary => $binary, date => $date, date_time => $date_time, password => $password); + $api_instance->test_endpoint_parameters(number => $number, double => $double, pattern_without_delimiter => $pattern_without_delimiter, byte => $byte, integer => $integer, int32 => $int32, int64 => $int64, float => $float, string => $string, binary => $binary, date => $date, date_time => $date_time, password => $password); }; if ($@) { warn "Exception when calling FakeApi->test_endpoint_parameters: $@\n"; @@ -94,12 +104,13 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **number** | **Number**| None | **double** | **double**| None | - **string** | **string**| None | + **pattern_without_delimiter** | **string**| None | **byte** | **string**| None | **integer** | **int**| None | [optional] **int32** | **int**| None | [optional] **int64** | **int**| None | [optional] **float** | **double**| None | [optional] + **string** | **string**| None | [optional] **binary** | **string**| None | [optional] **date** | **DateTime**| None | [optional] **date_time** | **DateTime**| None | [optional] @@ -111,7 +122,7 @@ void (empty response body) ### Authorization -No authorization required +[http_basic_test](../README.md#http_basic_test) ### HTTP request headers @@ -120,25 +131,32 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) -# **test_enum_query_parameters** -> test_enum_query_parameters(enum_query_string => $enum_query_string, enum_query_integer => $enum_query_integer, enum_query_double => $enum_query_double) +# **test_enum_parameters** +> test_enum_parameters(enum_form_string_array => $enum_form_string_array, enum_form_string => $enum_form_string, enum_header_string_array => $enum_header_string_array, enum_header_string => $enum_header_string, enum_query_string_array => $enum_query_string_array, enum_query_string => $enum_query_string, enum_query_integer => $enum_query_integer, enum_query_double => $enum_query_double) -To test enum query parameters +To test enum parameters ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::FakeApi; my $api_instance = WWW::SwaggerClient::FakeApi->new(); +my $enum_form_string_array = []; # ARRAY[string] | Form parameter enum test (string array) +my $enum_form_string = 'enum_form_string_example'; # string | Form parameter enum test (string) +my $enum_header_string_array = []; # ARRAY[string] | Header parameter enum test (string array) +my $enum_header_string = 'enum_header_string_example'; # string | Header parameter enum test (string) +my $enum_query_string_array = []; # ARRAY[string] | Query parameter enum test (string array) my $enum_query_string = 'enum_query_string_example'; # string | Query parameter enum test (string) my $enum_query_integer = 3.4; # Number | Query parameter enum test (double) my $enum_query_double = 1.2; # double | Query parameter enum test (double) eval { - $api_instance->test_enum_query_parameters(enum_query_string => $enum_query_string, enum_query_integer => $enum_query_integer, enum_query_double => $enum_query_double); + $api_instance->test_enum_parameters(enum_form_string_array => $enum_form_string_array, enum_form_string => $enum_form_string, enum_header_string_array => $enum_header_string_array, enum_header_string => $enum_header_string, enum_query_string_array => $enum_query_string_array, enum_query_string => $enum_query_string, enum_query_integer => $enum_query_integer, enum_query_double => $enum_query_double); }; if ($@) { - warn "Exception when calling FakeApi->test_enum_query_parameters: $@\n"; + warn "Exception when calling FakeApi->test_enum_parameters: $@\n"; } ``` @@ -146,6 +164,11 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- + **enum_form_string_array** | [**ARRAY[string]**](string.md)| Form parameter enum test (string array) | [optional] + **enum_form_string** | **string**| Form parameter enum test (string) | [optional] [default to -efg] + **enum_header_string_array** | [**ARRAY[string]**](string.md)| Header parameter enum test (string array) | [optional] + **enum_header_string** | **string**| Header parameter enum test (string) | [optional] [default to -efg] + **enum_query_string_array** | [**ARRAY[string]**](string.md)| Query parameter enum test (string array) | [optional] **enum_query_string** | **string**| Query parameter enum test (string) | [optional] [default to -efg] **enum_query_integer** | **Number**| Query parameter enum test (double) | [optional] **enum_query_double** | **double**| Query parameter enum test (double) | [optional] diff --git a/samples/client/petstore/perl/docs/PetApi.md b/samples/client/petstore/perl/docs/PetApi.md index c2f4e2ce4ee..ab07b6413a2 100644 --- a/samples/client/petstore/perl/docs/PetApi.md +++ b/samples/client/petstore/perl/docs/PetApi.md @@ -29,6 +29,8 @@ Add a new pet to the store ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::PetApi; # Configure OAuth2 access token for authorization: petstore_auth $WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; @@ -75,6 +77,8 @@ Deletes a pet ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::PetApi; # Configure OAuth2 access token for authorization: petstore_auth $WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; @@ -123,12 +127,14 @@ Multiple status values can be provided with comma separated strings ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::PetApi; # Configure OAuth2 access token for authorization: petstore_auth $WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; my $api_instance = WWW::SwaggerClient::PetApi->new(); -my $status = (); # ARRAY[string] | Status values that need to be considered for filter +my $status = []; # ARRAY[string] | Status values that need to be considered for filter eval { my $result = $api_instance->find_pets_by_status(status => $status); @@ -170,12 +176,14 @@ Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::PetApi; # Configure OAuth2 access token for authorization: petstore_auth $WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; my $api_instance = WWW::SwaggerClient::PetApi->new(); -my $tags = (); # ARRAY[string] | Tags to filter by +my $tags = []; # ARRAY[string] | Tags to filter by eval { my $result = $api_instance->find_pets_by_tags(tags => $tags); @@ -217,6 +225,8 @@ Returns a single pet ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::PetApi; # Configure API key authorization: api_key $WWW::SwaggerClient::Configuration::api_key->{'api_key'} = 'YOUR_API_KEY'; @@ -266,6 +276,8 @@ Update an existing pet ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::PetApi; # Configure OAuth2 access token for authorization: petstore_auth $WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; @@ -312,6 +324,8 @@ Updates a pet in the store with form data ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::PetApi; # Configure OAuth2 access token for authorization: petstore_auth $WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; @@ -362,6 +376,8 @@ uploads an image ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::PetApi; # Configure OAuth2 access token for authorization: petstore_auth $WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; diff --git a/samples/client/petstore/perl/docs/StoreApi.md b/samples/client/petstore/perl/docs/StoreApi.md index f0681b47167..d57b4121cc0 100644 --- a/samples/client/petstore/perl/docs/StoreApi.md +++ b/samples/client/petstore/perl/docs/StoreApi.md @@ -25,6 +25,8 @@ For valid response try integer IDs with value < 1000. Anything above 1000 or non ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::StoreApi; my $api_instance = WWW::SwaggerClient::StoreApi->new(); my $order_id = 'order_id_example'; # string | ID of the order that needs to be deleted @@ -68,6 +70,8 @@ Returns a map of status codes to quantities ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::StoreApi; # Configure API key authorization: api_key $WWW::SwaggerClient::Configuration::api_key->{'api_key'} = 'YOUR_API_KEY'; @@ -113,6 +117,8 @@ For valid response try integer IDs with value <= 5 or > 10. Other values will ge ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::StoreApi; my $api_instance = WWW::SwaggerClient::StoreApi->new(); my $order_id = 789; # int | ID of pet that needs to be fetched @@ -157,6 +163,8 @@ Place an order for a pet ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::StoreApi; my $api_instance = WWW::SwaggerClient::StoreApi->new(); my $body = WWW::SwaggerClient::Object::Order->new(); # Order | order placed for purchasing the pet diff --git a/samples/client/petstore/perl/docs/UserApi.md b/samples/client/petstore/perl/docs/UserApi.md index faa4c799739..081f0dc1d55 100644 --- a/samples/client/petstore/perl/docs/UserApi.md +++ b/samples/client/petstore/perl/docs/UserApi.md @@ -29,6 +29,8 @@ This can only be done by the logged in user. ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::UserApi; my $api_instance = WWW::SwaggerClient::UserApi->new(); my $body = WWW::SwaggerClient::Object::User->new(); # User | Created user object @@ -72,9 +74,11 @@ Creates list of users with given input array ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::UserApi; my $api_instance = WWW::SwaggerClient::UserApi->new(); -my $body = (WWW::SwaggerClient::Object::ARRAY[User]->new()); # ARRAY[User] | List of user object +my $body = [WWW::SwaggerClient::Object::ARRAY[User]->new()]; # ARRAY[User] | List of user object eval { $api_instance->create_users_with_array_input(body => $body); @@ -115,9 +119,11 @@ Creates list of users with given input array ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::UserApi; my $api_instance = WWW::SwaggerClient::UserApi->new(); -my $body = (WWW::SwaggerClient::Object::ARRAY[User]->new()); # ARRAY[User] | List of user object +my $body = [WWW::SwaggerClient::Object::ARRAY[User]->new()]; # ARRAY[User] | List of user object eval { $api_instance->create_users_with_list_input(body => $body); @@ -158,6 +164,8 @@ This can only be done by the logged in user. ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::UserApi; my $api_instance = WWW::SwaggerClient::UserApi->new(); my $username = 'username_example'; # string | The name that needs to be deleted @@ -201,6 +209,8 @@ Get user by user name ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::UserApi; my $api_instance = WWW::SwaggerClient::UserApi->new(); my $username = 'username_example'; # string | The name that needs to be fetched. Use user1 for testing. @@ -245,6 +255,8 @@ Logs user into the system ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::UserApi; my $api_instance = WWW::SwaggerClient::UserApi->new(); my $username = 'username_example'; # string | The user name for login @@ -291,6 +303,8 @@ Logs out current logged in user session ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::UserApi; my $api_instance = WWW::SwaggerClient::UserApi->new(); @@ -330,6 +344,8 @@ This can only be done by the logged in user. ### Example ```perl use Data::Dumper; +use WWW::SwaggerClient::Configuration; +use WWW::SwaggerClient::UserApi; my $api_instance = WWW::SwaggerClient::UserApi->new(); my $username = 'username_example'; # string | name that need to be deleted diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiClient.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiClient.pm index 92228e6c747..ad679c64cb7 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiClient.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiClient.pm @@ -363,6 +363,12 @@ elsif ($auth eq 'petstore_auth') { $header_params->{'Authorization'} = 'Bearer ' . $WWW::SwaggerClient::Configuration::access_token; } } +elsif ($auth eq 'http_basic_test') { + + if ($WWW::SwaggerClient::Configuration::username || $WWW::SwaggerClient::Configuration::password) { + $header_params->{'Authorization'} = 'Basic ' . encode_base64($WWW::SwaggerClient::Configuration::username . ":" . $WWW::SwaggerClient::Configuration::password); + } + } else { # TODO show warning about security definition not found } diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/FakeApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/FakeApi.pm index eefd2641288..ef2ba24f88a 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/FakeApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/FakeApi.pm @@ -64,60 +64,69 @@ sub new { # -# test_code_inject__end +# test_client_model # -# To test code injection */ +# To test \"client\" model # -# @param string $test code inject */ =end To test code injection */ (optional) +# @param Client $body client model (required) { my $params = { - 'test code inject */ =end' => { - data_type => 'string', - description => 'To test code injection */ ', - required => '0', + 'body' => { + data_type => 'Client', + description => 'client model', + required => '1', }, }; - __PACKAGE__->method_documentation->{ 'test_code_inject__end' } = { - summary => 'To test code injection */ ', + __PACKAGE__->method_documentation->{ 'test_client_model' } = { + summary => 'To test \"client\" model', params => $params, - returns => undef, + returns => 'Client', }; } -# @return void +# @return Client # -sub test_code_inject__end { +sub test_client_model { my ($self, %args) = @_; + # verify the required parameter 'body' is set + unless (exists $args{'body'}) { + croak("Missing the required parameter 'body' when calling test_client_model"); + } + # parse inputs my $_resource_path = '/fake'; $_resource_path =~ s/{format}/json/; # default format to json - my $_method = 'PUT'; + my $_method = 'PATCH'; my $query_params = {}; my $header_params = {}; my $form_params = {}; # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/json', '*/ end'); + my $_header_accept = $self->{api_client}->select_header_accept('application/json'); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json', '*/ =end));(phpinfo('); + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json'); - # form params - if ( exists $args{'test code inject */ =end'} ) { - $form_params->{'test code inject */ =end'} = $self->{api_client}->to_form_value($args{'test code inject */ =end'}); - } - my $_body_data; + # body params + if ( exists $args{'body'}) { + $_body_data = $args{'body'}; + } + # authentication setting, if any my $auth_settings = [qw()]; # make the API Call - $self->{api_client}->call_api($_resource_path, $_method, + my $response = $self->{api_client}->call_api($_resource_path, $_method, $query_params, $form_params, $header_params, $_body_data, $auth_settings); - return; + if (!$response) { + return; + } + my $_response_object = $self->{api_client}->deserialize('Client', $response); + return $_response_object; } # @@ -127,12 +136,13 @@ sub test_code_inject__end { # # @param Number $number None (required) # @param double $double None (required) -# @param string $string None (required) +# @param string $pattern_without_delimiter None (required) # @param string $byte None (required) # @param int $integer None (optional) # @param int $int32 None (optional) # @param int $int64 None (optional) # @param double $float None (optional) +# @param string $string None (optional) # @param string $binary None (optional) # @param DateTime $date None (optional) # @param DateTime $date_time None (optional) @@ -149,7 +159,7 @@ sub test_code_inject__end { description => 'None', required => '1', }, - 'string' => { + 'pattern_without_delimiter' => { data_type => 'string', description => 'None', required => '1', @@ -179,6 +189,11 @@ sub test_code_inject__end { description => 'None', required => '0', }, + 'string' => { + data_type => 'string', + description => 'None', + required => '0', + }, 'binary' => { data_type => 'string', description => 'None', @@ -221,9 +236,9 @@ sub test_endpoint_parameters { croak("Missing the required parameter 'double' when calling test_endpoint_parameters"); } - # verify the required parameter 'string' is set - unless (exists $args{'string'}) { - croak("Missing the required parameter 'string' when calling test_endpoint_parameters"); + # verify the required parameter 'pattern_without_delimiter' is set + unless (exists $args{'pattern_without_delimiter'}) { + croak("Missing the required parameter 'pattern_without_delimiter' when calling test_endpoint_parameters"); } # verify the required parameter 'byte' is set @@ -282,6 +297,11 @@ sub test_endpoint_parameters { $form_params->{'string'} = $self->{api_client}->to_form_value($args{'string'}); } + # form params + if ( exists $args{'pattern_without_delimiter'} ) { + $form_params->{'pattern_without_delimiter'} = $self->{api_client}->to_form_value($args{'pattern_without_delimiter'}); + } + # form params if ( exists $args{'byte'} ) { $form_params->{'byte'} = $self->{api_client}->to_form_value($args{'byte'}); @@ -309,7 +329,7 @@ sub test_endpoint_parameters { my $_body_data; # authentication setting, if any - my $auth_settings = [qw()]; + my $auth_settings = [qw(http_basic_test )]; # make the API Call $self->{api_client}->call_api($_resource_path, $_method, @@ -319,15 +339,45 @@ sub test_endpoint_parameters { } # -# test_enum_query_parameters +# test_enum_parameters # -# To test enum query parameters +# To test enum parameters # +# @param ARRAY[string] $enum_form_string_array Form parameter enum test (string array) (optional) +# @param string $enum_form_string Form parameter enum test (string) (optional, default to -efg) +# @param ARRAY[string] $enum_header_string_array Header parameter enum test (string array) (optional) +# @param string $enum_header_string Header parameter enum test (string) (optional, default to -efg) +# @param ARRAY[string] $enum_query_string_array Query parameter enum test (string array) (optional) # @param string $enum_query_string Query parameter enum test (string) (optional, default to -efg) # @param Number $enum_query_integer Query parameter enum test (double) (optional) # @param double $enum_query_double Query parameter enum test (double) (optional) { my $params = { + 'enum_form_string_array' => { + data_type => 'ARRAY[string]', + description => 'Form parameter enum test (string array)', + required => '0', + }, + 'enum_form_string' => { + data_type => 'string', + description => 'Form parameter enum test (string)', + required => '0', + }, + 'enum_header_string_array' => { + data_type => 'ARRAY[string]', + description => 'Header parameter enum test (string array)', + required => '0', + }, + 'enum_header_string' => { + data_type => 'string', + description => 'Header parameter enum test (string)', + required => '0', + }, + 'enum_query_string_array' => { + data_type => 'ARRAY[string]', + description => 'Query parameter enum test (string array)', + required => '0', + }, 'enum_query_string' => { data_type => 'string', description => 'Query parameter enum test (string)', @@ -344,15 +394,15 @@ sub test_endpoint_parameters { required => '0', }, }; - __PACKAGE__->method_documentation->{ 'test_enum_query_parameters' } = { - summary => 'To test enum query parameters', + __PACKAGE__->method_documentation->{ 'test_enum_parameters' } = { + summary => 'To test enum parameters', params => $params, returns => undef, }; } # @return void # -sub test_enum_query_parameters { +sub test_enum_parameters { my ($self, %args) = @_; # parse inputs @@ -371,14 +421,39 @@ sub test_enum_query_parameters { } $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json'); + # query params + if ( exists $args{'enum_query_string_array'}) { + $query_params->{'enum_query_string_array'} = $self->{api_client}->to_query_value($args{'enum_query_string_array'}); + } + + # query params + if ( exists $args{'enum_query_string'}) { + $query_params->{'enum_query_string'} = $self->{api_client}->to_query_value($args{'enum_query_string'}); + } + # query params if ( exists $args{'enum_query_integer'}) { $query_params->{'enum_query_integer'} = $self->{api_client}->to_query_value($args{'enum_query_integer'}); } + # header params + if ( exists $args{'enum_header_string_array'}) { + $header_params->{'enum_header_string_array'} = $self->{api_client}->to_header_value($args{'enum_header_string_array'}); + } + + # header params + if ( exists $args{'enum_header_string'}) { + $header_params->{'enum_header_string'} = $self->{api_client}->to_header_value($args{'enum_header_string'}); + } + + # form params + if ( exists $args{'enum_form_string_array'} ) { + $form_params->{'enum_form_string_array'} = $self->{api_client}->to_form_value($args{'enum_form_string_array'}); + } + # form params - if ( exists $args{'enum_query_string'} ) { - $form_params->{'enum_query_string'} = $self->{api_client}->to_form_value($args{'enum_query_string'}); + if ( exists $args{'enum_form_string'} ) { + $form_params->{'enum_form_string'} = $self->{api_client}->to_form_value($args{'enum_form_string'}); } # form params diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ArrayTest.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ArrayTest.pm index a0b3cdada05..17200d857f3 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ArrayTest.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ArrayTest.pm @@ -187,27 +187,18 @@ __PACKAGE__->method_documentation({ format => '', read_only => '', }, - 'array_of_enum' => { - datatype => 'ARRAY[string]', - base_name => 'array_of_enum', - description => '', - format => '', - read_only => '', - }, }); __PACKAGE__->swagger_types( { 'array_of_string' => 'ARRAY[string]', 'array_array_of_integer' => 'ARRAY[ARRAY[int]]', - 'array_array_of_model' => 'ARRAY[ARRAY[ReadOnlyFirst]]', - 'array_of_enum' => 'ARRAY[string]' + 'array_array_of_model' => 'ARRAY[ARRAY[ReadOnlyFirst]]' } ); __PACKAGE__->attribute_map( { 'array_of_string' => 'array_of_string', 'array_array_of_integer' => 'array_array_of_integer', - 'array_array_of_model' => 'array_array_of_model', - 'array_of_enum' => 'array_of_enum' + 'array_array_of_model' => 'array_array_of_model' } ); __PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm index 4e4fadcbb0e..6c1058b7e59 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm @@ -68,7 +68,7 @@ has version_info => ( is => 'ro', default => sub { { app_name => 'Swagger Petstore', app_version => '1.0.0', - generated_date => '2016-06-28T16:35:21.686+08:00', + generated_date => '2016-08-28T15:57:37.016+08:00', generator_class => 'class io.swagger.codegen.languages.PerlClientCodegen', } }, documentation => 'Information about the application version and the codegen codebase version' @@ -134,7 +134,7 @@ Automatically generated by the Perl Swagger Codegen project: =over 4 -=item Build date: 2016-06-28T16:35:21.686+08:00 +=item Build date: 2016-08-28T15:57:37.016+08:00 =item Build package: class io.swagger.codegen.languages.PerlClientCodegen From 598c21b06ef0d8b974726f9dc63bedac50f93bb1 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 28 Aug 2016 16:02:09 +0800 Subject: [PATCH 286/470] add new perl petstore files --- .../perl/docs/ArrayOfArrayOfNumberOnly.md | 15 ++ .../petstore/perl/docs/ArrayOfNumberOnly.md | 15 ++ samples/client/petstore/perl/docs/Client.md | 15 ++ .../client/petstore/perl/docs/EnumArrays.md | 16 ++ .../petstore/perl/docs/HasOnlyReadOnly.md | 16 ++ samples/client/petstore/perl/docs/List.md | 15 ++ samples/client/petstore/perl/docs/MapTest.md | 16 ++ .../client/petstore/perl/docs/NumberOnly.md | 15 ++ .../Object/ArrayOfArrayOfNumberOnly.pm | 189 +++++++++++++++++ .../SwaggerClient/Object/ArrayOfNumberOnly.pm | 189 +++++++++++++++++ .../lib/WWW/SwaggerClient/Object/Client.pm | 189 +++++++++++++++++ .../WWW/SwaggerClient/Object/EnumArrays.pm | 198 ++++++++++++++++++ .../SwaggerClient/Object/HasOnlyReadOnly.pm | 198 ++++++++++++++++++ .../perl/lib/WWW/SwaggerClient/Object/List.pm | 189 +++++++++++++++++ .../lib/WWW/SwaggerClient/Object/MapTest.pm | 198 ++++++++++++++++++ .../WWW/SwaggerClient/Object/NumberOnly.pm | 189 +++++++++++++++++ .../perl/t/ArrayOfArrayOfNumberOnlyTest.t | 45 ++++ .../petstore/perl/t/ArrayOfNumberOnlyTest.t | 45 ++++ samples/client/petstore/perl/t/ClientTest.t | 45 ++++ .../client/petstore/perl/t/EnumArraysTest.t | 45 ++++ .../petstore/perl/t/HasOnlyReadOnlyTest.t | 45 ++++ samples/client/petstore/perl/t/ListTest.t | 45 ++++ samples/client/petstore/perl/t/MapTestTest.t | 45 ++++ .../client/petstore/perl/t/NumberOnlyTest.t | 45 ++++ 24 files changed, 2022 insertions(+) create mode 100644 samples/client/petstore/perl/docs/ArrayOfArrayOfNumberOnly.md create mode 100644 samples/client/petstore/perl/docs/ArrayOfNumberOnly.md create mode 100644 samples/client/petstore/perl/docs/Client.md create mode 100644 samples/client/petstore/perl/docs/EnumArrays.md create mode 100644 samples/client/petstore/perl/docs/HasOnlyReadOnly.md create mode 100644 samples/client/petstore/perl/docs/List.md create mode 100644 samples/client/petstore/perl/docs/MapTest.md create mode 100644 samples/client/petstore/perl/docs/NumberOnly.md create mode 100644 samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ArrayOfArrayOfNumberOnly.pm create mode 100644 samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ArrayOfNumberOnly.pm create mode 100644 samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Client.pm create mode 100644 samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/EnumArrays.pm create mode 100644 samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/HasOnlyReadOnly.pm create mode 100644 samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/List.pm create mode 100644 samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/MapTest.pm create mode 100644 samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/NumberOnly.pm create mode 100644 samples/client/petstore/perl/t/ArrayOfArrayOfNumberOnlyTest.t create mode 100644 samples/client/petstore/perl/t/ArrayOfNumberOnlyTest.t create mode 100644 samples/client/petstore/perl/t/ClientTest.t create mode 100644 samples/client/petstore/perl/t/EnumArraysTest.t create mode 100644 samples/client/petstore/perl/t/HasOnlyReadOnlyTest.t create mode 100644 samples/client/petstore/perl/t/ListTest.t create mode 100644 samples/client/petstore/perl/t/MapTestTest.t create mode 100644 samples/client/petstore/perl/t/NumberOnlyTest.t diff --git a/samples/client/petstore/perl/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/perl/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 00000000000..aa02dc37dbb --- /dev/null +++ b/samples/client/petstore/perl/docs/ArrayOfArrayOfNumberOnly.md @@ -0,0 +1,15 @@ +# WWW::SwaggerClient::Object::ArrayOfArrayOfNumberOnly + +## Load the model package +```perl +use WWW::SwaggerClient::Object::ArrayOfArrayOfNumberOnly; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**array_array_number** | **ARRAY[ARRAY[Number]]** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/perl/docs/ArrayOfNumberOnly.md b/samples/client/petstore/perl/docs/ArrayOfNumberOnly.md new file mode 100644 index 00000000000..326b28c8afe --- /dev/null +++ b/samples/client/petstore/perl/docs/ArrayOfNumberOnly.md @@ -0,0 +1,15 @@ +# WWW::SwaggerClient::Object::ArrayOfNumberOnly + +## Load the model package +```perl +use WWW::SwaggerClient::Object::ArrayOfNumberOnly; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**array_number** | [**ARRAY[Number]**](Number.md) | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/perl/docs/Client.md b/samples/client/petstore/perl/docs/Client.md new file mode 100644 index 00000000000..08f3b74f010 --- /dev/null +++ b/samples/client/petstore/perl/docs/Client.md @@ -0,0 +1,15 @@ +# WWW::SwaggerClient::Object::Client + +## Load the model package +```perl +use WWW::SwaggerClient::Object::Client; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**client** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/perl/docs/EnumArrays.md b/samples/client/petstore/perl/docs/EnumArrays.md new file mode 100644 index 00000000000..b693b9a2641 --- /dev/null +++ b/samples/client/petstore/perl/docs/EnumArrays.md @@ -0,0 +1,16 @@ +# WWW::SwaggerClient::Object::EnumArrays + +## Load the model package +```perl +use WWW::SwaggerClient::Object::EnumArrays; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**just_symbol** | **string** | | [optional] +**array_enum** | **ARRAY[string]** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/perl/docs/HasOnlyReadOnly.md b/samples/client/petstore/perl/docs/HasOnlyReadOnly.md new file mode 100644 index 00000000000..04b609cb12b --- /dev/null +++ b/samples/client/petstore/perl/docs/HasOnlyReadOnly.md @@ -0,0 +1,16 @@ +# WWW::SwaggerClient::Object::HasOnlyReadOnly + +## Load the model package +```perl +use WWW::SwaggerClient::Object::HasOnlyReadOnly; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **string** | | [optional] +**foo** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/perl/docs/List.md b/samples/client/petstore/perl/docs/List.md new file mode 100644 index 00000000000..ea7bbed15a2 --- /dev/null +++ b/samples/client/petstore/perl/docs/List.md @@ -0,0 +1,15 @@ +# WWW::SwaggerClient::Object::List + +## Load the model package +```perl +use WWW::SwaggerClient::Object::List; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_123_list** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/perl/docs/MapTest.md b/samples/client/petstore/perl/docs/MapTest.md new file mode 100644 index 00000000000..8105d4d8756 --- /dev/null +++ b/samples/client/petstore/perl/docs/MapTest.md @@ -0,0 +1,16 @@ +# WWW::SwaggerClient::Object::MapTest + +## Load the model package +```perl +use WWW::SwaggerClient::Object::MapTest; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**map_map_of_string** | **HASH[string,HASH[string,string]]** | | [optional] +**map_of_enum_string** | **HASH[string,string]** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/perl/docs/NumberOnly.md b/samples/client/petstore/perl/docs/NumberOnly.md new file mode 100644 index 00000000000..068017e8fb6 --- /dev/null +++ b/samples/client/petstore/perl/docs/NumberOnly.md @@ -0,0 +1,15 @@ +# WWW::SwaggerClient::Object::NumberOnly + +## Load the model package +```perl +use WWW::SwaggerClient::Object::NumberOnly; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**just_number** | [**Number**](Number.md) | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ArrayOfArrayOfNumberOnly.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ArrayOfArrayOfNumberOnly.pm new file mode 100644 index 00000000000..5d2a2f5e575 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ArrayOfArrayOfNumberOnly.pm @@ -0,0 +1,189 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +package WWW::SwaggerClient::Object::ArrayOfArrayOfNumberOnly; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + +use base ("Class::Accessor", "Class::Data::Inheritable"); + + +# +# +# +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen +# + +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +__PACKAGE__->mk_classdata('attribute_map' => {}); +__PACKAGE__->mk_classdata('swagger_types' => {}); +__PACKAGE__->mk_classdata('method_documentation' => {}); +__PACKAGE__->mk_classdata('class_documentation' => {}); + +# new object +sub new { + my ($class, %args) = @_; + + my $self = bless {}, $class; + + foreach my $attribute (keys %{$class->attribute_map}) { + my $args_key = $class->attribute_map->{$attribute}; + $self->$attribute( $args{ $args_key } ); + } + + return $self; +} + +# return perl hash +sub to_hash { + return decode_json(JSON->new->convert_blessed->encode( shift )); +} + +# used by JSON for serialization +sub TO_JSON { + my $self = shift; + my $_data = {}; + foreach my $_key (keys %{$self->attribute_map}) { + if (defined $self->{$_key}) { + $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; + } + } + return $_data; +} + +# from Perl hashref +sub from_hash { + my ($self, $hash) = @_; + + # loop through attributes and use swagger_types to deserialize the data + while ( my ($_key, $_type) = each %{$self->swagger_types} ) { + my $_json_attribute = $self->attribute_map->{$_key}; + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$_json_attribute}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); + } else { + $log->debugf("Warning: %s (%s) does not exist in input hash\n", $_key, $_json_attribute); + } + } + + return $self; +} + +# deserialize non-array data +sub _deserialize { + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; + return $_instance->from_hash($data); + } +} + + + +__PACKAGE__->class_documentation({description => '', + class => 'ArrayOfArrayOfNumberOnly', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'array_array_number' => { + datatype => 'ARRAY[ARRAY[Number]]', + base_name => 'ArrayArrayNumber', + description => '', + format => '', + read_only => '', + }, +}); + +__PACKAGE__->swagger_types( { + 'array_array_number' => 'ARRAY[ARRAY[Number]]' +} ); + +__PACKAGE__->attribute_map( { + 'array_array_number' => 'ArrayArrayNumber' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ArrayOfNumberOnly.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ArrayOfNumberOnly.pm new file mode 100644 index 00000000000..4f3dbc51ece --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ArrayOfNumberOnly.pm @@ -0,0 +1,189 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +package WWW::SwaggerClient::Object::ArrayOfNumberOnly; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + +use base ("Class::Accessor", "Class::Data::Inheritable"); + + +# +# +# +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen +# + +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +__PACKAGE__->mk_classdata('attribute_map' => {}); +__PACKAGE__->mk_classdata('swagger_types' => {}); +__PACKAGE__->mk_classdata('method_documentation' => {}); +__PACKAGE__->mk_classdata('class_documentation' => {}); + +# new object +sub new { + my ($class, %args) = @_; + + my $self = bless {}, $class; + + foreach my $attribute (keys %{$class->attribute_map}) { + my $args_key = $class->attribute_map->{$attribute}; + $self->$attribute( $args{ $args_key } ); + } + + return $self; +} + +# return perl hash +sub to_hash { + return decode_json(JSON->new->convert_blessed->encode( shift )); +} + +# used by JSON for serialization +sub TO_JSON { + my $self = shift; + my $_data = {}; + foreach my $_key (keys %{$self->attribute_map}) { + if (defined $self->{$_key}) { + $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; + } + } + return $_data; +} + +# from Perl hashref +sub from_hash { + my ($self, $hash) = @_; + + # loop through attributes and use swagger_types to deserialize the data + while ( my ($_key, $_type) = each %{$self->swagger_types} ) { + my $_json_attribute = $self->attribute_map->{$_key}; + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$_json_attribute}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); + } else { + $log->debugf("Warning: %s (%s) does not exist in input hash\n", $_key, $_json_attribute); + } + } + + return $self; +} + +# deserialize non-array data +sub _deserialize { + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; + return $_instance->from_hash($data); + } +} + + + +__PACKAGE__->class_documentation({description => '', + class => 'ArrayOfNumberOnly', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'array_number' => { + datatype => 'ARRAY[Number]', + base_name => 'ArrayNumber', + description => '', + format => '', + read_only => '', + }, +}); + +__PACKAGE__->swagger_types( { + 'array_number' => 'ARRAY[Number]' +} ); + +__PACKAGE__->attribute_map( { + 'array_number' => 'ArrayNumber' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Client.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Client.pm new file mode 100644 index 00000000000..71072a8c809 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Client.pm @@ -0,0 +1,189 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +package WWW::SwaggerClient::Object::Client; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + +use base ("Class::Accessor", "Class::Data::Inheritable"); + + +# +# +# +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen +# + +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +__PACKAGE__->mk_classdata('attribute_map' => {}); +__PACKAGE__->mk_classdata('swagger_types' => {}); +__PACKAGE__->mk_classdata('method_documentation' => {}); +__PACKAGE__->mk_classdata('class_documentation' => {}); + +# new object +sub new { + my ($class, %args) = @_; + + my $self = bless {}, $class; + + foreach my $attribute (keys %{$class->attribute_map}) { + my $args_key = $class->attribute_map->{$attribute}; + $self->$attribute( $args{ $args_key } ); + } + + return $self; +} + +# return perl hash +sub to_hash { + return decode_json(JSON->new->convert_blessed->encode( shift )); +} + +# used by JSON for serialization +sub TO_JSON { + my $self = shift; + my $_data = {}; + foreach my $_key (keys %{$self->attribute_map}) { + if (defined $self->{$_key}) { + $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; + } + } + return $_data; +} + +# from Perl hashref +sub from_hash { + my ($self, $hash) = @_; + + # loop through attributes and use swagger_types to deserialize the data + while ( my ($_key, $_type) = each %{$self->swagger_types} ) { + my $_json_attribute = $self->attribute_map->{$_key}; + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$_json_attribute}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); + } else { + $log->debugf("Warning: %s (%s) does not exist in input hash\n", $_key, $_json_attribute); + } + } + + return $self; +} + +# deserialize non-array data +sub _deserialize { + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; + return $_instance->from_hash($data); + } +} + + + +__PACKAGE__->class_documentation({description => '', + class => 'Client', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'client' => { + datatype => 'string', + base_name => 'client', + description => '', + format => '', + read_only => '', + }, +}); + +__PACKAGE__->swagger_types( { + 'client' => 'string' +} ); + +__PACKAGE__->attribute_map( { + 'client' => 'client' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/EnumArrays.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/EnumArrays.pm new file mode 100644 index 00000000000..b4afe389e7d --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/EnumArrays.pm @@ -0,0 +1,198 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +package WWW::SwaggerClient::Object::EnumArrays; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + +use base ("Class::Accessor", "Class::Data::Inheritable"); + + +# +# +# +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen +# + +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +__PACKAGE__->mk_classdata('attribute_map' => {}); +__PACKAGE__->mk_classdata('swagger_types' => {}); +__PACKAGE__->mk_classdata('method_documentation' => {}); +__PACKAGE__->mk_classdata('class_documentation' => {}); + +# new object +sub new { + my ($class, %args) = @_; + + my $self = bless {}, $class; + + foreach my $attribute (keys %{$class->attribute_map}) { + my $args_key = $class->attribute_map->{$attribute}; + $self->$attribute( $args{ $args_key } ); + } + + return $self; +} + +# return perl hash +sub to_hash { + return decode_json(JSON->new->convert_blessed->encode( shift )); +} + +# used by JSON for serialization +sub TO_JSON { + my $self = shift; + my $_data = {}; + foreach my $_key (keys %{$self->attribute_map}) { + if (defined $self->{$_key}) { + $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; + } + } + return $_data; +} + +# from Perl hashref +sub from_hash { + my ($self, $hash) = @_; + + # loop through attributes and use swagger_types to deserialize the data + while ( my ($_key, $_type) = each %{$self->swagger_types} ) { + my $_json_attribute = $self->attribute_map->{$_key}; + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$_json_attribute}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); + } else { + $log->debugf("Warning: %s (%s) does not exist in input hash\n", $_key, $_json_attribute); + } + } + + return $self; +} + +# deserialize non-array data +sub _deserialize { + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; + return $_instance->from_hash($data); + } +} + + + +__PACKAGE__->class_documentation({description => '', + class => 'EnumArrays', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'just_symbol' => { + datatype => 'string', + base_name => 'just_symbol', + description => '', + format => '', + read_only => '', + }, + 'array_enum' => { + datatype => 'ARRAY[string]', + base_name => 'array_enum', + description => '', + format => '', + read_only => '', + }, +}); + +__PACKAGE__->swagger_types( { + 'just_symbol' => 'string', + 'array_enum' => 'ARRAY[string]' +} ); + +__PACKAGE__->attribute_map( { + 'just_symbol' => 'just_symbol', + 'array_enum' => 'array_enum' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/HasOnlyReadOnly.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/HasOnlyReadOnly.pm new file mode 100644 index 00000000000..7cb93df26de --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/HasOnlyReadOnly.pm @@ -0,0 +1,198 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +package WWW::SwaggerClient::Object::HasOnlyReadOnly; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + +use base ("Class::Accessor", "Class::Data::Inheritable"); + + +# +# +# +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen +# + +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +__PACKAGE__->mk_classdata('attribute_map' => {}); +__PACKAGE__->mk_classdata('swagger_types' => {}); +__PACKAGE__->mk_classdata('method_documentation' => {}); +__PACKAGE__->mk_classdata('class_documentation' => {}); + +# new object +sub new { + my ($class, %args) = @_; + + my $self = bless {}, $class; + + foreach my $attribute (keys %{$class->attribute_map}) { + my $args_key = $class->attribute_map->{$attribute}; + $self->$attribute( $args{ $args_key } ); + } + + return $self; +} + +# return perl hash +sub to_hash { + return decode_json(JSON->new->convert_blessed->encode( shift )); +} + +# used by JSON for serialization +sub TO_JSON { + my $self = shift; + my $_data = {}; + foreach my $_key (keys %{$self->attribute_map}) { + if (defined $self->{$_key}) { + $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; + } + } + return $_data; +} + +# from Perl hashref +sub from_hash { + my ($self, $hash) = @_; + + # loop through attributes and use swagger_types to deserialize the data + while ( my ($_key, $_type) = each %{$self->swagger_types} ) { + my $_json_attribute = $self->attribute_map->{$_key}; + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$_json_attribute}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); + } else { + $log->debugf("Warning: %s (%s) does not exist in input hash\n", $_key, $_json_attribute); + } + } + + return $self; +} + +# deserialize non-array data +sub _deserialize { + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; + return $_instance->from_hash($data); + } +} + + + +__PACKAGE__->class_documentation({description => '', + class => 'HasOnlyReadOnly', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'bar' => { + datatype => 'string', + base_name => 'bar', + description => '', + format => '', + read_only => '', + }, + 'foo' => { + datatype => 'string', + base_name => 'foo', + description => '', + format => '', + read_only => '', + }, +}); + +__PACKAGE__->swagger_types( { + 'bar' => 'string', + 'foo' => 'string' +} ); + +__PACKAGE__->attribute_map( { + 'bar' => 'bar', + 'foo' => 'foo' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/List.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/List.pm new file mode 100644 index 00000000000..da748e627dc --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/List.pm @@ -0,0 +1,189 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +package WWW::SwaggerClient::Object::List; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + +use base ("Class::Accessor", "Class::Data::Inheritable"); + + +# +# +# +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen +# + +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +__PACKAGE__->mk_classdata('attribute_map' => {}); +__PACKAGE__->mk_classdata('swagger_types' => {}); +__PACKAGE__->mk_classdata('method_documentation' => {}); +__PACKAGE__->mk_classdata('class_documentation' => {}); + +# new object +sub new { + my ($class, %args) = @_; + + my $self = bless {}, $class; + + foreach my $attribute (keys %{$class->attribute_map}) { + my $args_key = $class->attribute_map->{$attribute}; + $self->$attribute( $args{ $args_key } ); + } + + return $self; +} + +# return perl hash +sub to_hash { + return decode_json(JSON->new->convert_blessed->encode( shift )); +} + +# used by JSON for serialization +sub TO_JSON { + my $self = shift; + my $_data = {}; + foreach my $_key (keys %{$self->attribute_map}) { + if (defined $self->{$_key}) { + $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; + } + } + return $_data; +} + +# from Perl hashref +sub from_hash { + my ($self, $hash) = @_; + + # loop through attributes and use swagger_types to deserialize the data + while ( my ($_key, $_type) = each %{$self->swagger_types} ) { + my $_json_attribute = $self->attribute_map->{$_key}; + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$_json_attribute}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); + } else { + $log->debugf("Warning: %s (%s) does not exist in input hash\n", $_key, $_json_attribute); + } + } + + return $self; +} + +# deserialize non-array data +sub _deserialize { + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; + return $_instance->from_hash($data); + } +} + + + +__PACKAGE__->class_documentation({description => '', + class => 'List', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + '_123_list' => { + datatype => 'string', + base_name => '123-list', + description => '', + format => '', + read_only => '', + }, +}); + +__PACKAGE__->swagger_types( { + '_123_list' => 'string' +} ); + +__PACKAGE__->attribute_map( { + '_123_list' => '123-list' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/MapTest.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/MapTest.pm new file mode 100644 index 00000000000..5b6f05884b4 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/MapTest.pm @@ -0,0 +1,198 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +package WWW::SwaggerClient::Object::MapTest; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + +use base ("Class::Accessor", "Class::Data::Inheritable"); + + +# +# +# +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen +# + +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +__PACKAGE__->mk_classdata('attribute_map' => {}); +__PACKAGE__->mk_classdata('swagger_types' => {}); +__PACKAGE__->mk_classdata('method_documentation' => {}); +__PACKAGE__->mk_classdata('class_documentation' => {}); + +# new object +sub new { + my ($class, %args) = @_; + + my $self = bless {}, $class; + + foreach my $attribute (keys %{$class->attribute_map}) { + my $args_key = $class->attribute_map->{$attribute}; + $self->$attribute( $args{ $args_key } ); + } + + return $self; +} + +# return perl hash +sub to_hash { + return decode_json(JSON->new->convert_blessed->encode( shift )); +} + +# used by JSON for serialization +sub TO_JSON { + my $self = shift; + my $_data = {}; + foreach my $_key (keys %{$self->attribute_map}) { + if (defined $self->{$_key}) { + $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; + } + } + return $_data; +} + +# from Perl hashref +sub from_hash { + my ($self, $hash) = @_; + + # loop through attributes and use swagger_types to deserialize the data + while ( my ($_key, $_type) = each %{$self->swagger_types} ) { + my $_json_attribute = $self->attribute_map->{$_key}; + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$_json_attribute}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); + } else { + $log->debugf("Warning: %s (%s) does not exist in input hash\n", $_key, $_json_attribute); + } + } + + return $self; +} + +# deserialize non-array data +sub _deserialize { + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; + return $_instance->from_hash($data); + } +} + + + +__PACKAGE__->class_documentation({description => '', + class => 'MapTest', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'map_map_of_string' => { + datatype => 'HASH[string,HASH[string,string]]', + base_name => 'map_map_of_string', + description => '', + format => '', + read_only => '', + }, + 'map_of_enum_string' => { + datatype => 'HASH[string,string]', + base_name => 'map_of_enum_string', + description => '', + format => '', + read_only => '', + }, +}); + +__PACKAGE__->swagger_types( { + 'map_map_of_string' => 'HASH[string,HASH[string,string]]', + 'map_of_enum_string' => 'HASH[string,string]' +} ); + +__PACKAGE__->attribute_map( { + 'map_map_of_string' => 'map_map_of_string', + 'map_of_enum_string' => 'map_of_enum_string' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/NumberOnly.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/NumberOnly.pm new file mode 100644 index 00000000000..ae3486d8470 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/NumberOnly.pm @@ -0,0 +1,189 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +package WWW::SwaggerClient::Object::NumberOnly; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + +use base ("Class::Accessor", "Class::Data::Inheritable"); + + +# +# +# +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen +# + +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +__PACKAGE__->mk_classdata('attribute_map' => {}); +__PACKAGE__->mk_classdata('swagger_types' => {}); +__PACKAGE__->mk_classdata('method_documentation' => {}); +__PACKAGE__->mk_classdata('class_documentation' => {}); + +# new object +sub new { + my ($class, %args) = @_; + + my $self = bless {}, $class; + + foreach my $attribute (keys %{$class->attribute_map}) { + my $args_key = $class->attribute_map->{$attribute}; + $self->$attribute( $args{ $args_key } ); + } + + return $self; +} + +# return perl hash +sub to_hash { + return decode_json(JSON->new->convert_blessed->encode( shift )); +} + +# used by JSON for serialization +sub TO_JSON { + my $self = shift; + my $_data = {}; + foreach my $_key (keys %{$self->attribute_map}) { + if (defined $self->{$_key}) { + $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; + } + } + return $_data; +} + +# from Perl hashref +sub from_hash { + my ($self, $hash) = @_; + + # loop through attributes and use swagger_types to deserialize the data + while ( my ($_key, $_type) = each %{$self->swagger_types} ) { + my $_json_attribute = $self->attribute_map->{$_key}; + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$_json_attribute}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); + } else { + $log->debugf("Warning: %s (%s) does not exist in input hash\n", $_key, $_json_attribute); + } + } + + return $self; +} + +# deserialize non-array data +sub _deserialize { + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; + return $_instance->from_hash($data); + } +} + + + +__PACKAGE__->class_documentation({description => '', + class => 'NumberOnly', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'just_number' => { + datatype => 'Number', + base_name => 'JustNumber', + description => '', + format => '', + read_only => '', + }, +}); + +__PACKAGE__->swagger_types( { + 'just_number' => 'Number' +} ); + +__PACKAGE__->attribute_map( { + 'just_number' => 'JustNumber' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/t/ArrayOfArrayOfNumberOnlyTest.t b/samples/client/petstore/perl/t/ArrayOfArrayOfNumberOnlyTest.t new file mode 100644 index 00000000000..ce67b29d20f --- /dev/null +++ b/samples/client/petstore/perl/t/ArrayOfArrayOfNumberOnlyTest.t @@ -0,0 +1,45 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test cases below to test the model. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::ArrayOfArrayOfNumberOnly'); + +my $instance = WWW::SwaggerClient::Object::ArrayOfArrayOfNumberOnly->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::ArrayOfArrayOfNumberOnly'); + diff --git a/samples/client/petstore/perl/t/ArrayOfNumberOnlyTest.t b/samples/client/petstore/perl/t/ArrayOfNumberOnlyTest.t new file mode 100644 index 00000000000..bd6d5b2aa32 --- /dev/null +++ b/samples/client/petstore/perl/t/ArrayOfNumberOnlyTest.t @@ -0,0 +1,45 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test cases below to test the model. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::ArrayOfNumberOnly'); + +my $instance = WWW::SwaggerClient::Object::ArrayOfNumberOnly->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::ArrayOfNumberOnly'); + diff --git a/samples/client/petstore/perl/t/ClientTest.t b/samples/client/petstore/perl/t/ClientTest.t new file mode 100644 index 00000000000..210aaf9764b --- /dev/null +++ b/samples/client/petstore/perl/t/ClientTest.t @@ -0,0 +1,45 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test cases below to test the model. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::Client'); + +my $instance = WWW::SwaggerClient::Object::Client->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::Client'); + diff --git a/samples/client/petstore/perl/t/EnumArraysTest.t b/samples/client/petstore/perl/t/EnumArraysTest.t new file mode 100644 index 00000000000..5f555e1a2f6 --- /dev/null +++ b/samples/client/petstore/perl/t/EnumArraysTest.t @@ -0,0 +1,45 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test cases below to test the model. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::EnumArrays'); + +my $instance = WWW::SwaggerClient::Object::EnumArrays->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::EnumArrays'); + diff --git a/samples/client/petstore/perl/t/HasOnlyReadOnlyTest.t b/samples/client/petstore/perl/t/HasOnlyReadOnlyTest.t new file mode 100644 index 00000000000..e9a5c45fe24 --- /dev/null +++ b/samples/client/petstore/perl/t/HasOnlyReadOnlyTest.t @@ -0,0 +1,45 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test cases below to test the model. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::HasOnlyReadOnly'); + +my $instance = WWW::SwaggerClient::Object::HasOnlyReadOnly->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::HasOnlyReadOnly'); + diff --git a/samples/client/petstore/perl/t/ListTest.t b/samples/client/petstore/perl/t/ListTest.t new file mode 100644 index 00000000000..b068a9fe2b3 --- /dev/null +++ b/samples/client/petstore/perl/t/ListTest.t @@ -0,0 +1,45 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test cases below to test the model. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::List'); + +my $instance = WWW::SwaggerClient::Object::List->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::List'); + diff --git a/samples/client/petstore/perl/t/MapTestTest.t b/samples/client/petstore/perl/t/MapTestTest.t new file mode 100644 index 00000000000..29e75ad1f03 --- /dev/null +++ b/samples/client/petstore/perl/t/MapTestTest.t @@ -0,0 +1,45 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test cases below to test the model. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::MapTest'); + +my $instance = WWW::SwaggerClient::Object::MapTest->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::MapTest'); + diff --git a/samples/client/petstore/perl/t/NumberOnlyTest.t b/samples/client/petstore/perl/t/NumberOnlyTest.t new file mode 100644 index 00000000000..6c3202a1502 --- /dev/null +++ b/samples/client/petstore/perl/t/NumberOnlyTest.t @@ -0,0 +1,45 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test cases below to test the model. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::NumberOnly'); + +my $instance = WWW::SwaggerClient::Object::NumberOnly->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::NumberOnly'); + From 4337f050f56c5e1e8c0c147a14e3f8f938dbf84d Mon Sep 17 00:00:00 2001 From: Sebastian Haas Date: Sun, 28 Aug 2016 12:30:11 +0200 Subject: [PATCH 287/470] Angular2 rc5 (#3603) * Changes due to changes in Angular's http module. * Added link to issue re Headers clone. Removed use-strict since its emitted by default from TypeScript 1.8 on. * Added missing import for ResponseContentType. * Added null check fix for Angular http issue. * Updated package.json and typings Signed-off-by: Sebastian Haas --- .../TypeScriptAngular2ClientCodegen.java | 43 +++++++++++ .../typescript-angular2/api.mustache | 76 ++++++++++++------- .../typescript-angular2/model.mustache | 1 - .../typescript-angular2/package.mustache | 38 ++++++---- .../typescript-angular2/typings.mustache | 6 +- 5 files changed, 117 insertions(+), 47 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngular2ClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngular2ClientCodegen.java index b8a9f772ad1..1020375356a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngular2ClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngular2ClientCodegen.java @@ -3,10 +3,13 @@ import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; +import java.util.List; +import java.util.Map; import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenModel; import io.swagger.codegen.CodegenParameter; +import io.swagger.codegen.CodegenOperation; import io.swagger.codegen.SupportingFile; import io.swagger.models.ModelImpl; import io.swagger.models.properties.ArrayProperty; @@ -163,6 +166,46 @@ public void postProcessParameter(CodegenParameter parameter) { parameter.dataType = addModelPrefix(parameter.dataType); } + @Override + public Map postProcessOperations(Map operations) { + Map objs = (Map) operations.get("operations"); + List ops = (List) objs.get("operation"); + for (CodegenOperation op : ops) { + // Convert httpMethod to Angular's RequestMethod enum + // https://angular.io/docs/ts/latest/api/http/index/RequestMethod-enum.html + switch (op.httpMethod) { + case "GET": + op.httpMethod = "RequestMethod.Get"; + break; + case "POST": + op.httpMethod = "RequestMethod.Post"; + break; + case "PUT": + op.httpMethod = "RequestMethod.Put"; + break; + case "DELETE": + op.httpMethod = "RequestMethod.Delete"; + break; + case "OPTIONS": + op.httpMethod = "RequestMethod.Options"; + break; + case "HEAD": + op.httpMethod = "RequestMethod.Head"; + break; + case "PATCH": + op.httpMethod = "RequestMethod.Patch"; + break; + default: + throw new RuntimeException("Unknown HTTP Method " + op.httpMethod + " not allowed"); + } + + // Convert path to TypeScript template string + op.path = op.path.replaceAll("\\{(.*?)\\}", "\\$\\{$1\\}"); + } + + return operations; + } + public String getNpmName() { return npmName; } diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache index 8565dee4c5a..aadf38be181 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache @@ -1,15 +1,18 @@ {{>licenseInfo}} -import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; -import {Inject, Injectable, Optional} from '@angular/core'; -import {Observable} from 'rxjs/Observable'; -import * as models from '../model/models'; -import {BASE_PATH} from '../variables'; -import 'rxjs/Rx'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { Http, Headers, URLSearchParams } from '@angular/http'; +import { RequestMethod, RequestOptions, RequestOptionsArgs } from '@angular/http'; +import { Response, ResponseContentType } from '@angular/http'; + +import { Observable } from 'rxjs/Observable'; +import 'rxjs/add/operator/map'; + +import * as models from '../model/models'; +import { BASE_PATH } from '../variables'; /* tslint:disable:no-unused-variable member-ordering */ {{#operations}} -'use strict'; {{#description}} /** @@ -19,7 +22,7 @@ import 'rxjs/Rx'; @Injectable() export class {{classname}} { protected basePath = '{{basePath}}'; - public defaultHeaders : Headers = new Headers(); + public defaultHeaders: Headers = new Headers(); constructor(protected http: Http, @Optional()@Inject(BASE_PATH) basePath: string) { if (basePath) { @@ -33,12 +36,11 @@ export class {{classname}} { * {{notes}} {{#allParams}}* @param {{paramName}} {{description}} {{/allParams}}*/ - public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}extraHttpRequestParams?: any): Observable<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}{}{{/returnType}}> { - const path = this.basePath + '{{path}}'{{#pathParams}} - .replace('{' + '{{baseName}}' + '}', String({{paramName}})){{/pathParams}}; + public {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}extraHttpRequestParams?: any): Observable<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}{}{{/returnType}}> { + const path = this.basePath + `{{path}}`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 {{#hasFormParams}} let formParams = new URLSearchParams(); @@ -57,29 +59,49 @@ export class {{classname}} { } {{/queryParams}} -{{#headerParams}} - headerParams.set('{{baseName}}', String({{paramName}})); +{{#headers}} + headers.set('{{baseName}}', String({{paramName}})); + +{{/headers}} + + // to determine the Content-Type header + let consumes: string[] = [ + {{#consumes}} + '{{{mediaType}}}'{{#hasMore}}, {{/hasMore}} + {{/consumes}} + ]; + + // to determine the Accept header + let produces: string[] = [ + {{#produces}} + '{{{mediaType}}}'{{#hasMore}}, {{/hasMore}} + {{/produces}} + ]; -{{/headerParams}} {{#hasFormParams}} - headerParams.set('Content-Type', 'application/x-www-form-urlencoded'); + headers.set('Content-Type', 'application/x-www-form-urlencoded'); {{/hasFormParams}} +{{#bodyParam}} + headers.set('Content-Type', 'application/json'); + +{{/bodyParam}} {{#formParams}} formParams['{{baseName}}'] = {{paramName}}; {{/formParams}} - let requestOptions: RequestOptionsArgs = { - method: '{{httpMethod}}', - headers: headerParams, - search: queryParameters - }; - {{#bodyParam}} - requestOptions.body = JSON.stringify({{paramName}}); - {{/bodyParam}} - {{#hasFormParams}} - requestOptions.body = formParams.toString(); - {{/hasFormParams}} + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: {{httpMethod}}, + headers: headers, +{{#bodyParam}} + body: {{paramName}} == null ? '' : JSON.stringify({{paramName}}), // https://github.com/angular/angular/issues/10612 +{{/bodyParam}} +{{#hasFormParams}} + body: formParams.toString(), +{{/hasFormParams}} + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/model.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/model.mustache index 4e7a0d87a48..09320aa89d3 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/model.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/model.mustache @@ -1,7 +1,6 @@ {{>licenseInfo}} {{#models}} {{#model}} -'use strict'; import * as models from './models'; {{#description}} diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/package.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/package.mustache index 70cb98cce7e..6527831e62d 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/package.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/package.mustache @@ -13,27 +13,33 @@ "main": "./lib/index.js", "typings": "./lib/index.d.ts", "scripts": { - "build": "typings install && tsc" + "build": "typings install && tsc", + "postinstall": "npm run build" }, "peerDependencies": { - "@angular/core": "^2.0.0-rc.1", - "@angular/http": "^2.0.0-rc.1" + "@angular/core": "^2.0.0-rc.5", + "@angular/http": "^2.0.0-rc.5", + "@angular/common": "^2.0.0-rc.5", + "@angular/compiler": "^2.0.0-rc.5", + "core-js": "^2.4.0", + "reflect-metadata": "^0.1.3", + "rxjs": "5.0.0-beta.6", + "zone.js": "^0.6.17" }, "devDependencies": { - "@angular/common": "^2.0.0-rc.1", - "@angular/compiler": "^2.0.0-rc.1", - "@angular/core": "^2.0.0-rc.1", - "@angular/http": "^2.0.0-rc.1", - "@angular/platform-browser": "^2.0.0-rc.1", - "@angular/platform-browser-dynamic": "^2.0.0-rc.1", - "core-js": "^2.3.0", - "rxjs": "^5.0.0-beta.6", - "zone.js": "^0.6.12", + "@angular/core": "^2.0.0-rc.5", + "@angular/http": "^2.0.0-rc.5", + "@angular/common": "^2.0.0-rc.5", + "@angular/compiler": "^2.0.0-rc.5", + "@angular/platform-browser": "^2.0.0-rc.5", + "core-js": "^2.4.0", + "reflect-metadata": "^0.1.3", + "rxjs": "5.0.0-beta.6", + "zone.js": "^0.6.17", "typescript": "^1.8.10", - "typings": "^0.8.1", - "es6-shim": "^0.35.0", - "es7-reflect-metadata": "^1.6.0" - }{{#npmRepository}}, + "typings": "^1.3.2" + }{{#npmRepository}},{{/npmRepository}} +{{#npmRepository}} "publishConfig":{ "registry":"{{npmRepository}}" } diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/typings.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/typings.mustache index 0848dcffe31..507c40e5cbe 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/typings.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/typings.mustache @@ -1,5 +1,5 @@ { - "ambientDependencies": { - "core-js": "registry:dt/core-js#0.0.0+20160317120654" + "globalDependencies": { + "core-js": "registry:dt/core-js#0.0.0+20160725163759" } -} \ No newline at end of file +} From 9c92bcb69309ce559a3e64178bd00510ee7aef0e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Sun, 28 Aug 2016 15:11:32 +0300 Subject: [PATCH 288/470] perl: Sync default user agent with other languages --- .../src/main/resources/perl/Configuration.mustache | 2 +- .../client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache b/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache index 8fc7ef1a579..135349fdd82 100644 --- a/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache @@ -17,7 +17,7 @@ use constant VERSION => '{{moduleVersion}}'; # class/static variables our $http_timeout = 180; -our $http_user_agent = 'Perl-Swagger'; +our $http_user_agent = '{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{moduleVersion}}}/perl{{/httpUserAgent}}'; # authentication setting our $api_key = {}; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm index fa58024872b..f5489e038b1 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm @@ -42,7 +42,7 @@ use constant VERSION => '1.0.0'; # class/static variables our $http_timeout = 180; -our $http_user_agent = 'Perl-Swagger'; +our $http_user_agent = 'Swagger-Codegen/1.0.0/perl'; # authentication setting our $api_key = {}; From 2fbec6d9ebfe6d53ed560e4a9f7feeb728ae84de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Sun, 28 Aug 2016 17:05:34 +0300 Subject: [PATCH 289/470] Spelling fixes --- .../swagger-codegen/src/main/resources/Java/README.mustache | 2 +- .../src/main/resources/Java/libraries/feign/README.mustache | 2 +- .../main/resources/Java/libraries/retrofit/README.mustache | 2 +- .../src/main/resources/android/README.mustache | 2 +- .../swagger-codegen/src/main/resources/objc/README.mustache | 2 +- .../swagger-codegen/src/main/resources/perl/README.mustache | 2 +- samples/client/petstore/android/httpclient/README.md | 2 +- samples/client/petstore/android/volley/README.md | 2 +- samples/client/petstore/objc/core-data/README.md | 4 ++-- samples/client/petstore/objc/default/README.md | 4 ++-- samples/client/petstore/perl/README.md | 4 ++-- 11 files changed, 14 insertions(+), 14 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/README.mustache b/modules/swagger-codegen/src/main/resources/Java/README.mustache index 6849db6f8fe..17d2a93d43c 100644 --- a/modules/swagger-codegen/src/main/resources/Java/README.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/README.mustache @@ -140,7 +140,7 @@ Class | Method | HTTP request | Description ## Recommendation -It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issue. +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. ## Author diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/README.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/README.mustache index 50e2cf3fbe9..56560172ee3 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/README.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/README.mustache @@ -34,7 +34,7 @@ After the client library is installed/deployed, you can use it in your Maven pro ## Recommendation -It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issue. +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. ## Author diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/README.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/README.mustache index 50e2cf3fbe9..56560172ee3 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/README.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/README.mustache @@ -34,7 +34,7 @@ After the client library is installed/deployed, you can use it in your Maven pro ## Recommendation -It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issue. +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. ## Author diff --git a/modules/swagger-codegen/src/main/resources/android/README.mustache b/modules/swagger-codegen/src/main/resources/android/README.mustache index 8091b0adb06..4834927cd51 100644 --- a/modules/swagger-codegen/src/main/resources/android/README.mustache +++ b/modules/swagger-codegen/src/main/resources/android/README.mustache @@ -117,7 +117,7 @@ Class | Method | HTTP request | Description ## Recommendation -It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issue. +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. ## Author diff --git a/modules/swagger-codegen/src/main/resources/objc/README.mustache b/modules/swagger-codegen/src/main/resources/objc/README.mustache index 4355ecc1af5..8be7faffa3b 100644 --- a/modules/swagger-codegen/src/main/resources/objc/README.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/README.mustache @@ -55,7 +55,7 @@ Import the following: ## Recommendation -It's recommended to create an instance of ApiClient per thread in a multi-threaded environment to avoid any potential issue. +It's recommended to create an instance of ApiClient per thread in a multi-threaded environment to avoid any potential issues. ## Getting Started diff --git a/modules/swagger-codegen/src/main/resources/perl/README.mustache b/modules/swagger-codegen/src/main/resources/perl/README.mustache index 60f810eeb30..c732448cecf 100644 --- a/modules/swagger-codegen/src/main/resources/perl/README.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/README.mustache @@ -292,7 +292,7 @@ Class | Method | HTTP request | Description {{#models}}{{#model}} - [{{moduleName}}::Object::{{classname}}]({{modelDocPath}}{{classname}}.md) {{/model}}{{/models}} -# DOCUMENTATION FOR AUTHORIATION +# DOCUMENTATION FOR AUTHORIZATION {{^authMethods}} All endpoints do not require authorization. {{/authMethods}}{{#authMethods}}{{#last}} Authentication schemes defined for the API:{{/last}}{{/authMethods}} {{#authMethods}}## {{{name}}} diff --git a/samples/client/petstore/android/httpclient/README.md b/samples/client/petstore/android/httpclient/README.md index 65931066a32..3c9dcf27af0 100644 --- a/samples/client/petstore/android/httpclient/README.md +++ b/samples/client/petstore/android/httpclient/README.md @@ -134,7 +134,7 @@ Authentication schemes defined for the API: ## Recommendation -It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issue. +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. ## Author diff --git a/samples/client/petstore/android/volley/README.md b/samples/client/petstore/android/volley/README.md index e4aa4748243..c92f468b12b 100644 --- a/samples/client/petstore/android/volley/README.md +++ b/samples/client/petstore/android/volley/README.md @@ -134,7 +134,7 @@ Authentication schemes defined for the API: ## Recommendation -It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issue. +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. ## Author diff --git a/samples/client/petstore/objc/core-data/README.md b/samples/client/petstore/objc/core-data/README.md index 3fe81114d77..4474fdf4ce1 100644 --- a/samples/client/petstore/objc/core-data/README.md +++ b/samples/client/petstore/objc/core-data/README.md @@ -6,7 +6,7 @@ This ObjC package is automatically generated by the [Swagger Codegen](https://gi - API version: 1.0.0 - Package version: -- Build date: 2016-07-19T16:53:26.476+08:00 +- Build date: 2016-08-28T17:01:51.939+03:00 - Build package: class io.swagger.codegen.languages.ObjcClientCodegen ## Requirements @@ -56,7 +56,7 @@ Import the following: ## Recommendation -It's recommended to create an instance of ApiClient per thread in a multi-threaded environment to avoid any potential issue. +It's recommended to create an instance of ApiClient per thread in a multi-threaded environment to avoid any potential issues. ## Getting Started diff --git a/samples/client/petstore/objc/default/README.md b/samples/client/petstore/objc/default/README.md index 808a950606e..9852443b866 100644 --- a/samples/client/petstore/objc/default/README.md +++ b/samples/client/petstore/objc/default/README.md @@ -6,7 +6,7 @@ This ObjC package is automatically generated by the [Swagger Codegen](https://gi - API version: 1.0.0 - Package version: -- Build date: 2016-07-19T16:53:24.981+08:00 +- Build date: 2016-08-28T17:01:51.110+03:00 - Build package: class io.swagger.codegen.languages.ObjcClientCodegen ## Requirements @@ -56,7 +56,7 @@ Import the following: ## Recommendation -It's recommended to create an instance of ApiClient per thread in a multi-threaded environment to avoid any potential issue. +It's recommended to create an instance of ApiClient per thread in a multi-threaded environment to avoid any potential issues. ## Getting Started diff --git a/samples/client/petstore/perl/README.md b/samples/client/petstore/perl/README.md index 18df4f126f3..134da972c30 100644 --- a/samples/client/petstore/perl/README.md +++ b/samples/client/petstore/perl/README.md @@ -10,7 +10,7 @@ Automatically generated by the [Swagger Codegen](https://github.com/swagger-api/ - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-08-28T15:57:37.016+08:00 +- Build date: 2016-08-28T17:02:32.695+03:00 - Build package: class io.swagger.codegen.languages.PerlClientCodegen ## A note on Moose @@ -389,7 +389,7 @@ Class | Method | HTTP request | Description - [WWW::SwaggerClient::Object::User](docs/User.md) -# DOCUMENTATION FOR AUTHORIATION +# DOCUMENTATION FOR AUTHORIZATION ## api_key From 46c3bef40fb1934b4df18ea68c94fc417ff3d615 Mon Sep 17 00:00:00 2001 From: Brent Ryan Date: Sun, 28 Aug 2016 20:49:30 -0400 Subject: [PATCH 290/470] Fix to case of propertyClass which pukes on most checkstyle rules in java --- .../java/io/swagger/codegen/languages/AbstractJavaCodegen.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java index 5078328554a..4565eafd4da 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java @@ -351,7 +351,7 @@ public String toVarName(String name) { name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. if ("class".equals(name.toLowerCase())) { - return "PropertyClass"; + return "propertyClass"; } if("_".equals(name)) { From 8dfe230b7cd3a15f9cc701222c57da0d250fca6d Mon Sep 17 00:00:00 2001 From: sidhantgoyal Date: Mon, 29 Aug 2016 14:01:49 +0530 Subject: [PATCH 291/470] [android] volley socket timeout configurable (#3646) * [android] volley socket timeout configurable * Updated Android Volley Petstore sample --- .../android/libraries/volley/apiInvoker.mustache | 8 +++++++- samples/client/petstore/android/volley/README.md | 12 ++++++------ .../client/petstore/android/volley/docs/PetApi.md | 2 +- .../src/main/java/io/swagger/client/ApiInvoker.java | 10 ++++++++-- .../src/main/java/io/swagger/client/api/PetApi.java | 4 ++-- 5 files changed, 24 insertions(+), 12 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiInvoker.mustache index 76019d7c45e..94b6be45860 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiInvoker.mustache @@ -2,6 +2,7 @@ package {{invokerPackage}}; import com.android.volley.Cache; +import com.android.volley.DefaultRetryPolicy; import com.android.volley.Network; import com.android.volley.Request; import com.android.volley.RequestQueue; @@ -486,7 +487,12 @@ public class ApiInvoker { } else { request = new PatchRequest(url, headers, null, null, stringRequest, errorListener); } - } + } + + if (request != null) { + request.setRetryPolicy(new DefaultRetryPolicy((int)TimeUnit.SECONDS.toMillis(this.connectionTimeout), DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); + } + return request; } diff --git a/samples/client/petstore/android/volley/README.md b/samples/client/petstore/android/volley/README.md index c92f468b12b..7693866ff60 100644 --- a/samples/client/petstore/android/volley/README.md +++ b/samples/client/petstore/android/volley/README.md @@ -116,12 +116,6 @@ Class | Method | HTTP request | Description ## Documentation for Authorization Authentication schemes defined for the API: -### api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - ### petstore_auth - **Type**: OAuth @@ -131,6 +125,12 @@ Authentication schemes defined for the API: - write:pets: modify pets in your account - read:pets: read your pets +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + ## Recommendation diff --git a/samples/client/petstore/android/volley/docs/PetApi.md b/samples/client/petstore/android/volley/docs/PetApi.md index e7b393c8ea7..ff596b3d918 100644 --- a/samples/client/petstore/android/volley/docs/PetApi.md +++ b/samples/client/petstore/android/volley/docs/PetApi.md @@ -222,7 +222,7 @@ Name | Type | Description | Notes ### Authorization -[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) +[petstore_auth](../README.md#petstore_auth), [api_key](../README.md#api_key) ### HTTP request headers diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiInvoker.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiInvoker.java index 5867d0a3146..ec17f4582d4 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiInvoker.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiInvoker.java @@ -25,6 +25,7 @@ package io.swagger.client; import com.android.volley.Cache; +import com.android.volley.DefaultRetryPolicy; import com.android.volley.Network; import com.android.volley.Request; import com.android.volley.RequestQueue; @@ -213,9 +214,9 @@ public static void initializeInstance(Cache cache, Network network, int threadPo // Setup authentications (key: authentication name, value: authentication). INSTANCE.authentications = new HashMap(); - INSTANCE.authentications.put("api_key", new ApiKeyAuth("header", "api_key")); // TODO: comment out below as OAuth does not exist //INSTANCE.authentications.put("petstore_auth", new OAuth()); + INSTANCE.authentications.put("api_key", new ApiKeyAuth("header", "api_key")); // Prevent the authentications from being modified. INSTANCE.authentications = Collections.unmodifiableMap(INSTANCE.authentications); } @@ -500,7 +501,12 @@ else if ("PATCH".equals(method)) { } else { request = new PatchRequest(url, headers, null, null, stringRequest, errorListener); } - } + } + + if (request != null) { + request.setRetryPolicy(new DefaultRetryPolicy((int)TimeUnit.SECONDS.toMillis(this.connectionTimeout), DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); + } + return request; } diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/PetApi.java index ae9bcead7c5..5ef1079981a 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/PetApi.java @@ -623,7 +623,7 @@ public Pet getPetById (Long petId) throws TimeoutException, ExecutionException, // normal form params } - String[] authNames = new String[] { "api_key", "petstore_auth" }; + String[] authNames = new String[] { "petstore_auth", "api_key" }; try { String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); @@ -693,7 +693,7 @@ public void getPetById (Long petId, final Response.Listener responseListene // normal form params } - String[] authNames = new String[] { "api_key", "petstore_auth" }; + String[] authNames = new String[] { "petstore_auth", "api_key" }; try { apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames, From 10aa68c6b7243800b8419aeb24a9e86debb07a55 Mon Sep 17 00:00:00 2001 From: Zoltan Biro Date: Mon, 29 Aug 2016 16:08:45 +0200 Subject: [PATCH 292/470] Fix empty model object serialization in python client --- .../src/main/resources/python/api_client.mustache | 3 +++ 1 file changed, 3 insertions(+) diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index e75c6be52ed..2ea9b2299cc 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -581,6 +581,9 @@ class ApiClient(object): """ instance = klass() + if(not instance.swagger_types): + return data + for attr, attr_type in iteritems(instance.swagger_types): if data is not None \ and instance.attribute_map[attr] in data\ From b050ba9dc3536f173a7b93d91a309603f4e709aa Mon Sep 17 00:00:00 2001 From: Zoltan Biro Date: Mon, 29 Aug 2016 16:47:22 +0200 Subject: [PATCH 293/470] regenerate petstore sample --- samples/client/petstore/python/README.md | 2 +- samples/client/petstore/python/petstore_api/api_client.py | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/samples/client/petstore/python/README.md b/samples/client/petstore/python/README.md index db827de9ceb..3f9cea1e35a 100644 --- a/samples/client/petstore/python/README.md +++ b/samples/client/petstore/python/README.md @@ -5,7 +5,7 @@ This Python package is automatically generated by the [Swagger Codegen](https:// - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-08-22T17:54:52.358+08:00 +- Build date: 2016-08-29T16:39:50.642+02:00 - Build package: class io.swagger.codegen.languages.PythonClientCodegen ## Requirements. diff --git a/samples/client/petstore/python/petstore_api/api_client.py b/samples/client/petstore/python/petstore_api/api_client.py index ddfaf2ca744..8fb86fc0964 100644 --- a/samples/client/petstore/python/petstore_api/api_client.py +++ b/samples/client/petstore/python/petstore_api/api_client.py @@ -581,6 +581,9 @@ def __deserialize_model(self, data, klass): """ instance = klass() + if not instance.swagger_types: + return data + for attr, attr_type in iteritems(instance.swagger_types): if data is not None \ and instance.attribute_map[attr] in data\ From 646c4faa62f6391070bfbdda68c14ae504c17f5a Mon Sep 17 00:00:00 2001 From: Zoltan Biro Date: Mon, 29 Aug 2016 16:53:38 +0200 Subject: [PATCH 294/470] fixing python code formatting issue --- .../src/main/resources/python/api_client.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index 2ea9b2299cc..4a8c14c8dd6 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -581,7 +581,7 @@ class ApiClient(object): """ instance = klass() - if(not instance.swagger_types): + if not instance.swagger_types: return data for attr, attr_type in iteritems(instance.swagger_types): From d8406c0dd0be9ed488ef7b36cecb0467e37f59f6 Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 29 Aug 2016 23:21:28 +0800 Subject: [PATCH 295/470] add PR template (#3669) --- .github/PULL_REQUEST_TEMPLATE.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 .github/PULL_REQUEST_TEMPLATE.md diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000000..e111475b78d --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,10 @@ +### PR checklist + +- [ ] Read the [contribution guildelines](https://github.com/swagger-api/swagger-codegen/blob/master/CONTRIBUTING.md). +- [ ] Ran the shell/batch script under `./bin/` to update Petstore sample so that CIs can verify the change. (NOTE: no need to update *all* Petstore sample. For instance, only need to update PHP Petstore sample by running `./bin/php-petstore.sh` if updating the PHP code generator or PHP client's mustache templates) +- [ ] Filed the PR against the correct branch: master for non-breaking changes and `2.3.0` branch for breaking (non-backward compatible) changes. + +### Description of the PR + +(details of the change, additional tests that have been done, reference to the issue for tracking, etc) + From 224fd208e7c7d3f56c3e9f401ef70736b5f96c7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Tue, 30 Aug 2016 05:16:17 +0300 Subject: [PATCH 296/470] Various python cleanups (#3650) * python: Let logging format messages on demand * python: Use six more * python: Remove unused imports * python: flake8 fixes * python: Make examples compatible with Python 3 * python: Spelling fixes --- .../src/main/resources/python/README.mustache | 3 +- .../main/resources/python/api_client.mustache | 41 ++++++------------- .../main/resources/python/api_doc.mustache | 3 +- .../resources/python/configuration.mustache | 11 ++--- .../src/main/resources/python/rest.mustache | 17 +++----- .../python/petstore_api/rest.py | 2 +- samples/client/petstore/python/README.md | 5 ++- .../client/petstore/python/docs/FakeApi.md | 9 ++-- samples/client/petstore/python/docs/PetApi.md | 24 +++++++---- .../client/petstore/python/docs/StoreApi.md | 12 ++++-- .../client/petstore/python/docs/UserApi.md | 24 +++++++---- .../python/petstore_api/api_client.py | 41 ++++++------------- .../python/petstore_api/configuration.py | 11 ++--- .../petstore/python/petstore_api/rest.py | 17 +++----- 14 files changed, 94 insertions(+), 126 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/README.mustache b/modules/swagger-codegen/src/main/resources/python/README.mustache index 08f2d835c4c..d483fc3662a 100644 --- a/modules/swagger-codegen/src/main/resources/python/README.mustache +++ b/modules/swagger-codegen/src/main/resources/python/README.mustache @@ -51,6 +51,7 @@ import {{{packageName}}} Please follow the [installation procedure](#installation--usage) and then run the following: ```python +from __future__ import print_function import time import {{{packageName}}} from {{{packageName}}}.rest import ApiException @@ -76,7 +77,7 @@ try: {{/summary}} {{#returnType}}api_response = {{/returnType}}api_instance.{{{operationId}}}({{#allParams}}{{#required}}{{paramName}}{{/required}}{{^required}}{{paramName}}={{paramName}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}){{#returnType}} pprint(api_response){{/returnType}} except ApiException as e: - print "Exception when calling {{classname}}->{{operationId}}: %s\n" % e + print("Exception when calling {{classname}}->{{operationId}}: %s\n" % e) {{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} ``` diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index e75c6be52ed..c40c1b4b4d5 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -19,17 +19,15 @@ Copyright 2016 SmartBear Software """ from __future__ import absolute_import + from . import models from .rest import RESTClientObject from .rest import ApiException import os import re -import sys -import urllib import json import mimetypes -import random import tempfile import threading @@ -37,22 +35,8 @@ from datetime import datetime from datetime import date # python 2 and python 3 compatibility library -from six import iteritems - -try: - # for python3 - from urllib.parse import quote -except ImportError: - # for python2 - from urllib import quote - -# special handling of `long` (python2 only) -try: - # Python 2 - long -except NameError: - # Python 3 - long = int +from six import PY3, integer_types, iteritems, text_type +from six.moves.urllib.parse import quote from .configuration import Configuration @@ -113,7 +97,7 @@ class ApiClient(object): body=None, post_params=None, files=None, response_type=None, auth_settings=None, callback=None, _return_http_data_only=None): - # headers parameters + # header parameters header_params = header_params or {} header_params.update(self.default_headers) if self.cookie: @@ -167,11 +151,10 @@ class ApiClient(object): if callback: callback(deserialized_data) if _return_http_data_only else callback((deserialized_data, response_data.status, response_data.getheaders())) elif _return_http_data_only: - return ( deserialized_data ); + return (deserialized_data) else: return (deserialized_data, response_data.status, response_data.getheaders()) - def to_path_value(self, obj): """ Takes value and turn it into a string suitable for inclusion in @@ -201,9 +184,7 @@ class ApiClient(object): :param obj: The data to serialize. :return: The serialized form of data. """ - types = (str, int, long, float, bool, tuple) - if sys.version_info < (3, 0): - types = types + (unicode,) + types = (str, float, bool, tuple) + tuple(integer_types) + (text_type,) if isinstance(obj, type(None)): return None elif isinstance(obj, types): @@ -235,7 +216,7 @@ class ApiClient(object): :param response: RESTResponse object to be deserialized. :param response_type: class literal for - deserialzied object, or string of class name. + deserialized object, or string of class name. :return: deserialized object. """ @@ -277,14 +258,16 @@ class ApiClient(object): # convert str to class # for native types - if klass in ['int', 'long', 'float', 'str', 'bool', + if klass in ['int', 'float', 'str', 'bool', "date", 'datetime', "object"]: klass = eval(klass) + elif klass == 'long': + klass = int if PY3 else long # for model types else: klass = eval('models.' + klass) - if klass in [int, long, float, str, bool]: + if klass in integer_types or klass in (float, str, bool): return self.__deserialize_primitive(data, klass) elif klass == object: return self.__deserialize_object(data) @@ -339,7 +322,7 @@ class ApiClient(object): header_params, body, post_params, files, response_type, auth_settings, - callback,_return_http_data_only)) + callback, _return_http_data_only)) thread.start() return thread diff --git a/modules/swagger-codegen/src/main/resources/python/api_doc.mustache b/modules/swagger-codegen/src/main/resources/python/api_doc.mustache index 98dec04a393..f9a212c19e1 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_doc.mustache @@ -19,6 +19,7 @@ Method | HTTP request | Description ### Example ```python +from __future__ import print_statement import time import {{{packageName}}} from {{{packageName}}}.rest import ApiException @@ -45,7 +46,7 @@ try: {{/summary}} {{#returnType}}api_response = {{/returnType}}api_instance.{{{operationId}}}({{#allParams}}{{#required}}{{paramName}}{{/required}}{{^required}}{{paramName}}={{paramName}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}){{#returnType}} pprint(api_response){{/returnType}} except ApiException as e: - print "Exception when calling {{classname}}->{{operationId}}: %s\n" % e + print("Exception when calling {{classname}}->{{operationId}}: %s\n" % e) ``` ### Parameters diff --git a/modules/swagger-codegen/src/main/resources/python/configuration.mustache b/modules/swagger-codegen/src/main/resources/python/configuration.mustache index 3d2e8db228b..5ddc4ab7bca 100644 --- a/modules/swagger-codegen/src/main/resources/python/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/python/configuration.mustache @@ -3,19 +3,14 @@ {{>partial_header}} from __future__ import absolute_import -import base64 -import urllib3 -try: - import httplib -except ImportError: - # for python3 - import http.client as httplib +import urllib3 import sys import logging from six import iteritems +from six.moves import http_client as httplib def singleton(cls, *args, **kw): @@ -220,7 +215,7 @@ class Configuration(object): 'value': self.get_basic_auth_token() }, {{/isBasic}}{{#isOAuth}} - '{{name}}': + '{{name}}': { 'type': 'oauth2', 'in': 'header', diff --git a/modules/swagger-codegen/src/main/resources/python/rest.mustache b/modules/swagger-codegen/src/main/resources/python/rest.mustache index 19ec32440f8..d5133ac84f4 100644 --- a/modules/swagger-codegen/src/main/resources/python/rest.mustache +++ b/modules/swagger-codegen/src/main/resources/python/rest.mustache @@ -4,7 +4,6 @@ from __future__ import absolute_import -import sys import io import json import ssl @@ -13,7 +12,8 @@ import logging import re # python 2 and python 3 compatibility library -from six import iteritems +from six import PY3 +from six.moves.urllib.parse import urlencode from .configuration import Configuration @@ -22,13 +22,6 @@ try: except ImportError: raise ImportError('Swagger python client requires urllib3.') -try: - # for python3 - from urllib.parse import urlencode -except ImportError: - # for python2 - from urllib import urlencode - logger = logging.getLogger(__name__) @@ -100,7 +93,7 @@ class RESTClientObject(object): :param headers: http request headers :param body: request json body, for `application/json` :param post_params: request post parameters, - `application/x-www-form-urlencode` + `application/x-www-form-urlencoded` and `multipart/form-data` """ method = method.upper() @@ -155,11 +148,11 @@ class RESTClientObject(object): # In the python 3, the response.data is bytes. # we need to decode it to string. - if sys.version_info > (3,): + if PY3: r.data = r.data.decode('utf8') # log response body - logger.debug("response body: %s" % r.data) + logger.debug("response body: %s", r.data) if r.status not in range(200, 206): raise ApiException(http_resp=r) diff --git a/samples/client/petstore-security-test/python/petstore_api/rest.py b/samples/client/petstore-security-test/python/petstore_api/rest.py index 2d2bc8ce886..dfb139190d7 100644 --- a/samples/client/petstore-security-test/python/petstore_api/rest.py +++ b/samples/client/petstore-security-test/python/petstore_api/rest.py @@ -178,7 +178,7 @@ def request(self, method, url, query_params=None, headers=None, r.data = r.data.decode('utf8') # log response body - logger.debug("response body: %s" % r.data) + logger.debug("response body: %s", r.data) if r.status not in range(200, 206): raise ApiException(http_resp=r) diff --git a/samples/client/petstore/python/README.md b/samples/client/petstore/python/README.md index db827de9ceb..a2482fc1c6d 100644 --- a/samples/client/petstore/python/README.md +++ b/samples/client/petstore/python/README.md @@ -5,7 +5,7 @@ This Python package is automatically generated by the [Swagger Codegen](https:// - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-08-22T17:54:52.358+08:00 +- Build date: 2016-08-27T14:30:36.450+03:00 - Build package: class io.swagger.codegen.languages.PythonClientCodegen ## Requirements. @@ -46,6 +46,7 @@ import petstore_api Please follow the [installation procedure](#installation--usage) and then run the following: ```python +from __future__ import print_function import time import petstore_api from petstore_api.rest import ApiException @@ -59,7 +60,7 @@ try: api_response = api_instance.test_client_model(body) pprint(api_response) except ApiException as e: - print "Exception when calling FakeApi->test_client_model: %s\n" % e + print("Exception when calling FakeApi->test_client_model: %s\n" % e) ``` diff --git a/samples/client/petstore/python/docs/FakeApi.md b/samples/client/petstore/python/docs/FakeApi.md index cb88dd79d0d..bdece55c7a3 100644 --- a/samples/client/petstore/python/docs/FakeApi.md +++ b/samples/client/petstore/python/docs/FakeApi.md @@ -16,6 +16,7 @@ To test \"client\" model ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -30,7 +31,7 @@ try: api_response = api_instance.test_client_model(body) pprint(api_response) except ApiException as e: - print "Exception when calling FakeApi->test_client_model: %s\n" % e + print("Exception when calling FakeApi->test_client_model: %s\n" % e) ``` ### Parameters @@ -63,6 +64,7 @@ Fake endpoint for testing various parameters 假端點 偽のエンドポイン ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -92,7 +94,7 @@ try: # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 api_instance.test_endpoint_parameters(number, double, pattern_without_delimiter, byte, integer=integer, int32=int32, int64=int64, float=float, string=string, binary=binary, date=date, date_time=date_time, password=password) except ApiException as e: - print "Exception when calling FakeApi->test_endpoint_parameters: %s\n" % e + print("Exception when calling FakeApi->test_endpoint_parameters: %s\n" % e) ``` ### Parameters @@ -135,6 +137,7 @@ To test enum parameters ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -155,7 +158,7 @@ try: # To test enum parameters api_instance.test_enum_parameters(enum_form_string_array=enum_form_string_array, enum_form_string=enum_form_string, enum_header_string_array=enum_header_string_array, enum_header_string=enum_header_string, enum_query_string_array=enum_query_string_array, enum_query_string=enum_query_string, enum_query_integer=enum_query_integer, enum_query_double=enum_query_double) except ApiException as e: - print "Exception when calling FakeApi->test_enum_parameters: %s\n" % e + print("Exception when calling FakeApi->test_enum_parameters: %s\n" % e) ``` ### Parameters diff --git a/samples/client/petstore/python/docs/PetApi.md b/samples/client/petstore/python/docs/PetApi.md index 109b264942f..553c8152138 100644 --- a/samples/client/petstore/python/docs/PetApi.md +++ b/samples/client/petstore/python/docs/PetApi.md @@ -23,6 +23,7 @@ Add a new pet to the store ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -39,7 +40,7 @@ try: # Add a new pet to the store api_instance.add_pet(body) except ApiException as e: - print "Exception when calling PetApi->add_pet: %s\n" % e + print("Exception when calling PetApi->add_pet: %s\n" % e) ``` ### Parameters @@ -72,6 +73,7 @@ Deletes a pet ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -89,7 +91,7 @@ try: # Deletes a pet api_instance.delete_pet(pet_id, api_key=api_key) except ApiException as e: - print "Exception when calling PetApi->delete_pet: %s\n" % e + print("Exception when calling PetApi->delete_pet: %s\n" % e) ``` ### Parameters @@ -123,6 +125,7 @@ Multiple status values can be provided with comma separated strings ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -140,7 +143,7 @@ try: api_response = api_instance.find_pets_by_status(status) pprint(api_response) except ApiException as e: - print "Exception when calling PetApi->find_pets_by_status: %s\n" % e + print("Exception when calling PetApi->find_pets_by_status: %s\n" % e) ``` ### Parameters @@ -173,6 +176,7 @@ Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -190,7 +194,7 @@ try: api_response = api_instance.find_pets_by_tags(tags) pprint(api_response) except ApiException as e: - print "Exception when calling PetApi->find_pets_by_tags: %s\n" % e + print("Exception when calling PetApi->find_pets_by_tags: %s\n" % e) ``` ### Parameters @@ -223,6 +227,7 @@ Returns a single pet ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -242,7 +247,7 @@ try: api_response = api_instance.get_pet_by_id(pet_id) pprint(api_response) except ApiException as e: - print "Exception when calling PetApi->get_pet_by_id: %s\n" % e + print("Exception when calling PetApi->get_pet_by_id: %s\n" % e) ``` ### Parameters @@ -275,6 +280,7 @@ Update an existing pet ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -291,7 +297,7 @@ try: # Update an existing pet api_instance.update_pet(body) except ApiException as e: - print "Exception when calling PetApi->update_pet: %s\n" % e + print("Exception when calling PetApi->update_pet: %s\n" % e) ``` ### Parameters @@ -324,6 +330,7 @@ Updates a pet in the store with form data ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -342,7 +349,7 @@ try: # Updates a pet in the store with form data api_instance.update_pet_with_form(pet_id, name=name, status=status) except ApiException as e: - print "Exception when calling PetApi->update_pet_with_form: %s\n" % e + print("Exception when calling PetApi->update_pet_with_form: %s\n" % e) ``` ### Parameters @@ -377,6 +384,7 @@ uploads an image ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -396,7 +404,7 @@ try: api_response = api_instance.upload_file(pet_id, additional_metadata=additional_metadata, file=file) pprint(api_response) except ApiException as e: - print "Exception when calling PetApi->upload_file: %s\n" % e + print("Exception when calling PetApi->upload_file: %s\n" % e) ``` ### Parameters diff --git a/samples/client/petstore/python/docs/StoreApi.md b/samples/client/petstore/python/docs/StoreApi.md index 6b71a78659d..54007c9e8e7 100644 --- a/samples/client/petstore/python/docs/StoreApi.md +++ b/samples/client/petstore/python/docs/StoreApi.md @@ -19,6 +19,7 @@ For valid response try integer IDs with value < 1000. Anything above 1000 or non ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -32,7 +33,7 @@ try: # Delete purchase order by ID api_instance.delete_order(order_id) except ApiException as e: - print "Exception when calling StoreApi->delete_order: %s\n" % e + print("Exception when calling StoreApi->delete_order: %s\n" % e) ``` ### Parameters @@ -65,6 +66,7 @@ Returns a map of status codes to quantities ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -83,7 +85,7 @@ try: api_response = api_instance.get_inventory() pprint(api_response) except ApiException as e: - print "Exception when calling StoreApi->get_inventory: %s\n" % e + print("Exception when calling StoreApi->get_inventory: %s\n" % e) ``` ### Parameters @@ -113,6 +115,7 @@ For valid response try integer IDs with value <= 5 or > 10. Other values will ge ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -127,7 +130,7 @@ try: api_response = api_instance.get_order_by_id(order_id) pprint(api_response) except ApiException as e: - print "Exception when calling StoreApi->get_order_by_id: %s\n" % e + print("Exception when calling StoreApi->get_order_by_id: %s\n" % e) ``` ### Parameters @@ -160,6 +163,7 @@ Place an order for a pet ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -174,7 +178,7 @@ try: api_response = api_instance.place_order(body) pprint(api_response) except ApiException as e: - print "Exception when calling StoreApi->place_order: %s\n" % e + print("Exception when calling StoreApi->place_order: %s\n" % e) ``` ### Parameters diff --git a/samples/client/petstore/python/docs/UserApi.md b/samples/client/petstore/python/docs/UserApi.md index 4009418b13c..8c48c02d7a7 100644 --- a/samples/client/petstore/python/docs/UserApi.md +++ b/samples/client/petstore/python/docs/UserApi.md @@ -23,6 +23,7 @@ This can only be done by the logged in user. ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -36,7 +37,7 @@ try: # Create user api_instance.create_user(body) except ApiException as e: - print "Exception when calling UserApi->create_user: %s\n" % e + print("Exception when calling UserApi->create_user: %s\n" % e) ``` ### Parameters @@ -69,6 +70,7 @@ Creates list of users with given input array ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -82,7 +84,7 @@ try: # Creates list of users with given input array api_instance.create_users_with_array_input(body) except ApiException as e: - print "Exception when calling UserApi->create_users_with_array_input: %s\n" % e + print("Exception when calling UserApi->create_users_with_array_input: %s\n" % e) ``` ### Parameters @@ -115,6 +117,7 @@ Creates list of users with given input array ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -128,7 +131,7 @@ try: # Creates list of users with given input array api_instance.create_users_with_list_input(body) except ApiException as e: - print "Exception when calling UserApi->create_users_with_list_input: %s\n" % e + print("Exception when calling UserApi->create_users_with_list_input: %s\n" % e) ``` ### Parameters @@ -161,6 +164,7 @@ This can only be done by the logged in user. ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -174,7 +178,7 @@ try: # Delete user api_instance.delete_user(username) except ApiException as e: - print "Exception when calling UserApi->delete_user: %s\n" % e + print("Exception when calling UserApi->delete_user: %s\n" % e) ``` ### Parameters @@ -207,6 +211,7 @@ Get user by user name ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -221,7 +226,7 @@ try: api_response = api_instance.get_user_by_name(username) pprint(api_response) except ApiException as e: - print "Exception when calling UserApi->get_user_by_name: %s\n" % e + print("Exception when calling UserApi->get_user_by_name: %s\n" % e) ``` ### Parameters @@ -254,6 +259,7 @@ Logs user into the system ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -269,7 +275,7 @@ try: api_response = api_instance.login_user(username, password) pprint(api_response) except ApiException as e: - print "Exception when calling UserApi->login_user: %s\n" % e + print("Exception when calling UserApi->login_user: %s\n" % e) ``` ### Parameters @@ -303,6 +309,7 @@ Logs out current logged in user session ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -315,7 +322,7 @@ try: # Logs out current logged in user session api_instance.logout_user() except ApiException as e: - print "Exception when calling UserApi->logout_user: %s\n" % e + print("Exception when calling UserApi->logout_user: %s\n" % e) ``` ### Parameters @@ -345,6 +352,7 @@ This can only be done by the logged in user. ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -359,7 +367,7 @@ try: # Updated user api_instance.update_user(username, body) except ApiException as e: - print "Exception when calling UserApi->update_user: %s\n" % e + print("Exception when calling UserApi->update_user: %s\n" % e) ``` ### Parameters diff --git a/samples/client/petstore/python/petstore_api/api_client.py b/samples/client/petstore/python/petstore_api/api_client.py index ddfaf2ca744..81ecfb95c06 100644 --- a/samples/client/petstore/python/petstore_api/api_client.py +++ b/samples/client/petstore/python/petstore_api/api_client.py @@ -19,17 +19,15 @@ """ from __future__ import absolute_import + from . import models from .rest import RESTClientObject from .rest import ApiException import os import re -import sys -import urllib import json import mimetypes -import random import tempfile import threading @@ -37,22 +35,8 @@ from datetime import date # python 2 and python 3 compatibility library -from six import iteritems - -try: - # for python3 - from urllib.parse import quote -except ImportError: - # for python2 - from urllib import quote - -# special handling of `long` (python2 only) -try: - # Python 2 - long -except NameError: - # Python 3 - long = int +from six import PY3, integer_types, iteritems, text_type +from six.moves.urllib.parse import quote from .configuration import Configuration @@ -113,7 +97,7 @@ def __call_api(self, resource_path, method, body=None, post_params=None, files=None, response_type=None, auth_settings=None, callback=None, _return_http_data_only=None): - # headers parameters + # header parameters header_params = header_params or {} header_params.update(self.default_headers) if self.cookie: @@ -167,11 +151,10 @@ def __call_api(self, resource_path, method, if callback: callback(deserialized_data) if _return_http_data_only else callback((deserialized_data, response_data.status, response_data.getheaders())) elif _return_http_data_only: - return ( deserialized_data ); + return (deserialized_data) else: return (deserialized_data, response_data.status, response_data.getheaders()) - def to_path_value(self, obj): """ Takes value and turn it into a string suitable for inclusion in @@ -201,9 +184,7 @@ def sanitize_for_serialization(self, obj): :param obj: The data to serialize. :return: The serialized form of data. """ - types = (str, int, long, float, bool, tuple) - if sys.version_info < (3, 0): - types = types + (unicode,) + types = (str, float, bool, tuple) + tuple(integer_types) + (text_type,) if isinstance(obj, type(None)): return None elif isinstance(obj, types): @@ -235,7 +216,7 @@ def deserialize(self, response, response_type): :param response: RESTResponse object to be deserialized. :param response_type: class literal for - deserialzied object, or string of class name. + deserialized object, or string of class name. :return: deserialized object. """ @@ -277,14 +258,16 @@ def __deserialize(self, data, klass): # convert str to class # for native types - if klass in ['int', 'long', 'float', 'str', 'bool', + if klass in ['int', 'float', 'str', 'bool', "date", 'datetime', "object"]: klass = eval(klass) + elif klass == 'long': + klass = int if PY3 else long # for model types else: klass = eval('models.' + klass) - if klass in [int, long, float, str, bool]: + if klass in integer_types or klass in (float, str, bool): return self.__deserialize_primitive(data, klass) elif klass == object: return self.__deserialize_object(data) @@ -339,7 +322,7 @@ def call_api(self, resource_path, method, header_params, body, post_params, files, response_type, auth_settings, - callback,_return_http_data_only)) + callback, _return_http_data_only)) thread.start() return thread diff --git a/samples/client/petstore/python/petstore_api/configuration.py b/samples/client/petstore/python/petstore_api/configuration.py index d0db8fe5980..3d2a09adb9c 100644 --- a/samples/client/petstore/python/petstore_api/configuration.py +++ b/samples/client/petstore/python/petstore_api/configuration.py @@ -23,19 +23,14 @@ """ from __future__ import absolute_import -import base64 -import urllib3 -try: - import httplib -except ImportError: - # for python3 - import http.client as httplib +import urllib3 import sys import logging from six import iteritems +from six.moves import http_client as httplib def singleton(cls, *args, **kw): @@ -229,7 +224,7 @@ def auth_settings(self): 'value': self.get_api_key_with_prefix('api_key') }, - 'petstore_auth': + 'petstore_auth': { 'type': 'oauth2', 'in': 'header', diff --git a/samples/client/petstore/python/petstore_api/rest.py b/samples/client/petstore/python/petstore_api/rest.py index 632bba2055e..e5bfae61aa1 100644 --- a/samples/client/petstore/python/petstore_api/rest.py +++ b/samples/client/petstore/python/petstore_api/rest.py @@ -24,7 +24,6 @@ from __future__ import absolute_import -import sys import io import json import ssl @@ -33,7 +32,8 @@ import re # python 2 and python 3 compatibility library -from six import iteritems +from six import PY3 +from six.moves.urllib.parse import urlencode from .configuration import Configuration @@ -42,13 +42,6 @@ except ImportError: raise ImportError('Swagger python client requires urllib3.') -try: - # for python3 - from urllib.parse import urlencode -except ImportError: - # for python2 - from urllib import urlencode - logger = logging.getLogger(__name__) @@ -120,7 +113,7 @@ def request(self, method, url, query_params=None, headers=None, :param headers: http request headers :param body: request json body, for `application/json` :param post_params: request post parameters, - `application/x-www-form-urlencode` + `application/x-www-form-urlencoded` and `multipart/form-data` """ method = method.upper() @@ -175,11 +168,11 @@ def request(self, method, url, query_params=None, headers=None, # In the python 3, the response.data is bytes. # we need to decode it to string. - if sys.version_info > (3,): + if PY3: r.data = r.data.decode('utf8') # log response body - logger.debug("response body: %s" % r.data) + logger.debug("response body: %s", r.data) if r.status not in range(200, 206): raise ApiException(http_resp=r) From dd1ed1231884f08804fd5726ab5beabac59d7abd Mon Sep 17 00:00:00 2001 From: Daniel Ge Date: Mon, 29 Aug 2016 19:28:07 -0700 Subject: [PATCH 297/470] Make connection failures visible with generated Ruby SDKs (#3640) * Make connection failures visible in Ruby SDK The underlying HTTP library, Typhoeus, requires you to be explicit about error handling. Unfortunately, this also means that we can't assume that `response.success?` will be false only when the HTTP status code is not a 200; it could also be false when the request fails (timeouts, TLS verification issues, etc.). This commit adds explicit error handling for these cases. * Update samples --- .../main/resources/ruby/api_client.mustache | 16 ++++++++++++---- .../petstore-security-test/ruby/README.md | 18 +++++++++--------- .../ruby/lib/petstore/api_client.rb | 18 +++++++++++++----- .../ruby/lib/petstore/configuration.rb | 14 +++++++------- samples/client/petstore/ruby/README.md | 14 +++++++------- .../petstore/ruby/lib/petstore/api_client.rb | 16 ++++++++++++---- .../ruby/lib/petstore/configuration.rb | 14 +++++++------- 7 files changed, 67 insertions(+), 43 deletions(-) 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 c845b82f409..fcd4b3eebfa 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache @@ -47,10 +47,18 @@ module {{moduleName}} end unless response.success? - fail ApiError.new(:code => response.code, - :response_headers => response.headers, - :response_body => response.body), - response.status_message + if response.timed_out? + fail ApiError.new('Connection timed out') + elsif response.code == 0 + # Errors from libcurl will be made visible here + fail ApiError.new(:code => 0, + :message => response.return_message) + else + fail ApiError.new(:code => response.code, + :response_headers => response.headers, + :response_body => response.body), + response.status_message + end end if opts[:return_type] diff --git a/samples/client/petstore-security-test/ruby/README.md b/samples/client/petstore-security-test/ruby/README.md index 905a00d2242..29455303d53 100644 --- a/samples/client/petstore-security-test/ruby/README.md +++ b/samples/client/petstore-security-test/ruby/README.md @@ -8,7 +8,7 @@ This SDK is automatically generated by the [Swagger Codegen](https://github.com/ - API version: 1.0.0 */ ' \" =_end -- \\r\\n \\n \\r - Package version: 1.0.0 -- Build date: 2016-07-14T18:21:54.437+08:00 +- Build date: 2016-08-29T14:24:34.432-07:00 - Build package: class io.swagger.codegen.languages.RubyClientCodegen ## Installation @@ -87,18 +87,18 @@ Class | Method | HTTP request | Description ## Documentation for Authorization -### api_key - -- **Type**: API key -- **API key parameter name**: api_key */ ' " =end -- \r\n \n \r -- **Location**: HTTP header - ### petstore_auth - **Type**: OAuth - **Flow**: implicit - **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog - **Scopes**: - - write:pets: modify pets in your account */ ' " =end -- \r\n \n \r - - read:pets: read your pets */ ' " =end -- \r\n \n \r + - write:pets: modify pets in your account */ ' \" =_end -- \\r\\n \\n \\r + - read:pets: read your pets */ ' \" =_end -- \\r\\n \\n \\r + +### api_key + +- **Type**: API key +- **API key parameter name**: api_key */ ' " =end -- \r\n \n \r +- **Location**: HTTP header diff --git a/samples/client/petstore-security-test/ruby/lib/petstore/api_client.rb b/samples/client/petstore-security-test/ruby/lib/petstore/api_client.rb index 9bdf0103a99..176f301b171 100644 --- a/samples/client/petstore-security-test/ruby/lib/petstore/api_client.rb +++ b/samples/client/petstore-security-test/ruby/lib/petstore/api_client.rb @@ -66,10 +66,18 @@ def call_api(http_method, path, opts = {}) end unless response.success? - fail ApiError.new(:code => response.code, - :response_headers => response.headers, - :response_body => response.body), - response.status_message + if response.timed_out? + fail ApiError.new('Connection timed out') + elsif response.code == 0 + # Errors from libcurl will be made visible here + fail ApiError.new(:code => 0, + :message => response.return_message) + else + fail ApiError.new(:code => response.code, + :response_headers => response.headers, + :response_body => response.body), + response.status_message + end end if opts[:return_type] @@ -288,7 +296,7 @@ def build_request_body(header_params, form_params, body) # Update hearder and query params based on authentication settings. # # @param [Hash] header_params Header parameters - # @param [Hash] form_params Query parameters + # @param [Hash] query_params Query parameters # @param [String] auth_names Authentication scheme name def update_params_for_auth!(header_params, query_params, auth_names) Array(auth_names).each do |auth_name| diff --git a/samples/client/petstore-security-test/ruby/lib/petstore/configuration.rb b/samples/client/petstore-security-test/ruby/lib/petstore/configuration.rb index 86c40326971..57ecfab010b 100644 --- a/samples/client/petstore-security-test/ruby/lib/petstore/configuration.rb +++ b/samples/client/petstore-security-test/ruby/lib/petstore/configuration.rb @@ -201,13 +201,6 @@ def basic_auth_token # Returns Auth Settings hash for api client. def auth_settings { - 'api_key' => - { - type: 'api_key', - in: 'header', - key: 'api_key */ ' " =end -- \r\n \n \r', - value: api_key_with_prefix('api_key */ ' " =end -- \r\n \n \r') - }, 'petstore_auth' => { type: 'oauth2', @@ -215,6 +208,13 @@ def auth_settings key: 'Authorization', value: "Bearer #{access_token}" }, + 'api_key' => + { + type: 'api_key', + in: 'header', + key: 'api_key */ ' " =end -- \r\n \n \r', + value: api_key_with_prefix('api_key */ ' " =end -- \r\n \n \r') + }, } end end diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index 3d5441c5ab2..8f12077a335 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -8,7 +8,7 @@ This SDK is automatically generated by the [Swagger Codegen](https://github.com/ - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-08-22T16:46:39.641+08:00 +- Build date: 2016-08-29T14:24:29.182-07:00 - Build package: class io.swagger.codegen.languages.RubyClientCodegen ## Installation @@ -137,12 +137,6 @@ Class | Method | HTTP request | Description ## Documentation for Authorization -### api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - ### petstore_auth - **Type**: OAuth @@ -156,3 +150,9 @@ Class | Method | HTTP request | Description - **Type**: HTTP basic authentication +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + diff --git a/samples/client/petstore/ruby/lib/petstore/api_client.rb b/samples/client/petstore/ruby/lib/petstore/api_client.rb index c8170709bb6..0a95711ce43 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_client.rb @@ -66,10 +66,18 @@ def call_api(http_method, path, opts = {}) end unless response.success? - fail ApiError.new(:code => response.code, - :response_headers => response.headers, - :response_body => response.body), - response.status_message + if response.timed_out? + fail ApiError.new('Connection timed out') + elsif response.code == 0 + # Errors from libcurl will be made visible here + fail ApiError.new(:code => 0, + :message => response.return_message) + else + fail ApiError.new(:code => response.code, + :response_headers => response.headers, + :response_body => response.body), + response.status_message + end end if opts[:return_type] diff --git a/samples/client/petstore/ruby/lib/petstore/configuration.rb b/samples/client/petstore/ruby/lib/petstore/configuration.rb index 2b2d15dff4d..04679eac77b 100644 --- a/samples/client/petstore/ruby/lib/petstore/configuration.rb +++ b/samples/client/petstore/ruby/lib/petstore/configuration.rb @@ -201,13 +201,6 @@ def basic_auth_token # Returns Auth Settings hash for api client. def auth_settings { - 'api_key' => - { - type: 'api_key', - in: 'header', - key: 'api_key', - value: api_key_with_prefix('api_key') - }, 'petstore_auth' => { type: 'oauth2', @@ -222,6 +215,13 @@ def auth_settings key: 'Authorization', value: basic_auth_token }, + 'api_key' => + { + type: 'api_key', + in: 'header', + key: 'api_key', + value: api_key_with_prefix('api_key') + }, } end end From 8f98a6d6f5ffc9c2b561aba59b646a5ae2a2ef49 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Mon, 29 Aug 2016 21:45:03 +0300 Subject: [PATCH 298/470] php: Do not HTML escape patterns --- .../src/main/resources/php/api.mustache | 4 ++-- .../src/main/resources/php/model_generic.mustache | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index fb03a721e17..f039a6baa17 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -149,8 +149,8 @@ use \{{invokerPackage}}\ObjectSerializer; } {{/minimum}} {{#pattern}} - if ({{^required}}!is_null(${{paramName}}) && {{/required}}!preg_match("{{pattern}}", ${{paramName}})) { - throw new \InvalidArgumentException('invalid value for "{{paramName}}" when calling {{classname}}.{{operationId}}, must conform to the pattern {{pattern}}.'); + if ({{^required}}!is_null(${{paramName}}) && {{/required}}!preg_match("{{{pattern}}}", ${{paramName}})) { + throw new \InvalidArgumentException('invalid value for "{{paramName}}" when calling {{classname}}.{{operationId}}, must conform to the pattern {{{pattern}}}.'); } {{/pattern}} diff --git a/modules/swagger-codegen/src/main/resources/php/model_generic.mustache b/modules/swagger-codegen/src/main/resources/php/model_generic.mustache index c0ab1cd47e0..460c5c67419 100644 --- a/modules/swagger-codegen/src/main/resources/php/model_generic.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model_generic.mustache @@ -155,8 +155,8 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple {{/minimum}} {{#pattern}} - if ({{^required}}!is_null($this->container['{{name}}']) && {{/required}}!preg_match("{{pattern}}", $this->container['{{name}}'])) { - $invalid_properties[] = "invalid value for '{{name}}', must be conform to the pattern {{pattern}}."; + if ({{^required}}!is_null($this->container['{{name}}']) && {{/required}}!preg_match("{{{pattern}}}", $this->container['{{name}}'])) { + $invalid_properties[] = "invalid value for '{{name}}', must be conform to the pattern {{{pattern}}}."; } {{/pattern}} @@ -209,7 +209,7 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple } {{/minimum}} {{#pattern}} - if (!preg_match("{{pattern}}", $this->container['{{name}}'])) { + if (!preg_match("{{{pattern}}}", $this->container['{{name}}'])) { return false; } {{/pattern}} @@ -270,8 +270,8 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple } {{/minimum}} {{#pattern}} - if (!preg_match("{{pattern}}", ${{name}})) { - throw new \InvalidArgumentException('invalid value for ${{name}} when calling {{classname}}.{{operationId}}, must be conform to the pattern {{pattern}}.'); + if (!preg_match("{{{pattern}}}", ${{name}})) { + throw new \InvalidArgumentException('invalid value for ${{name}} when calling {{classname}}.{{operationId}}, must be conform to the pattern {{{pattern}}}.'); } {{/pattern}} {{/hasValidation}} From a95ade6d2af765c3856c840be34ab2e36ff49c84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Mon, 29 Aug 2016 21:45:45 +0300 Subject: [PATCH 299/470] php: Update petstore --- .../petstore/php/SwaggerClient-php/README.md | 8 +- .../php/SwaggerClient-php/docs/Api/FakeApi.md | 38 +++++--- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 88 +++++++++++++++---- 3 files changed, 102 insertions(+), 32 deletions(-) diff --git a/samples/client/petstore/php/SwaggerClient-php/README.md b/samples/client/petstore/php/SwaggerClient-php/README.md index 992cd394e4a..7081ea9c166 100644 --- a/samples/client/petstore/php/SwaggerClient-php/README.md +++ b/samples/client/petstore/php/SwaggerClient-php/README.md @@ -4,7 +4,7 @@ This spec is mainly for testing Petstore server and contains fake endpoints, mod This PHP package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: - API version: 1.0.0 -- Build date: 2016-08-05T11:24:33.550+02:00 +- Build date: 2016-08-29T21:41:18.885+03:00 - Build package: class io.swagger.codegen.languages.PhpClientCodegen ## Requirements @@ -78,7 +78,7 @@ Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- *FakeApi* | [**testClientModel**](docs/Api/FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model *FakeApi* | [**testEndpointParameters**](docs/Api/FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -*FakeApi* | [**testEnumQueryParameters**](docs/Api/FakeApi.md#testenumqueryparameters) | **GET** /fake | To test enum query parameters +*FakeApi* | [**testEnumParameters**](docs/Api/FakeApi.md#testenumparameters) | **GET** /fake | To test enum parameters *PetApi* | [**addPet**](docs/Api/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store *PetApi* | [**deletePet**](docs/Api/PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet *PetApi* | [**findPetsByStatus**](docs/Api/PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status @@ -146,6 +146,10 @@ Class | Method | HTTP request | Description - **write:pets**: modify pets in your account - **read:pets**: read your pets +## http_basic_test + +- **Type**: HTTP basic authentication + ## api_key - **Type**: API key diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Api/FakeApi.md b/samples/client/petstore/php/SwaggerClient-php/docs/Api/FakeApi.md index fa913078437..249841b68e9 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/Api/FakeApi.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Api/FakeApi.md @@ -6,7 +6,7 @@ Method | HTTP request | Description ------------- | ------------- | ------------- [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -[**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters +[**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters # **testClientModel** @@ -53,7 +53,7 @@ No authorization required [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) # **testEndpointParameters** -> testEndpointParameters($number, $double, $string, $byte, $integer, $int32, $int64, $float, $binary, $date, $date_time, $password) +> testEndpointParameters($number, $double, $pattern_without_delimiter, $byte, $integer, $int32, $int64, $float, $string, $binary, $date, $date_time, $password) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -64,22 +64,27 @@ Fake endpoint for testing various parameters 假端點 偽のエンドポイン setUsername('YOUR_USERNAME'); +Swagger\Client\Configuration::getDefaultConfiguration()->setPassword('YOUR_PASSWORD'); + $api_instance = new Swagger\Client\Api\FakeApi(); $number = 3.4; // float | None $double = 1.2; // double | None -$string = "string_example"; // string | None +$pattern_without_delimiter = "pattern_without_delimiter_example"; // string | None $byte = "B"; // string | None $integer = 56; // int | None $int32 = 56; // int | None $int64 = 789; // int | None $float = 3.4; // float | None +$string = "string_example"; // string | None $binary = "B"; // string | None $date = new \DateTime(); // \DateTime | None $date_time = new \DateTime(); // \DateTime | None $password = "password_example"; // string | None try { - $api_instance->testEndpointParameters($number, $double, $string, $byte, $integer, $int32, $int64, $float, $binary, $date, $date_time, $password); + $api_instance->testEndpointParameters($number, $double, $pattern_without_delimiter, $byte, $integer, $int32, $int64, $float, $string, $binary, $date, $date_time, $password); } catch (Exception $e) { echo 'Exception when calling FakeApi->testEndpointParameters: ', $e->getMessage(), PHP_EOL; } @@ -92,12 +97,13 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **number** | **float**| None | **double** | **double**| None | - **string** | **string**| None | + **pattern_without_delimiter** | **string**| None | **byte** | **string**| None | **integer** | **int**| None | [optional] **int32** | **int**| None | [optional] **int64** | **int**| None | [optional] **float** | **float**| None | [optional] + **string** | **string**| None | [optional] **binary** | **string**| None | [optional] **date** | **\DateTime**| None | [optional] **date_time** | **\DateTime**| None | [optional] @@ -109,7 +115,7 @@ void (empty response body) ### Authorization -No authorization required +[http_basic_test](../../README.md#http_basic_test) ### HTTP request headers @@ -118,10 +124,10 @@ No authorization required [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) -# **testEnumQueryParameters** -> testEnumQueryParameters($enum_query_string, $enum_query_integer, $enum_query_double) +# **testEnumParameters** +> testEnumParameters($enum_form_string_array, $enum_form_string, $enum_header_string_array, $enum_header_string, $enum_query_string_array, $enum_query_string, $enum_query_integer, $enum_query_double) -To test enum query parameters +To test enum parameters ### Example ```php @@ -129,14 +135,19 @@ To test enum query parameters require_once(__DIR__ . '/vendor/autoload.php'); $api_instance = new Swagger\Client\Api\FakeApi(); +$enum_form_string_array = array("enum_form_string_array_example"); // string[] | Form parameter enum test (string array) +$enum_form_string = "-efg"; // string | Form parameter enum test (string) +$enum_header_string_array = array("enum_header_string_array_example"); // string[] | Header parameter enum test (string array) +$enum_header_string = "-efg"; // string | Header parameter enum test (string) +$enum_query_string_array = array("enum_query_string_array_example"); // string[] | Query parameter enum test (string array) $enum_query_string = "-efg"; // string | Query parameter enum test (string) $enum_query_integer = 3.4; // float | Query parameter enum test (double) $enum_query_double = 1.2; // double | Query parameter enum test (double) try { - $api_instance->testEnumQueryParameters($enum_query_string, $enum_query_integer, $enum_query_double); + $api_instance->testEnumParameters($enum_form_string_array, $enum_form_string, $enum_header_string_array, $enum_header_string, $enum_query_string_array, $enum_query_string, $enum_query_integer, $enum_query_double); } catch (Exception $e) { - echo 'Exception when calling FakeApi->testEnumQueryParameters: ', $e->getMessage(), PHP_EOL; + echo 'Exception when calling FakeApi->testEnumParameters: ', $e->getMessage(), PHP_EOL; } ?> ``` @@ -145,6 +156,11 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- + **enum_form_string_array** | [**string[]**](../Model/string.md)| Form parameter enum test (string array) | [optional] + **enum_form_string** | **string**| Form parameter enum test (string) | [optional] [default to -efg] + **enum_header_string_array** | [**string[]**](../Model/string.md)| Header parameter enum test (string array) | [optional] + **enum_header_string** | **string**| Header parameter enum test (string) | [optional] [default to -efg] + **enum_query_string_array** | [**string[]**](../Model/string.md)| Query parameter enum test (string array) | [optional] **enum_query_string** | **string**| Query parameter enum test (string) | [optional] [default to -efg] **enum_query_integer** | **float**| Query parameter enum test (double) | [optional] **enum_query_double** | **double**| Query parameter enum test (double) | [optional] diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index 0029ecd0aed..3635aebefe8 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -191,12 +191,13 @@ public function testClientModelWithHttpInfo($body) * * @param float $number None (required) * @param double $double None (required) - * @param string $string None (required) + * @param string $pattern_without_delimiter None (required) * @param string $byte None (required) * @param int $integer None (optional) * @param int $int32 None (optional) * @param int $int64 None (optional) * @param float $float None (optional) + * @param string $string None (optional) * @param string $binary None (optional) * @param \DateTime $date None (optional) * @param \DateTime $date_time None (optional) @@ -204,9 +205,9 @@ public function testClientModelWithHttpInfo($body) * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function testEndpointParameters($number, $double, $string, $byte, $integer = null, $int32 = null, $int64 = null, $float = null, $binary = null, $date = null, $date_time = null, $password = null) + public function testEndpointParameters($number, $double, $pattern_without_delimiter, $byte, $integer = null, $int32 = null, $int64 = null, $float = null, $string = null, $binary = null, $date = null, $date_time = null, $password = null) { - list($response) = $this->testEndpointParametersWithHttpInfo($number, $double, $string, $byte, $integer, $int32, $int64, $float, $binary, $date, $date_time, $password); + list($response) = $this->testEndpointParametersWithHttpInfo($number, $double, $pattern_without_delimiter, $byte, $integer, $int32, $int64, $float, $string, $binary, $date, $date_time, $password); return $response; } @@ -217,12 +218,13 @@ public function testEndpointParameters($number, $double, $string, $byte, $intege * * @param float $number None (required) * @param double $double None (required) - * @param string $string None (required) + * @param string $pattern_without_delimiter None (required) * @param string $byte None (required) * @param int $integer None (optional) * @param int $int32 None (optional) * @param int $int64 None (optional) * @param float $float None (optional) + * @param string $string None (optional) * @param string $binary None (optional) * @param \DateTime $date None (optional) * @param \DateTime $date_time None (optional) @@ -230,7 +232,7 @@ public function testEndpointParameters($number, $double, $string, $byte, $intege * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ - public function testEndpointParametersWithHttpInfo($number, $double, $string, $byte, $integer = null, $int32 = null, $int64 = null, $float = null, $binary = null, $date = null, $date_time = null, $password = null) + public function testEndpointParametersWithHttpInfo($number, $double, $pattern_without_delimiter, $byte, $integer = null, $int32 = null, $int64 = null, $float = null, $string = null, $binary = null, $date = null, $date_time = null, $password = null) { // verify the required parameter 'number' is set if ($number === null) { @@ -254,12 +256,12 @@ public function testEndpointParametersWithHttpInfo($number, $double, $string, $b throw new \InvalidArgumentException('invalid value for "$double" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 67.8.'); } - // verify the required parameter 'string' is set - if ($string === null) { - throw new \InvalidArgumentException('Missing the required parameter $string when calling testEndpointParameters'); + // verify the required parameter 'pattern_without_delimiter' is set + if ($pattern_without_delimiter === null) { + throw new \InvalidArgumentException('Missing the required parameter $pattern_without_delimiter when calling testEndpointParameters'); } - if (!preg_match("/[a-z]/i", $string)) { - throw new \InvalidArgumentException('invalid value for "string" when calling FakeApi.testEndpointParameters, must conform to the pattern /[a-z]/i.'); + if (!preg_match("/^[A-Z].*_/", $pattern_without_delimiter)) { + throw new \InvalidArgumentException('invalid value for "pattern_without_delimiter" when calling FakeApi.testEndpointParameters, must conform to the pattern /^[A-Z].*_/.'); } // verify the required parameter 'byte' is set @@ -284,6 +286,10 @@ public function testEndpointParametersWithHttpInfo($number, $double, $string, $b throw new \InvalidArgumentException('invalid value for "$float" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 987.6.'); } + if (!is_null($string) && !preg_match("/[a-z]/i", $string)) { + throw new \InvalidArgumentException('invalid value for "string" when calling FakeApi.testEndpointParameters, must conform to the pattern /[a-z]/i.'); + } + if (!is_null($password) && (strlen($password) > 64)) { throw new \InvalidArgumentException('invalid length for "$password" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 64.'); } @@ -335,6 +341,10 @@ public function testEndpointParametersWithHttpInfo($number, $double, $string, $b $formParams['string'] = $this->apiClient->getSerializer()->toFormValue($string); } // form params + if ($pattern_without_delimiter !== null) { + $formParams['pattern_without_delimiter'] = $this->apiClient->getSerializer()->toFormValue($pattern_without_delimiter); + } + // form params if ($byte !== null) { $formParams['byte'] = $this->apiClient->getSerializer()->toFormValue($byte); } @@ -361,6 +371,10 @@ public function testEndpointParametersWithHttpInfo($number, $double, $string, $b } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } + // this endpoint requires HTTP basic authentication + 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()); + } // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( @@ -383,34 +397,44 @@ public function testEndpointParametersWithHttpInfo($number, $double, $string, $b } /** - * Operation testEnumQueryParameters + * Operation testEnumParameters * - * To test enum query parameters + * To test enum parameters * + * @param string[] $enum_form_string_array Form parameter enum test (string array) (optional) + * @param string $enum_form_string Form parameter enum test (string) (optional, default to -efg) + * @param string[] $enum_header_string_array Header parameter enum test (string array) (optional) + * @param string $enum_header_string Header parameter enum test (string) (optional, default to -efg) + * @param string[] $enum_query_string_array Query parameter enum test (string array) (optional) * @param string $enum_query_string Query parameter enum test (string) (optional, default to -efg) * @param float $enum_query_integer Query parameter enum test (double) (optional) * @param double $enum_query_double Query parameter enum test (double) (optional) * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function testEnumQueryParameters($enum_query_string = null, $enum_query_integer = null, $enum_query_double = null) + public function testEnumParameters($enum_form_string_array = null, $enum_form_string = null, $enum_header_string_array = null, $enum_header_string = null, $enum_query_string_array = null, $enum_query_string = null, $enum_query_integer = null, $enum_query_double = null) { - list($response) = $this->testEnumQueryParametersWithHttpInfo($enum_query_string, $enum_query_integer, $enum_query_double); + list($response) = $this->testEnumParametersWithHttpInfo($enum_form_string_array, $enum_form_string, $enum_header_string_array, $enum_header_string, $enum_query_string_array, $enum_query_string, $enum_query_integer, $enum_query_double); return $response; } /** - * Operation testEnumQueryParametersWithHttpInfo + * Operation testEnumParametersWithHttpInfo * - * To test enum query parameters + * To test enum parameters * + * @param string[] $enum_form_string_array Form parameter enum test (string array) (optional) + * @param string $enum_form_string Form parameter enum test (string) (optional, default to -efg) + * @param string[] $enum_header_string_array Header parameter enum test (string array) (optional) + * @param string $enum_header_string Header parameter enum test (string) (optional, default to -efg) + * @param string[] $enum_query_string_array Query parameter enum test (string array) (optional) * @param string $enum_query_string Query parameter enum test (string) (optional, default to -efg) * @param float $enum_query_integer Query parameter enum test (double) (optional) * @param double $enum_query_double Query parameter enum test (double) (optional) * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ - public function testEnumQueryParametersWithHttpInfo($enum_query_string = null, $enum_query_integer = null, $enum_query_double = null) + public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $enum_form_string = null, $enum_header_string_array = null, $enum_header_string = null, $enum_query_string_array = null, $enum_query_string = null, $enum_query_integer = null, $enum_query_double = null) { // parse inputs $resourcePath = "/fake"; @@ -424,16 +448,42 @@ public function testEnumQueryParametersWithHttpInfo($enum_query_string = null, $ } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json')); + // query params + if (is_array($enum_query_string_array)) { + $enum_query_string_array = $this->apiClient->getSerializer()->serializeCollection($enum_query_string_array, 'csv', true); + } + if ($enum_query_string_array !== null) { + $queryParams['enum_query_string_array'] = $this->apiClient->getSerializer()->toQueryValue($enum_query_string_array); + } + // query params + if ($enum_query_string !== null) { + $queryParams['enum_query_string'] = $this->apiClient->getSerializer()->toQueryValue($enum_query_string); + } // query params if ($enum_query_integer !== null) { $queryParams['enum_query_integer'] = $this->apiClient->getSerializer()->toQueryValue($enum_query_integer); } + // header params + if (is_array($enum_header_string_array)) { + $enum_header_string_array = $this->apiClient->getSerializer()->serializeCollection($enum_header_string_array, 'csv'); + } + if ($enum_header_string_array !== null) { + $headerParams['enum_header_string_array'] = $this->apiClient->getSerializer()->toHeaderValue($enum_header_string_array); + } + // header params + if ($enum_header_string !== null) { + $headerParams['enum_header_string'] = $this->apiClient->getSerializer()->toHeaderValue($enum_header_string); + } // default format to json $resourcePath = str_replace("{format}", "json", $resourcePath); // form params - if ($enum_query_string !== null) { - $formParams['enum_query_string'] = $this->apiClient->getSerializer()->toFormValue($enum_query_string); + if ($enum_form_string_array !== null) { + $formParams['enum_form_string_array'] = $this->apiClient->getSerializer()->toFormValue($enum_form_string_array); + } + // form params + if ($enum_form_string !== null) { + $formParams['enum_form_string'] = $this->apiClient->getSerializer()->toFormValue($enum_form_string); } // form params if ($enum_query_double !== null) { From cfe1b7a2b4da8012f255796ea3105fefa96c9d23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Mon, 29 Aug 2016 21:46:15 +0300 Subject: [PATCH 300/470] lumen: Do not HTML escape pattern --- .../swagger-codegen/src/main/resources/lumen/api.mustache | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/lumen/api.mustache b/modules/swagger-codegen/src/main/resources/lumen/api.mustache index fb735e2fb8e..34ce7b64955 100644 --- a/modules/swagger-codegen/src/main/resources/lumen/api.mustache +++ b/modules/swagger-codegen/src/main/resources/lumen/api.mustache @@ -53,8 +53,8 @@ use Illuminate\Support\Facades\Request; } {{/minimum}} {{#pattern}} - if (!preg_match("{{pattern}}", ${{paramName}}])) { - throw new \InvalidArgumentException('invalid value for ${{paramName}} when calling {{classname}}.{{operationId}}, must conform to the pattern {{pattern}}.'); + if (!preg_match("{{{pattern}}}", ${{paramName}}])) { + throw new \InvalidArgumentException('invalid value for ${{paramName}} when calling {{classname}}.{{operationId}}, must conform to the pattern {{{pattern}}}.'); } {{/pattern}} {{/hasValidation}} @@ -91,8 +91,8 @@ use Illuminate\Support\Facades\Request; } {{/minimum}} {{#pattern}} - if (!preg_match("{{pattern}}", $input['{{paramName}}'])) { - throw new \InvalidArgumentException('invalid value for ${{paramName}} when calling {{classname}}.{{operationId}}, must conform to the pattern {{pattern}}.'); + if (!preg_match("{{{pattern}}}", $input['{{paramName}}'])) { + throw new \InvalidArgumentException('invalid value for ${{paramName}} when calling {{classname}}.{{operationId}}, must conform to the pattern {{{pattern}}}.'); } {{/pattern}} {{/hasValidation}} From 77a2973da4f6616acae4248bdfc52c9d6f872a62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Mon, 29 Aug 2016 21:48:02 +0300 Subject: [PATCH 301/470] lumen: Update petstore --- .../lib/app/Http/Controllers/FakeApi.php | 33 ++++++++++++++----- .../petstore/lumen/lib/app/Http/routes.php | 6 ++-- 2 files changed, 27 insertions(+), 12 deletions(-) diff --git a/samples/server/petstore/lumen/lib/app/Http/Controllers/FakeApi.php b/samples/server/petstore/lumen/lib/app/Http/Controllers/FakeApi.php index 919b6f1bac2..d249e16dbab 100644 --- a/samples/server/petstore/lumen/lib/app/Http/Controllers/FakeApi.php +++ b/samples/server/petstore/lumen/lib/app/Http/Controllers/FakeApi.php @@ -100,13 +100,13 @@ public function testEndpointParameters() } $double = $input['double']; - if (!isset($input['string'])) { - throw new \InvalidArgumentException('Missing the required parameter $string when calling testEndpointParameters'); + if (!isset($input['pattern_without_delimiter'])) { + throw new \InvalidArgumentException('Missing the required parameter $pattern_without_delimiter when calling testEndpointParameters'); } - if (!preg_match("/[a-z]/i", $input['string'])) { - throw new \InvalidArgumentException('invalid value for $string when calling FakeApi.testEndpointParameters, must conform to the pattern /[a-z]/i.'); + if (!preg_match("/^[A-Z].", $input['pattern_without_delimiter'])) { + throw new \InvalidArgumentException('invalid value for $pattern_without_delimiter when calling FakeApi.testEndpointParameters, must conform to the pattern /^[A-Z]..'); } - $string = $input['string']; + $pattern_without_delimiter = $input['pattern_without_delimiter']; if (!isset($input['byte'])) { throw new \InvalidArgumentException('Missing the required parameter $byte when calling testEndpointParameters'); @@ -136,6 +136,11 @@ public function testEndpointParameters() } $float = $input['float']; + if (!preg_match("/[a-z]/i", $input['string'])) { + throw new \InvalidArgumentException('invalid value for $string when calling FakeApi.testEndpointParameters, must conform to the pattern /[a-z]/i.'); + } + $string = $input['string']; + $binary = $input['binary']; $date = $input['date']; @@ -154,14 +159,14 @@ public function testEndpointParameters() return response('How about implementing testEndpointParameters as a POST method ?'); } /** - * Operation testEnumQueryParameters + * Operation testEnumParameters * - * To test enum query parameters. + * To test enum parameters. * * * @return Http response */ - public function testEnumQueryParameters() + public function testEnumParameters() { $input = Request::all(); @@ -169,6 +174,16 @@ public function testEnumQueryParameters() //not path params validation + $enum_form_string_array = $input['enum_form_string_array']; + + $enum_form_string = $input['enum_form_string']; + + $enum_header_string_array = $input['enum_header_string_array']; + + $enum_header_string = $input['enum_header_string']; + + $enum_query_string_array = $input['enum_query_string_array']; + $enum_query_string = $input['enum_query_string']; $enum_query_integer = $input['enum_query_integer']; @@ -176,6 +191,6 @@ public function testEnumQueryParameters() $enum_query_double = $input['enum_query_double']; - return response('How about implementing testEnumQueryParameters as a GET method ?'); + return response('How about implementing testEnumParameters as a GET method ?'); } } diff --git a/samples/server/petstore/lumen/lib/app/Http/routes.php b/samples/server/petstore/lumen/lib/app/Http/routes.php index ea9b463bffa..70feeed6b6d 100644 --- a/samples/server/petstore/lumen/lib/app/Http/routes.php +++ b/samples/server/petstore/lumen/lib/app/Http/routes.php @@ -48,12 +48,12 @@ */ $app->POST('/v2/fake', 'FakeApi@testEndpointParameters'); /** - * GET testEnumQueryParameters - * Summary: To test enum query parameters + * GET testEnumParameters + * Summary: To test enum parameters * Notes: * Output-Formats: [application/json] */ -$app->GET('/v2/fake', 'FakeApi@testEnumQueryParameters'); +$app->GET('/v2/fake', 'FakeApi@testEnumParameters'); /** * POST addPet * Summary: Add a new pet to the store From a4dbd761f89f992304ebe7217a243e83a27c69fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Mon, 29 Aug 2016 21:25:13 +0300 Subject: [PATCH 302/470] python: Fix escaping of quote in patterns --- .../java/io/swagger/codegen/languages/PythonClientCodegen.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 aba01835481..6877e7e24a0 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 @@ -203,7 +203,7 @@ public void postProcessPattern(String pattern, Map vendorExtensi + "/pattern/modifiers convention. "+pattern+" is not valid."); } - String regex = pattern.substring(1, i).replace("'", "\'"); + String regex = pattern.substring(1, i).replace("'", "\\'"); List modifiers = new ArrayList(); for(char c : pattern.substring(i).toCharArray()) { From cdcc61b038aa730ad94e5f92fb37f8d77c54e672 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Mon, 29 Aug 2016 21:28:30 +0300 Subject: [PATCH 303/470] python: Do not HTML escape patterns --- .../swagger-codegen/src/main/resources/python/api.mustache | 4 ++-- .../swagger-codegen/src/main/resources/python/model.mustache | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index c866fc5805c..37e842a06ff 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -135,8 +135,8 @@ class {{classname}}(object): raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must be a value greater than or equal to `{{minimum}}`") {{/minimum}} {{#pattern}} - if '{{paramName}}' in params and not re.search('{{vendorExtensions.x-regex}}', params['{{paramName}}']{{#vendorExtensions.x-modifiers}}{{#-first}}, flags={{/-first}}re.{{.}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}): - raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must conform to the pattern `{{pattern}}`") + if '{{paramName}}' in params and not re.search('{{{vendorExtensions.x-regex}}}', params['{{paramName}}']{{#vendorExtensions.x-modifiers}}{{#-first}}, flags={{/-first}}re.{{.}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}): + raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must conform to the pattern `{{{pattern}}}`") {{/pattern}} {{/hasValidation}} {{/allParams}} diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index 7a4d11bcbfa..59dc13b83ce 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -89,8 +89,8 @@ class {{classname}}(object): raise ValueError("Invalid value for `{{name}}`, must be a value greater than or equal to `{{minimum}}`") {{/minimum}} {{#pattern}} - if not re.search('{{vendorExtensions.x-regex}}', {{name}}{{#vendorExtensions.x-modifiers}}{{#-first}}, flags={{/-first}}re.{{.}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}): - raise ValueError("Invalid value for `{{name}}`, must be a follow pattern or equal to `{{pattern}}`") + if not re.search('{{{vendorExtensions.x-regex}}}', {{name}}{{#vendorExtensions.x-modifiers}}{{#-first}}, flags={{/-first}}re.{{.}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}): + raise ValueError("Invalid value for `{{name}}`, must be a follow pattern or equal to `{{{pattern}}}`") {{/pattern}} {{/hasValidation}} {{/isEnum}} From fa0e0f4fcca8b52d3dca5276dccc3eaa64968ff6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Tue, 30 Aug 2016 08:07:35 +0300 Subject: [PATCH 304/470] python: Update petstore --- samples/client/petstore/python/README.md | 14 +++++++------- .../petstore/python/petstore_api/configuration.py | 14 +++++++------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/samples/client/petstore/python/README.md b/samples/client/petstore/python/README.md index a2482fc1c6d..1269b2f0029 100644 --- a/samples/client/petstore/python/README.md +++ b/samples/client/petstore/python/README.md @@ -5,7 +5,7 @@ This Python package is automatically generated by the [Swagger Codegen](https:// - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-08-27T14:30:36.450+03:00 +- Build date: 2016-08-30T08:06:49.587+03:00 - Build package: class io.swagger.codegen.languages.PythonClientCodegen ## Requirements. @@ -131,12 +131,6 @@ Class | Method | HTTP request | Description ## Documentation For Authorization -## api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - ## petstore_auth - **Type**: OAuth @@ -150,6 +144,12 @@ Class | Method | HTTP request | Description - **Type**: HTTP basic authentication +## api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + ## Author diff --git a/samples/client/petstore/python/petstore_api/configuration.py b/samples/client/petstore/python/petstore_api/configuration.py index 3d2a09adb9c..6cea276204a 100644 --- a/samples/client/petstore/python/petstore_api/configuration.py +++ b/samples/client/petstore/python/petstore_api/configuration.py @@ -216,13 +216,6 @@ def auth_settings(self): :return: The Auth Settings information dict. """ return { - 'api_key': - { - 'type': 'api_key', - 'in': 'header', - 'key': 'api_key', - 'value': self.get_api_key_with_prefix('api_key') - }, 'petstore_auth': { @@ -238,6 +231,13 @@ def auth_settings(self): 'key': 'Authorization', 'value': self.get_basic_auth_token() }, + 'api_key': + { + 'type': 'api_key', + 'in': 'header', + 'key': 'api_key', + 'value': self.get_api_key_with_prefix('api_key') + }, } From 9c8e4f60aa5d36c301224210ac2be0bae1185c56 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 31 Aug 2016 12:51:09 +0800 Subject: [PATCH 305/470] clearer wording --- .github/PULL_REQUEST_TEMPLATE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index e111475b78d..7e712f237c7 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,7 +1,7 @@ ### PR checklist - [ ] Read the [contribution guildelines](https://github.com/swagger-api/swagger-codegen/blob/master/CONTRIBUTING.md). -- [ ] Ran the shell/batch script under `./bin/` to update Petstore sample so that CIs can verify the change. (NOTE: no need to update *all* Petstore sample. For instance, only need to update PHP Petstore sample by running `./bin/php-petstore.sh` if updating the PHP code generator or PHP client's mustache templates) +- [ ] Ran the shell/batch script under `./bin/` to update Petstore sample so that CIs can verify the change. (For instance, only need to run`./bin/{LANG}-petstore.sh` if updating the {LANG} (e.g. php, ruby, python, etc) code generator or {LANG} client's mustache templates) - [ ] Filed the PR against the correct branch: master for non-breaking changes and `2.3.0` branch for breaking (non-backward compatible) changes. ### Description of the PR From ebfddd0a5829c3b4d6817fd5c2acfbe4b63696a3 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 31 Aug 2016 15:49:22 +0800 Subject: [PATCH 306/470] remove unnecessary changes for python codegen --- .../io/swagger/codegen/CodegenConstants.java | 2 ++ .../io/swagger/codegen/DefaultGenerator.java | 7 +++++++ .../languages/PythonClientCodegen.java | 7 +++++++ .../src/main/resources/python/README.mustache | 2 ++ .../options/PythonClientOptionsProvider.java | 1 + samples/client/petstore/python/README.md | 21 +++++++++---------- .../python/petstore_api/configuration.py | 18 ++++++++-------- 7 files changed, 38 insertions(+), 20 deletions(-) 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 df62dcc1937..65bf8e32db5 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 @@ -127,4 +127,6 @@ public static enum MODEL_PROPERTY_NAMING_TYPE {camelCase, PascalCase, snake_case public static final String GENERATE_MODEL_TESTS = "generateModelTests"; public static final String GENERATE_MODEL_TESTS_DESC = "Specifies that model tests are to be generated."; + public static final String HIDE_GENERATION_TIMESTAMP = "hideGenerationTimestamp"; + public static final String HIDE_GENERATION_TIMESTAMP_DESC = "Hides the generation timestamp."; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index 90059a85b57..664d70d46c4 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -507,6 +507,13 @@ public int compare(CodegenOperation one, CodegenOperation another) { bundle.put("modelPackage", config.modelPackage()); List authMethods = config.fromSecurity(swagger.getSecurityDefinitions()); if (authMethods != null && !authMethods.isEmpty()) { + // sort auth methods to maintain the same order + Collections.sort(authMethods, new Comparator() { + @Override + public int compare(CodegenSecurity one, CodegenSecurity another) { + return ObjectUtils.compare(one.name, another.name); + } + }); bundle.put("authMethods", authMethods); bundle.put("hasAuthMethods", true); } 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 6877e7e24a0..328968a553f 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 @@ -114,6 +114,8 @@ public PythonClientCodegen() { .defaultValue("1.0.0")); cliOptions.add(CliOption.newBoolean(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC).defaultValue(Boolean.TRUE.toString())); + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") + .defaultValue(Boolean.TRUE.toString())); } @Override @@ -139,6 +141,11 @@ public void processOpts() { setPackageVersion("1.0.0"); } + // default HIDE_GENERATION_TIMESTAMP to true + if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); + } + additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion); diff --git a/modules/swagger-codegen/src/main/resources/python/README.mustache b/modules/swagger-codegen/src/main/resources/python/README.mustache index d483fc3662a..9f592946b06 100644 --- a/modules/swagger-codegen/src/main/resources/python/README.mustache +++ b/modules/swagger-codegen/src/main/resources/python/README.mustache @@ -7,7 +7,9 @@ This Python package is automatically generated by the [Swagger Codegen](https:// - API version: {{appVersion}} - Package version: {{packageVersion}} +{{^hideGenerationTimestamp}} - Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} - Build package: {{generatorClass}} {{#infoUrl}} For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PythonClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PythonClientOptionsProvider.java index ec62e3f2b7c..ccdb38d7bab 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PythonClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PythonClientOptionsProvider.java @@ -21,6 +21,7 @@ public Map createOptions() { return builder.put(CodegenConstants.PACKAGE_NAME, PACKAGE_NAME_VALUE) .put(CodegenConstants.PACKAGE_VERSION, PACKAGE_VERSION_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "true") + .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") .build(); } diff --git a/samples/client/petstore/python/README.md b/samples/client/petstore/python/README.md index 1269b2f0029..ec654c5190e 100644 --- a/samples/client/petstore/python/README.md +++ b/samples/client/petstore/python/README.md @@ -5,7 +5,6 @@ This Python package is automatically generated by the [Swagger Codegen](https:// - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-08-30T08:06:49.587+03:00 - Build package: class io.swagger.codegen.languages.PythonClientCodegen ## Requirements. @@ -131,6 +130,16 @@ Class | Method | HTTP request | Description ## Documentation For Authorization +## api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + +## http_basic_test + +- **Type**: HTTP basic authentication + ## petstore_auth - **Type**: OAuth @@ -140,16 +149,6 @@ Class | Method | HTTP request | Description - **write:pets**: modify pets in your account - **read:pets**: read your pets -## http_basic_test - -- **Type**: HTTP basic authentication - -## api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - ## Author diff --git a/samples/client/petstore/python/petstore_api/configuration.py b/samples/client/petstore/python/petstore_api/configuration.py index 6cea276204a..d2f3b06a558 100644 --- a/samples/client/petstore/python/petstore_api/configuration.py +++ b/samples/client/petstore/python/petstore_api/configuration.py @@ -216,13 +216,12 @@ def auth_settings(self): :return: The Auth Settings information dict. """ return { - - 'petstore_auth': + 'api_key': { - 'type': 'oauth2', + 'type': 'api_key', 'in': 'header', - 'key': 'Authorization', - 'value': 'Bearer ' + self.access_token + 'key': 'api_key', + 'value': self.get_api_key_with_prefix('api_key') }, 'http_basic_test': { @@ -231,12 +230,13 @@ def auth_settings(self): 'key': 'Authorization', 'value': self.get_basic_auth_token() }, - 'api_key': + + 'petstore_auth': { - 'type': 'api_key', + 'type': 'oauth2', 'in': 'header', - 'key': 'api_key', - 'value': self.get_api_key_with_prefix('api_key') + 'key': 'Authorization', + 'value': 'Bearer ' + self.access_token }, } From 4ea44882125fc3d041d31bc53d8905baed81802e Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 31 Aug 2016 15:57:04 +0800 Subject: [PATCH 307/470] remove unnecessary change for ruby codegen --- .../codegen/languages/RubyClientCodegen.java | 8 +++++++ .../src/main/resources/ruby/README.mustache | 2 ++ .../options/RubyClientOptionsProvider.java | 1 + samples/client/petstore/ruby/README.md | 21 +++++++++---------- .../ruby/lib/petstore/configuration.rb | 16 +++++++------- 5 files changed, 29 insertions(+), 19 deletions(-) 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 eaf83992b5f..342674e62b1 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 @@ -156,12 +156,20 @@ public RubyClientCodegen() { cliOptions.add(new CliOption(GEM_AUTHOR_EMAIL, "gem author email (only one is supported).")); + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated"). + defaultValue(Boolean.TRUE.toString())); + } @Override public void processOpts() { super.processOpts(); + // default HIDE_GENERATION_TIMESTAMP to true + if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); + } + if (additionalProperties.containsKey(GEM_NAME)) { setGemName((String) additionalProperties.get(GEM_NAME)); } diff --git a/modules/swagger-codegen/src/main/resources/ruby/README.mustache b/modules/swagger-codegen/src/main/resources/ruby/README.mustache index 076192b75ce..abf26eeceda 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/README.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/README.mustache @@ -10,7 +10,9 @@ This SDK is automatically generated by the [Swagger Codegen](https://github.com/ - API version: {{appVersion}} - Package version: {{gemVersion}} +{{^hideGenerationTimestamp}} - Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} - Build package: {{generatorClass}} {{#infoUrl}} For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java index 64e388d38ef..55c81e6fdc4 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java @@ -39,6 +39,7 @@ public Map createOptions() { .put(RubyClientCodegen.GEM_AUTHOR_EMAIL, GEM_AUTHOR_EMAIL_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") .build(); } diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index 8f12077a335..188335045f6 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -8,7 +8,6 @@ This SDK is automatically generated by the [Swagger Codegen](https://github.com/ - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-08-29T14:24:29.182-07:00 - Build package: class io.swagger.codegen.languages.RubyClientCodegen ## Installation @@ -137,6 +136,16 @@ Class | Method | HTTP request | Description ## Documentation for Authorization +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + +### http_basic_test + +- **Type**: HTTP basic authentication + ### petstore_auth - **Type**: OAuth @@ -146,13 +155,3 @@ Class | Method | HTTP request | Description - write:pets: modify pets in your account - read:pets: read your pets -### http_basic_test - -- **Type**: HTTP basic authentication - -### api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - diff --git a/samples/client/petstore/ruby/lib/petstore/configuration.rb b/samples/client/petstore/ruby/lib/petstore/configuration.rb index 04679eac77b..64166258b47 100644 --- a/samples/client/petstore/ruby/lib/petstore/configuration.rb +++ b/samples/client/petstore/ruby/lib/petstore/configuration.rb @@ -201,12 +201,12 @@ def basic_auth_token # Returns Auth Settings hash for api client. def auth_settings { - 'petstore_auth' => + 'api_key' => { - type: 'oauth2', + type: 'api_key', in: 'header', - key: 'Authorization', - value: "Bearer #{access_token}" + key: 'api_key', + value: api_key_with_prefix('api_key') }, 'http_basic_test' => { @@ -215,12 +215,12 @@ def auth_settings key: 'Authorization', value: basic_auth_token }, - 'api_key' => + 'petstore_auth' => { - type: 'api_key', + type: 'oauth2', in: 'header', - key: 'api_key', - value: api_key_with_prefix('api_key') + key: 'Authorization', + value: "Bearer #{access_token}" }, } end From da45cb7ff515fd7cf10b142b7e23d58e2ab6f342 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 31 Aug 2016 16:38:30 +0800 Subject: [PATCH 308/470] remove unnecessary changes for php codegen --- .../languages/CSharpClientCodegen.java | 2 ++ .../codegen/languages/ObjcClientCodegen.java | 7 +++++++ .../codegen/languages/PhpClientCodegen.java | 16 +++++++++++++- .../languages/PythonClientCodegen.java | 3 +++ .../codegen/languages/RubyClientCodegen.java | 3 +++ .../src/main/resources/objc/README.mustache | 2 ++ .../src/main/resources/php/README.mustache | 2 ++ .../options/ObjcClientOptionsProvider.java | 1 + .../options/PhpClientOptionsProvider.java | 1 + .../client/petstore/objc/default/README.md | 1 - .../petstore/php/SwaggerClient-php/README.md | 21 +++++++++---------- .../lib/ObjectSerializer.php | 2 +- 12 files changed, 47 insertions(+), 14 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java index c898ee4ebe5..5dce9aff641 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java @@ -127,6 +127,8 @@ public CSharpClientCodegen() { addSwitch(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES, CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES_DESC, this.optionalEmitDefaultValue); + + } @Override 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 d8b20ae5dd0..18eaef43a0c 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 @@ -167,6 +167,8 @@ public ObjcClientCodegen() { cliOptions.add(new CliOption(AUTHOR_EMAIL, "Email to use in the podspec file.").defaultValue("apiteam@swagger.io")); cliOptions.add(new CliOption(GIT_REPO_URL, "URL for the git repo where this podspec should point to.") .defaultValue("https://github.com/swagger-api/swagger-codegen")); + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") + .defaultValue(Boolean.TRUE.toString())); } @Override @@ -188,6 +190,11 @@ public String getHelp() { public void processOpts() { super.processOpts(); + // default HIDE_GENERATION_TIMESTAMP to true + if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); + } + if (additionalProperties.containsKey(POD_NAME)) { setPodName((String) additionalProperties.get(POD_NAME)); } 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 783af9c753a..a3296170e1f 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 @@ -13,6 +13,8 @@ import java.io.File; import java.util.Arrays; +import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -101,7 +103,9 @@ public PhpClientCodegen() { // provide primitives to mustache template - String primitives = "'" + StringUtils.join(languageSpecificPrimitives, "', '") + "'"; + List sortedLanguageSpecificPrimitives= new ArrayList(languageSpecificPrimitives); + Collections.sort(sortedLanguageSpecificPrimitives); + String primitives = "'" + StringUtils.join(sortedLanguageSpecificPrimitives, "', '") + "'"; additionalProperties.put("primitives", primitives); // ref: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types @@ -137,6 +141,8 @@ public PhpClientCodegen() { cliOptions.add(new CliOption(COMPOSER_PROJECT_NAME, "The project name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. petstore-client. IMPORTANT NOTE (2016/03): composerProjectName will be deprecated and replaced by gitRepoId in the next swagger-codegen release")); cliOptions.add(new CliOption(CodegenConstants.GIT_REPO_ID, CodegenConstants.GIT_REPO_ID_DESC)); cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, "The version to use in the composer package version field. e.g. 1.2.3")); + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") + .defaultValue(Boolean.TRUE.toString())); } public String getPackagePath() { @@ -200,6 +206,14 @@ public String getHelp() { public void processOpts() { super.processOpts(); + // default HIDE_GENERATION_TIMESTAMP to true + if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); + } else { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + Boolean.valueOf((String)additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + } + if (additionalProperties.containsKey(PACKAGE_PATH)) { this.setPackagePath((String) additionalProperties.get(PACKAGE_PATH)); } else { 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 328968a553f..54c6febbf88 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 @@ -144,6 +144,9 @@ public void processOpts() { // default HIDE_GENERATION_TIMESTAMP to true if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); + } else { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + Boolean.valueOf((String)additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); } additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); 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 342674e62b1..5ccdf19cbdb 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 @@ -168,6 +168,9 @@ public void processOpts() { // default HIDE_GENERATION_TIMESTAMP to true if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); + } else { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + Boolean.valueOf((String)additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); } if (additionalProperties.containsKey(GEM_NAME)) { diff --git a/modules/swagger-codegen/src/main/resources/objc/README.mustache b/modules/swagger-codegen/src/main/resources/objc/README.mustache index 8be7faffa3b..1b917176eaa 100644 --- a/modules/swagger-codegen/src/main/resources/objc/README.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/README.mustache @@ -8,7 +8,9 @@ This ObjC package is automatically generated by the [Swagger Codegen](https://gi - API version: {{appVersion}} - Package version: {{artifactVersion}} +{{^hideGenerationTimestamp}} - Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} - Build package: {{generatorClass}} {{#infoUrl}} For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) diff --git a/modules/swagger-codegen/src/main/resources/php/README.mustache b/modules/swagger-codegen/src/main/resources/php/README.mustache index 4186ed0ea99..67f5e31f68a 100644 --- a/modules/swagger-codegen/src/main/resources/php/README.mustache +++ b/modules/swagger-codegen/src/main/resources/php/README.mustache @@ -9,7 +9,9 @@ This PHP package is automatically generated by the [Swagger Codegen](https://git {{#artifactVersion}} - Package version: {{artifactVersion}} {{/artifactVersion}} +{{^hideGenerationTimestamp}} - Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} - Build package: {{generatorClass}} {{#infoUrl}} For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ObjcClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ObjcClientOptionsProvider.java index 4df5c5e1db6..667fc1c9027 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ObjcClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ObjcClientOptionsProvider.java @@ -31,6 +31,7 @@ public Map createOptions() { .put(ObjcClientCodegen.AUTHOR_EMAIL, AUTHOR_EMAIL_VALUE) .put(ObjcClientCodegen.GIT_REPO_URL, GIT_REPO_URL_VALUE) .put(ObjcClientCodegen.CORE_DATA, CORE_DATA_VALUE) + .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PhpClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PhpClientOptionsProvider.java index 8aa37f12fd0..26cdacc98b2 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PhpClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PhpClientOptionsProvider.java @@ -43,6 +43,7 @@ public Map createOptions() { .put(PhpClientCodegen.COMPOSER_PROJECT_NAME, COMPOSER_PROJECT_NAME_VALUE) .put(CodegenConstants.GIT_REPO_ID, GIT_REPO_ID_VALUE) .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) + .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") .build(); } diff --git a/samples/client/petstore/objc/default/README.md b/samples/client/petstore/objc/default/README.md index 9852443b866..20e27d6fa0a 100644 --- a/samples/client/petstore/objc/default/README.md +++ b/samples/client/petstore/objc/default/README.md @@ -6,7 +6,6 @@ This ObjC package is automatically generated by the [Swagger Codegen](https://gi - API version: 1.0.0 - Package version: -- Build date: 2016-08-28T17:01:51.110+03:00 - Build package: class io.swagger.codegen.languages.ObjcClientCodegen ## Requirements diff --git a/samples/client/petstore/php/SwaggerClient-php/README.md b/samples/client/petstore/php/SwaggerClient-php/README.md index 7081ea9c166..055a49f1f5b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/README.md +++ b/samples/client/petstore/php/SwaggerClient-php/README.md @@ -4,7 +4,6 @@ This spec is mainly for testing Petstore server and contains fake endpoints, mod This PHP package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: - API version: 1.0.0 -- Build date: 2016-08-29T21:41:18.885+03:00 - Build package: class io.swagger.codegen.languages.PhpClientCodegen ## Requirements @@ -137,6 +136,16 @@ Class | Method | HTTP request | Description ## Documentation For Authorization +## api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + +## http_basic_test + +- **Type**: HTTP basic authentication + ## petstore_auth - **Type**: OAuth @@ -146,16 +155,6 @@ Class | Method | HTTP request | Description - **write:pets**: modify pets in your account - **read:pets**: read your pets -## http_basic_test - -- **Type**: HTTP basic authentication - -## api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - ## Author diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php index ce77aa6c3b3..f8c592c67cb 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -264,7 +264,7 @@ public static function deserialize($data, $class, $httpHeaders = null, $discrimi } else { return null; } - } elseif (in_array($class, array('void', 'bool', 'string', 'double', 'byte', 'mixed', 'integer', 'float', 'int', 'DateTime', 'number', 'boolean', 'object'))) { + } elseif (in_array($class, array('DateTime', 'bool', 'boolean', 'byte', 'double', 'float', 'int', 'integer', 'mixed', 'number', 'object', 'string', 'void'))) { settype($data, $class); return $data; } elseif ($class === '\SplFileObject') { From 322862c4b63408bf0614e2c82d8b30c36f363170 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 31 Aug 2016 16:45:12 +0800 Subject: [PATCH 309/470] add hided timestamp option to swfit codegen --- .../codegen/languages/SwiftCodegen.java | 7 ++ .../codegen/options/SwiftOptionsProvider.java | 1 + .../Classes/Swaggers/APIs/PetAPI.swift | 106 +++++++++--------- .../Classes/Swaggers/APIs/StoreAPI.swift | 64 +++++------ .../Classes/Swaggers/APIs/UserAPI.swift | 36 +++--- 5 files changed, 111 insertions(+), 103 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java index 3ce1342998d..9b41aa31702 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java @@ -154,11 +154,18 @@ public SwiftCodegen() { cliOptions.add(new CliOption(POD_SCREENSHOTS, "Screenshots used for Podspec")); cliOptions.add(new CliOption(POD_DOCUMENTATION_URL, "Documentation URL used for Podspec")); cliOptions.add(new CliOption(SWIFT_USE_API_NAMESPACE, "Flag to make all the API classes inner-class of {{projectName}}API")); + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") + .defaultValue(Boolean.TRUE.toString())); + } @Override public void processOpts() { super.processOpts(); + // default HIDE_GENERATION_TIMESTAMP to true + if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); + } // Setup project name if (additionalProperties.containsKey(PROJECT_NAME)) { diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwiftOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwiftOptionsProvider.java index 3794cb9a76f..b79ecfb351d 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwiftOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwiftOptionsProvider.java @@ -52,6 +52,7 @@ public Map createOptions() { .put(SwiftCodegen.POD_SCREENSHOTS, POD_SCREENSHOTS_VALUE) .put(SwiftCodegen.POD_DOCUMENTATION_URL, POD_DOCUMENTATION_URL_VALUE) .put(SwiftCodegen.SWIFT_USE_API_NAMESPACE, SWIFT_USE_API_NAMESPACE_VALUE) + .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") .build(); } diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index a64e2da9b57..06789661504 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -108,13 +108,13 @@ public class PetAPI: APIBase { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{contentType=application/json, example={ + - examples: [{example={ "name" : "Puma", "type" : "Dog", "color" : "Black", "gender" : "Female", "breed" : "Mixed" -}}] +}, contentType=application/json}] - parameter status: (query) Status values that need to be considered for filter (optional, default to available) @@ -157,20 +157,20 @@ public class PetAPI: APIBase { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{contentType=application/json, example=[ { - "photoUrls" : [ "aeiou" ], - "name" : "doggie", + - examples: [{example=[ { + "tags" : [ { + "id" : 123456789, + "name" : "aeiou" + } ], "id" : 123456789, "category" : { - "name" : "aeiou", - "id" : 123456789 + "id" : 123456789, + "name" : "aeiou" }, - "tags" : [ { - "name" : "aeiou", - "id" : 123456789 - } ], - "status" : "aeiou" -} ]}, {contentType=application/xml, example= + "status" : "aeiou", + "name" : "doggie", + "photoUrls" : [ "aeiou" ] +} ], contentType=application/json}, {example= 123456 doggie @@ -179,21 +179,21 @@ public class PetAPI: APIBase { string -}] - - examples: [{contentType=application/json, example=[ { - "photoUrls" : [ "aeiou" ], - "name" : "doggie", +, contentType=application/xml}] + - examples: [{example=[ { + "tags" : [ { + "id" : 123456789, + "name" : "aeiou" + } ], "id" : 123456789, "category" : { - "name" : "aeiou", - "id" : 123456789 + "id" : 123456789, + "name" : "aeiou" }, - "tags" : [ { - "name" : "aeiou", - "id" : 123456789 - } ], - "status" : "aeiou" -} ]}, {contentType=application/xml, example= + "status" : "aeiou", + "name" : "doggie", + "photoUrls" : [ "aeiou" ] +} ], contentType=application/json}, {example= 123456 doggie @@ -202,7 +202,7 @@ public class PetAPI: APIBase { string -}] +, contentType=application/xml}] - parameter tags: (query) Tags to filter by (optional) @@ -242,26 +242,26 @@ public class PetAPI: APIBase { Find pet by ID - GET /pet/{petId} - Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - - OAuth: - - type: oauth2 - - name: petstore_auth - API Key: - type: apiKey api_key - name: api_key - - examples: [{contentType=application/json, example={ - "photoUrls" : [ "aeiou" ], - "name" : "doggie", + - OAuth: + - type: oauth2 + - name: petstore_auth + - examples: [{example={ + "tags" : [ { + "id" : 123456789, + "name" : "aeiou" + } ], "id" : 123456789, "category" : { - "name" : "aeiou", - "id" : 123456789 + "id" : 123456789, + "name" : "aeiou" }, - "tags" : [ { - "name" : "aeiou", - "id" : 123456789 - } ], - "status" : "aeiou" -}}, {contentType=application/xml, example= + "status" : "aeiou", + "name" : "doggie", + "photoUrls" : [ "aeiou" ] +}, contentType=application/json}, {example= 123456 doggie @@ -270,21 +270,21 @@ public class PetAPI: APIBase { string -}] - - examples: [{contentType=application/json, example={ - "photoUrls" : [ "aeiou" ], - "name" : "doggie", +, contentType=application/xml}] + - examples: [{example={ + "tags" : [ { + "id" : 123456789, + "name" : "aeiou" + } ], "id" : 123456789, "category" : { - "name" : "aeiou", - "id" : 123456789 + "id" : 123456789, + "name" : "aeiou" }, - "tags" : [ { - "name" : "aeiou", - "id" : 123456789 - } ], - "status" : "aeiou" -}}, {contentType=application/xml, example= + "status" : "aeiou", + "name" : "doggie", + "photoUrls" : [ "aeiou" ] +}, contentType=application/json}, {example= 123456 doggie @@ -293,7 +293,7 @@ public class PetAPI: APIBase { string -}] +, contentType=application/xml}] - parameter petId: (path) ID of pet that needs to be fetched diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index c51d8d37357..1c575eb79f8 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -67,12 +67,12 @@ public class StoreAPI: APIBase { - API Key: - type: apiKey api_key - name: api_key - - examples: [{contentType=application/json, example={ + - examples: [{example={ "key" : 123 -}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}] - - examples: [{contentType=application/json, example={ +}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}] + - examples: [{example={ "key" : 123 -}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}] +}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}] - returns: RequestBuilder<[String:Int32]> */ @@ -108,36 +108,36 @@ public class StoreAPI: APIBase { Find purchase order by ID - GET /store/order/{orderId} - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - - examples: [{contentType=application/json, example={ - "petId" : 123456789, - "quantity" : 123, + - examples: [{example={ "id" : 123456789, - "shipDate" : "2000-01-23T04:56:07.000+00:00", + "petId" : 123456789, "complete" : true, - "status" : "aeiou" -}}, {contentType=application/xml, example= + "status" : "aeiou", + "quantity" : 123, + "shipDate" : "2000-01-23T04:56:07.000+00:00" +}, contentType=application/json}, {example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -}] - - examples: [{contentType=application/json, example={ - "petId" : 123456789, - "quantity" : 123, +, contentType=application/xml}] + - examples: [{example={ "id" : 123456789, - "shipDate" : "2000-01-23T04:56:07.000+00:00", + "petId" : 123456789, "complete" : true, - "status" : "aeiou" -}}, {contentType=application/xml, example= + "status" : "aeiou", + "quantity" : 123, + "shipDate" : "2000-01-23T04:56:07.000+00:00" +}, contentType=application/json}, {example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -}] +, contentType=application/xml}] - parameter orderId: (path) ID of pet that needs to be fetched @@ -176,36 +176,36 @@ public class StoreAPI: APIBase { Place an order for a pet - POST /store/order - - - examples: [{contentType=application/json, example={ - "petId" : 123456789, - "quantity" : 123, + - examples: [{example={ "id" : 123456789, - "shipDate" : "2000-01-23T04:56:07.000+00:00", + "petId" : 123456789, "complete" : true, - "status" : "aeiou" -}}, {contentType=application/xml, example= + "status" : "aeiou", + "quantity" : 123, + "shipDate" : "2000-01-23T04:56:07.000+00:00" +}, contentType=application/json}, {example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -}] - - examples: [{contentType=application/json, example={ - "petId" : 123456789, - "quantity" : 123, +, contentType=application/xml}] + - examples: [{example={ "id" : 123456789, - "shipDate" : "2000-01-23T04:56:07.000+00:00", + "petId" : 123456789, "complete" : true, - "status" : "aeiou" -}}, {contentType=application/xml, example= + "status" : "aeiou", + "quantity" : 123, + "shipDate" : "2000-01-23T04:56:07.000+00:00" +}, contentType=application/json}, {example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -}] +, contentType=application/xml}] - parameter body: (body) order placed for purchasing the pet (optional) diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index d6df7754683..a7497487f85 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -167,16 +167,16 @@ public class UserAPI: APIBase { Get user by user name - GET /user/{username} - - - examples: [{contentType=application/json, example={ - "firstName" : "aeiou", + - examples: [{example={ + "id" : 123456789, "lastName" : "aeiou", - "password" : "aeiou", - "userStatus" : 123, "phone" : "aeiou", - "id" : 123456789, + "username" : "aeiou", "email" : "aeiou", - "username" : "aeiou" -}}, {contentType=application/xml, example= + "userStatus" : 123, + "firstName" : "aeiou", + "password" : "aeiou" +}, contentType=application/json}, {example= 123456 string string @@ -185,17 +185,17 @@ public class UserAPI: APIBase { string string 0 -}] - - examples: [{contentType=application/json, example={ - "firstName" : "aeiou", +, contentType=application/xml}] + - examples: [{example={ + "id" : 123456789, "lastName" : "aeiou", - "password" : "aeiou", - "userStatus" : 123, "phone" : "aeiou", - "id" : 123456789, + "username" : "aeiou", "email" : "aeiou", - "username" : "aeiou" -}}, {contentType=application/xml, example= + "userStatus" : 123, + "firstName" : "aeiou", + "password" : "aeiou" +}, contentType=application/json}, {example= 123456 string string @@ -204,7 +204,7 @@ public class UserAPI: APIBase { string string 0 -}] +, contentType=application/xml}] - parameter username: (path) The name that needs to be fetched. Use user1 for testing. @@ -244,8 +244,8 @@ public class UserAPI: APIBase { Logs user into the system - GET /user/login - - - examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] - - examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] + - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}] + - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}] - parameter username: (query) The user name for login (optional) - parameter password: (query) The password for login in clear text (optional) From 5804fbc1dd3fb4c45fc16120a15832cc415c393a Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 31 Aug 2016 16:52:46 +0800 Subject: [PATCH 310/470] remove unnecesary change in JS codegen --- .../languages/JavascriptClientCodegen.java | 11 +++++++++++ .../codegen/languages/ObjcClientCodegen.java | 3 +++ .../codegen/languages/SwiftCodegen.java | 3 +++ .../main/resources/Javascript/README.mustache | 2 ++ .../options/JavaScriptOptionsProvider.java | 1 + .../petstore/javascript-promise/README.md | 9 ++++----- .../javascript-promise/docs/FakeApi.md | 10 ++++++---- .../javascript-promise/src/ApiClient.js | 2 +- .../javascript-promise/src/api/FakeApi.js | 18 ++++++++++-------- samples/client/petstore/javascript/README.md | 9 ++++----- .../client/petstore/javascript/docs/FakeApi.md | 10 ++++++---- .../petstore/javascript/src/ApiClient.js | 2 +- .../petstore/javascript/src/api/FakeApi.js | 18 ++++++++++-------- 13 files changed, 62 insertions(+), 36 deletions(-) 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 950212197b7..d26f18ceaa6 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 @@ -171,6 +171,8 @@ public JavascriptClientCodegen() { cliOptions.add(new CliOption(USE_INHERITANCE, "use JavaScript prototype chains & delegation for inheritance") .defaultValue(Boolean.TRUE.toString())); + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") + .defaultValue(Boolean.TRUE.toString())); } @Override @@ -192,6 +194,15 @@ public String getHelp() { public void processOpts() { super.processOpts(); + // default HIDE_GENERATION_TIMESTAMP to true + if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); + } else { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + Boolean.valueOf((String)additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + } + + if (additionalProperties.containsKey(PROJECT_NAME)) { setProjectName(((String) additionalProperties.get(PROJECT_NAME))); } 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 18eaef43a0c..c48974aa579 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 @@ -193,6 +193,9 @@ public void processOpts() { // default HIDE_GENERATION_TIMESTAMP to true if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); + } else { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + Boolean.valueOf((String)additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); } if (additionalProperties.containsKey(POD_NAME)) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java index 9b41aa31702..287afba9372 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java @@ -165,6 +165,9 @@ public void processOpts() { // default HIDE_GENERATION_TIMESTAMP to true if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); + } else { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + Boolean.valueOf((String)additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); } // Setup project name diff --git a/modules/swagger-codegen/src/main/resources/Javascript/README.mustache b/modules/swagger-codegen/src/main/resources/Javascript/README.mustache index 0f60fc38fd8..9bbf4b4f43a 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/README.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/README.mustache @@ -8,7 +8,9 @@ This SDK is automatically generated by the [Swagger Codegen](https://github.com/ - API version: {{appVersion}} - Package version: {{projectVersion}} +{{^hideGenerationTimestamp}} - Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} - Build package: {{generatorClass}} {{#infoUrl}} For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaScriptOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaScriptOptionsProvider.java index b445fc1c528..5b75f59b356 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaScriptOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaScriptOptionsProvider.java @@ -58,6 +58,7 @@ public JavaScriptOptionsProvider() { .put(JavascriptClientCodegen.USE_INHERITANCE, USE_INHERITANCE_VALUE) .put(JavascriptClientCodegen.EMIT_MODEL_METHODS, EMIT_MODEL_METHODS_VALUE) .put(JavascriptClientCodegen.EMIT_JS_DOC, EMIT_JS_DOC_VALUE) + .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") .build(); } diff --git a/samples/client/petstore/javascript-promise/README.md b/samples/client/petstore/javascript-promise/README.md index 0ab6d1c32a7..051eb9bf4ff 100644 --- a/samples/client/petstore/javascript-promise/README.md +++ b/samples/client/petstore/javascript-promise/README.md @@ -6,7 +6,6 @@ This SDK is automatically generated by the [Swagger Codegen](https://github.com/ - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-08-12T10:09:30.190+08:00 - Build package: class io.swagger.codegen.languages.JavascriptClientCodegen ## Installation @@ -139,6 +138,10 @@ Class | Method | HTTP request | Description - **API key parameter name**: api_key - **Location**: HTTP header +### http_basic_test + +- **Type**: HTTP basic authentication + ### petstore_auth - **Type**: OAuth @@ -148,7 +151,3 @@ Class | Method | HTTP request | Description - write:pets: modify pets in your account - read:pets: read your pets -### http_basic_test - -- **Type**: HTTP basic authentication - diff --git a/samples/client/petstore/javascript-promise/docs/FakeApi.md b/samples/client/petstore/javascript-promise/docs/FakeApi.md index 71a1c503a08..b3bc1ae145f 100644 --- a/samples/client/petstore/javascript-promise/docs/FakeApi.md +++ b/samples/client/petstore/javascript-promise/docs/FakeApi.md @@ -52,7 +52,7 @@ No authorization required # **testEndpointParameters** -> testEndpointParameters(_number, _double, _string, _byte, opts) +> testEndpointParameters(_number, _double, patternWithoutDelimiter, _byte, opts) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -74,7 +74,7 @@ var _number = 3.4; // Number | None var _double = 1.2; // Number | None -var _string = "_string_example"; // String | None +var patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None var _byte = "B"; // String | None @@ -83,12 +83,13 @@ var opts = { 'int32': 56, // Number | None 'int64': 789, // Number | None '_float': 3.4, // Number | None + '_string': "_string_example", // String | None 'binary': "B", // String | None '_date': new Date("2013-10-20"), // Date | None 'dateTime': new Date("2013-10-20T19:20:30+01:00"), // Date | None 'password': "password_example" // String | None }; -apiInstance.testEndpointParameters(_number, _double, _string, _byte, opts).then(function() { +apiInstance.testEndpointParameters(_number, _double, patternWithoutDelimiter, _byte, opts).then(function() { console.log('API called successfully.'); }, function(error) { console.error(error); @@ -102,12 +103,13 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **_number** | **Number**| None | **_double** | **Number**| None | - **_string** | **String**| None | + **patternWithoutDelimiter** | **String**| None | **_byte** | **String**| None | **integer** | **Number**| None | [optional] **int32** | **Number**| None | [optional] **int64** | **Number**| None | [optional] **_float** | **Number**| None | [optional] + **_string** | **String**| None | [optional] **binary** | **String**| None | [optional] **_date** | **Date**| None | [optional] **dateTime** | **Date**| None | [optional] diff --git a/samples/client/petstore/javascript-promise/src/ApiClient.js b/samples/client/petstore/javascript-promise/src/ApiClient.js index 935bad65808..b3d66a68174 100644 --- a/samples/client/petstore/javascript-promise/src/ApiClient.js +++ b/samples/client/petstore/javascript-promise/src/ApiClient.js @@ -65,8 +65,8 @@ */ this.authentications = { 'api_key': {type: 'apiKey', 'in': 'header', name: 'api_key'}, - 'petstore_auth': {type: 'oauth2'}, 'http_basic_test': {type: 'basic'} + 'petstore_auth': {type: 'oauth2'}, }; /** * The default HTTP headers to be included for all API calls. diff --git a/samples/client/petstore/javascript-promise/src/api/FakeApi.js b/samples/client/petstore/javascript-promise/src/api/FakeApi.js index 5ec891038c1..c4b4a1d8771 100644 --- a/samples/client/petstore/javascript-promise/src/api/FakeApi.js +++ b/samples/client/petstore/javascript-promise/src/api/FakeApi.js @@ -98,20 +98,21 @@ * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * @param {Number} _number None * @param {Number} _double None - * @param {String} _string None + * @param {String} patternWithoutDelimiter None * @param {String} _byte None * @param {Object} opts Optional parameters * @param {Number} opts.integer None * @param {Number} opts.int32 None * @param {Number} opts.int64 None * @param {Number} opts._float None + * @param {String} opts._string None * @param {String} opts.binary None * @param {Date} opts._date None * @param {Date} opts.dateTime None * @param {String} opts.password None * @return {Promise} a {@link https://www.promisejs.org/|Promise} */ - this.testEndpointParameters = function(_number, _double, _string, _byte, opts) { + this.testEndpointParameters = function(_number, _double, patternWithoutDelimiter, _byte, opts) { opts = opts || {}; var postBody = null; @@ -125,9 +126,9 @@ throw "Missing the required parameter '_double' when calling testEndpointParameters"; } - // verify the required parameter '_string' is set - if (_string == undefined || _string == null) { - throw "Missing the required parameter '_string' when calling testEndpointParameters"; + // verify the required parameter 'patternWithoutDelimiter' is set + if (patternWithoutDelimiter == undefined || patternWithoutDelimiter == null) { + throw "Missing the required parameter 'patternWithoutDelimiter' when calling testEndpointParameters"; } // verify the required parameter '_byte' is set @@ -149,7 +150,8 @@ 'number': _number, 'float': opts['_float'], 'double': _double, - 'string': _string, + 'string': opts['_string'], + 'pattern_without_delimiter': patternWithoutDelimiter, 'byte': _byte, 'binary': opts['binary'], 'date': opts['_date'], @@ -173,9 +175,9 @@ /** * To test enum parameters * @param {Object} opts Optional parameters - * @param {Array.} opts.enumFormStringArray Form parameter enum test (string array) + * @param {Array.} opts.enumFormStringArray Form parameter enum test (string array) * @param {module:model/String} opts.enumFormString Form parameter enum test (string) (default to -efg) - * @param {Array.} opts.enumHeaderStringArray Header parameter enum test (string array) + * @param {Array.} opts.enumHeaderStringArray Header parameter enum test (string array) * @param {module:model/String} opts.enumHeaderString Header parameter enum test (string) (default to -efg) * @param {Array.} opts.enumQueryStringArray Query parameter enum test (string array) * @param {module:model/String} opts.enumQueryString Query parameter enum test (string) (default to -efg) diff --git a/samples/client/petstore/javascript/README.md b/samples/client/petstore/javascript/README.md index 212e553ff8b..0a54168dd7c 100644 --- a/samples/client/petstore/javascript/README.md +++ b/samples/client/petstore/javascript/README.md @@ -6,7 +6,6 @@ This SDK is automatically generated by the [Swagger Codegen](https://github.com/ - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-08-12T10:09:27.758+08:00 - Build package: class io.swagger.codegen.languages.JavascriptClientCodegen ## Installation @@ -142,6 +141,10 @@ Class | Method | HTTP request | Description - **API key parameter name**: api_key - **Location**: HTTP header +### http_basic_test + +- **Type**: HTTP basic authentication + ### petstore_auth - **Type**: OAuth @@ -151,7 +154,3 @@ Class | Method | HTTP request | Description - write:pets: modify pets in your account - read:pets: read your pets -### http_basic_test - -- **Type**: HTTP basic authentication - diff --git a/samples/client/petstore/javascript/docs/FakeApi.md b/samples/client/petstore/javascript/docs/FakeApi.md index 5a529a815ca..b754b8815cf 100644 --- a/samples/client/petstore/javascript/docs/FakeApi.md +++ b/samples/client/petstore/javascript/docs/FakeApi.md @@ -55,7 +55,7 @@ No authorization required # **testEndpointParameters** -> testEndpointParameters(_number, _double, _string, _byte, opts) +> testEndpointParameters(_number, _double, patternWithoutDelimiter, _byte, opts) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -77,7 +77,7 @@ var _number = 3.4; // Number | None var _double = 1.2; // Number | None -var _string = "_string_example"; // String | None +var patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None var _byte = "B"; // String | None @@ -86,6 +86,7 @@ var opts = { 'int32': 56, // Number | None 'int64': 789, // Number | None '_float': 3.4, // Number | None + '_string': "_string_example", // String | None 'binary': "B", // String | None '_date': new Date("2013-10-20"), // Date | None 'dateTime': new Date("2013-10-20T19:20:30+01:00"), // Date | None @@ -99,7 +100,7 @@ var callback = function(error, data, response) { console.log('API called successfully.'); } }; -apiInstance.testEndpointParameters(_number, _double, _string, _byte, opts, callback); +apiInstance.testEndpointParameters(_number, _double, patternWithoutDelimiter, _byte, opts, callback); ``` ### Parameters @@ -108,12 +109,13 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **_number** | **Number**| None | **_double** | **Number**| None | - **_string** | **String**| None | + **patternWithoutDelimiter** | **String**| None | **_byte** | **String**| None | **integer** | **Number**| None | [optional] **int32** | **Number**| None | [optional] **int64** | **Number**| None | [optional] **_float** | **Number**| None | [optional] + **_string** | **String**| None | [optional] **binary** | **String**| None | [optional] **_date** | **Date**| None | [optional] **dateTime** | **Date**| None | [optional] diff --git a/samples/client/petstore/javascript/src/ApiClient.js b/samples/client/petstore/javascript/src/ApiClient.js index b534ef2f08e..aab7a6ebf98 100644 --- a/samples/client/petstore/javascript/src/ApiClient.js +++ b/samples/client/petstore/javascript/src/ApiClient.js @@ -65,8 +65,8 @@ */ this.authentications = { 'api_key': {type: 'apiKey', 'in': 'header', name: 'api_key'}, - 'petstore_auth': {type: 'oauth2'}, 'http_basic_test': {type: 'basic'} + 'petstore_auth': {type: 'oauth2'}, }; /** * The default HTTP headers to be included for all API calls. diff --git a/samples/client/petstore/javascript/src/api/FakeApi.js b/samples/client/petstore/javascript/src/api/FakeApi.js index c45298d1896..0d4ccca70ef 100644 --- a/samples/client/petstore/javascript/src/api/FakeApi.js +++ b/samples/client/petstore/javascript/src/api/FakeApi.js @@ -113,20 +113,21 @@ * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * @param {Number} _number None * @param {Number} _double None - * @param {String} _string None + * @param {String} patternWithoutDelimiter None * @param {String} _byte None * @param {Object} opts Optional parameters * @param {Number} opts.integer None * @param {Number} opts.int32 None * @param {Number} opts.int64 None * @param {Number} opts._float None + * @param {String} opts._string None * @param {String} opts.binary None * @param {Date} opts._date None * @param {Date} opts.dateTime None * @param {String} opts.password None * @param {module:api/FakeApi~testEndpointParametersCallback} callback The callback function, accepting three arguments: error, data, response */ - this.testEndpointParameters = function(_number, _double, _string, _byte, opts, callback) { + this.testEndpointParameters = function(_number, _double, patternWithoutDelimiter, _byte, opts, callback) { opts = opts || {}; var postBody = null; @@ -140,9 +141,9 @@ throw "Missing the required parameter '_double' when calling testEndpointParameters"; } - // verify the required parameter '_string' is set - if (_string == undefined || _string == null) { - throw "Missing the required parameter '_string' when calling testEndpointParameters"; + // verify the required parameter 'patternWithoutDelimiter' is set + if (patternWithoutDelimiter == undefined || patternWithoutDelimiter == null) { + throw "Missing the required parameter 'patternWithoutDelimiter' when calling testEndpointParameters"; } // verify the required parameter '_byte' is set @@ -164,7 +165,8 @@ 'number': _number, 'float': opts['_float'], 'double': _double, - 'string': _string, + 'string': opts['_string'], + 'pattern_without_delimiter': patternWithoutDelimiter, 'byte': _byte, 'binary': opts['binary'], 'date': opts['_date'], @@ -195,9 +197,9 @@ /** * To test enum parameters * @param {Object} opts Optional parameters - * @param {Array.} opts.enumFormStringArray Form parameter enum test (string array) + * @param {Array.} opts.enumFormStringArray Form parameter enum test (string array) * @param {module:model/String} opts.enumFormString Form parameter enum test (string) (default to -efg) - * @param {Array.} opts.enumHeaderStringArray Header parameter enum test (string array) + * @param {Array.} opts.enumHeaderStringArray Header parameter enum test (string array) * @param {module:model/String} opts.enumHeaderString Header parameter enum test (string) (default to -efg) * @param {Array.} opts.enumQueryStringArray Query parameter enum test (string array) * @param {module:model/String} opts.enumQueryString Query parameter enum test (string) (default to -efg) From 8523c57f8c701da3a33a8c25b1fb545e36e71c02 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 31 Aug 2016 17:13:35 +0800 Subject: [PATCH 311/470] remove unnecessary change in JS closure codegen --- .../codegen/languages/GoClientCodegen.java | 11 ++ ...JavascriptClosureAngularClientCodegen.java | 13 ++ .../Javascript-Closure-Angular/api.mustache | 2 + .../src/main/resources/go/README.mustache | 2 + .../options/GoClientOptionsProvider.java | 1 + ...iptClosureAnularClientOptionsProvider.java | 1 + .../client/petstore/go/go-petstore/README.md | 9 +- .../API/Client/PetApi.js | 119 +++++++-------- .../API/Client/StoreApi.js | 79 +++++----- .../API/Client/UserApi.js | 143 ++++++++---------- 10 files changed, 183 insertions(+), 197 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java index 8009e87982e..6bfd1df425f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java @@ -118,12 +118,23 @@ public GoClientCodegen() { .defaultValue("swagger")); cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "Go package version.") .defaultValue("1.0.0")); + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") + .defaultValue(Boolean.TRUE.toString())); + } @Override public void processOpts() { super.processOpts(); + // default HIDE_GENERATION_TIMESTAMP to true + if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); + } else { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + Boolean.valueOf((String)additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + } + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClosureAngularClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClosureAngularClientCodegen.java index 0371eee5e75..0b619824c4d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClosureAngularClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClosureAngularClientCodegen.java @@ -70,6 +70,19 @@ public JavascriptClosureAngularClientCodegen() { embeddedTemplateDir = templateDir = "Javascript-Closure-Angular"; apiPackage = "API.Client"; modelPackage = "API.Client"; + + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") + .defaultValue(Boolean.TRUE.toString())); + } + + @Override + public void processOpts() { + super.processOpts(); + + // default HIDE_GENERATION_TIMESTAMP to true + if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); + } } @Override diff --git a/modules/swagger-codegen/src/main/resources/Javascript-Closure-Angular/api.mustache b/modules/swagger-codegen/src/main/resources/Javascript-Closure-Angular/api.mustache index 35604bf73df..98e2f1c6713 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript-Closure-Angular/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript-Closure-Angular/api.mustache @@ -6,7 +6,9 @@ * {{ appDescription }}{{/appDescription}}{{#version}} * Version: {{version}}{{/version}}{{#appContact}} * Contact: {{appContact}}{{/appContact}} +{{^hideGenerationTimestamp}} * Generated at: {{generatedDate}} +{{/hideGenerationTimestamp}} * Generated by: {{generatorClass}} */{{#licenseInfo}} /** diff --git a/modules/swagger-codegen/src/main/resources/go/README.mustache b/modules/swagger-codegen/src/main/resources/go/README.mustache index 026d0648ea6..0cfe5bfcae3 100644 --- a/modules/swagger-codegen/src/main/resources/go/README.mustache +++ b/modules/swagger-codegen/src/main/resources/go/README.mustache @@ -9,7 +9,9 @@ This API client was generated by the [swagger-codegen](https://github.com/swagge - API version: {{appVersion}} - Package version: {{packageVersion}} +{{^hideGenerationTimestamp}} - Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} - Build package: {{generatorClass}} {{#infoUrl}} For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/GoClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/GoClientOptionsProvider.java index 304d8acf457..af1613e8051 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/GoClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/GoClientOptionsProvider.java @@ -23,6 +23,7 @@ public Map createOptions() { return builder .put(CodegenConstants.PACKAGE_VERSION, PACKAGE_VERSION_VALUE) .put(CodegenConstants.PACKAGE_NAME, PACKAGE_NAME_VALUE) + .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavascriptClosureAnularClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavascriptClosureAnularClientOptionsProvider.java index 3bc5a3df22d..baf4cfb8537 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavascriptClosureAnularClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavascriptClosureAnularClientOptionsProvider.java @@ -20,6 +20,7 @@ public Map createOptions() { ImmutableMap.Builder builder = new ImmutableMap.Builder(); return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") .build(); } diff --git a/samples/client/petstore/go/go-petstore/README.md b/samples/client/petstore/go/go-petstore/README.md index 2e20331eb94..164eaf91c07 100644 --- a/samples/client/petstore/go/go-petstore/README.md +++ b/samples/client/petstore/go/go-petstore/README.md @@ -7,7 +7,6 @@ This API client was generated by the [swagger-codegen](https://github.com/swagge - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-08-17T22:53:45.063+08:00 - Build package: class io.swagger.codegen.languages.GoClientCodegen ## Installation @@ -89,6 +88,10 @@ Class | Method | HTTP request | Description - **API key parameter name**: api_key - **Location**: HTTP header +## http_basic_test + +- **Type**: HTTP basic authentication + ## petstore_auth - **Type**: OAuth @@ -98,10 +101,6 @@ Class | Method | HTTP request | Description - **write:pets**: modify pets in your account - **read:pets**: read your pets -## http_basic_test - -- **Type**: HTTP basic authentication - ## Author diff --git a/samples/client/petstore/javascript-closure-angular/API/Client/PetApi.js b/samples/client/petstore/javascript-closure-angular/API/Client/PetApi.js index 39a22ebcdbe..06561bb4ab5 100644 --- a/samples/client/petstore/javascript-closure-angular/API/Client/PetApi.js +++ b/samples/client/petstore/javascript-closure-angular/API/Client/PetApi.js @@ -3,9 +3,8 @@ * Do not edit this file by hand or your changes will be lost next time it is * generated. * - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * Version: 1.0.0 - * Generated at: 2016-04-28T06:15:51.482Z * Generated by: class io.swagger.codegen.languages.JavascriptClosureAngularClientCodegen */ /** @@ -46,13 +45,13 @@ API.Client.PetApi = function($http, $httpParamSerializer, $injector) { API.Client.PetApi.$inject = ['$http', '$httpParamSerializer', '$injector']; /** - * Update an existing pet + * Add a new pet to the store * * @param {!Pet} body Pet object that needs to be added to the store * @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send. * @return {!angular.$q.Promise} */ -API.Client.PetApi.prototype.updatePet = function(body, opt_extraHttpRequestParams) { +API.Client.PetApi.prototype.addPet = function(body, opt_extraHttpRequestParams) { /** @const {string} */ var path = this.basePath_ + '/pet'; @@ -63,17 +62,15 @@ API.Client.PetApi.prototype.updatePet = function(body, opt_extraHttpRequestParam var headerParams = angular.extend({}, this.defaultHeaders_); // verify required parameter 'body' is set if (!body) { - throw new Error('Missing required parameter body when calling updatePet'); + throw new Error('Missing required parameter body when calling addPet'); } /** @type {!Object} */ var httpRequestParams = { - method: 'PUT', + method: 'POST', url: path, json: true, data: body, - - - params: queryParameters, + params: queryParameters, headers: headerParams }; @@ -85,34 +82,35 @@ API.Client.PetApi.prototype.updatePet = function(body, opt_extraHttpRequestParam } /** - * Add a new pet to the store + * Deletes a pet * - * @param {!Pet} body Pet object that needs to be added to the store + * @param {!number} petId Pet id to delete + * @param {!string=} opt_apiKey * @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send. * @return {!angular.$q.Promise} */ -API.Client.PetApi.prototype.addPet = function(body, opt_extraHttpRequestParams) { +API.Client.PetApi.prototype.deletePet = function(petId, opt_apiKey, opt_extraHttpRequestParams) { /** @const {string} */ - var path = this.basePath_ + '/pet'; + var path = this.basePath_ + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(petId)); /** @type {!Object} */ var queryParameters = {}; /** @type {!Object} */ var headerParams = angular.extend({}, this.defaultHeaders_); - // verify required parameter 'body' is set - if (!body) { - throw new Error('Missing required parameter body when calling addPet'); + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling deletePet'); } + headerParams['api_key'] = opt_apiKey; + /** @type {!Object} */ var httpRequestParams = { - method: 'POST', + method: 'DELETE', url: path, json: true, - data: body, - - - params: queryParameters, + params: queryParameters, headers: headerParams }; @@ -152,9 +150,7 @@ API.Client.PetApi.prototype.findPetsByStatus = function(status, opt_extraHttpReq method: 'GET', url: path, json: true, - - - params: queryParameters, + params: queryParameters, headers: headerParams }; @@ -194,9 +190,7 @@ API.Client.PetApi.prototype.findPetsByTags = function(tags, opt_extraHttpRequest method: 'GET', url: path, json: true, - - - params: queryParameters, + params: queryParameters, headers: headerParams }; @@ -233,9 +227,7 @@ API.Client.PetApi.prototype.getPetById = function(petId, opt_extraHttpRequestPar method: 'GET', url: path, json: true, - - - params: queryParameters, + params: queryParameters, headers: headerParams }; @@ -247,46 +239,32 @@ API.Client.PetApi.prototype.getPetById = function(petId, opt_extraHttpRequestPar } /** - * Updates a pet in the store with form data + * Update an existing pet * - * @param {!number} petId ID of pet that needs to be updated - * @param {!string=} opt_name Updated name of the pet - * @param {!string=} opt_status Updated status of the pet + * @param {!Pet} body Pet object that needs to be added to the store * @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send. * @return {!angular.$q.Promise} */ -API.Client.PetApi.prototype.updatePetWithForm = function(petId, opt_name, opt_status, opt_extraHttpRequestParams) { +API.Client.PetApi.prototype.updatePet = function(body, opt_extraHttpRequestParams) { /** @const {string} */ - var path = this.basePath_ + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(petId)); + var path = this.basePath_ + '/pet'; /** @type {!Object} */ var queryParameters = {}; /** @type {!Object} */ var headerParams = angular.extend({}, this.defaultHeaders_); - /** @type {!Object} */ - var formParams = {}; - - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling updatePetWithForm'); + // verify required parameter 'body' is set + if (!body) { + throw new Error('Missing required parameter body when calling updatePet'); } - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - - formParams['name'] = opt_name; - - formParams['status'] = opt_status; - /** @type {!Object} */ var httpRequestParams = { - method: 'POST', + method: 'PUT', url: path, - json: false, - - data: this.httpParamSerializer(formParams), - - params: queryParameters, + json: true, + data: body, + params: queryParameters, headers: headerParams }; @@ -298,14 +276,15 @@ API.Client.PetApi.prototype.updatePetWithForm = function(petId, opt_name, opt_st } /** - * Deletes a pet + * Updates a pet in the store with form data * - * @param {!number} petId Pet id to delete - * @param {!string=} opt_apiKey + * @param {!number} petId ID of pet that needs to be updated + * @param {!string=} opt_name Updated name of the pet + * @param {!string=} opt_status Updated status of the pet * @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send. * @return {!angular.$q.Promise} */ -API.Client.PetApi.prototype.deletePet = function(petId, opt_apiKey, opt_extraHttpRequestParams) { +API.Client.PetApi.prototype.updatePetWithForm = function(petId, opt_name, opt_status, opt_extraHttpRequestParams) { /** @const {string} */ var path = this.basePath_ + '/pet/{petId}' .replace('{' + 'petId' + '}', String(petId)); @@ -315,19 +294,25 @@ API.Client.PetApi.prototype.deletePet = function(petId, opt_apiKey, opt_extraHtt /** @type {!Object} */ var headerParams = angular.extend({}, this.defaultHeaders_); + /** @type {!Object} */ + var formParams = {}; + // verify required parameter 'petId' is set if (!petId) { - throw new Error('Missing required parameter petId when calling deletePet'); + throw new Error('Missing required parameter petId when calling updatePetWithForm'); } - headerParams['api_key'] = opt_apiKey; + headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; + + formParams['name'] = opt_name; + + formParams['status'] = opt_status; /** @type {!Object} */ var httpRequestParams = { - method: 'DELETE', + method: 'POST', url: path, - json: true, - - + json: false, + data: this.httpParamSerializer(formParams), params: queryParameters, headers: headerParams }; @@ -376,9 +361,7 @@ API.Client.PetApi.prototype.uploadFile = function(petId, opt_additionalMetadata, method: 'POST', url: path, json: false, - - data: this.httpParamSerializer(formParams), - + data: this.httpParamSerializer(formParams), params: queryParameters, headers: headerParams }; diff --git a/samples/client/petstore/javascript-closure-angular/API/Client/StoreApi.js b/samples/client/petstore/javascript-closure-angular/API/Client/StoreApi.js index 9e18eceefcc..d997cc15ce3 100644 --- a/samples/client/petstore/javascript-closure-angular/API/Client/StoreApi.js +++ b/samples/client/petstore/javascript-closure-angular/API/Client/StoreApi.js @@ -3,9 +3,8 @@ * Do not edit this file by hand or your changes will be lost next time it is * generated. * - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * Version: 1.0.0 - * Generated at: 2016-04-28T06:15:51.482Z * Generated by: class io.swagger.codegen.languages.JavascriptClosureAngularClientCodegen */ /** @@ -45,28 +44,32 @@ API.Client.StoreApi = function($http, $httpParamSerializer, $injector) { API.Client.StoreApi.$inject = ['$http', '$httpParamSerializer', '$injector']; /** - * Returns pet inventories by status - * Returns a map of status codes to quantities + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param {!string} orderId ID of the order that needs to be deleted * @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send. - * @return {!angular.$q.Promise>} + * @return {!angular.$q.Promise} */ -API.Client.StoreApi.prototype.getInventory = function(opt_extraHttpRequestParams) { +API.Client.StoreApi.prototype.deleteOrder = function(orderId, opt_extraHttpRequestParams) { /** @const {string} */ - var path = this.basePath_ + '/store/inventory'; + var path = this.basePath_ + '/store/order/{orderId}' + .replace('{' + 'orderId' + '}', String(orderId)); /** @type {!Object} */ var queryParameters = {}; /** @type {!Object} */ var headerParams = angular.extend({}, this.defaultHeaders_); + // verify required parameter 'orderId' is set + if (!orderId) { + throw new Error('Missing required parameter orderId when calling deleteOrder'); + } /** @type {!Object} */ var httpRequestParams = { - method: 'GET', + method: 'DELETE', url: path, json: true, - - - params: queryParameters, + params: queryParameters, headers: headerParams }; @@ -78,34 +81,26 @@ API.Client.StoreApi.prototype.getInventory = function(opt_extraHttpRequestParams } /** - * Place an order for a pet - * - * @param {!Order} body order placed for purchasing the pet + * Returns pet inventories by status + * Returns a map of status codes to quantities * @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send. - * @return {!angular.$q.Promise} + * @return {!angular.$q.Promise>} */ -API.Client.StoreApi.prototype.placeOrder = function(body, opt_extraHttpRequestParams) { +API.Client.StoreApi.prototype.getInventory = function(opt_extraHttpRequestParams) { /** @const {string} */ - var path = this.basePath_ + '/store/order'; + var path = this.basePath_ + '/store/inventory'; /** @type {!Object} */ var queryParameters = {}; /** @type {!Object} */ var headerParams = angular.extend({}, this.defaultHeaders_); - // verify required parameter 'body' is set - if (!body) { - throw new Error('Missing required parameter body when calling placeOrder'); - } /** @type {!Object} */ var httpRequestParams = { - method: 'POST', + method: 'GET', url: path, json: true, - data: body, - - - params: queryParameters, + params: queryParameters, headers: headerParams }; @@ -118,7 +113,7 @@ API.Client.StoreApi.prototype.placeOrder = function(body, opt_extraHttpRequestPa /** * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * @param {!number} orderId ID of pet that needs to be fetched * @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send. * @return {!angular.$q.Promise} @@ -142,9 +137,7 @@ API.Client.StoreApi.prototype.getOrderById = function(orderId, opt_extraHttpRequ method: 'GET', url: path, json: true, - - - params: queryParameters, + params: queryParameters, headers: headerParams }; @@ -156,34 +149,32 @@ API.Client.StoreApi.prototype.getOrderById = function(orderId, opt_extraHttpRequ } /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param {!string} orderId ID of the order that needs to be deleted + * Place an order for a pet + * + * @param {!Order} body order placed for purchasing the pet * @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send. - * @return {!angular.$q.Promise} + * @return {!angular.$q.Promise} */ -API.Client.StoreApi.prototype.deleteOrder = function(orderId, opt_extraHttpRequestParams) { +API.Client.StoreApi.prototype.placeOrder = function(body, opt_extraHttpRequestParams) { /** @const {string} */ - var path = this.basePath_ + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(orderId)); + var path = this.basePath_ + '/store/order'; /** @type {!Object} */ var queryParameters = {}; /** @type {!Object} */ var headerParams = angular.extend({}, this.defaultHeaders_); - // verify required parameter 'orderId' is set - if (!orderId) { - throw new Error('Missing required parameter orderId when calling deleteOrder'); + // verify required parameter 'body' is set + if (!body) { + throw new Error('Missing required parameter body when calling placeOrder'); } /** @type {!Object} */ var httpRequestParams = { - method: 'DELETE', + method: 'POST', url: path, json: true, - - - params: queryParameters, + data: body, + params: queryParameters, headers: headerParams }; diff --git a/samples/client/petstore/javascript-closure-angular/API/Client/UserApi.js b/samples/client/petstore/javascript-closure-angular/API/Client/UserApi.js index 733f7d65f5a..5a146fc04d6 100644 --- a/samples/client/petstore/javascript-closure-angular/API/Client/UserApi.js +++ b/samples/client/petstore/javascript-closure-angular/API/Client/UserApi.js @@ -3,9 +3,8 @@ * Do not edit this file by hand or your changes will be lost next time it is * generated. * - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * Version: 1.0.0 - * Generated at: 2016-04-28T06:15:51.482Z * Generated by: class io.swagger.codegen.languages.JavascriptClosureAngularClientCodegen */ /** @@ -70,9 +69,7 @@ API.Client.UserApi.prototype.createUser = function(body, opt_extraHttpRequestPar url: path, json: true, data: body, - - - params: queryParameters, + params: queryParameters, headers: headerParams }; @@ -109,9 +106,7 @@ API.Client.UserApi.prototype.createUsersWithArrayInput = function(body, opt_extr url: path, json: true, data: body, - - - params: queryParameters, + params: queryParameters, headers: headerParams }; @@ -148,9 +143,7 @@ API.Client.UserApi.prototype.createUsersWithListInput = function(body, opt_extra url: path, json: true, data: body, - - - params: queryParameters, + params: queryParameters, headers: headerParams }; @@ -162,16 +155,16 @@ API.Client.UserApi.prototype.createUsersWithListInput = function(body, opt_extra } /** - * Logs user into the system - * - * @param {!string} username The user name for login - * @param {!string} password The password for login in clear text + * Delete user + * This can only be done by the logged in user. + * @param {!string} username The name that needs to be deleted * @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send. - * @return {!angular.$q.Promise} + * @return {!angular.$q.Promise} */ -API.Client.UserApi.prototype.loginUser = function(username, password, opt_extraHttpRequestParams) { +API.Client.UserApi.prototype.deleteUser = function(username, opt_extraHttpRequestParams) { /** @const {string} */ - var path = this.basePath_ + '/user/login'; + var path = this.basePath_ + '/user/{username}' + .replace('{' + 'username' + '}', String(username)); /** @type {!Object} */ var queryParameters = {}; @@ -180,28 +173,14 @@ API.Client.UserApi.prototype.loginUser = function(username, password, opt_extraH var headerParams = angular.extend({}, this.defaultHeaders_); // verify required parameter 'username' is set if (!username) { - throw new Error('Missing required parameter username when calling loginUser'); - } - // verify required parameter 'password' is set - if (!password) { - throw new Error('Missing required parameter password when calling loginUser'); - } - if (username !== undefined) { - queryParameters['username'] = username; - } - - if (password !== undefined) { - queryParameters['password'] = password; + throw new Error('Missing required parameter username when calling deleteUser'); } - /** @type {!Object} */ var httpRequestParams = { - method: 'GET', + method: 'DELETE', url: path, json: true, - - - params: queryParameters, + params: queryParameters, headers: headerParams }; @@ -213,28 +192,32 @@ API.Client.UserApi.prototype.loginUser = function(username, password, opt_extraH } /** - * Logs out current logged in user session + * Get user by user name * + * @param {!string} username The name that needs to be fetched. Use user1 for testing. * @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send. - * @return {!angular.$q.Promise} + * @return {!angular.$q.Promise} */ -API.Client.UserApi.prototype.logoutUser = function(opt_extraHttpRequestParams) { +API.Client.UserApi.prototype.getUserByName = function(username, opt_extraHttpRequestParams) { /** @const {string} */ - var path = this.basePath_ + '/user/logout'; + var path = this.basePath_ + '/user/{username}' + .replace('{' + 'username' + '}', String(username)); /** @type {!Object} */ var queryParameters = {}; /** @type {!Object} */ var headerParams = angular.extend({}, this.defaultHeaders_); + // verify required parameter 'username' is set + if (!username) { + throw new Error('Missing required parameter username when calling getUserByName'); + } /** @type {!Object} */ var httpRequestParams = { method: 'GET', url: path, json: true, - - - params: queryParameters, + params: queryParameters, headers: headerParams }; @@ -246,16 +229,16 @@ API.Client.UserApi.prototype.logoutUser = function(opt_extraHttpRequestParams) { } /** - * Get user by user name + * Logs user into the system * - * @param {!string} username The name that needs to be fetched. Use user1 for testing. + * @param {!string} username The user name for login + * @param {!string} password The password for login in clear text * @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send. - * @return {!angular.$q.Promise} + * @return {!angular.$q.Promise} */ -API.Client.UserApi.prototype.getUserByName = function(username, opt_extraHttpRequestParams) { +API.Client.UserApi.prototype.loginUser = function(username, password, opt_extraHttpRequestParams) { /** @const {string} */ - var path = this.basePath_ + '/user/{username}' - .replace('{' + 'username' + '}', String(username)); + var path = this.basePath_ + '/user/login'; /** @type {!Object} */ var queryParameters = {}; @@ -264,16 +247,26 @@ API.Client.UserApi.prototype.getUserByName = function(username, opt_extraHttpReq var headerParams = angular.extend({}, this.defaultHeaders_); // verify required parameter 'username' is set if (!username) { - throw new Error('Missing required parameter username when calling getUserByName'); + throw new Error('Missing required parameter username when calling loginUser'); + } + // verify required parameter 'password' is set + if (!password) { + throw new Error('Missing required parameter password when calling loginUser'); + } + if (username !== undefined) { + queryParameters['username'] = username; + } + + if (password !== undefined) { + queryParameters['password'] = password; } + /** @type {!Object} */ var httpRequestParams = { method: 'GET', url: path, json: true, - - - params: queryParameters, + params: queryParameters, headers: headerParams }; @@ -285,40 +278,26 @@ API.Client.UserApi.prototype.getUserByName = function(username, opt_extraHttpReq } /** - * Updated user - * This can only be done by the logged in user. - * @param {!string} username name that need to be deleted - * @param {!User} body Updated user object + * Logs out current logged in user session + * * @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send. * @return {!angular.$q.Promise} */ -API.Client.UserApi.prototype.updateUser = function(username, body, opt_extraHttpRequestParams) { +API.Client.UserApi.prototype.logoutUser = function(opt_extraHttpRequestParams) { /** @const {string} */ - var path = this.basePath_ + '/user/{username}' - .replace('{' + 'username' + '}', String(username)); + var path = this.basePath_ + '/user/logout'; /** @type {!Object} */ var queryParameters = {}; /** @type {!Object} */ var headerParams = angular.extend({}, this.defaultHeaders_); - // verify required parameter 'username' is set - if (!username) { - throw new Error('Missing required parameter username when calling updateUser'); - } - // verify required parameter 'body' is set - if (!body) { - throw new Error('Missing required parameter body when calling updateUser'); - } /** @type {!Object} */ var httpRequestParams = { - method: 'PUT', + method: 'GET', url: path, json: true, - data: body, - - - params: queryParameters, + params: queryParameters, headers: headerParams }; @@ -330,13 +309,14 @@ API.Client.UserApi.prototype.updateUser = function(username, body, opt_extraHttp } /** - * Delete user + * Updated user * This can only be done by the logged in user. - * @param {!string} username The name that needs to be deleted + * @param {!string} username name that need to be deleted + * @param {!User} body Updated user object * @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send. * @return {!angular.$q.Promise} */ -API.Client.UserApi.prototype.deleteUser = function(username, opt_extraHttpRequestParams) { +API.Client.UserApi.prototype.updateUser = function(username, body, opt_extraHttpRequestParams) { /** @const {string} */ var path = this.basePath_ + '/user/{username}' .replace('{' + 'username' + '}', String(username)); @@ -348,16 +328,19 @@ API.Client.UserApi.prototype.deleteUser = function(username, opt_extraHttpReques var headerParams = angular.extend({}, this.defaultHeaders_); // verify required parameter 'username' is set if (!username) { - throw new Error('Missing required parameter username when calling deleteUser'); + throw new Error('Missing required parameter username when calling updateUser'); + } + // verify required parameter 'body' is set + if (!body) { + throw new Error('Missing required parameter body when calling updateUser'); } /** @type {!Object} */ var httpRequestParams = { - method: 'DELETE', + method: 'PUT', url: path, json: true, - - - params: queryParameters, + data: body, + params: queryParameters, headers: headerParams }; From eb59e2945e21354b635496f13729b83a1e6b7b3a Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 31 Aug 2016 17:31:55 +0800 Subject: [PATCH 312/470] remove unnecessary change for c# codegen --- .../io/swagger/codegen/DefaultCodegen.java | 1 + .../languages/CSharpClientCodegen.java | 14 +- .../src/main/resources/csharp/README.mustache | 2 + .../options/CSharpClientOptionsProvider.java | 1 + .../csharp/SwaggerClient/IO.Swagger.sln | 10 +- .../petstore/csharp/SwaggerClient/README.md | 8 +- .../csharp/SwaggerClient/docs/FakeApi.md | 44 +++-- .../src/IO.Swagger/Api/FakeApi.cs | 165 +++++++++++++----- .../src/IO.Swagger/IO.Swagger.csproj | 2 +- .../src/IO.Swagger/Model/EnumClass.cs | 2 +- 10 files changed, 179 insertions(+), 70 deletions(-) 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 aaa49ea79f6..c5a186a6e0f 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 @@ -106,6 +106,7 @@ public class DefaultCodegen { protected Boolean ensureUniqueParams = true; protected String gitUserId, gitRepoId, releaseNote; protected String httpUserAgent; + protected Boolean hideGenerationTimestamp = true; // How to encode special characters like $ // They are translated to words like "Dollar" and prefixed with ' // Then translated back during JSON encoding and decoding diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java index 5dce9aff641..bc61b839009 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java @@ -96,6 +96,10 @@ public CSharpClientCodegen() { cliOptions.add(framework); // CLI Switches + addSwitch(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC, + this.hideGenerationTimestamp); + addSwitch(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC, this.sortParamsByRequiredFlag); @@ -134,8 +138,16 @@ public CSharpClientCodegen() { @Override public void processOpts() { super.processOpts(); - Boolean excludeTests = false; + // default HIDE_GENERATION_TIMESTAMP to true + if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); + } else { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + Boolean.valueOf((String)additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + } + + Boolean excludeTests = false; if(additionalProperties.containsKey(CodegenConstants.EXCLUDE_TESTS)) { excludeTests = Boolean.valueOf(additionalProperties.get(CodegenConstants.EXCLUDE_TESTS).toString()); } diff --git a/modules/swagger-codegen/src/main/resources/csharp/README.mustache b/modules/swagger-codegen/src/main/resources/csharp/README.mustache index a72bb17f89b..7c8a3df52df 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/README.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/README.mustache @@ -8,7 +8,9 @@ This C# SDK is automatically generated by the [Swagger Codegen](https://github.c - API version: {{appVersion}} - SDK version: {{packageVersion}} +{{^hideGenerationTimestamp}} - Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} - Build package: {{generatorClass}} {{#infoUrl}} For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java index 5f43f5cf155..28d9e0d4b20 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java @@ -33,6 +33,7 @@ public Map createOptions() { .put(CodegenConstants.OPTIONAL_PROJECT_GUID, PACKAGE_GUID_VALUE) .put(CodegenConstants.DOTNET_FRAMEWORK, "4.x") .put(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES, "true") + .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") .build(); } diff --git a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln index 9dc6bc62fa2..5a4fa34db71 100644 --- a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln +++ b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln @@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 VisualStudioVersion = 12.0.0.0 MinimumVisualStudioVersion = 10.0.0.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{F616AC0A-13D9-4D7E-ACE1-93E41B628F88}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{497E0E11-BFD7-4CB3-BA32-A19285FBB551}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger.Test", "src\IO.Swagger.Test\IO.Swagger.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" EndProject @@ -12,10 +12,10 @@ Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution -{F616AC0A-13D9-4D7E-ACE1-93E41B628F88}.Debug|Any CPU.ActiveCfg = Debug|Any CPU -{F616AC0A-13D9-4D7E-ACE1-93E41B628F88}.Debug|Any CPU.Build.0 = Debug|Any CPU -{F616AC0A-13D9-4D7E-ACE1-93E41B628F88}.Release|Any CPU.ActiveCfg = Release|Any CPU -{F616AC0A-13D9-4D7E-ACE1-93E41B628F88}.Release|Any CPU.Build.0 = Release|Any CPU +{497E0E11-BFD7-4CB3-BA32-A19285FBB551}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{497E0E11-BFD7-4CB3-BA32-A19285FBB551}.Debug|Any CPU.Build.0 = Debug|Any CPU +{497E0E11-BFD7-4CB3-BA32-A19285FBB551}.Release|Any CPU.ActiveCfg = Release|Any CPU +{497E0E11-BFD7-4CB3-BA32-A19285FBB551}.Release|Any CPU.Build.0 = Release|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/samples/client/petstore/csharp/SwaggerClient/README.md b/samples/client/petstore/csharp/SwaggerClient/README.md index 94f420f1cba..24181432ff2 100644 --- a/samples/client/petstore/csharp/SwaggerClient/README.md +++ b/samples/client/petstore/csharp/SwaggerClient/README.md @@ -6,7 +6,6 @@ This C# SDK is automatically generated by the [Swagger Codegen](https://github.c - API version: 1.0.0 - SDK version: 1.0.0 -- Build date: 2016-07-31T22:04:18.446+08:00 - Build package: class io.swagger.codegen.languages.CSharpClientCodegen ## Frameworks supported @@ -80,7 +79,7 @@ Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- *FakeApi* | [**TestClientModel**](docs/FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model *FakeApi* | [**TestEndpointParameters**](docs/FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -*FakeApi* | [**TestEnumQueryParameters**](docs/FakeApi.md#testenumqueryparameters) | **GET** /fake | To test enum query parameters +*FakeApi* | [**TestEnumParameters**](docs/FakeApi.md#testenumparameters) | **GET** /fake | To test enum parameters *PetApi* | [**AddPet**](docs/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store *PetApi* | [**DeletePet**](docs/PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet *PetApi* | [**FindPetsByStatus**](docs/PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status @@ -116,6 +115,7 @@ Class | Method | HTTP request | Description - [Model.Cat](docs/Cat.md) - [Model.Category](docs/Category.md) - [Model.Dog](docs/Dog.md) + - [Model.EnumArrays](docs/EnumArrays.md) - [Model.EnumClass](docs/EnumClass.md) - [Model.EnumTest](docs/EnumTest.md) - [Model.FormatTest](docs/FormatTest.md) @@ -144,6 +144,10 @@ Class | Method | HTTP request | Description - **API key parameter name**: api_key - **Location**: HTTP header +### http_basic_test + +- **Type**: HTTP basic authentication + ### petstore_auth - **Type**: OAuth diff --git a/samples/client/petstore/csharp/SwaggerClient/docs/FakeApi.md b/samples/client/petstore/csharp/SwaggerClient/docs/FakeApi.md index 8ad352e0537..106daec81bf 100644 --- a/samples/client/petstore/csharp/SwaggerClient/docs/FakeApi.md +++ b/samples/client/petstore/csharp/SwaggerClient/docs/FakeApi.md @@ -6,7 +6,7 @@ Method | HTTP request | Description ------------- | ------------- | ------------- [**TestClientModel**](FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model [**TestEndpointParameters**](FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -[**TestEnumQueryParameters**](FakeApi.md#testenumqueryparameters) | **GET** /fake | To test enum query parameters +[**TestEnumParameters**](FakeApi.md#testenumparameters) | **GET** /fake | To test enum parameters @@ -71,7 +71,7 @@ No authorization required # **TestEndpointParameters** -> void TestEndpointParameters (decimal? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) +> void TestEndpointParameters (decimal? number, double? _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -92,15 +92,20 @@ namespace Example public void main() { + // Configure HTTP basic authorization: http_basic_test + Configuration.Default.Username = "YOUR_USERNAME"; + Configuration.Default.Password = "YOUR_PASSWORD"; + var apiInstance = new FakeApi(); var number = 3.4; // decimal? | None var _double = 1.2; // double? | None - var _string = _string_example; // string | None + var patternWithoutDelimiter = patternWithoutDelimiter_example; // string | None var _byte = B; // byte[] | None var integer = 56; // int? | None (optional) var int32 = 56; // int? | None (optional) var int64 = 789; // long? | None (optional) var _float = 3.4; // float? | None (optional) + var _string = _string_example; // string | None (optional) var binary = B; // byte[] | None (optional) var date = 2013-10-20; // DateTime? | None (optional) var dateTime = 2013-10-20T19:20:30+01:00; // DateTime? | None (optional) @@ -109,7 +114,7 @@ namespace Example try { // Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - apiInstance.TestEndpointParameters(number, _double, _string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + apiInstance.TestEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, dateTime, password); } catch (Exception e) { @@ -126,12 +131,13 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **number** | **decimal?**| None | **_double** | **double?**| None | - **_string** | **string**| None | + **patternWithoutDelimiter** | **string**| None | **_byte** | **byte[]**| None | **integer** | **int?**| None | [optional] **int32** | **int?**| None | [optional] **int64** | **long?**| None | [optional] **_float** | **float?**| None | [optional] + **_string** | **string**| None | [optional] **binary** | **byte[]**| None | [optional] **date** | **DateTime?**| None | [optional] **dateTime** | **DateTime?**| None | [optional] @@ -143,7 +149,7 @@ void (empty response body) ### Authorization -No authorization required +[http_basic_test](../README.md#http_basic_test) ### HTTP request headers @@ -152,11 +158,11 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **TestEnumQueryParameters** -> void TestEnumQueryParameters (string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null) + +# **TestEnumParameters** +> void TestEnumParameters (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null) -To test enum query parameters +To test enum parameters ### Example ```csharp @@ -168,24 +174,29 @@ using IO.Swagger.Model; namespace Example { - public class TestEnumQueryParametersExample + public class TestEnumParametersExample { public void main() { var apiInstance = new FakeApi(); + var enumFormStringArray = new List(); // List | Form parameter enum test (string array) (optional) + var enumFormString = enumFormString_example; // string | Form parameter enum test (string) (optional) (default to -efg) + var enumHeaderStringArray = new List(); // List | Header parameter enum test (string array) (optional) + var enumHeaderString = enumHeaderString_example; // string | Header parameter enum test (string) (optional) (default to -efg) + var enumQueryStringArray = new List(); // List | Query parameter enum test (string array) (optional) var enumQueryString = enumQueryString_example; // string | Query parameter enum test (string) (optional) (default to -efg) var enumQueryInteger = 3.4; // decimal? | Query parameter enum test (double) (optional) var enumQueryDouble = 1.2; // double? | Query parameter enum test (double) (optional) try { - // To test enum query parameters - apiInstance.TestEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); + // To test enum parameters + apiInstance.TestEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); } catch (Exception e) { - Debug.Print("Exception when calling FakeApi.TestEnumQueryParameters: " + e.Message ); + Debug.Print("Exception when calling FakeApi.TestEnumParameters: " + e.Message ); } } } @@ -196,6 +207,11 @@ namespace Example Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- + **enumFormStringArray** | [**List**](string.md)| Form parameter enum test (string array) | [optional] + **enumFormString** | **string**| Form parameter enum test (string) | [optional] [default to -efg] + **enumHeaderStringArray** | [**List**](string.md)| Header parameter enum test (string array) | [optional] + **enumHeaderString** | **string**| Header parameter enum test (string) | [optional] [default to -efg] + **enumQueryStringArray** | [**List**](string.md)| Query parameter enum test (string array) | [optional] **enumQueryString** | **string**| Query parameter enum test (string) | [optional] [default to -efg] **enumQueryInteger** | **decimal?**| Query parameter enum test (double) | [optional] **enumQueryDouble** | **double?**| Query parameter enum test (double) | [optional] diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/FakeApi.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/FakeApi.cs index 0bf1cdf583c..f6d4c85a6ce 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/FakeApi.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/FakeApi.cs @@ -66,18 +66,19 @@ public interface IFakeApi : IApiAccessor /// Thrown when fails to make API call /// None /// None - /// None + /// None /// None /// None (optional) /// None (optional) /// None (optional) /// None (optional) + /// None (optional) /// None (optional) /// None (optional) /// None (optional) /// None (optional) /// - void TestEndpointParameters (decimal? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null); + void TestEndpointParameters (decimal? number, double? _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null); /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -88,43 +89,54 @@ public interface IFakeApi : IApiAccessor /// Thrown when fails to make API call /// None /// None - /// None + /// None /// None /// None (optional) /// None (optional) /// None (optional) /// None (optional) + /// None (optional) /// None (optional) /// None (optional) /// None (optional) /// None (optional) /// ApiResponse of Object(void) - ApiResponse TestEndpointParametersWithHttpInfo (decimal? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null); + ApiResponse TestEndpointParametersWithHttpInfo (decimal? number, double? _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null); /// - /// To test enum query parameters + /// To test enum parameters /// /// /// /// /// Thrown when fails to make API call + /// Form parameter enum test (string array) (optional) + /// Form parameter enum test (string) (optional, default to -efg) + /// Header parameter enum test (string array) (optional) + /// Header parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (string array) (optional) /// Query parameter enum test (string) (optional, default to -efg) /// Query parameter enum test (double) (optional) /// Query parameter enum test (double) (optional) /// - void TestEnumQueryParameters (string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null); + void TestEnumParameters (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null); /// - /// To test enum query parameters + /// To test enum parameters /// /// /// /// /// Thrown when fails to make API call + /// Form parameter enum test (string array) (optional) + /// Form parameter enum test (string) (optional, default to -efg) + /// Header parameter enum test (string array) (optional) + /// Header parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (string array) (optional) /// Query parameter enum test (string) (optional, default to -efg) /// Query parameter enum test (double) (optional) /// Query parameter enum test (double) (optional) /// ApiResponse of Object(void) - ApiResponse TestEnumQueryParametersWithHttpInfo (string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null); + ApiResponse TestEnumParametersWithHttpInfo (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null); #endregion Synchronous Operations #region Asynchronous Operations /// @@ -157,18 +169,19 @@ public interface IFakeApi : IApiAccessor /// Thrown when fails to make API call /// None /// None - /// None + /// None /// None /// None (optional) /// None (optional) /// None (optional) /// None (optional) + /// None (optional) /// None (optional) /// None (optional) /// None (optional) /// None (optional) /// Task of void - System.Threading.Tasks.Task TestEndpointParametersAsync (decimal? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null); + System.Threading.Tasks.Task TestEndpointParametersAsync (decimal? number, double? _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null); /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -179,43 +192,54 @@ public interface IFakeApi : IApiAccessor /// Thrown when fails to make API call /// None /// None - /// None + /// None /// None /// None (optional) /// None (optional) /// None (optional) /// None (optional) + /// None (optional) /// None (optional) /// None (optional) /// None (optional) /// None (optional) /// Task of ApiResponse - System.Threading.Tasks.Task> TestEndpointParametersAsyncWithHttpInfo (decimal? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null); + System.Threading.Tasks.Task> TestEndpointParametersAsyncWithHttpInfo (decimal? number, double? _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null); /// - /// To test enum query parameters + /// To test enum parameters /// /// /// /// /// Thrown when fails to make API call + /// Form parameter enum test (string array) (optional) + /// Form parameter enum test (string) (optional, default to -efg) + /// Header parameter enum test (string array) (optional) + /// Header parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (string array) (optional) /// Query parameter enum test (string) (optional, default to -efg) /// Query parameter enum test (double) (optional) /// Query parameter enum test (double) (optional) /// Task of void - System.Threading.Tasks.Task TestEnumQueryParametersAsync (string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null); + System.Threading.Tasks.Task TestEnumParametersAsync (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null); /// - /// To test enum query parameters + /// To test enum parameters /// /// /// /// /// Thrown when fails to make API call + /// Form parameter enum test (string array) (optional) + /// Form parameter enum test (string) (optional, default to -efg) + /// Header parameter enum test (string array) (optional) + /// Header parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (string array) (optional) /// Query parameter enum test (string) (optional, default to -efg) /// Query parameter enum test (double) (optional) /// Query parameter enum test (double) (optional) /// Task of ApiResponse - System.Threading.Tasks.Task> TestEnumQueryParametersAsyncWithHttpInfo (string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null); + System.Threading.Tasks.Task> TestEnumParametersAsyncWithHttpInfo (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null); #endregion Asynchronous Operations } @@ -491,20 +515,21 @@ public async System.Threading.Tasks.Task> TestClientMod /// Thrown when fails to make API call /// None /// None - /// None + /// None /// None /// None (optional) /// None (optional) /// None (optional) /// None (optional) + /// None (optional) /// None (optional) /// None (optional) /// None (optional) /// None (optional) /// - public void TestEndpointParameters (decimal? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) + public void TestEndpointParameters (decimal? number, double? _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) { - TestEndpointParametersWithHttpInfo(number, _double, _string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + TestEndpointParametersWithHttpInfo(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, dateTime, password); } /// @@ -513,18 +538,19 @@ public void TestEndpointParameters (decimal? number, double? _double, string _st /// Thrown when fails to make API call /// None /// None - /// None + /// None /// None /// None (optional) /// None (optional) /// None (optional) /// None (optional) + /// None (optional) /// None (optional) /// None (optional) /// None (optional) /// None (optional) /// ApiResponse of Object(void) - public ApiResponse TestEndpointParametersWithHttpInfo (decimal? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) + public ApiResponse TestEndpointParametersWithHttpInfo (decimal? number, double? _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) { // verify the required parameter 'number' is set if (number == null) @@ -532,9 +558,9 @@ public ApiResponse TestEndpointParametersWithHttpInfo (decimal? number, // verify the required parameter '_double' is set if (_double == null) throw new ApiException(400, "Missing required parameter '_double' when calling FakeApi->TestEndpointParameters"); - // verify the required parameter '_string' is set - if (_string == null) - throw new ApiException(400, "Missing required parameter '_string' when calling FakeApi->TestEndpointParameters"); + // verify the required parameter 'patternWithoutDelimiter' is set + if (patternWithoutDelimiter == null) + throw new ApiException(400, "Missing required parameter 'patternWithoutDelimiter' when calling FakeApi->TestEndpointParameters"); // verify the required parameter '_byte' is set if (_byte == null) throw new ApiException(400, "Missing required parameter '_byte' when calling FakeApi->TestEndpointParameters"); @@ -573,12 +599,20 @@ public ApiResponse TestEndpointParametersWithHttpInfo (decimal? number, if (_float != null) localVarFormParams.Add("float", Configuration.ApiClient.ParameterToString(_float)); // form parameter if (_double != null) localVarFormParams.Add("double", Configuration.ApiClient.ParameterToString(_double)); // form parameter if (_string != null) localVarFormParams.Add("string", Configuration.ApiClient.ParameterToString(_string)); // form parameter + if (patternWithoutDelimiter != null) localVarFormParams.Add("pattern_without_delimiter", Configuration.ApiClient.ParameterToString(patternWithoutDelimiter)); // form parameter if (_byte != null) localVarFormParams.Add("byte", Configuration.ApiClient.ParameterToString(_byte)); // form parameter if (binary != null) localVarFormParams.Add("binary", Configuration.ApiClient.ParameterToString(binary)); // form parameter if (date != null) localVarFormParams.Add("date", Configuration.ApiClient.ParameterToString(date)); // form parameter if (dateTime != null) localVarFormParams.Add("dateTime", Configuration.ApiClient.ParameterToString(dateTime)); // form parameter if (password != null) localVarFormParams.Add("password", Configuration.ApiClient.ParameterToString(password)); // form parameter + // authentication (http_basic_test) required + // http basic authentication required + if (!String.IsNullOrEmpty(Configuration.Username) || !String.IsNullOrEmpty(Configuration.Password)) + { + localVarHeaderParams["Authorization"] = "Basic " + ApiClient.Base64Encode(Configuration.Username + ":" + Configuration.Password); + } + // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, @@ -605,20 +639,21 @@ public ApiResponse TestEndpointParametersWithHttpInfo (decimal? number, /// Thrown when fails to make API call /// None /// None - /// None + /// None /// None /// None (optional) /// None (optional) /// None (optional) /// None (optional) + /// None (optional) /// None (optional) /// None (optional) /// None (optional) /// None (optional) /// Task of void - public async System.Threading.Tasks.Task TestEndpointParametersAsync (decimal? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) + public async System.Threading.Tasks.Task TestEndpointParametersAsync (decimal? number, double? _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) { - await TestEndpointParametersAsyncWithHttpInfo(number, _double, _string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + await TestEndpointParametersAsyncWithHttpInfo(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, dateTime, password); } @@ -628,18 +663,19 @@ public async System.Threading.Tasks.Task TestEndpointParametersAsync (decimal? n /// Thrown when fails to make API call /// None /// None - /// None + /// None /// None /// None (optional) /// None (optional) /// None (optional) /// None (optional) + /// None (optional) /// None (optional) /// None (optional) /// None (optional) /// None (optional) /// Task of ApiResponse - public async System.Threading.Tasks.Task> TestEndpointParametersAsyncWithHttpInfo (decimal? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) + public async System.Threading.Tasks.Task> TestEndpointParametersAsyncWithHttpInfo (decimal? number, double? _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) { // verify the required parameter 'number' is set if (number == null) @@ -647,9 +683,9 @@ public async System.Threading.Tasks.Task> TestEndpointParame // verify the required parameter '_double' is set if (_double == null) throw new ApiException(400, "Missing required parameter '_double' when calling FakeApi->TestEndpointParameters"); - // verify the required parameter '_string' is set - if (_string == null) - throw new ApiException(400, "Missing required parameter '_string' when calling FakeApi->TestEndpointParameters"); + // verify the required parameter 'patternWithoutDelimiter' is set + if (patternWithoutDelimiter == null) + throw new ApiException(400, "Missing required parameter 'patternWithoutDelimiter' when calling FakeApi->TestEndpointParameters"); // verify the required parameter '_byte' is set if (_byte == null) throw new ApiException(400, "Missing required parameter '_byte' when calling FakeApi->TestEndpointParameters"); @@ -688,12 +724,19 @@ public async System.Threading.Tasks.Task> TestEndpointParame if (_float != null) localVarFormParams.Add("float", Configuration.ApiClient.ParameterToString(_float)); // form parameter if (_double != null) localVarFormParams.Add("double", Configuration.ApiClient.ParameterToString(_double)); // form parameter if (_string != null) localVarFormParams.Add("string", Configuration.ApiClient.ParameterToString(_string)); // form parameter + if (patternWithoutDelimiter != null) localVarFormParams.Add("pattern_without_delimiter", Configuration.ApiClient.ParameterToString(patternWithoutDelimiter)); // form parameter if (_byte != null) localVarFormParams.Add("byte", Configuration.ApiClient.ParameterToString(_byte)); // form parameter if (binary != null) localVarFormParams.Add("binary", Configuration.ApiClient.ParameterToString(binary)); // form parameter if (date != null) localVarFormParams.Add("date", Configuration.ApiClient.ParameterToString(date)); // form parameter if (dateTime != null) localVarFormParams.Add("dateTime", Configuration.ApiClient.ParameterToString(dateTime)); // form parameter if (password != null) localVarFormParams.Add("password", Configuration.ApiClient.ParameterToString(password)); // form parameter + // authentication (http_basic_test) required + // http basic authentication required + if (!String.IsNullOrEmpty(Configuration.Username) || !String.IsNullOrEmpty(Configuration.Password)) + { + localVarHeaderParams["Authorization"] = "Basic " + ApiClient.Base64Encode(Configuration.Username + ":" + Configuration.Password); + } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, @@ -715,27 +758,37 @@ public async System.Threading.Tasks.Task> TestEndpointParame } /// - /// To test enum query parameters + /// To test enum parameters /// /// Thrown when fails to make API call + /// Form parameter enum test (string array) (optional) + /// Form parameter enum test (string) (optional, default to -efg) + /// Header parameter enum test (string array) (optional) + /// Header parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (string array) (optional) /// Query parameter enum test (string) (optional, default to -efg) /// Query parameter enum test (double) (optional) /// Query parameter enum test (double) (optional) /// - public void TestEnumQueryParameters (string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null) + public void TestEnumParameters (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null) { - TestEnumQueryParametersWithHttpInfo(enumQueryString, enumQueryInteger, enumQueryDouble); + TestEnumParametersWithHttpInfo(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); } /// - /// To test enum query parameters + /// To test enum parameters /// /// Thrown when fails to make API call + /// Form parameter enum test (string array) (optional) + /// Form parameter enum test (string) (optional, default to -efg) + /// Header parameter enum test (string array) (optional) + /// Header parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (string array) (optional) /// Query parameter enum test (string) (optional, default to -efg) /// Query parameter enum test (double) (optional) /// Query parameter enum test (double) (optional) /// ApiResponse of Object(void) - public ApiResponse TestEnumQueryParametersWithHttpInfo (string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null) + public ApiResponse TestEnumParametersWithHttpInfo (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null) { var localVarPath = "/fake"; @@ -763,8 +816,13 @@ public ApiResponse TestEnumQueryParametersWithHttpInfo (string enumQuery // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); + if (enumQueryStringArray != null) localVarQueryParams.Add("enum_query_string_array", Configuration.ApiClient.ParameterToString(enumQueryStringArray)); // query parameter + if (enumQueryString != null) localVarQueryParams.Add("enum_query_string", Configuration.ApiClient.ParameterToString(enumQueryString)); // query parameter if (enumQueryInteger != null) localVarQueryParams.Add("enum_query_integer", Configuration.ApiClient.ParameterToString(enumQueryInteger)); // query parameter - if (enumQueryString != null) localVarFormParams.Add("enum_query_string", Configuration.ApiClient.ParameterToString(enumQueryString)); // form parameter + if (enumHeaderStringArray != null) localVarHeaderParams.Add("enum_header_string_array", Configuration.ApiClient.ParameterToString(enumHeaderStringArray)); // header parameter + if (enumHeaderString != null) localVarHeaderParams.Add("enum_header_string", Configuration.ApiClient.ParameterToString(enumHeaderString)); // header parameter + if (enumFormStringArray != null) localVarFormParams.Add("enum_form_string_array", Configuration.ApiClient.ParameterToString(enumFormStringArray)); // form parameter + if (enumFormString != null) localVarFormParams.Add("enum_form_string", Configuration.ApiClient.ParameterToString(enumFormString)); // form parameter if (enumQueryDouble != null) localVarFormParams.Add("enum_query_double", Configuration.ApiClient.ParameterToString(enumQueryDouble)); // form parameter @@ -777,7 +835,7 @@ public ApiResponse TestEnumQueryParametersWithHttpInfo (string enumQuery if (ExceptionFactory != null) { - Exception exception = ExceptionFactory("TestEnumQueryParameters", localVarResponse); + Exception exception = ExceptionFactory("TestEnumParameters", localVarResponse); if (exception != null) throw exception; } @@ -788,28 +846,38 @@ public ApiResponse TestEnumQueryParametersWithHttpInfo (string enumQuery } /// - /// To test enum query parameters + /// To test enum parameters /// /// Thrown when fails to make API call + /// Form parameter enum test (string array) (optional) + /// Form parameter enum test (string) (optional, default to -efg) + /// Header parameter enum test (string array) (optional) + /// Header parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (string array) (optional) /// Query parameter enum test (string) (optional, default to -efg) /// Query parameter enum test (double) (optional) /// Query parameter enum test (double) (optional) /// Task of void - public async System.Threading.Tasks.Task TestEnumQueryParametersAsync (string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null) + public async System.Threading.Tasks.Task TestEnumParametersAsync (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null) { - await TestEnumQueryParametersAsyncWithHttpInfo(enumQueryString, enumQueryInteger, enumQueryDouble); + await TestEnumParametersAsyncWithHttpInfo(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); } /// - /// To test enum query parameters + /// To test enum parameters /// /// Thrown when fails to make API call + /// Form parameter enum test (string array) (optional) + /// Form parameter enum test (string) (optional, default to -efg) + /// Header parameter enum test (string array) (optional) + /// Header parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (string array) (optional) /// Query parameter enum test (string) (optional, default to -efg) /// Query parameter enum test (double) (optional) /// Query parameter enum test (double) (optional) /// Task of ApiResponse - public async System.Threading.Tasks.Task> TestEnumQueryParametersAsyncWithHttpInfo (string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null) + public async System.Threading.Tasks.Task> TestEnumParametersAsyncWithHttpInfo (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null) { var localVarPath = "/fake"; @@ -837,8 +905,13 @@ public async System.Threading.Tasks.Task> TestEnumQueryParam // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); + if (enumQueryStringArray != null) localVarQueryParams.Add("enum_query_string_array", Configuration.ApiClient.ParameterToString(enumQueryStringArray)); // query parameter + if (enumQueryString != null) localVarQueryParams.Add("enum_query_string", Configuration.ApiClient.ParameterToString(enumQueryString)); // query parameter if (enumQueryInteger != null) localVarQueryParams.Add("enum_query_integer", Configuration.ApiClient.ParameterToString(enumQueryInteger)); // query parameter - if (enumQueryString != null) localVarFormParams.Add("enum_query_string", Configuration.ApiClient.ParameterToString(enumQueryString)); // form parameter + if (enumHeaderStringArray != null) localVarHeaderParams.Add("enum_header_string_array", Configuration.ApiClient.ParameterToString(enumHeaderStringArray)); // header parameter + if (enumHeaderString != null) localVarHeaderParams.Add("enum_header_string", Configuration.ApiClient.ParameterToString(enumHeaderString)); // header parameter + if (enumFormStringArray != null) localVarFormParams.Add("enum_form_string_array", Configuration.ApiClient.ParameterToString(enumFormStringArray)); // form parameter + if (enumFormString != null) localVarFormParams.Add("enum_form_string", Configuration.ApiClient.ParameterToString(enumFormString)); // form parameter if (enumQueryDouble != null) localVarFormParams.Add("enum_query_double", Configuration.ApiClient.ParameterToString(enumQueryDouble)); // form parameter @@ -851,7 +924,7 @@ public async System.Threading.Tasks.Task> TestEnumQueryParam if (ExceptionFactory != null) { - Exception exception = ExceptionFactory("TestEnumQueryParameters", localVarResponse); + Exception exception = ExceptionFactory("TestEnumParameters", localVarResponse); if (exception != null) throw exception; } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj index dcdc39039c7..ee6eca49a65 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj @@ -24,7 +24,7 @@ limitations under the License. Debug AnyCPU - {F616AC0A-13D9-4D7E-ACE1-93E41B628F88} + {497E0E11-BFD7-4CB3-BA32-A19285FBB551} Library Properties IO.Swagger diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumClass.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumClass.cs index 215eff11a18..7f63ebe77c0 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumClass.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumClass.cs @@ -34,7 +34,7 @@ namespace IO.Swagger.Model { /// - /// Gets or Sets EnumClass + /// Defines EnumClass /// [JsonConverter(typeof(StringEnumConverter))] public enum EnumClass From d464bfbd593e8ace83027699f0a3d65d417b7e54 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 31 Aug 2016 17:50:56 +0800 Subject: [PATCH 313/470] fix JS auth issue due to missig comma --- .../main/resources/Javascript/ApiClient.mustache | 16 ++++++++++++---- .../client/petstore/javascript/src/ApiClient.js | 4 ++-- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache index 30147a1fc0e..a85ebf9fbdd 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache @@ -40,10 +40,18 @@ * The authentication methods to be included for all API calls. * @type {Array.} */ -{{/emitJSDoc}}{{=< >=}} this.authentications = {<#authMethods><#isBasic> - '': {type: 'basic'}<#isApiKey> - '': {type: 'apiKey', 'in': <#isKeyInHeader>'header'<^isKeyInHeader>'query', name: ''}<#isOAuth> - '': {type: 'oauth2'}<#hasMore>, +{{/emitJSDoc}}{{=< >=}} this.authentications = { +<#authMethods> +<#isBasic> + '': {type: 'basic'}<^-last>, + +<#isApiKey> + '': {type: 'apiKey', 'in': <#isKeyInHeader>'header'<^isKeyInHeader>'query', name: ''}<^-last>, + +<#isOAuth> + '': {type: 'oauth2'}<^-last>, + + }; <={{ }}=> {{#emitJSDoc}} /** diff --git a/samples/client/petstore/javascript/src/ApiClient.js b/samples/client/petstore/javascript/src/ApiClient.js index aab7a6ebf98..1ca3143bc09 100644 --- a/samples/client/petstore/javascript/src/ApiClient.js +++ b/samples/client/petstore/javascript/src/ApiClient.js @@ -65,8 +65,8 @@ */ this.authentications = { 'api_key': {type: 'apiKey', 'in': 'header', name: 'api_key'}, - 'http_basic_test': {type: 'basic'} - 'petstore_auth': {type: 'oauth2'}, + 'http_basic_test': {type: 'basic'}, + 'petstore_auth': {type: 'oauth2'} }; /** * The default HTTP headers to be included for all API calls. From 8e7d3d1a7203a062627ab1ffe7cc0b01315287c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Thu, 1 Sep 2016 10:05:52 +0300 Subject: [PATCH 314/470] Python fixes (#3689) * python: Fix unsupported method exception message * python: Implement form data collection formatting --- .../src/main/resources/python/api.mustache | 2 +- .../main/resources/python/api_client.mustache | 27 +++++++++++++++- .../python/petstore_api/api_client.py | 27 +++++++++++++++- .../python/petstore_api/apis/fake_api.py | 32 +++++++++---------- .../python/petstore_api/apis/pet_api.py | 6 ++-- 5 files changed, 72 insertions(+), 22 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index 37e842a06ff..b6b7ac400ec 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -163,7 +163,7 @@ class {{classname}}(object): local_var_files = {} {{#formParams}} if '{{paramName}}' in params: - {{#notFile}}form_params.append(('{{baseName}}', params['{{paramName}}'])){{/notFile}}{{#isFile}}local_var_files['{{baseName}}'] = params['{{paramName}}']{{/isFile}} + {{#notFile}}form_params.extend(self.api_client.parameter_to_tuples('{{collectionFormat}}', '{{baseName}}', params['{{paramName}}'])){{/notFile}}{{#isFile}}local_var_files['{{baseName}}'] = params['{{paramName}}']{{/isFile}} {{/formParams}} body_params = None diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index ea721a1bc3e..5abc2a360d9 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -370,10 +370,35 @@ class ApiClient(object): body=body) else: raise ValueError( - "http method must be `GET`, `HEAD`," + "http method must be `GET`, `HEAD`, `OPTIONS`," " `POST`, `PATCH`, `PUT` or `DELETE`." ) + def parameter_to_tuples(self, collection_format, name, value): + """ + Get parameter as list of tuples according to collection format. + + :param str collection_format: Collection format + :param str name: Parameter name + :param value: Parameter value + :return: Parameter as list of tuples + """ + if isinstance(value, (list, tuple)): + if collection_format == "multi": + return [(name, v) for v in value] + else: + if collection_format == "ssv": + delimiter = " " + elif collection_format == "tsv": + delimiter = "\t" + elif collection_format == "pipes": + delimiter = "|" + else: # csv is the default + delimiter = "," + return [(name, delimiter.join(value))] + else: + return [(name, value)] + def prepare_post_parameters(self, post_params=None, files=None): """ Builds form parameters. diff --git a/samples/client/petstore/python/petstore_api/api_client.py b/samples/client/petstore/python/petstore_api/api_client.py index c4096d4bc63..e36a115e0d6 100644 --- a/samples/client/petstore/python/petstore_api/api_client.py +++ b/samples/client/petstore/python/petstore_api/api_client.py @@ -370,10 +370,35 @@ def request(self, method, url, query_params=None, headers=None, body=body) else: raise ValueError( - "http method must be `GET`, `HEAD`," + "http method must be `GET`, `HEAD`, `OPTIONS`," " `POST`, `PATCH`, `PUT` or `DELETE`." ) + def parameter_to_tuples(self, collection_format, name, value): + """ + Get parameter as list of tuples according to collection format. + + :param str collection_format: Collection format + :param str name: Parameter name + :param value: Parameter value + :return: Parameter as list of tuples + """ + if isinstance(value, (list, tuple)): + if collection_format == "multi": + return [(name, v) for v in value] + else: + if collection_format == "ssv": + delimiter = " " + elif collection_format == "tsv": + delimiter = "\t" + elif collection_format == "pipes": + delimiter = "|" + else: # csv is the default + delimiter = "," + return [(name, delimiter.join(value))] + else: + return [(name, value)] + def prepare_post_parameters(self, post_params=None, files=None): """ Builds form parameters. diff --git a/samples/client/petstore/python/petstore_api/apis/fake_api.py b/samples/client/petstore/python/petstore_api/apis/fake_api.py index 6a2dd0b852a..5dd2a327021 100644 --- a/samples/client/petstore/python/petstore_api/apis/fake_api.py +++ b/samples/client/petstore/python/petstore_api/apis/fake_api.py @@ -289,31 +289,31 @@ def test_endpoint_parameters_with_http_info(self, number, double, pattern_withou form_params = [] local_var_files = {} if 'integer' in params: - form_params.append(('integer', params['integer'])) + form_params.extend(self.api_client.parameter_to_tuples('', 'integer', params['integer'])) if 'int32' in params: - form_params.append(('int32', params['int32'])) + form_params.extend(self.api_client.parameter_to_tuples('', 'int32', params['int32'])) if 'int64' in params: - form_params.append(('int64', params['int64'])) + form_params.extend(self.api_client.parameter_to_tuples('', 'int64', params['int64'])) if 'number' in params: - form_params.append(('number', params['number'])) + form_params.extend(self.api_client.parameter_to_tuples('', 'number', params['number'])) if 'float' in params: - form_params.append(('float', params['float'])) + form_params.extend(self.api_client.parameter_to_tuples('', 'float', params['float'])) if 'double' in params: - form_params.append(('double', params['double'])) + form_params.extend(self.api_client.parameter_to_tuples('', 'double', params['double'])) if 'string' in params: - form_params.append(('string', params['string'])) + form_params.extend(self.api_client.parameter_to_tuples('', 'string', params['string'])) if 'pattern_without_delimiter' in params: - form_params.append(('pattern_without_delimiter', params['pattern_without_delimiter'])) + form_params.extend(self.api_client.parameter_to_tuples('', 'pattern_without_delimiter', params['pattern_without_delimiter'])) if 'byte' in params: - form_params.append(('byte', params['byte'])) + form_params.extend(self.api_client.parameter_to_tuples('', 'byte', params['byte'])) if 'binary' in params: - form_params.append(('binary', params['binary'])) + form_params.extend(self.api_client.parameter_to_tuples('', 'binary', params['binary'])) if 'date' in params: - form_params.append(('date', params['date'])) + form_params.extend(self.api_client.parameter_to_tuples('', 'date', params['date'])) if 'date_time' in params: - form_params.append(('dateTime', params['date_time'])) + form_params.extend(self.api_client.parameter_to_tuples('', 'dateTime', params['date_time'])) if 'password' in params: - form_params.append(('password', params['password'])) + form_params.extend(self.api_client.parameter_to_tuples('', 'password', params['password'])) body_params = None @@ -438,11 +438,11 @@ def test_enum_parameters_with_http_info(self, **kwargs): form_params = [] local_var_files = {} if 'enum_form_string_array' in params: - form_params.append(('enum_form_string_array', params['enum_form_string_array'])) + form_params.extend(self.api_client.parameter_to_tuples('csv', 'enum_form_string_array', params['enum_form_string_array'])) if 'enum_form_string' in params: - form_params.append(('enum_form_string', params['enum_form_string'])) + form_params.extend(self.api_client.parameter_to_tuples('', 'enum_form_string', params['enum_form_string'])) if 'enum_query_double' in params: - form_params.append(('enum_query_double', params['enum_query_double'])) + form_params.extend(self.api_client.parameter_to_tuples('', 'enum_query_double', params['enum_query_double'])) body_params = None diff --git a/samples/client/petstore/python/petstore_api/apis/pet_api.py b/samples/client/petstore/python/petstore_api/apis/pet_api.py index a186727b958..9357e8e70e1 100644 --- a/samples/client/petstore/python/petstore_api/apis/pet_api.py +++ b/samples/client/petstore/python/petstore_api/apis/pet_api.py @@ -760,9 +760,9 @@ def update_pet_with_form_with_http_info(self, pet_id, **kwargs): form_params = [] local_var_files = {} if 'name' in params: - form_params.append(('name', params['name'])) + form_params.extend(self.api_client.parameter_to_tuples('', 'name', params['name'])) if 'status' in params: - form_params.append(('status', params['status'])) + form_params.extend(self.api_client.parameter_to_tuples('', 'status', params['status'])) body_params = None @@ -872,7 +872,7 @@ def upload_file_with_http_info(self, pet_id, **kwargs): form_params = [] local_var_files = {} if 'additional_metadata' in params: - form_params.append(('additionalMetadata', params['additional_metadata'])) + form_params.extend(self.api_client.parameter_to_tuples('', 'additionalMetadata', params['additional_metadata'])) if 'file' in params: local_var_files['file'] = params['file'] From 062e6fc3ac88cda8bc44d5f459369a13899e81f9 Mon Sep 17 00:00:00 2001 From: Jyotsna Karan Date: Thu, 1 Sep 2016 15:41:23 +0530 Subject: [PATCH 315/470] Added functionality to handle optional parameters for Scala (#3683) * 1. Modified api.mushtache to handle optional paramters for scala (#3665) 2. Updated petstore sample for scala * Generated scala-petstore.sh (#3665) * 1. Updated api.mustache to handle optional thing with headers and file parameters 2. Generated petstore sample for the above changes --- .../src/main/resources/scala/api.mustache | 40 ++++++++++++-- .../scala/io/swagger/client/api/PetApi.scala | 53 +++++++++---------- .../io/swagger/client/api/StoreApi.scala | 16 +++--- .../scala/io/swagger/client/api/UserApi.scala | 34 ++++++------ 4 files changed, 86 insertions(+), 57 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/scala/api.mustache b/modules/swagger-codegen/src/main/resources/scala/api.mustache index 584441ee14e..ce927fa304e 100644 --- a/modules/swagger-codegen/src/main/resources/scala/api.mustache +++ b/modules/swagger-codegen/src/main/resources/scala/api.mustache @@ -31,7 +31,7 @@ class {{classname}}(val defBasePath: String = "{{basePath}}", {{#allParams}} * @param {{paramName}} {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} */ - def {{operationId}} ({{#allParams}}{{paramName}}: {{dataType}}{{#defaultValue}} /* = {{{defaultValue}}} */{{/defaultValue}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {{#returnType}}: Option[{{returnType}}]{{/returnType}} = { + def {{operationId}}({{#allParams}}{{paramName}}: {{#required}}{{dataType}}{{#defaultValue}} /* = {{{defaultValue}}}*/{{/defaultValue}}{{/required}}{{^required}}Option[{{dataType}}]{{#defaultValue}} /* = {{{defaultValue}}}*/{{/defaultValue}}{{^defaultValue}} = None{{/defaultValue}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}){{#returnType}}: Option[{{returnType}}]{{/returnType}} = { // create path and map variables val path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}.replaceAll("\\{" + "{{baseName}}" + "\\}",apiInvoker.escape({{paramName}})) @@ -53,27 +53,57 @@ class {{classname}}(val defBasePath: String = "{{basePath}}", {{/isPrimitiveType}} {{/required}} {{/allParams}} - {{#queryParams}}if(String.valueOf({{paramName}}) != "null") queryParams += "{{baseName}}" -> {{paramName}}.toString + {{#queryParams}} + {{#required}} + if(String.valueOf({{paramName}}) != "null") queryParams += "{{baseName}}" -> {{paramName}}.toString + {{/required}} + {{^required}} + {{paramName}}.map(paramVal => queryParams += "{{baseName}}" -> paramVal.toString) + {{/required}} {{/queryParams}} - {{#headerParams}}headerParams += "{{baseName}}" -> {{paramName}} + {{#headerParams}} + {{#required}} + headerParams += "{{baseName}}" -> {{paramName}} + {{/required}} + {{^required}} + {{paramName}}.map(paramVal => headerParams += "{{baseName}}" -> paramVal) + {{/required}} {{/headerParams}} - var postBody: AnyRef = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}} + var postBody: AnyRef = {{#bodyParam}}{{#required}}{{paramName}}{{/required}}{{^required}}{{paramName}}.map(paramVal => paramVal){{/required}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}} if(contentType.startsWith("multipart/form-data")) { val mp = new FormDataMultiPart() {{#formParams}}{{#notFile}} + {{#required}} mp.field("{{baseName}}", {{paramName}}.toString(), MediaType.MULTIPART_FORM_DATA_TYPE) + {{/required}} + {{^required}} + {{paramName}}.map(paramVal => mp.field("{{baseName}}", paramVal.toString, MediaType.MULTIPART_FORM_DATA_TYPE)) + {{/required}} {{/notFile}}{{#isFile}} + {{#required}} mp.field("{{baseName}}", file.getName) mp.bodyPart(new FileDataBodyPart("{{baseName}}", {{paramName}}, MediaType.MULTIPART_FORM_DATA_TYPE)) + {{/required}} + {{^required}} + file.map(fileVal => mp.field("{{baseName}}", fileVal.getName)) + {{paramName}}.map(paramVal => mp.bodyPart(new FileDataBodyPart("{{baseName}}", paramVal, MediaType.MULTIPART_FORM_DATA_TYPE))) + {{/required}} {{/isFile}}{{/formParams}} postBody = mp } else { {{#formParams}} - {{#notFile}}formParams += "{{baseName}}" -> {{paramName}}.toString(){{/notFile}} + {{#notFile}} + {{#required}} + formParams += "{{baseName}}" -> {{paramName}}.toString() + {{/required}} + {{^required}} + {{paramName}}.map(paramVal => formParams += "{{baseName}}" -> paramVal.toString) + {{/required}} + {{/notFile}} {{/formParams}} } diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala index 66ff610e9b3..52974fb7e86 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala @@ -25,8 +25,8 @@ package io.swagger.client.api import io.swagger.client.model.Pet -import io.swagger.client.model.ApiResponse import java.io.File +import io.swagger.client.model.ApiResponse import io.swagger.client.ApiInvoker import io.swagger.client.ApiException @@ -53,7 +53,7 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param body Pet object that needs to be added to the store * @return void */ - def addPet (body: Pet) = { + def addPet(body: Pet) = { // create path and map variables val path = "/pet".replaceAll("\\{format\\}","json") val contentTypes = List("application/json", "application/xml", "application/json") @@ -66,8 +66,8 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", if (body == null) throw new Exception("Missing required parameter 'body' when calling PetApi->addPet") - + var postBody: AnyRef = body if(contentType.startsWith("multipart/form-data")) { @@ -96,7 +96,7 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param apiKey (optional) * @return void */ - def deletePet (petId: Long, apiKey: String) = { + def deletePet(petId: Long, apiKey: Option[String] = None) = { // create path and map variables val path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}",apiInvoker.escape(petId)) @@ -109,8 +109,8 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", val headerParams = new HashMap[String, String] val formParams = new HashMap[String, String] - - headerParams += "api_key" -> apiKey + + apiKey.map(paramVal => headerParams += "api_key" -> paramVal) var postBody: AnyRef = null @@ -139,7 +139,7 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param status Status values that need to be considered for filter * @return List[Pet] */ - def findPetsByStatus (status: List[String]) : Option[List[Pet]] = { + def findPetsByStatus(status: List[String]): Option[List[Pet]] = { // create path and map variables val path = "/pet/findByStatus".replaceAll("\\{format\\}","json") val contentTypes = List("application/json") @@ -154,7 +154,7 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", if(String.valueOf(status) != "null") queryParams += "status" -> status.toString - + var postBody: AnyRef = null if(contentType.startsWith("multipart/form-data")) { @@ -183,7 +183,7 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param tags Tags to filter by * @return List[Pet] */ - def findPetsByTags (tags: List[String]) : Option[List[Pet]] = { + def findPetsByTags(tags: List[String]): Option[List[Pet]] = { // create path and map variables val path = "/pet/findByTags".replaceAll("\\{format\\}","json") val contentTypes = List("application/json") @@ -198,7 +198,7 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", if(String.valueOf(tags) != "null") queryParams += "tags" -> tags.toString - + var postBody: AnyRef = null if(contentType.startsWith("multipart/form-data")) { @@ -227,7 +227,7 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param petId ID of pet to return * @return Pet */ - def getPetById (petId: Long) : Option[Pet] = { + def getPetById(petId: Long): Option[Pet] = { // create path and map variables val path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}",apiInvoker.escape(petId)) @@ -240,8 +240,8 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", val headerParams = new HashMap[String, String] val formParams = new HashMap[String, String] - + var postBody: AnyRef = null if(contentType.startsWith("multipart/form-data")) { @@ -270,7 +270,7 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param body Pet object that needs to be added to the store * @return void */ - def updatePet (body: Pet) = { + def updatePet(body: Pet) = { // create path and map variables val path = "/pet".replaceAll("\\{format\\}","json") val contentTypes = List("application/json", "application/xml", "application/json") @@ -283,8 +283,8 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", if (body == null) throw new Exception("Missing required parameter 'body' when calling PetApi->updatePet") - + var postBody: AnyRef = body if(contentType.startsWith("multipart/form-data")) { @@ -314,7 +314,7 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param status Updated status of the pet (optional) * @return void */ - def updatePetWithForm (petId: Long, name: String, status: String) = { + def updatePetWithForm(petId: Long, name: Option[String] = None, status: Option[String] = None) = { // create path and map variables val path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}",apiInvoker.escape(petId)) @@ -327,22 +327,22 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", val headerParams = new HashMap[String, String] val formParams = new HashMap[String, String] - + var postBody: AnyRef = null if(contentType.startsWith("multipart/form-data")) { val mp = new FormDataMultiPart() - mp.field("name", name.toString(), MediaType.MULTIPART_FORM_DATA_TYPE) + name.map(paramVal => mp.field("name", paramVal.toString, MediaType.MULTIPART_FORM_DATA_TYPE)) - mp.field("status", status.toString(), MediaType.MULTIPART_FORM_DATA_TYPE) + status.map(paramVal => mp.field("status", paramVal.toString, MediaType.MULTIPART_FORM_DATA_TYPE)) postBody = mp } else { - formParams += "name" -> name.toString() - formParams += "status" -> status.toString() + name.map(paramVal => formParams += "name" -> paramVal.toString) + status.map(paramVal => formParams += "status" -> paramVal.toString) } try { @@ -364,7 +364,7 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param file file to upload (optional) * @return ApiResponse */ - def uploadFile (petId: Long, additionalMetadata: String, file: File) : Option[ApiResponse] = { + def uploadFile(petId: Long, additionalMetadata: Option[String] = None, file: Option[File] = None): Option[ApiResponse] = { // create path and map variables val path = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}",apiInvoker.escape(petId)) @@ -377,23 +377,22 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", val headerParams = new HashMap[String, String] val formParams = new HashMap[String, String] - + var postBody: AnyRef = null if(contentType.startsWith("multipart/form-data")) { val mp = new FormDataMultiPart() - mp.field("additionalMetadata", additionalMetadata.toString(), MediaType.MULTIPART_FORM_DATA_TYPE) + additionalMetadata.map(paramVal => mp.field("additionalMetadata", paramVal.toString, MediaType.MULTIPART_FORM_DATA_TYPE)) - mp.field("file", file.getName) - mp.bodyPart(new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE)) + file.map(fileVal => mp.field("file", fileVal.getName)) + file.map(paramVal => mp.bodyPart(new FileDataBodyPart("file", paramVal, MediaType.MULTIPART_FORM_DATA_TYPE))) postBody = mp } else { - formParams += "additionalMetadata" -> additionalMetadata.toString() - + additionalMetadata.map(paramVal => formParams += "additionalMetadata" -> paramVal.toString) } try { diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/StoreApi.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/StoreApi.scala index 2d184550d13..94052904927 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/StoreApi.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/StoreApi.scala @@ -51,7 +51,7 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param orderId ID of the order that needs to be deleted * @return void */ - def deleteOrder (orderId: String) = { + def deleteOrder(orderId: String) = { // create path and map variables val path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}",apiInvoker.escape(orderId)) @@ -64,8 +64,8 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", val headerParams = new HashMap[String, String] val formParams = new HashMap[String, String] - + var postBody: AnyRef = null if(contentType.startsWith("multipart/form-data")) { @@ -92,7 +92,7 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", * Returns a map of status codes to quantities * @return Map[String, Integer] */ - def getInventory () : Option[Map[String, Integer]] = { + def getInventory(): Option[Map[String, Integer]] = { // create path and map variables val path = "/store/inventory".replaceAll("\\{format\\}","json") val contentTypes = List("application/json") @@ -103,8 +103,8 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", val headerParams = new HashMap[String, String] val formParams = new HashMap[String, String] - + var postBody: AnyRef = null if(contentType.startsWith("multipart/form-data")) { @@ -133,7 +133,7 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param orderId ID of pet that needs to be fetched * @return Order */ - def getOrderById (orderId: Long) : Option[Order] = { + def getOrderById(orderId: Long): Option[Order] = { // create path and map variables val path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}",apiInvoker.escape(orderId)) @@ -146,8 +146,8 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", val headerParams = new HashMap[String, String] val formParams = new HashMap[String, String] - + var postBody: AnyRef = null if(contentType.startsWith("multipart/form-data")) { @@ -176,7 +176,7 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param body order placed for purchasing the pet * @return Order */ - def placeOrder (body: Order) : Option[Order] = { + def placeOrder(body: Order): Option[Order] = { // create path and map variables val path = "/store/order".replaceAll("\\{format\\}","json") val contentTypes = List("application/json") @@ -189,8 +189,8 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", if (body == null) throw new Exception("Missing required parameter 'body' when calling StoreApi->placeOrder") - + var postBody: AnyRef = body if(contentType.startsWith("multipart/form-data")) { diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/UserApi.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/UserApi.scala index db6ada19ebc..d996b7f4f16 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/UserApi.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/UserApi.scala @@ -51,7 +51,7 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param body Created user object * @return void */ - def createUser (body: User) = { + def createUser(body: User) = { // create path and map variables val path = "/user".replaceAll("\\{format\\}","json") val contentTypes = List("application/json") @@ -64,8 +64,8 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", if (body == null) throw new Exception("Missing required parameter 'body' when calling UserApi->createUser") - + var postBody: AnyRef = body if(contentType.startsWith("multipart/form-data")) { @@ -93,7 +93,7 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param body List of user object * @return void */ - def createUsersWithArrayInput (body: List[User]) = { + def createUsersWithArrayInput(body: List[User]) = { // create path and map variables val path = "/user/createWithArray".replaceAll("\\{format\\}","json") val contentTypes = List("application/json") @@ -106,8 +106,8 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", if (body == null) throw new Exception("Missing required parameter 'body' when calling UserApi->createUsersWithArrayInput") - + var postBody: AnyRef = body if(contentType.startsWith("multipart/form-data")) { @@ -135,7 +135,7 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param body List of user object * @return void */ - def createUsersWithListInput (body: List[User]) = { + def createUsersWithListInput(body: List[User]) = { // create path and map variables val path = "/user/createWithList".replaceAll("\\{format\\}","json") val contentTypes = List("application/json") @@ -148,8 +148,8 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", if (body == null) throw new Exception("Missing required parameter 'body' when calling UserApi->createUsersWithListInput") - + var postBody: AnyRef = body if(contentType.startsWith("multipart/form-data")) { @@ -177,7 +177,7 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param username The name that needs to be deleted * @return void */ - def deleteUser (username: String) = { + def deleteUser(username: String) = { // create path and map variables val path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}",apiInvoker.escape(username)) @@ -190,8 +190,8 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", val headerParams = new HashMap[String, String] val formParams = new HashMap[String, String] - + var postBody: AnyRef = null if(contentType.startsWith("multipart/form-data")) { @@ -219,7 +219,7 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param username The name that needs to be fetched. Use user1 for testing. * @return User */ - def getUserByName (username: String) : Option[User] = { + def getUserByName(username: String): Option[User] = { // create path and map variables val path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}",apiInvoker.escape(username)) @@ -232,8 +232,8 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", val headerParams = new HashMap[String, String] val formParams = new HashMap[String, String] - + var postBody: AnyRef = null if(contentType.startsWith("multipart/form-data")) { @@ -263,7 +263,7 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param password The password for login in clear text * @return String */ - def loginUser (username: String, password: String) : Option[String] = { + def loginUser(username: String, password: String): Option[String] = { // create path and map variables val path = "/user/login".replaceAll("\\{format\\}","json") val contentTypes = List("application/json") @@ -275,9 +275,9 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", val formParams = new HashMap[String, String] if(String.valueOf(username) != "null") queryParams += "username" -> username.toString -if(String.valueOf(password) != "null") queryParams += "password" -> password.toString - + if(String.valueOf(password) != "null") queryParams += "password" -> password.toString + var postBody: AnyRef = null if(contentType.startsWith("multipart/form-data")) { @@ -305,7 +305,7 @@ if(String.valueOf(password) != "null") queryParams += "password" -> password.toS * * @return void */ - def logoutUser () = { + def logoutUser() = { // create path and map variables val path = "/user/logout".replaceAll("\\{format\\}","json") val contentTypes = List("application/json") @@ -316,8 +316,8 @@ if(String.valueOf(password) != "null") queryParams += "password" -> password.toS val headerParams = new HashMap[String, String] val formParams = new HashMap[String, String] - + var postBody: AnyRef = null if(contentType.startsWith("multipart/form-data")) { @@ -346,7 +346,7 @@ if(String.valueOf(password) != "null") queryParams += "password" -> password.toS * @param body Updated user object * @return void */ - def updateUser (username: String, body: User) = { + def updateUser(username: String, body: User) = { // create path and map variables val path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}",apiInvoker.escape(username)) @@ -361,8 +361,8 @@ if(String.valueOf(password) != "null") queryParams += "password" -> password.toS if (body == null) throw new Exception("Missing required parameter 'body' when calling UserApi->updateUser") - + var postBody: AnyRef = body if(contentType.startsWith("multipart/form-data")) { From e7ec360ba8c100f5984ec7b0727e47e2404c78d8 Mon Sep 17 00:00:00 2001 From: Arpit Suthar Date: Thu, 1 Sep 2016 15:52:03 +0530 Subject: [PATCH 316/470] Added 'modelPropertyNaming' option for Scala (#3685) * Closed #3675 1. Added 'modelPropertyNaming' option for scala 2. Executed ./bin/scala-petstore.sh (no changes). * Removed unwanted code #3675 --- .../codegen/languages/ScalaClientCodegen.java | 43 +++++++++++++++++-- .../options/ScalaClientOptionsProvider.java | 2 + .../codegen/scala/ScalaClientOptionsTest.java | 2 + 3 files changed, 44 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java index 157d650a42f..a4f263f858a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java @@ -29,6 +29,7 @@ import org.apache.commons.lang3.StringUtils; public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig { + protected String modelPropertyNaming= "camelCase"; protected String invokerPackage = "io.swagger.client"; protected String groupId = "io.swagger"; protected String artifactId = "swagger-scala-client"; @@ -136,6 +137,44 @@ public ScalaClientCodegen() { cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.MODEL_PROPERTY_NAMING, CodegenConstants.MODEL_PROPERTY_NAMING_DESC).defaultValue("camelCase")); + } + + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey(CodegenConstants.MODEL_PROPERTY_NAMING)) { + setModelPropertyNaming((String) additionalProperties.get(CodegenConstants.MODEL_PROPERTY_NAMING)); + } + } + + public void setModelPropertyNaming(String naming) { + if ("original".equals(naming) || "camelCase".equals(naming) || + "PascalCase".equals(naming) || "snake_case".equals(naming)) { + this.modelPropertyNaming = naming; + } else { + throw new IllegalArgumentException("Invalid model property naming '" + + naming + "'. Must be 'original', 'camelCase', " + + "'PascalCase' or 'snake_case'"); + } + } + + public String getModelPropertyNaming() { + return this.modelPropertyNaming; + } + + public String getNameUsingModelPropertyNaming(String name) { + switch (CodegenConstants.MODEL_PROPERTY_NAMING_TYPE.valueOf(getModelPropertyNaming())) { + case original: return name; + case camelCase: return camelize(name, true); + case PascalCase: return camelize(name); + case snake_case: return underscore(name); + default: throw new IllegalArgumentException("Invalid model property naming '" + + name + "'. Must be 'original', 'camelCase', " + + "'PascalCase' or 'snake_case'"); + } + } @Override @@ -287,9 +326,7 @@ public String toVarName(String name) { return name; } - // camelize (lower first character) the variable name - // pet_id => petId - name = camelize(name, true); + name = getNameUsingModelPropertyNaming(name); // for reserved word or word starting with number, append _ if (isReservedWord(name) || name.matches("^\\d.*")) { diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalaClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalaClientOptionsProvider.java index 867482f145b..fade9a7cc07 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalaClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalaClientOptionsProvider.java @@ -11,6 +11,7 @@ public class ScalaClientOptionsProvider implements OptionsProvider { public static final String API_PACKAGE_VALUE = "apiPackage"; public static final String SORT_PARAMS_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final String MODEL_PROPERTY_NAMING = "modelPropertyNaming"; @Override public String getLanguage() { @@ -24,6 +25,7 @@ public Map createOptions() { .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaClientOptionsTest.java index fe0b3b3b544..4a934025dc3 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaClientOptionsTest.java @@ -32,6 +32,8 @@ protected void setExpectations() { times = 1; clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(ScalaClientOptionsProvider.SORT_PARAMS_VALUE)); times = 1; + clientCodegen.setModelPropertyNaming(ScalaClientOptionsProvider.MODEL_PROPERTY_NAMING); + times = 1; }}; } } From e52a8e34cbd1939a2f73f83d2591e22e23b8de12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Thu, 1 Sep 2016 17:39:30 +0300 Subject: [PATCH 317/470] Spelling fixes --- .../src/main/java/io/swagger/codegen/DefaultCodegen.java | 4 ++-- .../src/main/resources/php/model_generic.mustache | 2 +- .../SwaggerClient-php/lib/Model/AdditionalPropertiesClass.php | 2 +- .../petstore/php/SwaggerClient-php/lib/Model/Animal.php | 2 +- .../petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php | 2 +- .../petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php | 2 +- .../SwaggerClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php | 2 +- .../php/SwaggerClient-php/lib/Model/ArrayOfNumberOnly.php | 2 +- .../petstore/php/SwaggerClient-php/lib/Model/ArrayTest.php | 2 +- .../client/petstore/php/SwaggerClient-php/lib/Model/Cat.php | 2 +- .../petstore/php/SwaggerClient-php/lib/Model/Category.php | 2 +- .../petstore/php/SwaggerClient-php/lib/Model/Client.php | 2 +- .../client/petstore/php/SwaggerClient-php/lib/Model/Dog.php | 2 +- .../petstore/php/SwaggerClient-php/lib/Model/EnumArrays.php | 2 +- .../petstore/php/SwaggerClient-php/lib/Model/EnumTest.php | 2 +- .../petstore/php/SwaggerClient-php/lib/Model/FormatTest.php | 2 +- .../php/SwaggerClient-php/lib/Model/HasOnlyReadOnly.php | 2 +- .../petstore/php/SwaggerClient-php/lib/Model/MapTest.php | 2 +- .../lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php | 2 +- .../php/SwaggerClient-php/lib/Model/Model200Response.php | 2 +- .../petstore/php/SwaggerClient-php/lib/Model/ModelList.php | 2 +- .../petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php | 2 +- .../client/petstore/php/SwaggerClient-php/lib/Model/Name.php | 2 +- .../petstore/php/SwaggerClient-php/lib/Model/NumberOnly.php | 2 +- .../client/petstore/php/SwaggerClient-php/lib/Model/Order.php | 2 +- .../client/petstore/php/SwaggerClient-php/lib/Model/Pet.php | 2 +- .../php/SwaggerClient-php/lib/Model/ReadOnlyFirst.php | 2 +- .../php/SwaggerClient-php/lib/Model/SpecialModelName.php | 2 +- .../client/petstore/php/SwaggerClient-php/lib/Model/Tag.php | 2 +- .../client/petstore/php/SwaggerClient-php/lib/Model/User.php | 2 +- 30 files changed, 31 insertions(+), 31 deletions(-) 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 c5a186a6e0f..7ba6dff419d 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 @@ -798,12 +798,12 @@ public DefaultCodegen() { cliOptions.add(CliOption.newBoolean(CodegenConstants.ENSURE_UNIQUE_PARAMS, CodegenConstants .ENSURE_UNIQUE_PARAMS_DESC).defaultValue(Boolean.TRUE.toString())); - // initalize special character mapping + // initialize special character mapping initalizeSpecialCharacterMapping(); } /** - * Initalize special character mapping + * Initialize special character mapping */ protected void initalizeSpecialCharacterMapping() { // Initialize special characters diff --git a/modules/swagger-codegen/src/main/resources/php/model_generic.mustache b/modules/swagger-codegen/src/main/resources/php/model_generic.mustache index 460c5c67419..e66d4247430 100644 --- a/modules/swagger-codegen/src/main/resources/php/model_generic.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model_generic.mustache @@ -87,7 +87,7 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AdditionalPropertiesClass.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AdditionalPropertiesClass.php index 1f64ea68602..32f33b0fda2 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AdditionalPropertiesClass.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AdditionalPropertiesClass.php @@ -129,7 +129,7 @@ public static function getters() /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php index d25c852fa6b..3f1b303817e 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php @@ -129,7 +129,7 @@ public static function getters() /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php index e5c3849fac7..05ded47d5e5 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php @@ -125,7 +125,7 @@ public static function getters() /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php index 767a4340343..eeccb4b25d3 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php @@ -133,7 +133,7 @@ public static function getters() /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php index 6f7133db758..43c4c6291cb 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php @@ -125,7 +125,7 @@ public static function getters() /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfNumberOnly.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfNumberOnly.php index 1548460932b..63aa548fc4c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfNumberOnly.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfNumberOnly.php @@ -125,7 +125,7 @@ public static function getters() /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayTest.php index 5e8f450368a..efa14332750 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayTest.php @@ -133,7 +133,7 @@ public static function getters() /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php index 0245b27774b..46cdad4d91c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php @@ -125,7 +125,7 @@ public static function getters() /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php index a453d750b12..873589afdb4 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php @@ -129,7 +129,7 @@ public static function getters() /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Client.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Client.php index ef606fe751d..5452d61cdf1 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Client.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Client.php @@ -125,7 +125,7 @@ public static function getters() /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php index 23530dab46d..dbee0bd23cb 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php @@ -125,7 +125,7 @@ public static function getters() /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumArrays.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumArrays.php index dc24e411cb8..2fc2c3605ff 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumArrays.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumArrays.php @@ -157,7 +157,7 @@ public function getArrayEnumAllowableValues() /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php index 656da77ac0a..5079dcd362e 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php @@ -175,7 +175,7 @@ public function getEnumNumberAllowableValues() /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php index ca6187e6a21..e61c0f33ce1 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php @@ -173,7 +173,7 @@ public static function getters() /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/HasOnlyReadOnly.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/HasOnlyReadOnly.php index 8767cd25093..15262d99cb2 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/HasOnlyReadOnly.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/HasOnlyReadOnly.php @@ -129,7 +129,7 @@ public static function getters() /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/MapTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/MapTest.php index f706034736a..4d8372d7654 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/MapTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/MapTest.php @@ -143,7 +143,7 @@ public function getMapOfEnumStringAllowableValues() /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php index 16bd741e91d..97d3394bac2 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php @@ -133,7 +133,7 @@ public static function getters() /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php index 04e5f99322d..699f20048f2 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php @@ -130,7 +130,7 @@ public static function getters() /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelList.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelList.php index 94413c5ec75..9009470c98b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelList.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelList.php @@ -125,7 +125,7 @@ public static function getters() /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php index 9e0edd0e426..f36b12dae60 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php @@ -126,7 +126,7 @@ public static function getters() /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php index 780842932f1..a5c9f9696a2 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php @@ -138,7 +138,7 @@ public static function getters() /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/NumberOnly.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/NumberOnly.php index a5c1a292dd0..387b53c1898 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/NumberOnly.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/NumberOnly.php @@ -125,7 +125,7 @@ public static function getters() /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php index 9b30e8de267..9e7d3642320 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php @@ -161,7 +161,7 @@ public function getStatusAllowableValues() /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php index d352976547d..2ef11c3f961 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php @@ -161,7 +161,7 @@ public function getStatusAllowableValues() /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ReadOnlyFirst.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ReadOnlyFirst.php index f0021e2965a..ab4a4899e71 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ReadOnlyFirst.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ReadOnlyFirst.php @@ -129,7 +129,7 @@ public static function getters() /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php index a1bb04e5c72..f4443fa322c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php @@ -125,7 +125,7 @@ public static function getters() /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php index d1043125e38..2e75cf94493 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php @@ -129,7 +129,7 @@ public static function getters() /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php index 5f1a183d6e5..cb812f55334 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php @@ -153,7 +153,7 @@ public static function getters() /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { From 0363858672449a91b472d58aeb8dc296038dc99d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Thu, 1 Sep 2016 18:07:35 +0300 Subject: [PATCH 318/470] java: Javadoc fixes --- .../okhttp-gson/ApiResponse.mustache | 2 +- .../Java/libraries/okhttp-gson/JSON.mustache | 3 +- .../main/resources/Java/licenseInfo.mustache | 2 +- .../java/io/swagger/client/ApiResponse.java | 2 +- .../src/main/java/io/swagger/client/JSON.java | 2 +- .../java/io/swagger/client/ApiClient.java | 2 + .../java/io/swagger/client/StringUtil.java | 2 +- .../java/io/swagger/client/api/FakeApi.java | 21 +++-- .../java/io/swagger/client/api/PetApi.java | 2 +- .../io/swagger/client/auth/OAuthFlow.java | 2 +- .../model/AdditionalPropertiesClass.java | 2 +- .../java/io/swagger/client/model/Animal.java | 2 +- .../io/swagger/client/model/AnimalFarm.java | 2 +- .../model/ArrayOfArrayOfNumberOnly.java | 2 +- .../client/model/ArrayOfNumberOnly.java | 2 +- .../io/swagger/client/model/ArrayTest.java | 2 +- .../java/io/swagger/client/model/Cat.java | 2 +- .../io/swagger/client/model/Category.java | 2 +- .../java/io/swagger/client/model/Client.java | 2 +- .../java/io/swagger/client/model/Dog.java | 2 +- .../io/swagger/client/model/EnumArrays.java | 2 +- .../io/swagger/client/model/EnumClass.java | 2 +- .../io/swagger/client/model/EnumTest.java | 2 +- .../io/swagger/client/model/FormatTest.java | 2 +- .../swagger/client/model/HasOnlyReadOnly.java | 2 +- .../java/io/swagger/client/model/MapTest.java | 2 +- ...ropertiesAndAdditionalPropertiesClass.java | 2 +- .../client/model/Model200Response.java | 24 ++--- .../client/model/ModelApiResponse.java | 2 +- .../io/swagger/client/model/ModelReturn.java | 2 +- .../java/io/swagger/client/model/Name.java | 2 +- .../io/swagger/client/model/NumberOnly.java | 2 +- .../java/io/swagger/client/model/Order.java | 2 +- .../java/io/swagger/client/model/Pet.java | 2 +- .../swagger/client/model/ReadOnlyFirst.java | 2 +- .../client/model/SpecialModelName.java | 2 +- .../java/io/swagger/client/model/Tag.java | 2 +- .../java/io/swagger/client/model/User.java | 2 +- .../petstore/java/jersey1/docs/FakeApi.md | 45 +++++++--- .../java/jersey1/docs/Model200Response.md | 2 +- .../java/io/swagger/client/ApiClient.java | 3 +- .../java/io/swagger/client/ApiException.java | 2 +- .../java/io/swagger/client/Configuration.java | 2 +- .../src/main/java/io/swagger/client/Pair.java | 2 +- .../java/io/swagger/client/StringUtil.java | 2 +- .../java/io/swagger/client/api/FakeApi.java | 42 ++++++--- .../java/io/swagger/client/api/PetApi.java | 4 +- .../java/io/swagger/client/api/StoreApi.java | 2 +- .../java/io/swagger/client/api/UserApi.java | 2 +- .../io/swagger/client/auth/ApiKeyAuth.java | 2 +- .../swagger/client/auth/Authentication.java | 2 +- .../io/swagger/client/auth/HttpBasicAuth.java | 2 +- .../java/io/swagger/client/auth/OAuth.java | 2 +- .../io/swagger/client/auth/OAuthFlow.java | 2 +- .../model/AdditionalPropertiesClass.java | 2 +- .../java/io/swagger/client/model/Animal.java | 2 +- .../io/swagger/client/model/AnimalFarm.java | 2 +- .../model/ArrayOfArrayOfNumberOnly.java | 2 +- .../client/model/ArrayOfNumberOnly.java | 2 +- .../io/swagger/client/model/ArrayTest.java | 2 +- .../java/io/swagger/client/model/Cat.java | 2 +- .../io/swagger/client/model/Category.java | 2 +- .../java/io/swagger/client/model/Client.java | 2 +- .../java/io/swagger/client/model/Dog.java | 2 +- .../io/swagger/client/model/EnumArrays.java | 2 +- .../io/swagger/client/model/EnumClass.java | 2 +- .../io/swagger/client/model/EnumTest.java | 2 +- .../io/swagger/client/model/FormatTest.java | 2 +- .../swagger/client/model/HasOnlyReadOnly.java | 2 +- .../java/io/swagger/client/model/MapTest.java | 2 +- ...ropertiesAndAdditionalPropertiesClass.java | 2 +- .../client/model/Model200Response.java | 24 ++--- .../client/model/ModelApiResponse.java | 2 +- .../io/swagger/client/model/ModelReturn.java | 2 +- .../java/io/swagger/client/model/Name.java | 2 +- .../io/swagger/client/model/NumberOnly.java | 2 +- .../java/io/swagger/client/model/Order.java | 2 +- .../java/io/swagger/client/model/Pet.java | 2 +- .../swagger/client/model/ReadOnlyFirst.java | 2 +- .../client/model/SpecialModelName.java | 2 +- .../java/io/swagger/client/model/Tag.java | 2 +- .../java/io/swagger/client/model/User.java | 2 +- .../java/jersey2-java8/docs/FakeApi.md | 45 +++++++--- .../jersey2-java8/docs/Model200Response.md | 2 +- .../java/io/swagger/client/ApiClient.java | 1 + .../java/io/swagger/client/ApiException.java | 2 +- .../java/io/swagger/client/Configuration.java | 2 +- .../src/main/java/io/swagger/client/Pair.java | 2 +- .../java/io/swagger/client/StringUtil.java | 2 +- .../java/io/swagger/client/api/FakeApi.java | 40 ++++++--- .../java/io/swagger/client/api/PetApi.java | 2 +- .../io/swagger/client/auth/ApiKeyAuth.java | 2 +- .../swagger/client/auth/Authentication.java | 2 +- .../io/swagger/client/auth/HttpBasicAuth.java | 2 +- .../java/io/swagger/client/auth/OAuth.java | 2 +- .../io/swagger/client/auth/OAuthFlow.java | 2 +- .../model/AdditionalPropertiesClass.java | 2 +- .../java/io/swagger/client/model/Animal.java | 2 +- .../io/swagger/client/model/AnimalFarm.java | 2 +- .../model/ArrayOfArrayOfNumberOnly.java | 2 +- .../client/model/ArrayOfNumberOnly.java | 2 +- .../io/swagger/client/model/ArrayTest.java | 2 +- .../java/io/swagger/client/model/Cat.java | 2 +- .../io/swagger/client/model/Category.java | 2 +- .../java/io/swagger/client/model/Client.java | 2 +- .../java/io/swagger/client/model/Dog.java | 2 +- .../io/swagger/client/model/EnumArrays.java | 2 +- .../io/swagger/client/model/EnumClass.java | 2 +- .../io/swagger/client/model/EnumTest.java | 2 +- .../io/swagger/client/model/FormatTest.java | 2 +- .../swagger/client/model/HasOnlyReadOnly.java | 2 +- .../java/io/swagger/client/model/MapTest.java | 2 +- ...ropertiesAndAdditionalPropertiesClass.java | 2 +- .../client/model/Model200Response.java | 24 ++--- .../client/model/ModelApiResponse.java | 2 +- .../io/swagger/client/model/ModelReturn.java | 2 +- .../java/io/swagger/client/model/Name.java | 2 +- .../io/swagger/client/model/NumberOnly.java | 2 +- .../java/io/swagger/client/model/Order.java | 2 +- .../java/io/swagger/client/model/Pet.java | 2 +- .../swagger/client/model/ReadOnlyFirst.java | 2 +- .../client/model/SpecialModelName.java | 2 +- .../java/io/swagger/client/model/Tag.java | 2 +- .../java/io/swagger/client/model/User.java | 2 +- .../petstore/java/jersey2/docs/FakeApi.md | 45 +++++++--- .../java/jersey2/docs/Model200Response.md | 2 +- .../java/io/swagger/client/ApiClient.java | 1 + .../java/io/swagger/client/ApiException.java | 2 +- .../java/io/swagger/client/Configuration.java | 2 +- .../src/main/java/io/swagger/client/Pair.java | 2 +- .../java/io/swagger/client/StringUtil.java | 2 +- .../java/io/swagger/client/api/FakeApi.java | 40 ++++++--- .../java/io/swagger/client/api/PetApi.java | 2 +- .../io/swagger/client/auth/ApiKeyAuth.java | 2 +- .../swagger/client/auth/Authentication.java | 2 +- .../io/swagger/client/auth/HttpBasicAuth.java | 2 +- .../java/io/swagger/client/auth/OAuth.java | 2 +- .../io/swagger/client/auth/OAuthFlow.java | 2 +- .../model/AdditionalPropertiesClass.java | 2 +- .../java/io/swagger/client/model/Animal.java | 2 +- .../io/swagger/client/model/AnimalFarm.java | 2 +- .../model/ArrayOfArrayOfNumberOnly.java | 2 +- .../client/model/ArrayOfNumberOnly.java | 2 +- .../io/swagger/client/model/ArrayTest.java | 2 +- .../java/io/swagger/client/model/Cat.java | 2 +- .../io/swagger/client/model/Category.java | 2 +- .../java/io/swagger/client/model/Client.java | 2 +- .../java/io/swagger/client/model/Dog.java | 2 +- .../io/swagger/client/model/EnumArrays.java | 2 +- .../io/swagger/client/model/EnumClass.java | 2 +- .../io/swagger/client/model/EnumTest.java | 2 +- .../io/swagger/client/model/FormatTest.java | 2 +- .../swagger/client/model/HasOnlyReadOnly.java | 2 +- .../java/io/swagger/client/model/MapTest.java | 2 +- ...ropertiesAndAdditionalPropertiesClass.java | 2 +- .../client/model/Model200Response.java | 24 ++--- .../client/model/ModelApiResponse.java | 2 +- .../io/swagger/client/model/ModelReturn.java | 2 +- .../java/io/swagger/client/model/Name.java | 2 +- .../io/swagger/client/model/NumberOnly.java | 2 +- .../java/io/swagger/client/model/Order.java | 2 +- .../java/io/swagger/client/model/Pet.java | 2 +- .../swagger/client/model/ReadOnlyFirst.java | 2 +- .../client/model/SpecialModelName.java | 2 +- .../java/io/swagger/client/model/Tag.java | 2 +- .../java/io/swagger/client/model/User.java | 2 +- .../petstore/java/okhttp-gson/docs/FakeApi.md | 45 +++++++--- .../java/okhttp-gson/docs/Model200Response.md | 2 +- .../java/io/swagger/client/ApiCallback.java | 2 +- .../java/io/swagger/client/ApiClient.java | 3 +- .../java/io/swagger/client/ApiException.java | 2 +- .../java/io/swagger/client/ApiResponse.java | 4 +- .../java/io/swagger/client/Configuration.java | 2 +- .../src/main/java/io/swagger/client/JSON.java | 5 +- .../src/main/java/io/swagger/client/Pair.java | 2 +- .../swagger/client/ProgressRequestBody.java | 2 +- .../swagger/client/ProgressResponseBody.java | 2 +- .../java/io/swagger/client/StringUtil.java | 2 +- .../java/io/swagger/client/api/FakeApi.java | 88 +++++++++++++------ .../java/io/swagger/client/api/PetApi.java | 4 +- .../java/io/swagger/client/api/StoreApi.java | 2 +- .../java/io/swagger/client/api/UserApi.java | 2 +- .../io/swagger/client/auth/ApiKeyAuth.java | 2 +- .../swagger/client/auth/Authentication.java | 2 +- .../io/swagger/client/auth/HttpBasicAuth.java | 2 +- .../java/io/swagger/client/auth/OAuth.java | 2 +- .../io/swagger/client/auth/OAuthFlow.java | 2 +- .../model/AdditionalPropertiesClass.java | 2 +- .../java/io/swagger/client/model/Animal.java | 2 +- .../io/swagger/client/model/AnimalFarm.java | 2 +- .../model/ArrayOfArrayOfNumberOnly.java | 2 +- .../client/model/ArrayOfNumberOnly.java | 2 +- .../io/swagger/client/model/ArrayTest.java | 2 +- .../java/io/swagger/client/model/Cat.java | 2 +- .../io/swagger/client/model/Category.java | 2 +- .../java/io/swagger/client/model/Client.java | 2 +- .../java/io/swagger/client/model/Dog.java | 2 +- .../io/swagger/client/model/EnumArrays.java | 2 +- .../io/swagger/client/model/EnumClass.java | 2 +- .../io/swagger/client/model/EnumTest.java | 2 +- .../io/swagger/client/model/FormatTest.java | 2 +- .../swagger/client/model/HasOnlyReadOnly.java | 2 +- .../java/io/swagger/client/model/MapTest.java | 2 +- ...ropertiesAndAdditionalPropertiesClass.java | 2 +- .../client/model/Model200Response.java | 24 ++--- .../client/model/ModelApiResponse.java | 2 +- .../io/swagger/client/model/ModelReturn.java | 2 +- .../java/io/swagger/client/model/Name.java | 2 +- .../io/swagger/client/model/NumberOnly.java | 2 +- .../java/io/swagger/client/model/Order.java | 2 +- .../java/io/swagger/client/model/Pet.java | 2 +- .../swagger/client/model/ReadOnlyFirst.java | 2 +- .../client/model/SpecialModelName.java | 2 +- .../java/io/swagger/client/model/Tag.java | 2 +- .../java/io/swagger/client/model/User.java | 2 +- .../java/io/swagger/client/ApiClient.java | 2 + .../java/io/swagger/client/StringUtil.java | 2 +- .../java/io/swagger/client/api/FakeApi.java | 34 ++++--- .../java/io/swagger/client/api/PetApi.java | 2 +- .../io/swagger/client/auth/OAuthFlow.java | 2 +- .../model/AdditionalPropertiesClass.java | 2 +- .../java/io/swagger/client/model/Animal.java | 2 +- .../io/swagger/client/model/AnimalFarm.java | 2 +- .../model/ArrayOfArrayOfNumberOnly.java | 2 +- .../client/model/ArrayOfNumberOnly.java | 2 +- .../io/swagger/client/model/ArrayTest.java | 2 +- .../java/io/swagger/client/model/Cat.java | 2 +- .../io/swagger/client/model/Category.java | 2 +- .../java/io/swagger/client/model/Client.java | 2 +- .../java/io/swagger/client/model/Dog.java | 2 +- .../io/swagger/client/model/EnumArrays.java | 2 +- .../io/swagger/client/model/EnumClass.java | 2 +- .../io/swagger/client/model/EnumTest.java | 2 +- .../io/swagger/client/model/FormatTest.java | 2 +- .../swagger/client/model/HasOnlyReadOnly.java | 2 +- .../java/io/swagger/client/model/MapTest.java | 2 +- ...ropertiesAndAdditionalPropertiesClass.java | 2 +- .../client/model/Model200Response.java | 24 ++--- .../client/model/ModelApiResponse.java | 2 +- .../io/swagger/client/model/ModelReturn.java | 2 +- .../java/io/swagger/client/model/Name.java | 2 +- .../io/swagger/client/model/NumberOnly.java | 2 +- .../java/io/swagger/client/model/Order.java | 2 +- .../java/io/swagger/client/model/Pet.java | 2 +- .../swagger/client/model/ReadOnlyFirst.java | 2 +- .../client/model/SpecialModelName.java | 2 +- .../java/io/swagger/client/model/Tag.java | 2 +- .../java/io/swagger/client/model/User.java | 2 +- .../petstore/java/retrofit2/docs/FakeApi.md | 45 +++++++--- .../java/retrofit2/docs/Model200Response.md | 2 +- .../java/io/swagger/client/ApiClient.java | 2 + .../java/io/swagger/client/StringUtil.java | 2 +- .../java/io/swagger/client/api/FakeApi.java | 18 ++-- .../java/io/swagger/client/api/PetApi.java | 2 +- .../io/swagger/client/auth/OAuthFlow.java | 2 +- .../model/AdditionalPropertiesClass.java | 2 +- .../java/io/swagger/client/model/Animal.java | 2 +- .../io/swagger/client/model/AnimalFarm.java | 2 +- .../model/ArrayOfArrayOfNumberOnly.java | 2 +- .../client/model/ArrayOfNumberOnly.java | 2 +- .../io/swagger/client/model/ArrayTest.java | 2 +- .../java/io/swagger/client/model/Cat.java | 2 +- .../io/swagger/client/model/Category.java | 2 +- .../java/io/swagger/client/model/Client.java | 2 +- .../java/io/swagger/client/model/Dog.java | 2 +- .../io/swagger/client/model/EnumArrays.java | 2 +- .../io/swagger/client/model/EnumClass.java | 2 +- .../io/swagger/client/model/EnumTest.java | 2 +- .../io/swagger/client/model/FormatTest.java | 2 +- .../swagger/client/model/HasOnlyReadOnly.java | 2 +- .../java/io/swagger/client/model/MapTest.java | 2 +- ...ropertiesAndAdditionalPropertiesClass.java | 2 +- .../client/model/Model200Response.java | 24 ++--- .../client/model/ModelApiResponse.java | 2 +- .../io/swagger/client/model/ModelReturn.java | 2 +- .../java/io/swagger/client/model/Name.java | 2 +- .../io/swagger/client/model/NumberOnly.java | 2 +- .../java/io/swagger/client/model/Order.java | 2 +- .../java/io/swagger/client/model/Pet.java | 2 +- .../swagger/client/model/ReadOnlyFirst.java | 2 +- .../client/model/SpecialModelName.java | 2 +- .../java/io/swagger/client/model/Tag.java | 2 +- .../java/io/swagger/client/model/User.java | 2 +- .../petstore/java/retrofit2rx/docs/FakeApi.md | 45 +++++++--- .../java/retrofit2rx/docs/Model200Response.md | 2 +- .../java/io/swagger/client/ApiClient.java | 2 + .../java/io/swagger/client/StringUtil.java | 2 +- .../java/io/swagger/client/api/FakeApi.java | 18 ++-- .../java/io/swagger/client/api/PetApi.java | 2 +- .../io/swagger/client/auth/OAuthFlow.java | 2 +- .../model/AdditionalPropertiesClass.java | 2 +- .../java/io/swagger/client/model/Animal.java | 2 +- .../io/swagger/client/model/AnimalFarm.java | 2 +- .../model/ArrayOfArrayOfNumberOnly.java | 2 +- .../client/model/ArrayOfNumberOnly.java | 2 +- .../io/swagger/client/model/ArrayTest.java | 2 +- .../java/io/swagger/client/model/Cat.java | 2 +- .../io/swagger/client/model/Category.java | 2 +- .../java/io/swagger/client/model/Client.java | 2 +- .../java/io/swagger/client/model/Dog.java | 2 +- .../io/swagger/client/model/EnumArrays.java | 2 +- .../io/swagger/client/model/EnumClass.java | 2 +- .../io/swagger/client/model/EnumTest.java | 2 +- .../io/swagger/client/model/FormatTest.java | 2 +- .../swagger/client/model/HasOnlyReadOnly.java | 2 +- .../java/io/swagger/client/model/MapTest.java | 2 +- ...ropertiesAndAdditionalPropertiesClass.java | 2 +- .../client/model/Model200Response.java | 24 ++--- .../client/model/ModelApiResponse.java | 2 +- .../io/swagger/client/model/ModelReturn.java | 2 +- .../java/io/swagger/client/model/Name.java | 2 +- .../io/swagger/client/model/NumberOnly.java | 2 +- .../java/io/swagger/client/model/Order.java | 2 +- .../java/io/swagger/client/model/Pet.java | 2 +- .../swagger/client/model/ReadOnlyFirst.java | 2 +- .../client/model/SpecialModelName.java | 2 +- .../java/io/swagger/client/model/Tag.java | 2 +- .../java/io/swagger/client/model/User.java | 2 +- 318 files changed, 806 insertions(+), 559 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiResponse.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiResponse.mustache index 82c86b3e215..3909393697c 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiResponse.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiResponse.mustache @@ -8,7 +8,7 @@ import java.util.Map; /** * API response returned by API call. * - * @param T The type of data that is deserialized from response body + * @param The type of data that is deserialized from response body */ public class ApiResponse { final private int statusCode; diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache index 3c199a941bd..06f26da304b 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache @@ -151,10 +151,9 @@ class DateAdapter implements JsonSerializer, JsonDeserializer { * * @param json Json element * @param date Type - * @param typeOfSrc Type * @param context Json Serialization Context * @return Date - * @throw JsonParseException if fail to parse + * @throws JsonParseException if fail to parse */ @Override public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException { diff --git a/modules/swagger-codegen/src/main/resources/Java/licenseInfo.mustache b/modules/swagger-codegen/src/main/resources/Java/licenseInfo.mustache index 861d97234cf..26b9876c7e1 100644 --- a/modules/swagger-codegen/src/main/resources/Java/licenseInfo.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/licenseInfo.mustache @@ -1,4 +1,4 @@ -/** +/* * {{{appName}}} * {{{appDescription}}} * diff --git a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/ApiResponse.java b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/ApiResponse.java index 2bf75061339..e8e0ff2288a 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/ApiResponse.java +++ b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/ApiResponse.java @@ -31,7 +31,7 @@ /** * API response returned by API call. * - * @param T The type of data that is deserialized from response body + * @param The type of data that is deserialized from response body */ public class ApiResponse { final private int statusCode; diff --git a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java index ba757cd0d3d..c308440a0e4 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java @@ -164,7 +164,7 @@ public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext * @param typeOfSrc Type * @param context Json Serialization Context * @return Date - * @throw JsonParseException if fail to parse + * @throws JsonParseException if fail to parse */ @Override public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java index e21bded5212..95d8ca9db48 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java @@ -43,6 +43,8 @@ public ApiClient(String[] authNames) { RequestInterceptor auth; if (authName == "api_key") { auth = new ApiKeyAuth("header", "api_key"); + } else if (authName == "http_basic_test") { + auth = new HttpBasicAuth(); } else if (authName == "petstore_auth") { auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); } else { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java index fdcef6b1010..31140c76df4 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java index 57fa0cdd95a..b843c876ebb 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java @@ -4,8 +4,8 @@ import io.swagger.client.model.Client; import org.joda.time.LocalDate; -import org.joda.time.DateTime; import java.math.BigDecimal; +import org.joda.time.DateTime; import java.util.ArrayList; import java.util.HashMap; @@ -35,12 +35,13 @@ public interface FakeApi extends ApiClient.Api { * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * @param number None (required) * @param _double None (required) - * @param string None (required) + * @param patternWithoutDelimiter None (required) * @param _byte None (required) * @param integer None (optional) * @param int32 None (optional) * @param int64 None (optional) * @param _float None (optional) + * @param string None (optional) * @param binary None (optional) * @param date None (optional) * @param dateTime None (optional) @@ -52,20 +53,28 @@ public interface FakeApi extends ApiClient.Api { "Content-type: application/xml; charset=utf-8", "Accept: application/xml; charset=utf-8,application/json; charset=utf-8", }) - void testEndpointParameters(@Param("number") BigDecimal number, @Param("_double") Double _double, @Param("string") String string, @Param("_byte") byte[] _byte, @Param("integer") Integer integer, @Param("int32") Integer int32, @Param("int64") Long int64, @Param("_float") Float _float, @Param("binary") byte[] binary, @Param("date") LocalDate date, @Param("dateTime") DateTime dateTime, @Param("password") String password); + void testEndpointParameters(@Param("number") BigDecimal number, @Param("_double") Double _double, @Param("patternWithoutDelimiter") String patternWithoutDelimiter, @Param("_byte") byte[] _byte, @Param("integer") Integer integer, @Param("int32") Integer int32, @Param("int64") Long int64, @Param("_float") Float _float, @Param("string") String string, @Param("binary") byte[] binary, @Param("date") LocalDate date, @Param("dateTime") DateTime dateTime, @Param("password") String password); /** - * To test enum query parameters + * To test enum parameters * + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) * @param enumQueryInteger Query parameter enum test (double) (optional) * @param enumQueryDouble Query parameter enum test (double) (optional) * @return void */ - @RequestLine("GET /fake?enum_query_integer={enumQueryInteger}") + @RequestLine("GET /fake?enum_query_string_array={enumQueryStringArray}&enum_query_string={enumQueryString}&enum_query_integer={enumQueryInteger}") @Headers({ "Content-type: application/json", "Accept: application/json", + "enum_header_string_array: {enumHeaderStringArray}", + + "enum_header_string: {enumHeaderString}" }) - void testEnumQueryParameters(@Param("enumQueryString") String enumQueryString, @Param("enumQueryInteger") BigDecimal enumQueryInteger, @Param("enumQueryDouble") Double enumQueryDouble); + void testEnumParameters(@Param("enumFormStringArray") List enumFormStringArray, @Param("enumFormString") String enumFormString, @Param("enumHeaderStringArray") List enumHeaderStringArray, @Param("enumHeaderString") String enumHeaderString, @Param("enumQueryStringArray") List enumQueryStringArray, @Param("enumQueryString") String enumQueryString, @Param("enumQueryInteger") BigDecimal enumQueryInteger, @Param("enumQueryDouble") Double enumQueryDouble); } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java index 555203d8811..b6fbdf208dc 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java @@ -3,8 +3,8 @@ import io.swagger.client.ApiClient; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.ModelApiResponse; +import java.io.File; import java.util.ArrayList; import java.util.HashMap; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuthFlow.java index 50d5260cfd9..18c25738e0f 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 699b351594c..2da13804a0d 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java index 45f312394b9..346da224ad1 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java index b54adb09d7b..563476ccb3d 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 80d588dd41c..a99f2009385 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index eb02c1adee0..1aaf27b9921 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayTest.java index 1234e946d12..124d8bfa3a1 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java index a78d6e92515..41dc312a10f 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java index 45ceb1a1f17..ba4ce89c297 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Client.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Client.java index 46831a0baf6..43ade4b6fcb 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Client.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Client.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java index 83885a79439..788aee5c226 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumArrays.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumArrays.java index d99bf0a0a97..45295c524f6 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumArrays.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumArrays.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumClass.java index a76173ac1a1..f9887c69340 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumClass.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java index c06b2f182cb..a7268316c40 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java index e1822b29ea1..2b5b4204281 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java index e1fa6b49b0a..d874a545244 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MapTest.java index 7107101445a..f8cf1ad5d1a 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MapTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index a6653e1b41e..20958fd50d8 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java index d617f1d9069..8f48dd8020e 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -42,7 +42,7 @@ public class Model200Response { private Integer name = null; @JsonProperty("class") - private String PropertyClass = null; + private String propertyClass = null; public Model200Response name(Integer name) { this.name = name; @@ -62,22 +62,22 @@ public void setName(Integer name) { this.name = name; } - public Model200Response PropertyClass(String PropertyClass) { - this.PropertyClass = PropertyClass; + public Model200Response propertyClass(String propertyClass) { + this.propertyClass = propertyClass; return this; } /** - * Get PropertyClass - * @return PropertyClass + * Get propertyClass + * @return propertyClass **/ @ApiModelProperty(example = "null", value = "") public String getPropertyClass() { - return PropertyClass; + return propertyClass; } - public void setPropertyClass(String PropertyClass) { - this.PropertyClass = PropertyClass; + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; } @@ -91,12 +91,12 @@ public boolean equals(java.lang.Object o) { } Model200Response _200Response = (Model200Response) o; return Objects.equals(this.name, _200Response.name) && - Objects.equals(this.PropertyClass, _200Response.PropertyClass); + Objects.equals(this.propertyClass, _200Response.propertyClass); } @Override public int hashCode() { - return Objects.hash(name, PropertyClass); + return Objects.hash(name, propertyClass); } @Override @@ -105,7 +105,7 @@ public String toString() { sb.append("class Model200Response {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" PropertyClass: ").append(toIndentedString(PropertyClass)).append("\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java index 65b2ad8ddc6..70ee2a834c0 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java index 15193d8d3ba..28294a15090 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java index d3a4044150e..4b70e8df1a6 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/NumberOnly.java index 147e5e00ca3..ad74058d2e5 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/NumberOnly.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/NumberOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java index 509f85fa31e..1616b030b9d 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java index bb383f45a85..a89e0ea3e05 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index aa4c0b5daa0..63e11bf14fd 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java index 4f0d8cc6083..f8c5c06ca40 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java index 7f28005570a..27be94678da 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java index 09dd7156087..84e3b147049 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/docs/FakeApi.md b/samples/client/petstore/java/jersey1/docs/FakeApi.md index c145425060f..9012aff618e 100644 --- a/samples/client/petstore/java/jersey1/docs/FakeApi.md +++ b/samples/client/petstore/java/jersey1/docs/FakeApi.md @@ -6,7 +6,7 @@ Method | HTTP request | Description ------------- | ------------- | ------------- [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -[**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters +[**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters @@ -54,7 +54,7 @@ No authorization required # **testEndpointParameters** -> testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) +> testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -63,25 +63,35 @@ Fake endpoint for testing various parameters 假端點 偽のエンドポイン ### Example ```java // Import classes: +//import io.swagger.client.ApiClient; //import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; //import io.swagger.client.api.FakeApi; +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure HTTP basic authorization: http_basic_test +HttpBasicAuth http_basic_test = (HttpBasicAuth) defaultClient.getAuthentication("http_basic_test"); +http_basic_test.setUsername("YOUR USERNAME"); +http_basic_test.setPassword("YOUR PASSWORD"); FakeApi apiInstance = new FakeApi(); BigDecimal number = new BigDecimal(); // BigDecimal | None Double _double = 3.4D; // Double | None -String string = "string_example"; // String | None +String patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None byte[] _byte = B; // byte[] | None Integer integer = 56; // Integer | None Integer int32 = 56; // Integer | None Long int64 = 789L; // Long | None Float _float = 3.4F; // Float | None +String string = "string_example"; // String | None byte[] binary = B; // byte[] | None LocalDate date = new LocalDate(); // LocalDate | None DateTime dateTime = new DateTime(); // DateTime | None String password = "password_example"; // String | None try { - apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + apiInstance.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password); } catch (ApiException e) { System.err.println("Exception when calling FakeApi#testEndpointParameters"); e.printStackTrace(); @@ -94,12 +104,13 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **number** | **BigDecimal**| None | **_double** | **Double**| None | - **string** | **String**| None | + **patternWithoutDelimiter** | **String**| None | **_byte** | **byte[]**| None | **integer** | **Integer**| None | [optional] **int32** | **Integer**| None | [optional] **int64** | **Long**| None | [optional] **_float** | **Float**| None | [optional] + **string** | **String**| None | [optional] **binary** | **byte[]**| None | [optional] **date** | **LocalDate**| None | [optional] **dateTime** | **DateTime**| None | [optional] @@ -111,18 +122,18 @@ null (empty response body) ### Authorization -No authorization required +[http_basic_test](../README.md#http_basic_test) ### HTTP request headers - **Content-Type**: application/xml; charset=utf-8, application/json; charset=utf-8 - **Accept**: application/xml; charset=utf-8, application/json; charset=utf-8 - -# **testEnumQueryParameters** -> testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble) + +# **testEnumParameters** +> testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble) -To test enum query parameters +To test enum parameters ### Example ```java @@ -132,13 +143,18 @@ To test enum query parameters FakeApi apiInstance = new FakeApi(); +List enumFormStringArray = Arrays.asList("enumFormStringArray_example"); // List | Form parameter enum test (string array) +String enumFormString = "-efg"; // String | Form parameter enum test (string) +List enumHeaderStringArray = Arrays.asList("enumHeaderStringArray_example"); // List | Header parameter enum test (string array) +String enumHeaderString = "-efg"; // String | Header parameter enum test (string) +List enumQueryStringArray = Arrays.asList("enumQueryStringArray_example"); // List | Query parameter enum test (string array) String enumQueryString = "-efg"; // String | Query parameter enum test (string) BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | Query parameter enum test (double) Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) try { - apiInstance.testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); + apiInstance.testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testEnumQueryParameters"); + System.err.println("Exception when calling FakeApi#testEnumParameters"); e.printStackTrace(); } ``` @@ -147,6 +163,11 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- + **enumFormStringArray** | [**List<String>**](String.md)| Form parameter enum test (string array) | [optional] [enum: >, $] + **enumFormString** | **String**| Form parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + **enumHeaderStringArray** | [**List<String>**](String.md)| Header parameter enum test (string array) | [optional] [enum: >, $] + **enumHeaderString** | **String**| Header parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + **enumQueryStringArray** | [**List<String>**](String.md)| Query parameter enum test (string array) | [optional] [enum: >, $] **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] **enumQueryInteger** | **BigDecimal**| Query parameter enum test (double) | [optional] **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] diff --git a/samples/client/petstore/java/jersey1/docs/Model200Response.md b/samples/client/petstore/java/jersey1/docs/Model200Response.md index b47618b28cc..5b3a9a0e46d 100644 --- a/samples/client/petstore/java/jersey1/docs/Model200Response.md +++ b/samples/client/petstore/java/jersey1/docs/Model200Response.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **Integer** | | [optional] -**PropertyClass** | **String** | | [optional] +**propertyClass** | **String** | | [optional] diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java index c3d9ef3457a..278a088c48c 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -100,6 +100,7 @@ public ApiClient() { // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap(); authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("http_basic_test", new HttpBasicAuth()); authentications.put("petstore_auth", new OAuth()); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiException.java index 3bed001f002..02a967d8373 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiException.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/Configuration.java index 5191b9b73c6..57e53b2d598 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/Configuration.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/Configuration.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/Pair.java index 15b247eea93..9ad2d246519 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/Pair.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/StringUtil.java index fdcef6b1010..31140c76df4 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/StringUtil.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java index f949514a7ff..bbf7b711513 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -34,8 +34,8 @@ import io.swagger.client.model.Client; import org.joda.time.LocalDate; -import org.joda.time.DateTime; import java.math.BigDecimal; +import org.joda.time.DateTime; import java.util.ArrayList; @@ -109,19 +109,20 @@ public Client testClientModel(Client body) throws ApiException { * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * @param number None (required) * @param _double None (required) - * @param string None (required) + * @param patternWithoutDelimiter None (required) * @param _byte None (required) * @param integer None (optional) * @param int32 None (optional) * @param int64 None (optional) * @param _float None (optional) + * @param string None (optional) * @param binary None (optional) * @param date None (optional) * @param dateTime None (optional) * @param password None (optional) * @throws ApiException if fails to make API call */ - public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { + public void testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { Object localVarPostBody = null; // verify the required parameter 'number' is set @@ -134,9 +135,9 @@ public void testEndpointParameters(BigDecimal number, Double _double, String str throw new ApiException(400, "Missing the required parameter '_double' when calling testEndpointParameters"); } - // verify the required parameter 'string' is set - if (string == null) { - throw new ApiException(400, "Missing the required parameter 'string' when calling testEndpointParameters"); + // verify the required parameter 'patternWithoutDelimiter' is set + if (patternWithoutDelimiter == null) { + throw new ApiException(400, "Missing the required parameter 'patternWithoutDelimiter' when calling testEndpointParameters"); } // verify the required parameter '_byte' is set @@ -168,6 +169,8 @@ public void testEndpointParameters(BigDecimal number, Double _double, String str localVarFormParams.put("double", _double); if (string != null) localVarFormParams.put("string", string); +if (patternWithoutDelimiter != null) + localVarFormParams.put("pattern_without_delimiter", patternWithoutDelimiter); if (_byte != null) localVarFormParams.put("byte", _byte); if (binary != null) @@ -189,20 +192,25 @@ public void testEndpointParameters(BigDecimal number, Double _double, String str }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - String[] localVarAuthNames = new String[] { }; + String[] localVarAuthNames = new String[] { "http_basic_test" }; apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); } /** - * To test enum query parameters + * To test enum parameters * + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) * @param enumQueryInteger Query parameter enum test (double) (optional) * @param enumQueryDouble Query parameter enum test (double) (optional) * @throws ApiException if fails to make API call */ - public void testEnumQueryParameters(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { + public void testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { Object localVarPostBody = null; // create path and map variables @@ -213,11 +221,19 @@ public void testEnumQueryParameters(String enumQueryString, BigDecimal enumQuery Map localVarHeaderParams = new HashMap(); Map localVarFormParams = new HashMap(); + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "enum_query_string_array", enumQueryStringArray)); + localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_string", enumQueryString)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_integer", enumQueryInteger)); - - if (enumQueryString != null) - localVarFormParams.put("enum_query_string", enumQueryString); + if (enumHeaderStringArray != null) + localVarHeaderParams.put("enum_header_string_array", apiClient.parameterToString(enumHeaderStringArray)); +if (enumHeaderString != null) + localVarHeaderParams.put("enum_header_string", apiClient.parameterToString(enumHeaderString)); + + if (enumFormStringArray != null) + localVarFormParams.put("enum_form_string_array", enumFormStringArray); +if (enumFormString != null) + localVarFormParams.put("enum_form_string", enumFormString); if (enumQueryDouble != null) localVarFormParams.put("enum_query_double", enumQueryDouble); diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java index c126283d2aa..90c256ee9ce 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -33,8 +33,8 @@ import io.swagger.client.Pair; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.ModelApiResponse; +import java.io.File; import java.util.ArrayList; diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/StoreApi.java index b30edd4f22f..99b240aa071 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/StoreApi.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/UserApi.java index 9d6a1bb12fd..9325af8abda 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/UserApi.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index ad7abe402f8..0e0fdb63fb3 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/Authentication.java index 221a7d9dd1f..0ff06e3b86f 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/Authentication.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 592648b2bba..420178c112d 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/OAuth.java index 14521f6ed7e..c1b64913ab8 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/OAuth.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/OAuthFlow.java index 50d5260cfd9..18c25738e0f 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 699b351594c..2da13804a0d 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Animal.java index 45f312394b9..346da224ad1 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Animal.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AnimalFarm.java index b54adb09d7b..563476ccb3d 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 80d588dd41c..a99f2009385 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index eb02c1adee0..1aaf27b9921 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayTest.java index 1234e946d12..124d8bfa3a1 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Cat.java index a78d6e92515..41dc312a10f 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Cat.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Category.java index 45ceb1a1f17..ba4ce89c297 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Category.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Client.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Client.java index 46831a0baf6..43ade4b6fcb 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Client.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Client.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Dog.java index 83885a79439..788aee5c226 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Dog.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumArrays.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumArrays.java index d99bf0a0a97..45295c524f6 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumArrays.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumArrays.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumClass.java index a76173ac1a1..f9887c69340 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumClass.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumTest.java index c06b2f182cb..a7268316c40 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/FormatTest.java index e1822b29ea1..2b5b4204281 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/FormatTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java index e1fa6b49b0a..d874a545244 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MapTest.java index 7107101445a..f8cf1ad5d1a 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MapTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index a6653e1b41e..20958fd50d8 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Model200Response.java index d617f1d9069..8f48dd8020e 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Model200Response.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -42,7 +42,7 @@ public class Model200Response { private Integer name = null; @JsonProperty("class") - private String PropertyClass = null; + private String propertyClass = null; public Model200Response name(Integer name) { this.name = name; @@ -62,22 +62,22 @@ public void setName(Integer name) { this.name = name; } - public Model200Response PropertyClass(String PropertyClass) { - this.PropertyClass = PropertyClass; + public Model200Response propertyClass(String propertyClass) { + this.propertyClass = propertyClass; return this; } /** - * Get PropertyClass - * @return PropertyClass + * Get propertyClass + * @return propertyClass **/ @ApiModelProperty(example = "null", value = "") public String getPropertyClass() { - return PropertyClass; + return propertyClass; } - public void setPropertyClass(String PropertyClass) { - this.PropertyClass = PropertyClass; + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; } @@ -91,12 +91,12 @@ public boolean equals(java.lang.Object o) { } Model200Response _200Response = (Model200Response) o; return Objects.equals(this.name, _200Response.name) && - Objects.equals(this.PropertyClass, _200Response.PropertyClass); + Objects.equals(this.propertyClass, _200Response.propertyClass); } @Override public int hashCode() { - return Objects.hash(name, PropertyClass); + return Objects.hash(name, propertyClass); } @Override @@ -105,7 +105,7 @@ public String toString() { sb.append("class Model200Response {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" PropertyClass: ").append(toIndentedString(PropertyClass)).append("\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelApiResponse.java index 65b2ad8ddc6..70ee2a834c0 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelReturn.java index 15193d8d3ba..28294a15090 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelReturn.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Name.java index d3a4044150e..4b70e8df1a6 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Name.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/NumberOnly.java index 147e5e00ca3..ad74058d2e5 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/NumberOnly.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/NumberOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Order.java index 509f85fa31e..1616b030b9d 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Order.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Pet.java index bb383f45a85..a89e0ea3e05 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Pet.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index aa4c0b5daa0..63e11bf14fd 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/SpecialModelName.java index 4f0d8cc6083..f8c5c06ca40 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Tag.java index 7f28005570a..27be94678da 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Tag.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/User.java index 09dd7156087..84e3b147049 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/User.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/docs/FakeApi.md b/samples/client/petstore/java/jersey2-java8/docs/FakeApi.md index c60ae94adfe..48dd79dd0e3 100644 --- a/samples/client/petstore/java/jersey2-java8/docs/FakeApi.md +++ b/samples/client/petstore/java/jersey2-java8/docs/FakeApi.md @@ -6,7 +6,7 @@ Method | HTTP request | Description ------------- | ------------- | ------------- [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -[**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters +[**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters @@ -54,7 +54,7 @@ No authorization required # **testEndpointParameters** -> testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) +> testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -63,25 +63,35 @@ Fake endpoint for testing various parameters 假端點 偽のエンドポイン ### Example ```java // Import classes: +//import io.swagger.client.ApiClient; //import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; //import io.swagger.client.api.FakeApi; +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure HTTP basic authorization: http_basic_test +HttpBasicAuth http_basic_test = (HttpBasicAuth) defaultClient.getAuthentication("http_basic_test"); +http_basic_test.setUsername("YOUR USERNAME"); +http_basic_test.setPassword("YOUR PASSWORD"); FakeApi apiInstance = new FakeApi(); BigDecimal number = new BigDecimal(); // BigDecimal | None Double _double = 3.4D; // Double | None -String string = "string_example"; // String | None +String patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None byte[] _byte = B; // byte[] | None Integer integer = 56; // Integer | None Integer int32 = 56; // Integer | None Long int64 = 789L; // Long | None Float _float = 3.4F; // Float | None +String string = "string_example"; // String | None byte[] binary = B; // byte[] | None LocalDate date = new LocalDate(); // LocalDate | None OffsetDateTime dateTime = new OffsetDateTime(); // OffsetDateTime | None String password = "password_example"; // String | None try { - apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + apiInstance.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password); } catch (ApiException e) { System.err.println("Exception when calling FakeApi#testEndpointParameters"); e.printStackTrace(); @@ -94,12 +104,13 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **number** | **BigDecimal**| None | **_double** | **Double**| None | - **string** | **String**| None | + **patternWithoutDelimiter** | **String**| None | **_byte** | **byte[]**| None | **integer** | **Integer**| None | [optional] **int32** | **Integer**| None | [optional] **int64** | **Long**| None | [optional] **_float** | **Float**| None | [optional] + **string** | **String**| None | [optional] **binary** | **byte[]**| None | [optional] **date** | **LocalDate**| None | [optional] **dateTime** | **OffsetDateTime**| None | [optional] @@ -111,18 +122,18 @@ null (empty response body) ### Authorization -No authorization required +[http_basic_test](../README.md#http_basic_test) ### HTTP request headers - **Content-Type**: application/xml; charset=utf-8, application/json; charset=utf-8 - **Accept**: application/xml; charset=utf-8, application/json; charset=utf-8 - -# **testEnumQueryParameters** -> testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble) + +# **testEnumParameters** +> testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble) -To test enum query parameters +To test enum parameters ### Example ```java @@ -132,13 +143,18 @@ To test enum query parameters FakeApi apiInstance = new FakeApi(); +List enumFormStringArray = Arrays.asList("enumFormStringArray_example"); // List | Form parameter enum test (string array) +String enumFormString = "-efg"; // String | Form parameter enum test (string) +List enumHeaderStringArray = Arrays.asList("enumHeaderStringArray_example"); // List | Header parameter enum test (string array) +String enumHeaderString = "-efg"; // String | Header parameter enum test (string) +List enumQueryStringArray = Arrays.asList("enumQueryStringArray_example"); // List | Query parameter enum test (string array) String enumQueryString = "-efg"; // String | Query parameter enum test (string) BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | Query parameter enum test (double) Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) try { - apiInstance.testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); + apiInstance.testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testEnumQueryParameters"); + System.err.println("Exception when calling FakeApi#testEnumParameters"); e.printStackTrace(); } ``` @@ -147,6 +163,11 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- + **enumFormStringArray** | [**List<String>**](String.md)| Form parameter enum test (string array) | [optional] [enum: >, $] + **enumFormString** | **String**| Form parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + **enumHeaderStringArray** | [**List<String>**](String.md)| Header parameter enum test (string array) | [optional] [enum: >, $] + **enumHeaderString** | **String**| Header parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + **enumQueryStringArray** | [**List<String>**](String.md)| Query parameter enum test (string array) | [optional] [enum: >, $] **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] **enumQueryInteger** | **BigDecimal**| Query parameter enum test (double) | [optional] **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] diff --git a/samples/client/petstore/java/jersey2-java8/docs/Model200Response.md b/samples/client/petstore/java/jersey2-java8/docs/Model200Response.md index b47618b28cc..5b3a9a0e46d 100644 --- a/samples/client/petstore/java/jersey2-java8/docs/Model200Response.md +++ b/samples/client/petstore/java/jersey2-java8/docs/Model200Response.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **Integer** | | [optional] -**PropertyClass** | **String** | | [optional] +**propertyClass** | **String** | | [optional] diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiClient.java index 35ee3db9b32..dc056fe3b7c 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiClient.java @@ -85,6 +85,7 @@ public ApiClient() { // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap(); authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("http_basic_test", new HttpBasicAuth()); authentications.put("petstore_auth", new OAuth()); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiException.java index 3bed001f002..02a967d8373 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiException.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/Configuration.java index 5191b9b73c6..57e53b2d598 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/Configuration.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/Configuration.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/Pair.java index 15b247eea93..9ad2d246519 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/Pair.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/StringUtil.java index fdcef6b1010..31140c76df4 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/StringUtil.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/FakeApi.java index c010d34a655..4a0a926dfc8 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/FakeApi.java @@ -8,8 +8,8 @@ import javax.ws.rs.core.GenericType; import io.swagger.client.model.Client; -import java.time.LocalDate; import java.time.OffsetDateTime; +import java.time.LocalDate; import java.math.BigDecimal; import java.util.ArrayList; @@ -83,19 +83,20 @@ public Client testClientModel(Client body) throws ApiException { * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * @param number None (required) * @param _double None (required) - * @param string None (required) + * @param patternWithoutDelimiter None (required) * @param _byte None (required) * @param integer None (optional) * @param int32 None (optional) * @param int64 None (optional) * @param _float None (optional) + * @param string None (optional) * @param binary None (optional) * @param date None (optional) * @param dateTime None (optional) * @param password None (optional) * @throws ApiException if fails to make API call */ - public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password) throws ApiException { + public void testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password) throws ApiException { Object localVarPostBody = null; // verify the required parameter 'number' is set @@ -108,9 +109,9 @@ public void testEndpointParameters(BigDecimal number, Double _double, String str throw new ApiException(400, "Missing the required parameter '_double' when calling testEndpointParameters"); } - // verify the required parameter 'string' is set - if (string == null) { - throw new ApiException(400, "Missing the required parameter 'string' when calling testEndpointParameters"); + // verify the required parameter 'patternWithoutDelimiter' is set + if (patternWithoutDelimiter == null) { + throw new ApiException(400, "Missing the required parameter 'patternWithoutDelimiter' when calling testEndpointParameters"); } // verify the required parameter '_byte' is set @@ -142,6 +143,8 @@ public void testEndpointParameters(BigDecimal number, Double _double, String str localVarFormParams.put("double", _double); if (string != null) localVarFormParams.put("string", string); +if (patternWithoutDelimiter != null) + localVarFormParams.put("pattern_without_delimiter", patternWithoutDelimiter); if (_byte != null) localVarFormParams.put("byte", _byte); if (binary != null) @@ -163,20 +166,25 @@ public void testEndpointParameters(BigDecimal number, Double _double, String str }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - String[] localVarAuthNames = new String[] { }; + String[] localVarAuthNames = new String[] { "http_basic_test" }; apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); } /** - * To test enum query parameters + * To test enum parameters * + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) * @param enumQueryInteger Query parameter enum test (double) (optional) * @param enumQueryDouble Query parameter enum test (double) (optional) * @throws ApiException if fails to make API call */ - public void testEnumQueryParameters(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { + public void testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { Object localVarPostBody = null; // create path and map variables @@ -187,11 +195,19 @@ public void testEnumQueryParameters(String enumQueryString, BigDecimal enumQuery Map localVarHeaderParams = new HashMap(); Map localVarFormParams = new HashMap(); + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "enum_query_string_array", enumQueryStringArray)); + localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_string", enumQueryString)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_integer", enumQueryInteger)); - - if (enumQueryString != null) - localVarFormParams.put("enum_query_string", enumQueryString); + if (enumHeaderStringArray != null) + localVarHeaderParams.put("enum_header_string_array", apiClient.parameterToString(enumHeaderStringArray)); +if (enumHeaderString != null) + localVarHeaderParams.put("enum_header_string", apiClient.parameterToString(enumHeaderString)); + + if (enumFormStringArray != null) + localVarFormParams.put("enum_form_string_array", enumFormStringArray); +if (enumFormString != null) + localVarFormParams.put("enum_form_string", enumFormString); if (enumQueryDouble != null) localVarFormParams.put("enum_query_double", enumQueryDouble); diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/PetApi.java index ab85c4ac394..ad66598406d 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/PetApi.java @@ -8,8 +8,8 @@ import javax.ws.rs.core.GenericType; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.ModelApiResponse; +import java.io.File; import java.util.ArrayList; import java.util.HashMap; diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index ad7abe402f8..0e0fdb63fb3 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/Authentication.java index 221a7d9dd1f..0ff06e3b86f 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/Authentication.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 592648b2bba..420178c112d 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/OAuth.java index 14521f6ed7e..c1b64913ab8 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/OAuth.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/OAuthFlow.java index 50d5260cfd9..18c25738e0f 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 699b351594c..2da13804a0d 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Animal.java index 45f312394b9..346da224ad1 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Animal.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AnimalFarm.java index b54adb09d7b..563476ccb3d 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 80d588dd41c..a99f2009385 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index eb02c1adee0..1aaf27b9921 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayTest.java index 1234e946d12..124d8bfa3a1 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ArrayTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Cat.java index a78d6e92515..41dc312a10f 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Cat.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Category.java index 45ceb1a1f17..ba4ce89c297 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Category.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Client.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Client.java index 46831a0baf6..43ade4b6fcb 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Client.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Client.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Dog.java index 83885a79439..788aee5c226 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Dog.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumArrays.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumArrays.java index d99bf0a0a97..45295c524f6 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumArrays.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumArrays.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumClass.java index a76173ac1a1..f9887c69340 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumClass.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumTest.java index c06b2f182cb..a7268316c40 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/FormatTest.java index 92daed84f5f..17f85c6739f 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/FormatTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java index e1fa6b49b0a..d874a545244 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MapTest.java index 7107101445a..f8cf1ad5d1a 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MapTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 90878808b8e..1a70a3aa1dd 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Model200Response.java index d617f1d9069..8f48dd8020e 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Model200Response.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -42,7 +42,7 @@ public class Model200Response { private Integer name = null; @JsonProperty("class") - private String PropertyClass = null; + private String propertyClass = null; public Model200Response name(Integer name) { this.name = name; @@ -62,22 +62,22 @@ public void setName(Integer name) { this.name = name; } - public Model200Response PropertyClass(String PropertyClass) { - this.PropertyClass = PropertyClass; + public Model200Response propertyClass(String propertyClass) { + this.propertyClass = propertyClass; return this; } /** - * Get PropertyClass - * @return PropertyClass + * Get propertyClass + * @return propertyClass **/ @ApiModelProperty(example = "null", value = "") public String getPropertyClass() { - return PropertyClass; + return propertyClass; } - public void setPropertyClass(String PropertyClass) { - this.PropertyClass = PropertyClass; + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; } @@ -91,12 +91,12 @@ public boolean equals(java.lang.Object o) { } Model200Response _200Response = (Model200Response) o; return Objects.equals(this.name, _200Response.name) && - Objects.equals(this.PropertyClass, _200Response.PropertyClass); + Objects.equals(this.propertyClass, _200Response.propertyClass); } @Override public int hashCode() { - return Objects.hash(name, PropertyClass); + return Objects.hash(name, propertyClass); } @Override @@ -105,7 +105,7 @@ public String toString() { sb.append("class Model200Response {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" PropertyClass: ").append(toIndentedString(PropertyClass)).append("\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelApiResponse.java index 65b2ad8ddc6..70ee2a834c0 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelReturn.java index 15193d8d3ba..28294a15090 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ModelReturn.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Name.java index d3a4044150e..4b70e8df1a6 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Name.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/NumberOnly.java index 147e5e00ca3..ad74058d2e5 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/NumberOnly.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/NumberOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Order.java index 4ca2c823f5b..87db4c744d8 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Order.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Pet.java index bb383f45a85..a89e0ea3e05 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Pet.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index aa4c0b5daa0..63e11bf14fd 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/SpecialModelName.java index 4f0d8cc6083..f8c5c06ca40 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Tag.java index 7f28005570a..27be94678da 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Tag.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/User.java index 09dd7156087..84e3b147049 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/User.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/docs/FakeApi.md b/samples/client/petstore/java/jersey2/docs/FakeApi.md index c145425060f..9012aff618e 100644 --- a/samples/client/petstore/java/jersey2/docs/FakeApi.md +++ b/samples/client/petstore/java/jersey2/docs/FakeApi.md @@ -6,7 +6,7 @@ Method | HTTP request | Description ------------- | ------------- | ------------- [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -[**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters +[**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters @@ -54,7 +54,7 @@ No authorization required # **testEndpointParameters** -> testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) +> testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -63,25 +63,35 @@ Fake endpoint for testing various parameters 假端點 偽のエンドポイン ### Example ```java // Import classes: +//import io.swagger.client.ApiClient; //import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; //import io.swagger.client.api.FakeApi; +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure HTTP basic authorization: http_basic_test +HttpBasicAuth http_basic_test = (HttpBasicAuth) defaultClient.getAuthentication("http_basic_test"); +http_basic_test.setUsername("YOUR USERNAME"); +http_basic_test.setPassword("YOUR PASSWORD"); FakeApi apiInstance = new FakeApi(); BigDecimal number = new BigDecimal(); // BigDecimal | None Double _double = 3.4D; // Double | None -String string = "string_example"; // String | None +String patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None byte[] _byte = B; // byte[] | None Integer integer = 56; // Integer | None Integer int32 = 56; // Integer | None Long int64 = 789L; // Long | None Float _float = 3.4F; // Float | None +String string = "string_example"; // String | None byte[] binary = B; // byte[] | None LocalDate date = new LocalDate(); // LocalDate | None DateTime dateTime = new DateTime(); // DateTime | None String password = "password_example"; // String | None try { - apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + apiInstance.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password); } catch (ApiException e) { System.err.println("Exception when calling FakeApi#testEndpointParameters"); e.printStackTrace(); @@ -94,12 +104,13 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **number** | **BigDecimal**| None | **_double** | **Double**| None | - **string** | **String**| None | + **patternWithoutDelimiter** | **String**| None | **_byte** | **byte[]**| None | **integer** | **Integer**| None | [optional] **int32** | **Integer**| None | [optional] **int64** | **Long**| None | [optional] **_float** | **Float**| None | [optional] + **string** | **String**| None | [optional] **binary** | **byte[]**| None | [optional] **date** | **LocalDate**| None | [optional] **dateTime** | **DateTime**| None | [optional] @@ -111,18 +122,18 @@ null (empty response body) ### Authorization -No authorization required +[http_basic_test](../README.md#http_basic_test) ### HTTP request headers - **Content-Type**: application/xml; charset=utf-8, application/json; charset=utf-8 - **Accept**: application/xml; charset=utf-8, application/json; charset=utf-8 - -# **testEnumQueryParameters** -> testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble) + +# **testEnumParameters** +> testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble) -To test enum query parameters +To test enum parameters ### Example ```java @@ -132,13 +143,18 @@ To test enum query parameters FakeApi apiInstance = new FakeApi(); +List enumFormStringArray = Arrays.asList("enumFormStringArray_example"); // List | Form parameter enum test (string array) +String enumFormString = "-efg"; // String | Form parameter enum test (string) +List enumHeaderStringArray = Arrays.asList("enumHeaderStringArray_example"); // List | Header parameter enum test (string array) +String enumHeaderString = "-efg"; // String | Header parameter enum test (string) +List enumQueryStringArray = Arrays.asList("enumQueryStringArray_example"); // List | Query parameter enum test (string array) String enumQueryString = "-efg"; // String | Query parameter enum test (string) BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | Query parameter enum test (double) Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) try { - apiInstance.testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); + apiInstance.testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testEnumQueryParameters"); + System.err.println("Exception when calling FakeApi#testEnumParameters"); e.printStackTrace(); } ``` @@ -147,6 +163,11 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- + **enumFormStringArray** | [**List<String>**](String.md)| Form parameter enum test (string array) | [optional] [enum: >, $] + **enumFormString** | **String**| Form parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + **enumHeaderStringArray** | [**List<String>**](String.md)| Header parameter enum test (string array) | [optional] [enum: >, $] + **enumHeaderString** | **String**| Header parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + **enumQueryStringArray** | [**List<String>**](String.md)| Query parameter enum test (string array) | [optional] [enum: >, $] **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] **enumQueryInteger** | **BigDecimal**| Query parameter enum test (double) | [optional] **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] diff --git a/samples/client/petstore/java/jersey2/docs/Model200Response.md b/samples/client/petstore/java/jersey2/docs/Model200Response.md index b47618b28cc..5b3a9a0e46d 100644 --- a/samples/client/petstore/java/jersey2/docs/Model200Response.md +++ b/samples/client/petstore/java/jersey2/docs/Model200Response.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **Integer** | | [optional] -**PropertyClass** | **String** | | [optional] +**propertyClass** | **String** | | [optional] 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 35ee3db9b32..dc056fe3b7c 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 @@ -85,6 +85,7 @@ public ApiClient() { // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap(); authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("http_basic_test", new HttpBasicAuth()); authentications.put("petstore_auth", new OAuth()); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java index 3bed001f002..02a967d8373 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java index 5191b9b73c6..57e53b2d598 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java index 15b247eea93..9ad2d246519 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java index fdcef6b1010..31140c76df4 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java index d4a083ffe88..70d8b276c1c 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java @@ -9,8 +9,8 @@ import io.swagger.client.model.Client; import org.joda.time.LocalDate; -import org.joda.time.DateTime; import java.math.BigDecimal; +import org.joda.time.DateTime; import java.util.ArrayList; import java.util.HashMap; @@ -83,19 +83,20 @@ public Client testClientModel(Client body) throws ApiException { * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * @param number None (required) * @param _double None (required) - * @param string None (required) + * @param patternWithoutDelimiter None (required) * @param _byte None (required) * @param integer None (optional) * @param int32 None (optional) * @param int64 None (optional) * @param _float None (optional) + * @param string None (optional) * @param binary None (optional) * @param date None (optional) * @param dateTime None (optional) * @param password None (optional) * @throws ApiException if fails to make API call */ - public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { + public void testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { Object localVarPostBody = null; // verify the required parameter 'number' is set @@ -108,9 +109,9 @@ public void testEndpointParameters(BigDecimal number, Double _double, String str throw new ApiException(400, "Missing the required parameter '_double' when calling testEndpointParameters"); } - // verify the required parameter 'string' is set - if (string == null) { - throw new ApiException(400, "Missing the required parameter 'string' when calling testEndpointParameters"); + // verify the required parameter 'patternWithoutDelimiter' is set + if (patternWithoutDelimiter == null) { + throw new ApiException(400, "Missing the required parameter 'patternWithoutDelimiter' when calling testEndpointParameters"); } // verify the required parameter '_byte' is set @@ -142,6 +143,8 @@ public void testEndpointParameters(BigDecimal number, Double _double, String str localVarFormParams.put("double", _double); if (string != null) localVarFormParams.put("string", string); +if (patternWithoutDelimiter != null) + localVarFormParams.put("pattern_without_delimiter", patternWithoutDelimiter); if (_byte != null) localVarFormParams.put("byte", _byte); if (binary != null) @@ -163,20 +166,25 @@ public void testEndpointParameters(BigDecimal number, Double _double, String str }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - String[] localVarAuthNames = new String[] { }; + String[] localVarAuthNames = new String[] { "http_basic_test" }; apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); } /** - * To test enum query parameters + * To test enum parameters * + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) * @param enumQueryInteger Query parameter enum test (double) (optional) * @param enumQueryDouble Query parameter enum test (double) (optional) * @throws ApiException if fails to make API call */ - public void testEnumQueryParameters(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { + public void testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { Object localVarPostBody = null; // create path and map variables @@ -187,11 +195,19 @@ public void testEnumQueryParameters(String enumQueryString, BigDecimal enumQuery Map localVarHeaderParams = new HashMap(); Map localVarFormParams = new HashMap(); + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "enum_query_string_array", enumQueryStringArray)); + localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_string", enumQueryString)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_integer", enumQueryInteger)); - - if (enumQueryString != null) - localVarFormParams.put("enum_query_string", enumQueryString); + if (enumHeaderStringArray != null) + localVarHeaderParams.put("enum_header_string_array", apiClient.parameterToString(enumHeaderStringArray)); +if (enumHeaderString != null) + localVarHeaderParams.put("enum_header_string", apiClient.parameterToString(enumHeaderString)); + + if (enumFormStringArray != null) + localVarFormParams.put("enum_form_string_array", enumFormStringArray); +if (enumFormString != null) + localVarFormParams.put("enum_form_string", enumFormString); if (enumQueryDouble != null) localVarFormParams.put("enum_query_double", enumQueryDouble); 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 ab85c4ac394..ad66598406d 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java @@ -8,8 +8,8 @@ import javax.ws.rs.core.GenericType; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.ModelApiResponse; +import java.io.File; import java.util.ArrayList; import java.util.HashMap; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index ad7abe402f8..0e0fdb63fb3 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java index 221a7d9dd1f..0ff06e3b86f 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 592648b2bba..420178c112d 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java index 14521f6ed7e..c1b64913ab8 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuthFlow.java index 50d5260cfd9..18c25738e0f 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 699b351594c..2da13804a0d 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java index 45f312394b9..346da224ad1 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AnimalFarm.java index b54adb09d7b..563476ccb3d 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 80d588dd41c..a99f2009385 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index eb02c1adee0..1aaf27b9921 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayTest.java index 1234e946d12..124d8bfa3a1 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Cat.java index a78d6e92515..41dc312a10f 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Cat.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java index 45ceb1a1f17..ba4ce89c297 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Client.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Client.java index 46831a0baf6..43ade4b6fcb 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Client.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Client.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Dog.java index 83885a79439..788aee5c226 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Dog.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumArrays.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumArrays.java index d99bf0a0a97..45295c524f6 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumArrays.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumArrays.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumClass.java index a76173ac1a1..f9887c69340 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumClass.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java index c06b2f182cb..a7268316c40 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/FormatTest.java index e1822b29ea1..2b5b4204281 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/FormatTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java index e1fa6b49b0a..d874a545244 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MapTest.java index 7107101445a..f8cf1ad5d1a 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MapTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index a6653e1b41e..20958fd50d8 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Model200Response.java index d617f1d9069..8f48dd8020e 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Model200Response.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -42,7 +42,7 @@ public class Model200Response { private Integer name = null; @JsonProperty("class") - private String PropertyClass = null; + private String propertyClass = null; public Model200Response name(Integer name) { this.name = name; @@ -62,22 +62,22 @@ public void setName(Integer name) { this.name = name; } - public Model200Response PropertyClass(String PropertyClass) { - this.PropertyClass = PropertyClass; + public Model200Response propertyClass(String propertyClass) { + this.propertyClass = propertyClass; return this; } /** - * Get PropertyClass - * @return PropertyClass + * Get propertyClass + * @return propertyClass **/ @ApiModelProperty(example = "null", value = "") public String getPropertyClass() { - return PropertyClass; + return propertyClass; } - public void setPropertyClass(String PropertyClass) { - this.PropertyClass = PropertyClass; + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; } @@ -91,12 +91,12 @@ public boolean equals(java.lang.Object o) { } Model200Response _200Response = (Model200Response) o; return Objects.equals(this.name, _200Response.name) && - Objects.equals(this.PropertyClass, _200Response.PropertyClass); + Objects.equals(this.propertyClass, _200Response.propertyClass); } @Override public int hashCode() { - return Objects.hash(name, PropertyClass); + return Objects.hash(name, propertyClass); } @Override @@ -105,7 +105,7 @@ public String toString() { sb.append("class Model200Response {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" PropertyClass: ").append(toIndentedString(PropertyClass)).append("\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelApiResponse.java index 65b2ad8ddc6..70ee2a834c0 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelReturn.java index 15193d8d3ba..28294a15090 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelReturn.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Name.java index d3a4044150e..4b70e8df1a6 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Name.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/NumberOnly.java index 147e5e00ca3..ad74058d2e5 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/NumberOnly.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/NumberOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java index 509f85fa31e..1616b030b9d 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java index bb383f45a85..a89e0ea3e05 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index aa4c0b5daa0..63e11bf14fd 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/SpecialModelName.java index 4f0d8cc6083..f8c5c06ca40 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java index 7f28005570a..27be94678da 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java index 09dd7156087..84e3b147049 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md b/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md index c145425060f..9012aff618e 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md +++ b/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md @@ -6,7 +6,7 @@ Method | HTTP request | Description ------------- | ------------- | ------------- [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -[**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters +[**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters @@ -54,7 +54,7 @@ No authorization required # **testEndpointParameters** -> testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) +> testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -63,25 +63,35 @@ Fake endpoint for testing various parameters 假端點 偽のエンドポイン ### Example ```java // Import classes: +//import io.swagger.client.ApiClient; //import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; //import io.swagger.client.api.FakeApi; +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure HTTP basic authorization: http_basic_test +HttpBasicAuth http_basic_test = (HttpBasicAuth) defaultClient.getAuthentication("http_basic_test"); +http_basic_test.setUsername("YOUR USERNAME"); +http_basic_test.setPassword("YOUR PASSWORD"); FakeApi apiInstance = new FakeApi(); BigDecimal number = new BigDecimal(); // BigDecimal | None Double _double = 3.4D; // Double | None -String string = "string_example"; // String | None +String patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None byte[] _byte = B; // byte[] | None Integer integer = 56; // Integer | None Integer int32 = 56; // Integer | None Long int64 = 789L; // Long | None Float _float = 3.4F; // Float | None +String string = "string_example"; // String | None byte[] binary = B; // byte[] | None LocalDate date = new LocalDate(); // LocalDate | None DateTime dateTime = new DateTime(); // DateTime | None String password = "password_example"; // String | None try { - apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + apiInstance.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password); } catch (ApiException e) { System.err.println("Exception when calling FakeApi#testEndpointParameters"); e.printStackTrace(); @@ -94,12 +104,13 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **number** | **BigDecimal**| None | **_double** | **Double**| None | - **string** | **String**| None | + **patternWithoutDelimiter** | **String**| None | **_byte** | **byte[]**| None | **integer** | **Integer**| None | [optional] **int32** | **Integer**| None | [optional] **int64** | **Long**| None | [optional] **_float** | **Float**| None | [optional] + **string** | **String**| None | [optional] **binary** | **byte[]**| None | [optional] **date** | **LocalDate**| None | [optional] **dateTime** | **DateTime**| None | [optional] @@ -111,18 +122,18 @@ null (empty response body) ### Authorization -No authorization required +[http_basic_test](../README.md#http_basic_test) ### HTTP request headers - **Content-Type**: application/xml; charset=utf-8, application/json; charset=utf-8 - **Accept**: application/xml; charset=utf-8, application/json; charset=utf-8 - -# **testEnumQueryParameters** -> testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble) + +# **testEnumParameters** +> testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble) -To test enum query parameters +To test enum parameters ### Example ```java @@ -132,13 +143,18 @@ To test enum query parameters FakeApi apiInstance = new FakeApi(); +List enumFormStringArray = Arrays.asList("enumFormStringArray_example"); // List | Form parameter enum test (string array) +String enumFormString = "-efg"; // String | Form parameter enum test (string) +List enumHeaderStringArray = Arrays.asList("enumHeaderStringArray_example"); // List | Header parameter enum test (string array) +String enumHeaderString = "-efg"; // String | Header parameter enum test (string) +List enumQueryStringArray = Arrays.asList("enumQueryStringArray_example"); // List | Query parameter enum test (string array) String enumQueryString = "-efg"; // String | Query parameter enum test (string) BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | Query parameter enum test (double) Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) try { - apiInstance.testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); + apiInstance.testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testEnumQueryParameters"); + System.err.println("Exception when calling FakeApi#testEnumParameters"); e.printStackTrace(); } ``` @@ -147,6 +163,11 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- + **enumFormStringArray** | [**List<String>**](String.md)| Form parameter enum test (string array) | [optional] [enum: >, $] + **enumFormString** | **String**| Form parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + **enumHeaderStringArray** | [**List<String>**](String.md)| Header parameter enum test (string array) | [optional] [enum: >, $] + **enumHeaderString** | **String**| Header parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + **enumQueryStringArray** | [**List<String>**](String.md)| Query parameter enum test (string array) | [optional] [enum: >, $] **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] **enumQueryInteger** | **BigDecimal**| Query parameter enum test (double) | [optional] **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] diff --git a/samples/client/petstore/java/okhttp-gson/docs/Model200Response.md b/samples/client/petstore/java/okhttp-gson/docs/Model200Response.md index b47618b28cc..5b3a9a0e46d 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/Model200Response.md +++ b/samples/client/petstore/java/okhttp-gson/docs/Model200Response.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **Integer** | | [optional] -**PropertyClass** | **String** | | [optional] +**propertyClass** | **String** | | [optional] diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java index 3ca33cf8017..a2460c37ee3 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * 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 b7b04e3e4c5..c4137dcb816 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -174,6 +174,7 @@ public ApiClient() { // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap(); authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("http_basic_test", new HttpBasicAuth()); authentications.put("petstore_auth", new OAuth()); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java index 3bed001f002..02a967d8373 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiResponse.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiResponse.java index d7dde1ee939..b87ea49a02e 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiResponse.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiResponse.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -31,7 +31,7 @@ /** * API response returned by API call. * - * @param T The type of data that is deserialized from response body + * @param The type of data that is deserialized from response body */ public class ApiResponse { final private int statusCode; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java index 5191b9b73c6..57e53b2d598 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java index 99f9bab36ac..a734bec47f1 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -162,10 +162,9 @@ public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext * * @param json Json element * @param date Type - * @param typeOfSrc Type * @param context Json Serialization Context * @return Date - * @throw JsonParseException if fail to parse + * @throws JsonParseException if fail to parse */ @Override public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException { diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java index 15b247eea93..9ad2d246519 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressRequestBody.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressRequestBody.java index d9ca742ecd2..fee9da83ddd 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressRequestBody.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressRequestBody.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressResponseBody.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressResponseBody.java index f8af685999d..761a23a2869 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressResponseBody.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressResponseBody.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java index fdcef6b1010..31140c76df4 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java index c6e71e5f1b6..dda8d66e206 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -40,8 +40,8 @@ import io.swagger.client.model.Client; import org.joda.time.LocalDate; -import org.joda.time.DateTime; import java.math.BigDecimal; +import org.joda.time.DateTime; import java.lang.reflect.Type; import java.util.ArrayList; @@ -175,7 +175,7 @@ public void onRequestProgress(long bytesWritten, long contentLength, boolean don return call; } /* Build call for testEndpointParameters */ - private com.squareup.okhttp.Call testEndpointParametersCall(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + private com.squareup.okhttp.Call testEndpointParametersCall(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, DateTime dateTime, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; // verify the required parameter 'number' is set @@ -188,9 +188,9 @@ private com.squareup.okhttp.Call testEndpointParametersCall(BigDecimal number, D throw new ApiException("Missing the required parameter '_double' when calling testEndpointParameters(Async)"); } - // verify the required parameter 'string' is set - if (string == null) { - throw new ApiException("Missing the required parameter 'string' when calling testEndpointParameters(Async)"); + // verify the required parameter 'patternWithoutDelimiter' is set + if (patternWithoutDelimiter == null) { + throw new ApiException("Missing the required parameter 'patternWithoutDelimiter' when calling testEndpointParameters(Async)"); } // verify the required parameter '_byte' is set @@ -221,6 +221,8 @@ private com.squareup.okhttp.Call testEndpointParametersCall(BigDecimal number, D localVarFormParams.put("double", _double); if (string != null) localVarFormParams.put("string", string); + if (patternWithoutDelimiter != null) + localVarFormParams.put("pattern_without_delimiter", patternWithoutDelimiter); if (_byte != null) localVarFormParams.put("byte", _byte); if (binary != null) @@ -256,7 +258,7 @@ public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Ch }); } - String[] localVarAuthNames = new String[] { }; + String[] localVarAuthNames = new String[] { "http_basic_test" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @@ -265,20 +267,21 @@ public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Ch * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * @param number None (required) * @param _double None (required) - * @param string None (required) + * @param patternWithoutDelimiter None (required) * @param _byte None (required) * @param integer None (optional) * @param int32 None (optional) * @param int64 None (optional) * @param _float None (optional) + * @param string None (optional) * @param binary None (optional) * @param date None (optional) * @param dateTime None (optional) * @param password None (optional) * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ - public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { - testEndpointParametersWithHttpInfo(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + public void testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { + testEndpointParametersWithHttpInfo(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password); } /** @@ -286,12 +289,13 @@ public void testEndpointParameters(BigDecimal number, Double _double, String str * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * @param number None (required) * @param _double None (required) - * @param string None (required) + * @param patternWithoutDelimiter None (required) * @param _byte None (required) * @param integer None (optional) * @param int32 None (optional) * @param int64 None (optional) * @param _float None (optional) + * @param string None (optional) * @param binary None (optional) * @param date None (optional) * @param dateTime None (optional) @@ -299,8 +303,8 @@ public void testEndpointParameters(BigDecimal number, Double _double, String str * @return ApiResponse<Void> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ - public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { - com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password, null, null); + public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { + com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, null, null); return apiClient.execute(call); } @@ -309,12 +313,13 @@ public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, D * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * @param number None (required) * @param _double None (required) - * @param string None (required) + * @param patternWithoutDelimiter None (required) * @param _byte None (required) * @param integer None (optional) * @param int32 None (optional) * @param int64 None (optional) * @param _float None (optional) + * @param string None (optional) * @param binary None (optional) * @param date None (optional) * @param dateTime None (optional) @@ -323,7 +328,7 @@ public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, D * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ - public com.squareup.okhttp.Call testEndpointParametersAsync(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password, final ApiCallback callback) throws ApiException { + public com.squareup.okhttp.Call testEndpointParametersAsync(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, DateTime dateTime, String password, final ApiCallback callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; @@ -344,12 +349,12 @@ public void onRequestProgress(long bytesWritten, long contentLength, boolean don }; } - com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password, progressListener, progressRequestListener); + com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, progressListener, progressRequestListener); apiClient.executeAsync(call, callback); return call; } - /* Build call for testEnumQueryParameters */ - private com.squareup.okhttp.Call testEnumQueryParametersCall(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + /* Build call for testEnumParameters */ + private com.squareup.okhttp.Call testEnumParametersCall(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; @@ -357,14 +362,24 @@ private com.squareup.okhttp.Call testEnumQueryParametersCall(String enumQueryStr String localVarPath = "/fake".replaceAll("\\{format\\}","json"); List localVarQueryParams = new ArrayList(); + if (enumQueryStringArray != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "enum_query_string_array", enumQueryStringArray)); + if (enumQueryString != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_string", enumQueryString)); if (enumQueryInteger != null) localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_integer", enumQueryInteger)); Map localVarHeaderParams = new HashMap(); + if (enumHeaderStringArray != null) + localVarHeaderParams.put("enum_header_string_array", apiClient.parameterToString(enumHeaderStringArray)); + if (enumHeaderString != null) + localVarHeaderParams.put("enum_header_string", apiClient.parameterToString(enumHeaderString)); Map localVarFormParams = new HashMap(); - if (enumQueryString != null) - localVarFormParams.put("enum_query_string", enumQueryString); + if (enumFormStringArray != null) + localVarFormParams.put("enum_form_string_array", enumFormStringArray); + if (enumFormString != null) + localVarFormParams.put("enum_form_string", enumFormString); if (enumQueryDouble != null) localVarFormParams.put("enum_query_double", enumQueryDouble); @@ -397,34 +412,49 @@ public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Ch } /** - * To test enum query parameters + * To test enum parameters * + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) * @param enumQueryInteger Query parameter enum test (double) (optional) * @param enumQueryDouble Query parameter enum test (double) (optional) * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ - public void testEnumQueryParameters(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { - testEnumQueryParametersWithHttpInfo(enumQueryString, enumQueryInteger, enumQueryDouble); + public void testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { + testEnumParametersWithHttpInfo(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); } /** - * To test enum query parameters + * To test enum parameters * + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) * @param enumQueryInteger Query parameter enum test (double) (optional) * @param enumQueryDouble Query parameter enum test (double) (optional) * @return ApiResponse<Void> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ - public ApiResponse testEnumQueryParametersWithHttpInfo(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { - com.squareup.okhttp.Call call = testEnumQueryParametersCall(enumQueryString, enumQueryInteger, enumQueryDouble, null, null); + public ApiResponse testEnumParametersWithHttpInfo(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { + com.squareup.okhttp.Call call = testEnumParametersCall(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, null, null); return apiClient.execute(call); } /** - * To test enum query parameters (asynchronously) + * To test enum parameters (asynchronously) * + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) * @param enumQueryInteger Query parameter enum test (double) (optional) * @param enumQueryDouble Query parameter enum test (double) (optional) @@ -432,7 +462,7 @@ public ApiResponse testEnumQueryParametersWithHttpInfo(String enumQueryStr * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ - public com.squareup.okhttp.Call testEnumQueryParametersAsync(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, final ApiCallback callback) throws ApiException { + public com.squareup.okhttp.Call testEnumParametersAsync(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, final ApiCallback callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; @@ -453,7 +483,7 @@ public void onRequestProgress(long bytesWritten, long contentLength, boolean don }; } - com.squareup.okhttp.Call call = testEnumQueryParametersCall(enumQueryString, enumQueryInteger, enumQueryDouble, progressListener, progressRequestListener); + com.squareup.okhttp.Call call = testEnumParametersCall(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, progressListener, progressRequestListener); apiClient.executeAsync(call, callback); return call; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java index 2039a8842c1..6c459540701 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -39,8 +39,8 @@ import java.io.IOException; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.ModelApiResponse; +import java.io.File; import java.lang.reflect.Type; import java.util.ArrayList; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java index 0768744c263..04ad8deb2a6 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java index 1c4fc3101a1..adcdda4b6d1 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index ad7abe402f8..0e0fdb63fb3 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java index 221a7d9dd1f..0ff06e3b86f 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 4eb2300b69d..d54692966a9 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java index 14521f6ed7e..c1b64913ab8 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuthFlow.java index 50d5260cfd9..18c25738e0f 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 7b1955e7601..d20b1402ce2 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Animal.java index ba3806dc875..9b1ff3df1c5 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Animal.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AnimalFarm.java index b54adb09d7b..563476ccb3d 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 81ba53bf660..4c2fa22800f 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index e4860d0f095..3c7d74dc3b5 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java index 22fb331103f..7e08b24fa6e 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Cat.java index 985342803a8..9c5cb39f648 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Cat.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java index 2178a866f62..44e76030eff 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Client.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Client.java index 6eac2866846..54a54647918 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Client.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Client.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Dog.java index c59b3783d18..880c159616c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Dog.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumArrays.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumArrays.java index aef9b16ef15..c5096738755 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumArrays.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumArrays.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumClass.java index b53ad4fa8f6..7862a8b8952 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumClass.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java index 9aad1223215..83896fbd849 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java index 91109681509..a05f1d5c811 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java index d77fc7ac36b..e53b1a0d8be 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MapTest.java index 0ab3cb990e0..e7d394ed035 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MapTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 192175a03af..887ba516d72 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Model200Response.java index d8da58aca9c..980bc83e869 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Model200Response.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -41,7 +41,7 @@ public class Model200Response { private Integer name = null; @SerializedName("class") - private String PropertyClass = null; + private String propertyClass = null; public Model200Response name(Integer name) { this.name = name; @@ -61,22 +61,22 @@ public void setName(Integer name) { this.name = name; } - public Model200Response PropertyClass(String PropertyClass) { - this.PropertyClass = PropertyClass; + public Model200Response propertyClass(String propertyClass) { + this.propertyClass = propertyClass; return this; } /** - * Get PropertyClass - * @return PropertyClass + * Get propertyClass + * @return propertyClass **/ @ApiModelProperty(example = "null", value = "") public String getPropertyClass() { - return PropertyClass; + return propertyClass; } - public void setPropertyClass(String PropertyClass) { - this.PropertyClass = PropertyClass; + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; } @@ -90,12 +90,12 @@ public boolean equals(java.lang.Object o) { } Model200Response _200Response = (Model200Response) o; return Objects.equals(this.name, _200Response.name) && - Objects.equals(this.PropertyClass, _200Response.PropertyClass); + Objects.equals(this.propertyClass, _200Response.propertyClass); } @Override public int hashCode() { - return Objects.hash(name, PropertyClass); + return Objects.hash(name, propertyClass); } @Override @@ -104,7 +104,7 @@ public String toString() { sb.append("class Model200Response {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" PropertyClass: ").append(toIndentedString(PropertyClass)).append("\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelApiResponse.java index 2a823298323..f9c162a7934 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelReturn.java index 024a9c0df1c..bbe7780055c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelReturn.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Name.java index 318a2ddd50e..d51354ceffa 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Name.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/NumberOnly.java index 9b9ca048dfb..2b1817300a9 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/NumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/NumberOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java index 90cfd2f3892..f52e7bd5db4 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java index 5aad989d5b1..06443e56915 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index 13b729bb94d..75dbc55f9f5 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/SpecialModelName.java index b46b8367a01..9744ad08268 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java index e56eb535d1e..9eef0141c71 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java index 6c1ed6ceacc..73584bfdccb 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java index 08cfb4b3751..59094331de2 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java @@ -56,6 +56,8 @@ public ApiClient(String[] authNames) { Interceptor auth; if (authName == "api_key") { auth = new ApiKeyAuth("header", "api_key"); + } else if (authName == "http_basic_test") { + auth = new HttpBasicAuth(); } else if (authName == "petstore_auth") { auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); } else { diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java index fdcef6b1010..31140c76df4 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java index 076b9fc2ab1..fb02bbde690 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java @@ -8,8 +8,8 @@ import io.swagger.client.model.Client; import org.joda.time.LocalDate; -import org.joda.time.DateTime; import java.math.BigDecimal; +import org.joda.time.DateTime; import java.util.ArrayList; import java.util.HashMap; @@ -48,12 +48,13 @@ void testClientModel( * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * @param number None (required) * @param _double None (required) - * @param string None (required) + * @param patternWithoutDelimiter None (required) * @param _byte None (required) * @param integer None (optional) * @param int32 None (optional) * @param int64 None (optional) * @param _float None (optional) + * @param string None (optional) * @param binary None (optional) * @param date None (optional) * @param dateTime None (optional) @@ -64,7 +65,7 @@ void testClientModel( @FormUrlEncoded @POST("/fake") Void testEndpointParameters( - @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password + @Field("number") BigDecimal number, @Field("double") Double _double, @Field("pattern_without_delimiter") String patternWithoutDelimiter, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("string") String string, @Field("binary") byte[] binary, @Field("date") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password ); /** @@ -72,12 +73,13 @@ Void testEndpointParameters( * Async method * @param number None (required) * @param _double None (required) - * @param string None (required) + * @param patternWithoutDelimiter None (required) * @param _byte None (required) * @param integer None (optional) * @param int32 None (optional) * @param int64 None (optional) * @param _float None (optional) + * @param string None (optional) * @param binary None (optional) * @param date None (optional) * @param dateTime None (optional) @@ -89,12 +91,17 @@ Void testEndpointParameters( @FormUrlEncoded @POST("/fake") void testEndpointParameters( - @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password, Callback cb + @Field("number") BigDecimal number, @Field("double") Double _double, @Field("pattern_without_delimiter") String patternWithoutDelimiter, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("string") String string, @Field("binary") byte[] binary, @Field("date") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password, Callback cb ); /** - * To test enum query parameters + * To test enum parameters * Sync method * + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) * @param enumQueryInteger Query parameter enum test (double) (optional) * @param enumQueryDouble Query parameter enum test (double) (optional) @@ -103,13 +110,18 @@ void testEndpointParameters( @FormUrlEncoded @GET("/fake") - Void testEnumQueryParameters( - @Field("enum_query_string") String enumQueryString, @Query("enum_query_integer") BigDecimal enumQueryInteger, @Field("enum_query_double") Double enumQueryDouble + Void testEnumParameters( + @Field("enum_form_string_array") List enumFormStringArray, @Field("enum_form_string") String enumFormString, @Header("enum_header_string_array") List enumHeaderStringArray, @Header("enum_header_string") String enumHeaderString, @Query("enum_query_string_array") CSVParams enumQueryStringArray, @Query("enum_query_string") String enumQueryString, @Query("enum_query_integer") BigDecimal enumQueryInteger, @Field("enum_query_double") Double enumQueryDouble ); /** - * To test enum query parameters + * To test enum parameters * Async method + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) * @param enumQueryInteger Query parameter enum test (double) (optional) * @param enumQueryDouble Query parameter enum test (double) (optional) @@ -119,7 +131,7 @@ Void testEnumQueryParameters( @FormUrlEncoded @GET("/fake") - void testEnumQueryParameters( - @Field("enum_query_string") String enumQueryString, @Query("enum_query_integer") BigDecimal enumQueryInteger, @Field("enum_query_double") Double enumQueryDouble, Callback cb + void testEnumParameters( + @Field("enum_form_string_array") List enumFormStringArray, @Field("enum_form_string") String enumFormString, @Header("enum_header_string_array") List enumHeaderStringArray, @Header("enum_header_string") String enumHeaderString, @Query("enum_query_string_array") CSVParams enumQueryStringArray, @Query("enum_query_string") String enumQueryString, @Query("enum_query_integer") BigDecimal enumQueryInteger, @Field("enum_query_double") Double enumQueryDouble, Callback cb ); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java index 66ed6aea981..a019a4bf886 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java @@ -7,8 +7,8 @@ import retrofit.mime.*; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.ModelApiResponse; +import java.io.File; import java.util.ArrayList; import java.util.HashMap; diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthFlow.java index 50d5260cfd9..18c25738e0f 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 7b1955e7601..d20b1402ce2 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Animal.java index ba3806dc875..9b1ff3df1c5 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Animal.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AnimalFarm.java index b54adb09d7b..563476ccb3d 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 81ba53bf660..4c2fa22800f 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index e4860d0f095..3c7d74dc3b5 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayTest.java index 22fb331103f..7e08b24fa6e 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Cat.java index 985342803a8..9c5cb39f648 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Cat.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Category.java index 2178a866f62..44e76030eff 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Category.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Client.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Client.java index 6eac2866846..54a54647918 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Client.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Client.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Dog.java index c59b3783d18..880c159616c 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Dog.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumArrays.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumArrays.java index aef9b16ef15..c5096738755 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumArrays.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumArrays.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumClass.java index b53ad4fa8f6..7862a8b8952 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumClass.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumTest.java index 9aad1223215..83896fbd849 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/FormatTest.java index 91109681509..a05f1d5c811 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/FormatTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java index d77fc7ac36b..e53b1a0d8be 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MapTest.java index 0ab3cb990e0..e7d394ed035 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MapTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 192175a03af..887ba516d72 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Model200Response.java index d8da58aca9c..980bc83e869 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Model200Response.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -41,7 +41,7 @@ public class Model200Response { private Integer name = null; @SerializedName("class") - private String PropertyClass = null; + private String propertyClass = null; public Model200Response name(Integer name) { this.name = name; @@ -61,22 +61,22 @@ public void setName(Integer name) { this.name = name; } - public Model200Response PropertyClass(String PropertyClass) { - this.PropertyClass = PropertyClass; + public Model200Response propertyClass(String propertyClass) { + this.propertyClass = propertyClass; return this; } /** - * Get PropertyClass - * @return PropertyClass + * Get propertyClass + * @return propertyClass **/ @ApiModelProperty(example = "null", value = "") public String getPropertyClass() { - return PropertyClass; + return propertyClass; } - public void setPropertyClass(String PropertyClass) { - this.PropertyClass = PropertyClass; + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; } @@ -90,12 +90,12 @@ public boolean equals(java.lang.Object o) { } Model200Response _200Response = (Model200Response) o; return Objects.equals(this.name, _200Response.name) && - Objects.equals(this.PropertyClass, _200Response.PropertyClass); + Objects.equals(this.propertyClass, _200Response.propertyClass); } @Override public int hashCode() { - return Objects.hash(name, PropertyClass); + return Objects.hash(name, propertyClass); } @Override @@ -104,7 +104,7 @@ public String toString() { sb.append("class Model200Response {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" PropertyClass: ").append(toIndentedString(PropertyClass)).append("\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ModelApiResponse.java index 2a823298323..f9c162a7934 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ModelReturn.java index 024a9c0df1c..bbe7780055c 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ModelReturn.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Name.java index 318a2ddd50e..d51354ceffa 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Name.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/NumberOnly.java index 9b9ca048dfb..2b1817300a9 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/NumberOnly.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/NumberOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java index 90cfd2f3892..f52e7bd5db4 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Pet.java index 5aad989d5b1..06443e56915 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Pet.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index 13b729bb94d..75dbc55f9f5 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/SpecialModelName.java index b46b8367a01..9744ad08268 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Tag.java index e56eb535d1e..9eef0141c71 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Tag.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/User.java index 6c1ed6ceacc..73584bfdccb 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/User.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2/docs/FakeApi.md b/samples/client/petstore/java/retrofit2/docs/FakeApi.md index ce1e37babc3..f4cfc7e19cc 100644 --- a/samples/client/petstore/java/retrofit2/docs/FakeApi.md +++ b/samples/client/petstore/java/retrofit2/docs/FakeApi.md @@ -6,7 +6,7 @@ Method | HTTP request | Description ------------- | ------------- | ------------- [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** fake | To test \"client\" model [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -[**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** fake | To test enum query parameters +[**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** fake | To test enum parameters @@ -54,7 +54,7 @@ No authorization required # **testEndpointParameters** -> Void testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) +> Void testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -63,25 +63,35 @@ Fake endpoint for testing various parameters 假端點 偽のエンドポイン ### Example ```java // Import classes: +//import io.swagger.client.ApiClient; //import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; //import io.swagger.client.api.FakeApi; +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure HTTP basic authorization: http_basic_test +HttpBasicAuth http_basic_test = (HttpBasicAuth) defaultClient.getAuthentication("http_basic_test"); +http_basic_test.setUsername("YOUR USERNAME"); +http_basic_test.setPassword("YOUR PASSWORD"); FakeApi apiInstance = new FakeApi(); BigDecimal number = new BigDecimal(); // BigDecimal | None Double _double = 3.4D; // Double | None -String string = "string_example"; // String | None +String patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None byte[] _byte = B; // byte[] | None Integer integer = 56; // Integer | None Integer int32 = 56; // Integer | None Long int64 = 789L; // Long | None Float _float = 3.4F; // Float | None +String string = "string_example"; // String | None byte[] binary = B; // byte[] | None LocalDate date = new LocalDate(); // LocalDate | None DateTime dateTime = new DateTime(); // DateTime | None String password = "password_example"; // String | None try { - Void result = apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + Void result = apiInstance.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password); System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling FakeApi#testEndpointParameters"); @@ -95,12 +105,13 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **number** | **BigDecimal**| None | **_double** | **Double**| None | - **string** | **String**| None | + **patternWithoutDelimiter** | **String**| None | **_byte** | **byte[]**| None | **integer** | **Integer**| None | [optional] **int32** | **Integer**| None | [optional] **int64** | **Long**| None | [optional] **_float** | **Float**| None | [optional] + **string** | **String**| None | [optional] **binary** | **byte[]**| None | [optional] **date** | **LocalDate**| None | [optional] **dateTime** | **DateTime**| None | [optional] @@ -112,18 +123,18 @@ Name | Type | Description | Notes ### Authorization -No authorization required +[http_basic_test](../README.md#http_basic_test) ### HTTP request headers - **Content-Type**: application/xml; charset=utf-8, application/json; charset=utf-8 - **Accept**: application/xml; charset=utf-8, application/json; charset=utf-8 - -# **testEnumQueryParameters** -> Void testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble) + +# **testEnumParameters** +> Void testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble) -To test enum query parameters +To test enum parameters ### Example ```java @@ -133,14 +144,19 @@ To test enum query parameters FakeApi apiInstance = new FakeApi(); +List enumFormStringArray = Arrays.asList("enumFormStringArray_example"); // List | Form parameter enum test (string array) +String enumFormString = "-efg"; // String | Form parameter enum test (string) +List enumHeaderStringArray = Arrays.asList("enumHeaderStringArray_example"); // List | Header parameter enum test (string array) +String enumHeaderString = "-efg"; // String | Header parameter enum test (string) +List enumQueryStringArray = Arrays.asList("enumQueryStringArray_example"); // List | Query parameter enum test (string array) String enumQueryString = "-efg"; // String | Query parameter enum test (string) BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | Query parameter enum test (double) Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) try { - Void result = apiInstance.testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); + Void result = apiInstance.testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); System.out.println(result); } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testEnumQueryParameters"); + System.err.println("Exception when calling FakeApi#testEnumParameters"); e.printStackTrace(); } ``` @@ -149,6 +165,11 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- + **enumFormStringArray** | [**List<String>**](String.md)| Form parameter enum test (string array) | [optional] [enum: >, $] + **enumFormString** | **String**| Form parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + **enumHeaderStringArray** | [**List<String>**](String.md)| Header parameter enum test (string array) | [optional] [enum: >, $] + **enumHeaderString** | **String**| Header parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + **enumQueryStringArray** | [**List<String>**](String.md)| Query parameter enum test (string array) | [optional] [enum: >, $] **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] **enumQueryInteger** | **BigDecimal**| Query parameter enum test (double) | [optional] **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] diff --git a/samples/client/petstore/java/retrofit2/docs/Model200Response.md b/samples/client/petstore/java/retrofit2/docs/Model200Response.md index b47618b28cc..5b3a9a0e46d 100644 --- a/samples/client/petstore/java/retrofit2/docs/Model200Response.md +++ b/samples/client/petstore/java/retrofit2/docs/Model200Response.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **Integer** | | [optional] -**PropertyClass** | **String** | | [optional] +**propertyClass** | **String** | | [optional] diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java index 604861f6072..be9eadc33ba 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java @@ -55,6 +55,8 @@ public ApiClient(String[] authNames) { Interceptor auth; if (authName == "api_key") { auth = new ApiKeyAuth("header", "api_key"); + } else if (authName == "http_basic_test") { + auth = new HttpBasicAuth(); } else if (authName == "petstore_auth") { auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); } else { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/StringUtil.java index fdcef6b1010..31140c76df4 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/StringUtil.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java index 9bd1f7b9882..25bde1256dc 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java @@ -10,8 +10,8 @@ import io.swagger.client.model.Client; import org.joda.time.LocalDate; -import org.joda.time.DateTime; import java.math.BigDecimal; +import org.joda.time.DateTime; import java.util.ArrayList; import java.util.HashMap; @@ -36,12 +36,13 @@ Call testClientModel( * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * @param number None (required) * @param _double None (required) - * @param string None (required) + * @param patternWithoutDelimiter None (required) * @param _byte None (required) * @param integer None (optional) * @param int32 None (optional) * @param int64 None (optional) * @param _float None (optional) + * @param string None (optional) * @param binary None (optional) * @param date None (optional) * @param dateTime None (optional) @@ -52,12 +53,17 @@ Call testClientModel( @FormUrlEncoded @POST("fake") Call testEndpointParameters( - @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password + @Field("number") BigDecimal number, @Field("double") Double _double, @Field("pattern_without_delimiter") String patternWithoutDelimiter, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("string") String string, @Field("binary") byte[] binary, @Field("date") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password ); /** - * To test enum query parameters + * To test enum parameters * + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) * @param enumQueryInteger Query parameter enum test (double) (optional) * @param enumQueryDouble Query parameter enum test (double) (optional) @@ -66,8 +72,8 @@ Call testEndpointParameters( @FormUrlEncoded @GET("fake") - Call testEnumQueryParameters( - @Field("enum_query_string") String enumQueryString, @Query("enum_query_integer") BigDecimal enumQueryInteger, @Field("enum_query_double") Double enumQueryDouble + Call testEnumParameters( + @Field("enum_form_string_array") List enumFormStringArray, @Field("enum_form_string") String enumFormString, @Header("enum_header_string_array") List enumHeaderStringArray, @Header("enum_header_string") String enumHeaderString, @Query("enum_query_string_array") CSVParams enumQueryStringArray, @Query("enum_query_string") String enumQueryString, @Query("enum_query_integer") BigDecimal enumQueryInteger, @Field("enum_query_double") Double enumQueryDouble ); } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java index a55cb2ee17f..a1ea00e368a 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java @@ -9,8 +9,8 @@ import okhttp3.RequestBody; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.ModelApiResponse; +import java.io.File; import java.util.ArrayList; import java.util.HashMap; diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthFlow.java index 50d5260cfd9..18c25738e0f 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 7b1955e7601..d20b1402ce2 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Animal.java index ba3806dc875..9b1ff3df1c5 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Animal.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AnimalFarm.java index b54adb09d7b..563476ccb3d 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 81ba53bf660..4c2fa22800f 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index e4860d0f095..3c7d74dc3b5 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayTest.java index 22fb331103f..7e08b24fa6e 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Cat.java index 985342803a8..9c5cb39f648 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Cat.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Category.java index 2178a866f62..44e76030eff 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Category.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Client.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Client.java index 6eac2866846..54a54647918 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Client.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Client.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Dog.java index c59b3783d18..880c159616c 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Dog.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumArrays.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumArrays.java index aef9b16ef15..c5096738755 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumArrays.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumArrays.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumClass.java index b53ad4fa8f6..7862a8b8952 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumClass.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumTest.java index 9aad1223215..83896fbd849 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/FormatTest.java index 91109681509..a05f1d5c811 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/FormatTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java index d77fc7ac36b..e53b1a0d8be 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MapTest.java index 0ab3cb990e0..e7d394ed035 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MapTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 192175a03af..887ba516d72 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Model200Response.java index d8da58aca9c..980bc83e869 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Model200Response.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -41,7 +41,7 @@ public class Model200Response { private Integer name = null; @SerializedName("class") - private String PropertyClass = null; + private String propertyClass = null; public Model200Response name(Integer name) { this.name = name; @@ -61,22 +61,22 @@ public void setName(Integer name) { this.name = name; } - public Model200Response PropertyClass(String PropertyClass) { - this.PropertyClass = PropertyClass; + public Model200Response propertyClass(String propertyClass) { + this.propertyClass = propertyClass; return this; } /** - * Get PropertyClass - * @return PropertyClass + * Get propertyClass + * @return propertyClass **/ @ApiModelProperty(example = "null", value = "") public String getPropertyClass() { - return PropertyClass; + return propertyClass; } - public void setPropertyClass(String PropertyClass) { - this.PropertyClass = PropertyClass; + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; } @@ -90,12 +90,12 @@ public boolean equals(java.lang.Object o) { } Model200Response _200Response = (Model200Response) o; return Objects.equals(this.name, _200Response.name) && - Objects.equals(this.PropertyClass, _200Response.PropertyClass); + Objects.equals(this.propertyClass, _200Response.propertyClass); } @Override public int hashCode() { - return Objects.hash(name, PropertyClass); + return Objects.hash(name, propertyClass); } @Override @@ -104,7 +104,7 @@ public String toString() { sb.append("class Model200Response {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" PropertyClass: ").append(toIndentedString(PropertyClass)).append("\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ModelApiResponse.java index 2a823298323..f9c162a7934 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ModelReturn.java index 024a9c0df1c..bbe7780055c 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ModelReturn.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Name.java index 318a2ddd50e..d51354ceffa 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Name.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/NumberOnly.java index 9b9ca048dfb..2b1817300a9 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/NumberOnly.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/NumberOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Order.java index 90cfd2f3892..f52e7bd5db4 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Order.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Pet.java index 5aad989d5b1..06443e56915 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Pet.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index 13b729bb94d..75dbc55f9f5 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/SpecialModelName.java index b46b8367a01..9744ad08268 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Tag.java index e56eb535d1e..9eef0141c71 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Tag.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/User.java index 6c1ed6ceacc..73584bfdccb 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/User.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md b/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md index ce1e37babc3..f4cfc7e19cc 100644 --- a/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md +++ b/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md @@ -6,7 +6,7 @@ Method | HTTP request | Description ------------- | ------------- | ------------- [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** fake | To test \"client\" model [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -[**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** fake | To test enum query parameters +[**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** fake | To test enum parameters @@ -54,7 +54,7 @@ No authorization required # **testEndpointParameters** -> Void testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) +> Void testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -63,25 +63,35 @@ Fake endpoint for testing various parameters 假端點 偽のエンドポイン ### Example ```java // Import classes: +//import io.swagger.client.ApiClient; //import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; //import io.swagger.client.api.FakeApi; +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure HTTP basic authorization: http_basic_test +HttpBasicAuth http_basic_test = (HttpBasicAuth) defaultClient.getAuthentication("http_basic_test"); +http_basic_test.setUsername("YOUR USERNAME"); +http_basic_test.setPassword("YOUR PASSWORD"); FakeApi apiInstance = new FakeApi(); BigDecimal number = new BigDecimal(); // BigDecimal | None Double _double = 3.4D; // Double | None -String string = "string_example"; // String | None +String patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None byte[] _byte = B; // byte[] | None Integer integer = 56; // Integer | None Integer int32 = 56; // Integer | None Long int64 = 789L; // Long | None Float _float = 3.4F; // Float | None +String string = "string_example"; // String | None byte[] binary = B; // byte[] | None LocalDate date = new LocalDate(); // LocalDate | None DateTime dateTime = new DateTime(); // DateTime | None String password = "password_example"; // String | None try { - Void result = apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + Void result = apiInstance.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password); System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling FakeApi#testEndpointParameters"); @@ -95,12 +105,13 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **number** | **BigDecimal**| None | **_double** | **Double**| None | - **string** | **String**| None | + **patternWithoutDelimiter** | **String**| None | **_byte** | **byte[]**| None | **integer** | **Integer**| None | [optional] **int32** | **Integer**| None | [optional] **int64** | **Long**| None | [optional] **_float** | **Float**| None | [optional] + **string** | **String**| None | [optional] **binary** | **byte[]**| None | [optional] **date** | **LocalDate**| None | [optional] **dateTime** | **DateTime**| None | [optional] @@ -112,18 +123,18 @@ Name | Type | Description | Notes ### Authorization -No authorization required +[http_basic_test](../README.md#http_basic_test) ### HTTP request headers - **Content-Type**: application/xml; charset=utf-8, application/json; charset=utf-8 - **Accept**: application/xml; charset=utf-8, application/json; charset=utf-8 - -# **testEnumQueryParameters** -> Void testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble) + +# **testEnumParameters** +> Void testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble) -To test enum query parameters +To test enum parameters ### Example ```java @@ -133,14 +144,19 @@ To test enum query parameters FakeApi apiInstance = new FakeApi(); +List enumFormStringArray = Arrays.asList("enumFormStringArray_example"); // List | Form parameter enum test (string array) +String enumFormString = "-efg"; // String | Form parameter enum test (string) +List enumHeaderStringArray = Arrays.asList("enumHeaderStringArray_example"); // List | Header parameter enum test (string array) +String enumHeaderString = "-efg"; // String | Header parameter enum test (string) +List enumQueryStringArray = Arrays.asList("enumQueryStringArray_example"); // List | Query parameter enum test (string array) String enumQueryString = "-efg"; // String | Query parameter enum test (string) BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | Query parameter enum test (double) Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) try { - Void result = apiInstance.testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); + Void result = apiInstance.testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); System.out.println(result); } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testEnumQueryParameters"); + System.err.println("Exception when calling FakeApi#testEnumParameters"); e.printStackTrace(); } ``` @@ -149,6 +165,11 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- + **enumFormStringArray** | [**List<String>**](String.md)| Form parameter enum test (string array) | [optional] [enum: >, $] + **enumFormString** | **String**| Form parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + **enumHeaderStringArray** | [**List<String>**](String.md)| Header parameter enum test (string array) | [optional] [enum: >, $] + **enumHeaderString** | **String**| Header parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + **enumQueryStringArray** | [**List<String>**](String.md)| Query parameter enum test (string array) | [optional] [enum: >, $] **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] **enumQueryInteger** | **BigDecimal**| Query parameter enum test (double) | [optional] **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] diff --git a/samples/client/petstore/java/retrofit2rx/docs/Model200Response.md b/samples/client/petstore/java/retrofit2rx/docs/Model200Response.md index b47618b28cc..5b3a9a0e46d 100644 --- a/samples/client/petstore/java/retrofit2rx/docs/Model200Response.md +++ b/samples/client/petstore/java/retrofit2rx/docs/Model200Response.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **Integer** | | [optional] -**PropertyClass** | **String** | | [optional] +**propertyClass** | **String** | | [optional] diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java index 43eaeba87f4..cc82b88c425 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java @@ -55,6 +55,8 @@ public ApiClient(String[] authNames) { Interceptor auth; if (authName == "api_key") { auth = new ApiKeyAuth("header", "api_key"); + } else if (authName == "http_basic_test") { + auth = new HttpBasicAuth(); } else if (authName == "petstore_auth") { auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); } else { diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/StringUtil.java index fdcef6b1010..31140c76df4 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/StringUtil.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java index aadcdfdee76..2bf3ea9e839 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java @@ -10,8 +10,8 @@ import io.swagger.client.model.Client; import org.joda.time.LocalDate; -import org.joda.time.DateTime; import java.math.BigDecimal; +import org.joda.time.DateTime; import java.util.ArrayList; import java.util.HashMap; @@ -36,12 +36,13 @@ Observable testClientModel( * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * @param number None (required) * @param _double None (required) - * @param string None (required) + * @param patternWithoutDelimiter None (required) * @param _byte None (required) * @param integer None (optional) * @param int32 None (optional) * @param int64 None (optional) * @param _float None (optional) + * @param string None (optional) * @param binary None (optional) * @param date None (optional) * @param dateTime None (optional) @@ -52,12 +53,17 @@ Observable testClientModel( @FormUrlEncoded @POST("fake") Observable testEndpointParameters( - @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password + @Field("number") BigDecimal number, @Field("double") Double _double, @Field("pattern_without_delimiter") String patternWithoutDelimiter, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("string") String string, @Field("binary") byte[] binary, @Field("date") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password ); /** - * To test enum query parameters + * To test enum parameters * + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) * @param enumQueryInteger Query parameter enum test (double) (optional) * @param enumQueryDouble Query parameter enum test (double) (optional) @@ -66,8 +72,8 @@ Observable testEndpointParameters( @FormUrlEncoded @GET("fake") - Observable testEnumQueryParameters( - @Field("enum_query_string") String enumQueryString, @Query("enum_query_integer") BigDecimal enumQueryInteger, @Field("enum_query_double") Double enumQueryDouble + Observable testEnumParameters( + @Field("enum_form_string_array") List enumFormStringArray, @Field("enum_form_string") String enumFormString, @Header("enum_header_string_array") List enumHeaderStringArray, @Header("enum_header_string") String enumHeaderString, @Query("enum_query_string_array") CSVParams enumQueryStringArray, @Query("enum_query_string") String enumQueryString, @Query("enum_query_integer") BigDecimal enumQueryInteger, @Field("enum_query_double") Double enumQueryDouble ); } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java index 94e2161d5a4..836de6f11fa 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java @@ -9,8 +9,8 @@ import okhttp3.RequestBody; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.ModelApiResponse; +import java.io.File; import java.util.ArrayList; import java.util.HashMap; diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthFlow.java index 50d5260cfd9..18c25738e0f 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 7b1955e7601..d20b1402ce2 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Animal.java index ba3806dc875..9b1ff3df1c5 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Animal.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AnimalFarm.java index b54adb09d7b..563476ccb3d 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 81ba53bf660..4c2fa22800f 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index e4860d0f095..3c7d74dc3b5 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayTest.java index 22fb331103f..7e08b24fa6e 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Cat.java index 985342803a8..9c5cb39f648 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Cat.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Category.java index 2178a866f62..44e76030eff 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Category.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Client.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Client.java index 6eac2866846..54a54647918 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Client.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Client.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Dog.java index c59b3783d18..880c159616c 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Dog.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumArrays.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumArrays.java index aef9b16ef15..c5096738755 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumArrays.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumArrays.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumClass.java index b53ad4fa8f6..7862a8b8952 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumClass.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumTest.java index 9aad1223215..83896fbd849 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/FormatTest.java index 91109681509..a05f1d5c811 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/FormatTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java index d77fc7ac36b..e53b1a0d8be 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MapTest.java index 0ab3cb990e0..e7d394ed035 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MapTest.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 192175a03af..887ba516d72 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Model200Response.java index d8da58aca9c..980bc83e869 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Model200Response.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -41,7 +41,7 @@ public class Model200Response { private Integer name = null; @SerializedName("class") - private String PropertyClass = null; + private String propertyClass = null; public Model200Response name(Integer name) { this.name = name; @@ -61,22 +61,22 @@ public void setName(Integer name) { this.name = name; } - public Model200Response PropertyClass(String PropertyClass) { - this.PropertyClass = PropertyClass; + public Model200Response propertyClass(String propertyClass) { + this.propertyClass = propertyClass; return this; } /** - * Get PropertyClass - * @return PropertyClass + * Get propertyClass + * @return propertyClass **/ @ApiModelProperty(example = "null", value = "") public String getPropertyClass() { - return PropertyClass; + return propertyClass; } - public void setPropertyClass(String PropertyClass) { - this.PropertyClass = PropertyClass; + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; } @@ -90,12 +90,12 @@ public boolean equals(java.lang.Object o) { } Model200Response _200Response = (Model200Response) o; return Objects.equals(this.name, _200Response.name) && - Objects.equals(this.PropertyClass, _200Response.PropertyClass); + Objects.equals(this.propertyClass, _200Response.propertyClass); } @Override public int hashCode() { - return Objects.hash(name, PropertyClass); + return Objects.hash(name, propertyClass); } @Override @@ -104,7 +104,7 @@ public String toString() { sb.append("class Model200Response {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" PropertyClass: ").append(toIndentedString(PropertyClass)).append("\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ModelApiResponse.java index 2a823298323..f9c162a7934 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ModelReturn.java index 024a9c0df1c..bbe7780055c 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ModelReturn.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Name.java index 318a2ddd50e..d51354ceffa 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Name.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/NumberOnly.java index 9b9ca048dfb..2b1817300a9 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/NumberOnly.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/NumberOnly.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Order.java index 90cfd2f3892..f52e7bd5db4 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Order.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Pet.java index 5aad989d5b1..06443e56915 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Pet.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index 13b729bb94d..75dbc55f9f5 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/SpecialModelName.java index b46b8367a01..9744ad08268 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Tag.java index e56eb535d1e..9eef0141c71 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Tag.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/User.java index 6c1ed6ceacc..73584bfdccb 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/User.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * From 11ae12b09d0505d2820bc58720b75a2aeff69356 Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 2 Sep 2016 00:25:07 +0800 Subject: [PATCH 319/470] [Scalatra] replace {} with : in scalatra path (#3694) * replace {} with : in scalatra path * remove unused var in scalatra code gen --- .../languages/ScalatraServerCodegen.java | 22 +++ .../src/main/resources/scalatra/api.mustache | 2 +- .../src/main/scala/ScalatraBootstrap.scala | 4 +- .../scalatra/src/main/scala/ServletApp.scala | 24 +-- .../scala/com/wordnik/client/api/PetApi.scala | 167 +++++++++++------- .../com/wordnik/client/api/StoreApi.scala | 54 +++--- .../com/wordnik/client/api/UserApi.scala | 118 ++++++++----- .../wordnik/client/model/ApiResponse.scala | 9 +- .../com/wordnik/client/model/Category.scala | 7 +- .../com/wordnik/client/model/Order.scala | 14 +- .../scala/com/wordnik/client/model/Pet.scala | 15 +- .../scala/com/wordnik/client/model/Tag.scala | 7 +- .../scala/com/wordnik/client/model/User.scala | 20 ++- 13 files changed, 282 insertions(+), 181 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java index 63f43dfd383..3672ddd9857 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java @@ -4,6 +4,7 @@ import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenOperation; +import io.swagger.codegen.CodegenParameter; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; @@ -161,8 +162,29 @@ public Map postProcessOperations(Map objs) { Map operations = (Map) objs.get("operations"); List operationList = (List) operations.get("operation"); for (CodegenOperation op : operationList) { + // force http method to lower case op.httpMethod = op.httpMethod.toLowerCase(); + + String[] items = op.path.split("/", -1); + String scalaPath = ""; + int pathParamIndex = 0; + + for (int i = 0; i < items.length; ++i) { + if (items[i].matches("^\\{(.*)\\}$")) { // wrap in {} + scalaPath = scalaPath + ":" + items[i].replace("{", "").replace("}", ""); + pathParamIndex++; + } else { + scalaPath = scalaPath + items[i]; + } + + if (i != items.length -1) { + scalaPath = scalaPath + "/"; + } + } + + op.vendorExtensions.put("x-scalatra-path", scalaPath); } + return objs; } diff --git a/modules/swagger-codegen/src/main/resources/scalatra/api.mustache b/modules/swagger-codegen/src/main/resources/scalatra/api.mustache index a5e281f6280..7e0641396c7 100644 --- a/modules/swagger-codegen/src/main/resources/scalatra/api.mustache +++ b/modules/swagger-codegen/src/main/resources/scalatra/api.mustache @@ -38,7 +38,7 @@ class {{classname}} (implicit val swagger: Swagger) extends ScalatraServlet parameters({{#allParams}}{{>queryParam}}{{>pathParam}}{{>bodyParam}}{{>formParam}}{{>headerParam}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) ) - {{httpMethod}}("{{path}}",operation({{nickname}}Operation)) { + {{httpMethod}}("{{{vendorExtensions.x-scalatra-path}}}",operation({{nickname}}Operation)) { {{#allParams}} {{#isFile}}val {{paramName}} = fileParams("{{paramName}}"){{/isFile}} {{^isFile}}{{#isPathParam}} diff --git a/samples/server/petstore/scalatra/src/main/scala/ScalatraBootstrap.scala b/samples/server/petstore/scalatra/src/main/scala/ScalatraBootstrap.scala index 1f984f994b2..385bf47207c 100644 --- a/samples/server/petstore/scalatra/src/main/scala/ScalatraBootstrap.scala +++ b/samples/server/petstore/scalatra/src/main/scala/ScalatraBootstrap.scala @@ -24,7 +24,7 @@ import com.wordnik.client.api._ import akka.actor.ActorSystem -import io.swagger.app.{ ResourcesApp, SwaggerApp } +import io.swagger.app.{ResourcesApp, SwaggerApp} import javax.servlet.ServletContext import org.scalatra.LifeCycle @@ -37,7 +37,7 @@ class ScalatraBootstrap extends LifeCycle { context mount (new PetApi, "/v2/Pet/*") context mount (new StoreApi, "/v2/Store/*") context mount (new UserApi, "/v2/User/*") - + context mount (new ResourcesApp, "/api-docs/*") } catch { case e: Throwable => e.printStackTrace() diff --git a/samples/server/petstore/scalatra/src/main/scala/ServletApp.scala b/samples/server/petstore/scalatra/src/main/scala/ServletApp.scala index 83b8e784c47..35c8a3a84d0 100644 --- a/samples/server/petstore/scalatra/src/main/scala/ServletApp.scala +++ b/samples/server/petstore/scalatra/src/main/scala/ServletApp.scala @@ -27,26 +27,26 @@ package io.swagger.app import _root_.akka.actor.ActorSystem import org.scalatra.swagger.{ ApiInfo, SwaggerWithAuth, Swagger } -import org.scalatra.swagger.{ JacksonSwaggerBase, Swagger } +import org.scalatra.swagger.{JacksonSwaggerBase, Swagger} import org.scalatra.ScalatraServlet -import org.json4s.{ DefaultFormats, Formats } +import org.json4s.{DefaultFormats, Formats} class ResourcesApp(implicit protected val system: ActorSystem, val swagger: SwaggerApp) - extends ScalatraServlet with JacksonSwaggerBase { + extends ScalatraServlet with JacksonSwaggerBase { before() { response.headers += ("Access-Control-Allow-Origin" -> "*") } protected def buildFullUrl(path: String) = if (path.startsWith("http")) path else { - val port = request.getServerPort - val h = request.getServerName - val prot = if (port == 443) "https" else "http" - val (proto, host) = if (port != 80 && port != 443) ("http", h + ":" + port.toString) else (prot, h) - "%s://%s%s%s".format( - proto, - host, - request.getContextPath, - path) + val port = request.getServerPort + val h = request.getServerName + val prot = if (port == 443) "https" else "http" + val (proto, host) = if (port != 80 && port != 443) ("http", h+":"+port.toString) else (prot, h) + "%s://%s%s%s".format( + proto, + host, + request.getContextPath, + path) } } diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala index 73ac60b6cd3..9995f630123 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala @@ -25,8 +25,8 @@ package com.wordnik.client.api import com.wordnik.client.model.Pet -import java.io.File import com.wordnik.client.model.ApiResponse +import java.io.File import java.io.File @@ -35,11 +35,11 @@ import org.scalatra.swagger._ import org.json4s._ import org.json4s.JsonDSL._ import org.scalatra.json.{ JValueResult, JacksonJsonSupport } -import org.scalatra.servlet.{ FileUploadSupport, MultipartConfig, SizeConstraintExceededException } +import org.scalatra.servlet.{FileUploadSupport, MultipartConfig, SizeConstraintExceededException} import scala.collection.JavaConverters._ -class PetApi(implicit val swagger: Swagger) extends ScalatraServlet +class PetApi (implicit val swagger: Swagger) extends ScalatraServlet with FileUploadSupport with JacksonJsonSupport with SwaggerSupport { @@ -52,133 +52,164 @@ class PetApi(implicit val swagger: Swagger) extends ScalatraServlet contentType = formats("json") response.headers += ("Access-Control-Allow-Origin" -> "*") } + val addPetOperation = (apiOperation[Unit]("addPet") - summary "Add a new pet to the store" - parameters (bodyParam[Pet]("body").description("")) + summary "Add a new pet to the store" + parameters(bodyParam[Pet]("body").description("")) ) - post("/pet", operation(addPetOperation)) { - - val body = parsedBody.extract[Pet] + post("/pet",operation(addPetOperation)) { + + + val body = parsedBody.extract[Pet] println("body: " + body) } + + val deletePetOperation = (apiOperation[Unit]("deletePet") - summary "Deletes a pet" - parameters (pathParam[Long]("petId").description(""), headerParam[String]("apiKey").description("").optional) + summary "Deletes a pet" + parameters(pathParam[Long]("petId").description(""), headerParam[String]("apiKey").description("").optional) ) - delete("/pet/{petId}", operation(deletePetOperation)) { - - val petId = params.getOrElse("petId", halt(400)) - + delete("/pet/:petId",operation(deletePetOperation)) { + + + val petId = params.getOrElse("petId", halt(400)) + println("petId: " + petId) - - val apiKey = request.getHeader("apiKey") + + + val apiKey = request.getHeader("apiKey") println("apiKey: " + apiKey) } + + val findPetsByStatusOperation = (apiOperation[List[Pet]]("findPetsByStatus") - summary "Finds Pets by status" - parameters (queryParam[List[String]]("status").description("")) + summary "Finds Pets by status" + parameters(queryParam[List[String]]("status").description("")) ) - get("/pet/findByStatus", operation(findPetsByStatusOperation)) { - - val statusString = params.getAs[String]("status") - val status = if ("multi".equals("default")) { - statusString match { - case Some(str) => str.split(",") - case None => List() + get("/pet/findByStatus",operation(findPetsByStatusOperation)) { + + + val statusString = params.getAs[String]("status") + val status = if("csv".equals("default")) { + statusString match { + case Some(str) => str.split(",") + case None => List() + } } - } else - List() + else + List() + println("status: " + status) } + + val findPetsByTagsOperation = (apiOperation[List[Pet]]("findPetsByTags") - summary "Finds Pets by tags" - parameters (queryParam[List[String]]("tags").description("")) + summary "Finds Pets by tags" + parameters(queryParam[List[String]]("tags").description("")) ) - get("/pet/findByTags", operation(findPetsByTagsOperation)) { - - val tagsString = params.getAs[String]("tags") - val tags = if ("multi".equals("default")) { - tagsString match { - case Some(str) => str.split(",") - case None => List() + get("/pet/findByTags",operation(findPetsByTagsOperation)) { + + + val tagsString = params.getAs[String]("tags") + val tags = if("csv".equals("default")) { + tagsString match { + case Some(str) => str.split(",") + case None => List() + } } - } else - List() + else + List() + println("tags: " + tags) } + + val getPetByIdOperation = (apiOperation[Pet]("getPetById") - summary "Find pet by ID" - parameters (pathParam[Long]("petId").description("")) + summary "Find pet by ID" + parameters(pathParam[Long]("petId").description("")) ) - get("/pet/{petId}", operation(getPetByIdOperation)) { - - val petId = params.getOrElse("petId", halt(400)) - + get("/pet/:petId",operation(getPetByIdOperation)) { + + + val petId = params.getOrElse("petId", halt(400)) + println("petId: " + petId) } + + val updatePetOperation = (apiOperation[Unit]("updatePet") - summary "Update an existing pet" - parameters (bodyParam[Pet]("body").description("")) + summary "Update an existing pet" + parameters(bodyParam[Pet]("body").description("")) ) - put("/pet", operation(updatePetOperation)) { - - val body = parsedBody.extract[Pet] + put("/pet",operation(updatePetOperation)) { + + + val body = parsedBody.extract[Pet] println("body: " + body) } + + val updatePetWithFormOperation = (apiOperation[Unit]("updatePetWithForm") - summary "Updates a pet in the store with form data" - parameters (pathParam[Long]("petId").description(""), formParam[String]("name").description("").optional, formParam[String]("status").description("").optional) + summary "Updates a pet in the store with form data" + parameters(pathParam[Long]("petId").description(""), formParam[String]("name").description("").optional, formParam[String]("status").description("").optional) ) - post("/pet/{petId}", operation(updatePetWithFormOperation)) { - - val petId = params.getOrElse("petId", halt(400)) - + post("/pet/:petId",operation(updatePetWithFormOperation)) { + + + val petId = params.getOrElse("petId", halt(400)) + println("petId: " + petId) - - val name = params.getAs[String]("name") + + + val name = params.getAs[String]("name") println("name: " + name) - - val status = params.getAs[String]("status") + + + val status = params.getAs[String]("status") println("status: " + status) } + + val uploadFileOperation = (apiOperation[ApiResponse]("uploadFile") - summary "uploads an image" - parameters (pathParam[Long]("petId").description(""), formParam[String]("additionalMetadata").description("").optional, formParam[File]("file").description("").optional) + summary "uploads an image" + parameters(pathParam[Long]("petId").description(""), formParam[String]("additionalMetadata").description("").optional, formParam[File]("file").description("").optional) ) - post("/pet/{petId}/uploadImage", operation(uploadFileOperation)) { - - val petId = params.getOrElse("petId", halt(400)) - + post("/pet/:petId/uploadImage",operation(uploadFileOperation)) { + + + val petId = params.getOrElse("petId", halt(400)) + println("petId: " + petId) - - val additionalMetadata = params.getAs[String]("additionalMetadata") + + + val additionalMetadata = params.getAs[String]("additionalMetadata") println("additionalMetadata: " + additionalMetadata) val file = fileParams("file") - println("file: " + file) + println("file: " + file) } } diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/StoreApi.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/StoreApi.scala index c2ac0af6e8b..3a6d8e8e9bc 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/StoreApi.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/StoreApi.scala @@ -33,11 +33,11 @@ import org.scalatra.swagger._ import org.json4s._ import org.json4s.JsonDSL._ import org.scalatra.json.{ JValueResult, JacksonJsonSupport } -import org.scalatra.servlet.{ FileUploadSupport, MultipartConfig, SizeConstraintExceededException } +import org.scalatra.servlet.{FileUploadSupport, MultipartConfig, SizeConstraintExceededException} import scala.collection.JavaConverters._ -class StoreApi(implicit val swagger: Swagger) extends ScalatraServlet +class StoreApi (implicit val swagger: Swagger) extends ScalatraServlet with FileUploadSupport with JacksonJsonSupport with SwaggerSupport { @@ -50,47 +50,57 @@ class StoreApi(implicit val swagger: Swagger) extends ScalatraServlet contentType = formats("json") response.headers += ("Access-Control-Allow-Origin" -> "*") } + val deleteOrderOperation = (apiOperation[Unit]("deleteOrder") - summary "Delete purchase order by ID" - parameters (pathParam[Long]("orderId").description("")) + summary "Delete purchase order by ID" + parameters(pathParam[String]("orderId").description("")) ) - delete("/store/order/{orderId}", operation(deleteOrderOperation)) { - - val orderId = params.getOrElse("orderId", halt(400)) - + delete("/store/order/:orderId",operation(deleteOrderOperation)) { + + + val orderId = params.getOrElse("orderId", halt(400)) + println("orderId: " + orderId) } + + val getInventoryOperation = (apiOperation[Map[String, Int]]("getInventory") - summary "Returns pet inventories by status" - parameters () + summary "Returns pet inventories by status" + parameters() ) - get("/store/inventory", operation(getInventoryOperation)) { + get("/store/inventory",operation(getInventoryOperation)) { } + + val getOrderByIdOperation = (apiOperation[Order]("getOrderById") - summary "Find purchase order by ID" - parameters (pathParam[Long]("orderId").description("")) + summary "Find purchase order by ID" + parameters(pathParam[Long]("orderId").description("")) ) - get("/store/order/{orderId}", operation(getOrderByIdOperation)) { - - val orderId = params.getOrElse("orderId", halt(400)) - + get("/store/order/:orderId",operation(getOrderByIdOperation)) { + + + val orderId = params.getOrElse("orderId", halt(400)) + println("orderId: " + orderId) } + + val placeOrderOperation = (apiOperation[Order]("placeOrder") - summary "Place an order for a pet" - parameters (bodyParam[Order]("body").description("")) + summary "Place an order for a pet" + parameters(bodyParam[Order]("body").description("")) ) - post("/store/order", operation(placeOrderOperation)) { - - val body = parsedBody.extract[Order] + post("/store/order",operation(placeOrderOperation)) { + + + val body = parsedBody.extract[Order] println("body: " + body) } diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/UserApi.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/UserApi.scala index c0dadc2375f..4b00593af62 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/UserApi.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/UserApi.scala @@ -33,11 +33,11 @@ import org.scalatra.swagger._ import org.json4s._ import org.json4s.JsonDSL._ import org.scalatra.json.{ JValueResult, JacksonJsonSupport } -import org.scalatra.servlet.{ FileUploadSupport, MultipartConfig, SizeConstraintExceededException } +import org.scalatra.servlet.{FileUploadSupport, MultipartConfig, SizeConstraintExceededException} import scala.collection.JavaConverters._ -class UserApi(implicit val swagger: Swagger) extends ScalatraServlet +class UserApi (implicit val swagger: Swagger) extends ScalatraServlet with FileUploadSupport with JacksonJsonSupport with SwaggerSupport { @@ -50,103 +50,127 @@ class UserApi(implicit val swagger: Swagger) extends ScalatraServlet contentType = formats("json") response.headers += ("Access-Control-Allow-Origin" -> "*") } + val createUserOperation = (apiOperation[Unit]("createUser") - summary "Create user" - parameters (bodyParam[User]("body").description("")) + summary "Create user" + parameters(bodyParam[User]("body").description("")) ) - post("/user", operation(createUserOperation)) { - - val body = parsedBody.extract[User] + post("/user",operation(createUserOperation)) { + + + val body = parsedBody.extract[User] println("body: " + body) } + + val createUsersWithArrayInputOperation = (apiOperation[Unit]("createUsersWithArrayInput") - summary "Creates list of users with given input array" - parameters (bodyParam[List[User]]("body").description("")) + summary "Creates list of users with given input array" + parameters(bodyParam[List[User]]("body").description("")) ) - post("/user/createWithArray", operation(createUsersWithArrayInputOperation)) { - - val body = parsedBody.extract[List[User]] + post("/user/createWithArray",operation(createUsersWithArrayInputOperation)) { + + + val body = parsedBody.extract[List[User]] println("body: " + body) } + + val createUsersWithListInputOperation = (apiOperation[Unit]("createUsersWithListInput") - summary "Creates list of users with given input array" - parameters (bodyParam[List[User]]("body").description("")) + summary "Creates list of users with given input array" + parameters(bodyParam[List[User]]("body").description("")) ) - post("/user/createWithList", operation(createUsersWithListInputOperation)) { - - val body = parsedBody.extract[List[User]] + post("/user/createWithList",operation(createUsersWithListInputOperation)) { + + + val body = parsedBody.extract[List[User]] println("body: " + body) } + + val deleteUserOperation = (apiOperation[Unit]("deleteUser") - summary "Delete user" - parameters (pathParam[String]("username").description("")) + summary "Delete user" + parameters(pathParam[String]("username").description("")) ) - delete("/user/{username}", operation(deleteUserOperation)) { - - val username = params.getOrElse("username", halt(400)) - + delete("/user/:username",operation(deleteUserOperation)) { + + + val username = params.getOrElse("username", halt(400)) + println("username: " + username) } + + val getUserByNameOperation = (apiOperation[User]("getUserByName") - summary "Get user by user name" - parameters (pathParam[String]("username").description("")) + summary "Get user by user name" + parameters(pathParam[String]("username").description("")) ) - get("/user/{username}", operation(getUserByNameOperation)) { - - val username = params.getOrElse("username", halt(400)) - + get("/user/:username",operation(getUserByNameOperation)) { + + + val username = params.getOrElse("username", halt(400)) + println("username: " + username) } + + val loginUserOperation = (apiOperation[String]("loginUser") - summary "Logs user into the system" - parameters (queryParam[String]("username").description(""), queryParam[String]("password").description("")) + summary "Logs user into the system" + parameters(queryParam[String]("username").description(""), queryParam[String]("password").description("")) ) - get("/user/login", operation(loginUserOperation)) { - - val username = params.getAs[String]("username") + get("/user/login",operation(loginUserOperation)) { + + + val username = params.getAs[String]("username") println("username: " + username) - - val password = params.getAs[String]("password") + + + val password = params.getAs[String]("password") println("password: " + password) } + + val logoutUserOperation = (apiOperation[Unit]("logoutUser") - summary "Logs out current logged in user session" - parameters () + summary "Logs out current logged in user session" + parameters() ) - get("/user/logout", operation(logoutUserOperation)) { + get("/user/logout",operation(logoutUserOperation)) { } + + val updateUserOperation = (apiOperation[Unit]("updateUser") - summary "Updated user" - parameters (pathParam[String]("username").description(""), bodyParam[User]("body").description("")) + summary "Updated user" + parameters(pathParam[String]("username").description(""), bodyParam[User]("body").description("")) ) - put("/user/{username}", operation(updateUserOperation)) { - - val username = params.getOrElse("username", halt(400)) - + put("/user/:username",operation(updateUserOperation)) { + + + val username = params.getOrElse("username", halt(400)) + println("username: " + username) - - val body = parsedBody.extract[User] + + + val body = parsedBody.extract[User] println("body: " + body) } diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/ApiResponse.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/ApiResponse.scala index 5388c99eca8..c09ed4217e7 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/ApiResponse.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/ApiResponse.scala @@ -24,7 +24,10 @@ package com.wordnik.client.model -case class ApiResponse( + + +case class ApiResponse ( code: Option[Int], - _type: Option[String], - message: Option[String]) +_type: Option[String], +message: Option[String] +) diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Category.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Category.scala index 0173c137595..4bdadfbbe5c 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Category.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Category.scala @@ -24,6 +24,9 @@ package com.wordnik.client.model -case class Category( + + +case class Category ( id: Option[Long], - name: Option[String]) +name: Option[String] +) diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Order.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Order.scala index eda2b851860..6f399b0d1c3 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Order.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Order.scala @@ -26,10 +26,12 @@ package com.wordnik.client.model import java.util.Date -case class Order( + +case class Order ( id: Option[Long], - petId: Option[Long], - quantity: Option[Int], - shipDate: Option[Date], - status: Option[String], // Order Status - complete: Option[Boolean]) +petId: Option[Long], +quantity: Option[Int], +shipDate: Option[Date], +status: Option[String], // Order Status +complete: Option[Boolean] +) diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Pet.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Pet.scala index d9f123eafc3..01aa08e73ce 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Pet.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Pet.scala @@ -27,11 +27,12 @@ package com.wordnik.client.model import com.wordnik.client.model.Category import com.wordnik.client.model.Tag -case class Pet( + +case class Pet ( id: Option[Long], - category: Option[Category], - name: String, - photoUrls: List[String], - tags: Option[List[Tag]], - status: Option[String] // pet status in the store - ) +category: Option[Category], +name: String, +photoUrls: List[String], +tags: Option[List[Tag]], +status: Option[String] // pet status in the store +) diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Tag.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Tag.scala index 1b6ccd3e2ca..a3d34e8d557 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Tag.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Tag.scala @@ -24,6 +24,9 @@ package com.wordnik.client.model -case class Tag( + + +case class Tag ( id: Option[Long], - name: Option[String]) +name: Option[String] +) diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/User.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/User.scala index 5115e77c528..ff792d91371 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/User.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/User.scala @@ -24,13 +24,15 @@ package com.wordnik.client.model -case class User( + + +case class User ( id: Option[Long], - username: Option[String], - firstName: Option[String], - lastName: Option[String], - email: Option[String], - password: Option[String], - phone: Option[String], - userStatus: Option[Int] // User Status - ) +username: Option[String], +firstName: Option[String], +lastName: Option[String], +email: Option[String], +password: Option[String], +phone: Option[String], +userStatus: Option[Int] // User Status +) From 6bb0ea2e8a285af73db81b8a5c983cbd9efdb5ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Thu, 1 Sep 2016 20:45:52 +0300 Subject: [PATCH 320/470] ruby: Fix syntax error when pattern contains a single quote --- modules/swagger-codegen/src/main/resources/ruby/api.mustache | 2 +- samples/client/petstore/ruby/lib/petstore/api/fake_api.rb | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index ca3e2c153cb..e69765707d2 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -82,7 +82,7 @@ module {{moduleName}} {{/minimum}} {{#pattern}} if {{^required}}!opts[:'{{{paramName}}}'].nil? && {{/required}}{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}} !~ Regexp.new({{{pattern}}}) - fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, must conform to the pattern {{{pattern}}}.' + fail ArgumentError, "invalid value for '{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:\"{{{paramName}}}\"]{{/required}}' when calling {{classname}}.{{operationId}}, must conform to the pattern {{{pattern}}}." end {{/pattern}} diff --git a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb index b83b97d2db5..5a0398b6bc9 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb @@ -154,7 +154,7 @@ def test_endpoint_parameters_with_http_info(number, double, pattern_without_deli # verify the required parameter 'pattern_without_delimiter' is set fail ArgumentError, "Missing the required parameter 'pattern_without_delimiter' when calling FakeApi.test_endpoint_parameters" if pattern_without_delimiter.nil? if pattern_without_delimiter !~ Regexp.new(/^[A-Z].*/) - fail ArgumentError, 'invalid value for "pattern_without_delimiter" when calling FakeApi.test_endpoint_parameters, must conform to the pattern /^[A-Z].*/.' + fail ArgumentError, "invalid value for 'pattern_without_delimiter' when calling FakeApi.test_endpoint_parameters, must conform to the pattern /^[A-Z].*/." end # verify the required parameter 'byte' is set @@ -180,7 +180,7 @@ def test_endpoint_parameters_with_http_info(number, double, pattern_without_deli end if !opts[:'string'].nil? && opts[:'string'] !~ Regexp.new(/[a-z]/i) - fail ArgumentError, 'invalid value for "opts[:"string"]" when calling FakeApi.test_endpoint_parameters, must conform to the pattern /[a-z]/i.' + fail ArgumentError, "invalid value for 'opts[:\"string\"]' when calling FakeApi.test_endpoint_parameters, must conform to the pattern /[a-z]/i." end if !opts[:'password'].nil? && opts[:'password'].to_s.length > 64 From 2af822677f4ea80e4a31db9b7e838e4bd1f6bc9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Thu, 1 Sep 2016 18:52:00 +0300 Subject: [PATCH 321/470] php: Fix syntax error when pattern contains a single quote --- modules/swagger-codegen/src/main/resources/php/api.mustache | 2 +- .../src/main/resources/php/model_generic.mustache | 2 +- .../client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php | 4 ++-- .../petstore/php/SwaggerClient-php/lib/Model/FormatTest.php | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index f039a6baa17..61874746b39 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -150,7 +150,7 @@ use \{{invokerPackage}}\ObjectSerializer; {{/minimum}} {{#pattern}} if ({{^required}}!is_null(${{paramName}}) && {{/required}}!preg_match("{{{pattern}}}", ${{paramName}})) { - throw new \InvalidArgumentException('invalid value for "{{paramName}}" when calling {{classname}}.{{operationId}}, must conform to the pattern {{{pattern}}}.'); + throw new \InvalidArgumentException("invalid value for \"{{paramName}}\" when calling {{classname}}.{{operationId}}, must conform to the pattern {{{pattern}}}."); } {{/pattern}} diff --git a/modules/swagger-codegen/src/main/resources/php/model_generic.mustache b/modules/swagger-codegen/src/main/resources/php/model_generic.mustache index e66d4247430..8286a9b9f4d 100644 --- a/modules/swagger-codegen/src/main/resources/php/model_generic.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model_generic.mustache @@ -271,7 +271,7 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple {{/minimum}} {{#pattern}} if (!preg_match("{{{pattern}}}", ${{name}})) { - throw new \InvalidArgumentException('invalid value for ${{name}} when calling {{classname}}.{{operationId}}, must be conform to the pattern {{{pattern}}}.'); + throw new \InvalidArgumentException("invalid value for ${{name}} when calling {{classname}}.{{operationId}}, must conform to the pattern {{{pattern}}}."); } {{/pattern}} {{/hasValidation}} diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index 3635aebefe8..ccc4a5019fe 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -261,7 +261,7 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi throw new \InvalidArgumentException('Missing the required parameter $pattern_without_delimiter when calling testEndpointParameters'); } if (!preg_match("/^[A-Z].*_/", $pattern_without_delimiter)) { - throw new \InvalidArgumentException('invalid value for "pattern_without_delimiter" when calling FakeApi.testEndpointParameters, must conform to the pattern /^[A-Z].*_/.'); + throw new \InvalidArgumentException("invalid value for \"pattern_without_delimiter\" when calling FakeApi.testEndpointParameters, must conform to the pattern /^[A-Z].*_/."); } // verify the required parameter 'byte' is set @@ -287,7 +287,7 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi } if (!is_null($string) && !preg_match("/[a-z]/i", $string)) { - throw new \InvalidArgumentException('invalid value for "string" when calling FakeApi.testEndpointParameters, must conform to the pattern /[a-z]/i.'); + throw new \InvalidArgumentException("invalid value for \"string\" when calling FakeApi.testEndpointParameters, must conform to the pattern /[a-z]/i."); } if (!is_null($password) && (strlen($password) > 64)) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php index e61c0f33ce1..819f3a5013d 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php @@ -509,7 +509,7 @@ public function setString($string) { if (!preg_match("/[a-z]/i", $string)) { - throw new \InvalidArgumentException('invalid value for $string when calling FormatTest., must be conform to the pattern /[a-z]/i.'); + throw new \InvalidArgumentException("invalid value for $string when calling FormatTest., must conform to the pattern /[a-z]/i."); } $this->container['string'] = $string; From c43286c569c405a621aed1da3c1a7b7acfede202 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Fri, 2 Sep 2016 11:17:46 +0300 Subject: [PATCH 322/470] Python collection formatting fixes/support (#3697) * python: Rework form data collection formatting support * python: Add/fix support for query string collection formatting * python: Add/fix support for path collection formatting * python: Add/fix support for header collection formatting --- .../src/main/resources/python/api.mustache | 18 +++- .../main/resources/python/api_client.mustache | 95 ++++++++++--------- .../python/petstore_api/api_client.py | 95 ++++++++++--------- .../python/petstore_api/apis/fake_api.py | 53 +++++++---- .../python/petstore_api/apis/pet_api.py | 56 ++++++++--- .../python/petstore_api/apis/store_api.py | 24 ++++- .../python/petstore_api/apis/user_api.py | 48 ++++++++-- 7 files changed, 250 insertions(+), 139 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index b6b7ac400ec..9b355a32fba 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -140,30 +140,37 @@ class {{classname}}(object): {{/pattern}} {{/hasValidation}} {{/allParams}} + + collection_formats = {} + resource_path = '{{path}}'.replace('{format}', 'json') path_params = {} {{#pathParams}} if '{{paramName}}' in params: - path_params['{{baseName}}'] = params['{{paramName}}'] + path_params['{{baseName}}'] = params['{{paramName}}']{{#isListContainer}} + collection_formats['{{baseName}}'] = '{{collectionFormat}}'{{/isListContainer}} {{/pathParams}} query_params = {} {{#queryParams}} if '{{paramName}}' in params: - query_params['{{baseName}}'] = params['{{paramName}}'] + query_params['{{baseName}}'] = params['{{paramName}}']{{#isListContainer}} + collection_formats['{{baseName}}'] = '{{collectionFormat}}'{{/isListContainer}} {{/queryParams}} header_params = {} {{#headerParams}} if '{{paramName}}' in params: - header_params['{{baseName}}'] = params['{{paramName}}'] + header_params['{{baseName}}'] = params['{{paramName}}']{{#isListContainer}} + collection_formats['{{baseName}}'] = '{{collectionFormat}}'{{/isListContainer}} {{/headerParams}} form_params = [] local_var_files = {} {{#formParams}} if '{{paramName}}' in params: - {{#notFile}}form_params.extend(self.api_client.parameter_to_tuples('{{collectionFormat}}', '{{baseName}}', params['{{paramName}}'])){{/notFile}}{{#isFile}}local_var_files['{{baseName}}'] = params['{{paramName}}']{{/isFile}} + {{#notFile}}form_params.append(('{{baseName}}', params['{{paramName}}'])){{/notFile}}{{#isFile}}local_var_files['{{baseName}}'] = params['{{paramName}}']{{/isFile}}{{#isListContainer}} + collection_formats['{{baseName}}'] = '{{collectionFormat}}'{{/isListContainer}} {{/formParams}} body_params = None @@ -195,6 +202,7 @@ class {{classname}}(object): response_type={{#returnType}}'{{returnType}}'{{/returnType}}{{^returnType}}None{{/returnType}}, auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) {{/operation}} {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index 5abc2a360d9..3879b3cd706 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -95,7 +95,8 @@ class ApiClient(object): def __call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, - response_type=None, auth_settings=None, callback=None, _return_http_data_only=None): + response_type=None, auth_settings=None, callback=None, + _return_http_data_only=None, collection_formats=None): # header parameters header_params = header_params or {} @@ -104,25 +105,30 @@ class ApiClient(object): header_params['Cookie'] = self.cookie if header_params: header_params = self.sanitize_for_serialization(header_params) + header_params = dict(self.parameters_to_tuples(header_params, + collection_formats)) # path parameters if path_params: path_params = self.sanitize_for_serialization(path_params) - for k, v in iteritems(path_params): - replacement = quote(str(self.to_path_value(v))) - resource_path = resource_path.\ - replace('{' + k + '}', replacement) + path_params = self.parameters_to_tuples(path_params, + collection_formats) + for k, v in path_params: + resource_path = resource_path.replace( + '{%s}' % k, quote(str(v))) # query parameters if query_params: query_params = self.sanitize_for_serialization(query_params) - query_params = {k: self.to_path_value(v) - for k, v in iteritems(query_params)} + query_params = self.parameters_to_tuples(query_params, + collection_formats) # post parameters if post_params or files: post_params = self.prepare_post_parameters(post_params, files) post_params = self.sanitize_for_serialization(post_params) + post_params = self.parameters_to_tuples(post_params, + collection_formats) # auth setting self.update_params_for_auth(header_params, query_params, auth_settings) @@ -154,20 +160,6 @@ class ApiClient(object): return (deserialized_data) else: return (deserialized_data, response_data.status, response_data.getheaders()) - - def to_path_value(self, obj): - """ - Takes value and turn it into a string suitable for inclusion in - the path, by url-encoding. - - :param obj: object or string value. - - :return string: quoted value. - """ - if type(obj) == list: - return ','.join(obj) - else: - return str(obj) def sanitize_for_serialization(self, obj): """ @@ -281,7 +273,8 @@ class ApiClient(object): def call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, - response_type=None, auth_settings=None, callback=None, _return_http_data_only=None): + response_type=None, auth_settings=None, callback=None, + _return_http_data_only=None, collection_formats=None): """ Makes the HTTP request (synchronous) and return the deserialized data. To make an async request, define a function for callback. @@ -303,6 +296,8 @@ class ApiClient(object): If provide this parameter, the request will be called asynchronously. :param _return_http_data_only: response data without head status code and headers + :param collection_formats: dict of collection formats for path, query, + header, and post parameters. :return: If provide parameter callback, the request will be called asynchronously. @@ -314,7 +309,8 @@ class ApiClient(object): return self.__call_api(resource_path, method, path_params, query_params, header_params, body, post_params, files, - response_type, auth_settings, callback, _return_http_data_only) + response_type, auth_settings, callback, + _return_http_data_only, collection_formats) else: thread = threading.Thread(target=self.__call_api, args=(resource_path, method, @@ -322,7 +318,8 @@ class ApiClient(object): header_params, body, post_params, files, response_type, auth_settings, - callback, _return_http_data_only)) + callback, _return_http_data_only, + collection_formats)) thread.start() return thread @@ -374,30 +371,36 @@ class ApiClient(object): " `POST`, `PATCH`, `PUT` or `DELETE`." ) - def parameter_to_tuples(self, collection_format, name, value): + def parameters_to_tuples(self, params, collection_formats): """ - Get parameter as list of tuples according to collection format. + Get parameters as list of tuples, formatting collections. - :param str collection_format: Collection format - :param str name: Parameter name - :param value: Parameter value - :return: Parameter as list of tuples + :param params: Parameters as dict or list of two-tuples + :param dict collection_formats: Parameter collection formats + :return: Parameters as list of tuples, collections formatted """ - if isinstance(value, (list, tuple)): - if collection_format == "multi": - return [(name, v) for v in value] + new_params = [] + if collection_formats is None: + collection_formats = {} + for k, v in iteritems(params) if isinstance(params, dict) else params: + if k in collection_formats: + collection_format = collection_formats[k] + if collection_format == 'multi': + new_params.extend((k, value) for value in v) + else: + if collection_format == 'ssv': + delimiter = ' ' + elif collection_format == 'tsv': + delimiter = '\t' + elif collection_format == 'pipes': + delimiter = '|' + else: # csv is the default + delimiter = ',' + new_params.append( + (k, delimiter.join(str(value) for value in v))) else: - if collection_format == "ssv": - delimiter = " " - elif collection_format == "tsv": - delimiter = "\t" - elif collection_format == "pipes": - delimiter = "|" - else: # csv is the default - delimiter = "," - return [(name, delimiter.join(value))] - else: - return [(name, value)] + new_params.append((k, v)) + return new_params def prepare_post_parameters(self, post_params=None, files=None): """ @@ -466,7 +469,7 @@ class ApiClient(object): Updates header and query params based on authentication setting. :param headers: Header parameters dict to be updated. - :param querys: Query parameters dict to be updated. + :param querys: Query parameters tuple list to be updated. :param auth_settings: Authentication setting identifiers list. """ config = Configuration() @@ -482,7 +485,7 @@ class ApiClient(object): elif auth_setting['in'] == 'header': headers[auth_setting['key']] = auth_setting['value'] elif auth_setting['in'] == 'query': - querys[auth_setting['key']] = auth_setting['value'] + querys.append((auth_setting['key'], auth_setting['value'])) else: raise ValueError( 'Authentication token must be in `query` or `header`' diff --git a/samples/client/petstore/python/petstore_api/api_client.py b/samples/client/petstore/python/petstore_api/api_client.py index e36a115e0d6..2c8dc409135 100644 --- a/samples/client/petstore/python/petstore_api/api_client.py +++ b/samples/client/petstore/python/petstore_api/api_client.py @@ -95,7 +95,8 @@ def set_default_header(self, header_name, header_value): def __call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, - response_type=None, auth_settings=None, callback=None, _return_http_data_only=None): + response_type=None, auth_settings=None, callback=None, + _return_http_data_only=None, collection_formats=None): # header parameters header_params = header_params or {} @@ -104,25 +105,30 @@ def __call_api(self, resource_path, method, header_params['Cookie'] = self.cookie if header_params: header_params = self.sanitize_for_serialization(header_params) + header_params = dict(self.parameters_to_tuples(header_params, + collection_formats)) # path parameters if path_params: path_params = self.sanitize_for_serialization(path_params) - for k, v in iteritems(path_params): - replacement = quote(str(self.to_path_value(v))) - resource_path = resource_path.\ - replace('{' + k + '}', replacement) + path_params = self.parameters_to_tuples(path_params, + collection_formats) + for k, v in path_params: + resource_path = resource_path.replace( + '{%s}' % k, quote(str(v))) # query parameters if query_params: query_params = self.sanitize_for_serialization(query_params) - query_params = {k: self.to_path_value(v) - for k, v in iteritems(query_params)} + query_params = self.parameters_to_tuples(query_params, + collection_formats) # post parameters if post_params or files: post_params = self.prepare_post_parameters(post_params, files) post_params = self.sanitize_for_serialization(post_params) + post_params = self.parameters_to_tuples(post_params, + collection_formats) # auth setting self.update_params_for_auth(header_params, query_params, auth_settings) @@ -154,20 +160,6 @@ def __call_api(self, resource_path, method, return (deserialized_data) else: return (deserialized_data, response_data.status, response_data.getheaders()) - - def to_path_value(self, obj): - """ - Takes value and turn it into a string suitable for inclusion in - the path, by url-encoding. - - :param obj: object or string value. - - :return string: quoted value. - """ - if type(obj) == list: - return ','.join(obj) - else: - return str(obj) def sanitize_for_serialization(self, obj): """ @@ -281,7 +273,8 @@ def __deserialize(self, data, klass): def call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, - response_type=None, auth_settings=None, callback=None, _return_http_data_only=None): + response_type=None, auth_settings=None, callback=None, + _return_http_data_only=None, collection_formats=None): """ Makes the HTTP request (synchronous) and return the deserialized data. To make an async request, define a function for callback. @@ -303,6 +296,8 @@ def call_api(self, resource_path, method, If provide this parameter, the request will be called asynchronously. :param _return_http_data_only: response data without head status code and headers + :param collection_formats: dict of collection formats for path, query, + header, and post parameters. :return: If provide parameter callback, the request will be called asynchronously. @@ -314,7 +309,8 @@ def call_api(self, resource_path, method, return self.__call_api(resource_path, method, path_params, query_params, header_params, body, post_params, files, - response_type, auth_settings, callback, _return_http_data_only) + response_type, auth_settings, callback, + _return_http_data_only, collection_formats) else: thread = threading.Thread(target=self.__call_api, args=(resource_path, method, @@ -322,7 +318,8 @@ def call_api(self, resource_path, method, header_params, body, post_params, files, response_type, auth_settings, - callback, _return_http_data_only)) + callback, _return_http_data_only, + collection_formats)) thread.start() return thread @@ -374,30 +371,36 @@ def request(self, method, url, query_params=None, headers=None, " `POST`, `PATCH`, `PUT` or `DELETE`." ) - def parameter_to_tuples(self, collection_format, name, value): + def parameters_to_tuples(self, params, collection_formats): """ - Get parameter as list of tuples according to collection format. + Get parameters as list of tuples, formatting collections. - :param str collection_format: Collection format - :param str name: Parameter name - :param value: Parameter value - :return: Parameter as list of tuples + :param params: Parameters as dict or list of two-tuples + :param dict collection_formats: Parameter collection formats + :return: Parameters as list of tuples, collections formatted """ - if isinstance(value, (list, tuple)): - if collection_format == "multi": - return [(name, v) for v in value] + new_params = [] + if collection_formats is None: + collection_formats = {} + for k, v in iteritems(params) if isinstance(params, dict) else params: + if k in collection_formats: + collection_format = collection_formats[k] + if collection_format == 'multi': + new_params.extend((k, value) for value in v) + else: + if collection_format == 'ssv': + delimiter = ' ' + elif collection_format == 'tsv': + delimiter = '\t' + elif collection_format == 'pipes': + delimiter = '|' + else: # csv is the default + delimiter = ',' + new_params.append( + (k, delimiter.join(str(value) for value in v))) else: - if collection_format == "ssv": - delimiter = " " - elif collection_format == "tsv": - delimiter = "\t" - elif collection_format == "pipes": - delimiter = "|" - else: # csv is the default - delimiter = "," - return [(name, delimiter.join(value))] - else: - return [(name, value)] + new_params.append((k, v)) + return new_params def prepare_post_parameters(self, post_params=None, files=None): """ @@ -466,7 +469,7 @@ def update_params_for_auth(self, headers, querys, auth_settings): Updates header and query params based on authentication setting. :param headers: Header parameters dict to be updated. - :param querys: Query parameters dict to be updated. + :param querys: Query parameters tuple list to be updated. :param auth_settings: Authentication setting identifiers list. """ config = Configuration() @@ -482,7 +485,7 @@ def update_params_for_auth(self, headers, querys, auth_settings): elif auth_setting['in'] == 'header': headers[auth_setting['key']] = auth_setting['value'] elif auth_setting['in'] == 'query': - querys[auth_setting['key']] = auth_setting['value'] + querys.append((auth_setting['key'], auth_setting['value'])) else: raise ValueError( 'Authentication token must be in `query` or `header`' diff --git a/samples/client/petstore/python/petstore_api/apis/fake_api.py b/samples/client/petstore/python/petstore_api/apis/fake_api.py index 5dd2a327021..5ed13ee9c2a 100644 --- a/samples/client/petstore/python/petstore_api/apis/fake_api.py +++ b/samples/client/petstore/python/petstore_api/apis/fake_api.py @@ -116,6 +116,9 @@ def test_client_model_with_http_info(self, body, **kwargs): if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `test_client_model`") + + collection_formats = {} + resource_path = '/fake'.replace('{format}', 'json') path_params = {} @@ -153,7 +156,8 @@ def test_client_model_with_http_info(self, body, **kwargs): response_type='Client', auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def test_endpoint_parameters(self, number, double, pattern_without_delimiter, byte, **kwargs): """ @@ -279,6 +283,9 @@ def test_endpoint_parameters_with_http_info(self, number, double, pattern_withou raise ValueError("Invalid value for parameter `password` when calling `test_endpoint_parameters`, length must be less than or equal to `64`") if 'password' in params and len(params['password']) < 10: raise ValueError("Invalid value for parameter `password` when calling `test_endpoint_parameters`, length must be greater than or equal to `10`") + + collection_formats = {} + resource_path = '/fake'.replace('{format}', 'json') path_params = {} @@ -289,31 +296,31 @@ def test_endpoint_parameters_with_http_info(self, number, double, pattern_withou form_params = [] local_var_files = {} if 'integer' in params: - form_params.extend(self.api_client.parameter_to_tuples('', 'integer', params['integer'])) + form_params.append(('integer', params['integer'])) if 'int32' in params: - form_params.extend(self.api_client.parameter_to_tuples('', 'int32', params['int32'])) + form_params.append(('int32', params['int32'])) if 'int64' in params: - form_params.extend(self.api_client.parameter_to_tuples('', 'int64', params['int64'])) + form_params.append(('int64', params['int64'])) if 'number' in params: - form_params.extend(self.api_client.parameter_to_tuples('', 'number', params['number'])) + form_params.append(('number', params['number'])) if 'float' in params: - form_params.extend(self.api_client.parameter_to_tuples('', 'float', params['float'])) + form_params.append(('float', params['float'])) if 'double' in params: - form_params.extend(self.api_client.parameter_to_tuples('', 'double', params['double'])) + form_params.append(('double', params['double'])) if 'string' in params: - form_params.extend(self.api_client.parameter_to_tuples('', 'string', params['string'])) + form_params.append(('string', params['string'])) if 'pattern_without_delimiter' in params: - form_params.extend(self.api_client.parameter_to_tuples('', 'pattern_without_delimiter', params['pattern_without_delimiter'])) + form_params.append(('pattern_without_delimiter', params['pattern_without_delimiter'])) if 'byte' in params: - form_params.extend(self.api_client.parameter_to_tuples('', 'byte', params['byte'])) + form_params.append(('byte', params['byte'])) if 'binary' in params: - form_params.extend(self.api_client.parameter_to_tuples('', 'binary', params['binary'])) + form_params.append(('binary', params['binary'])) if 'date' in params: - form_params.extend(self.api_client.parameter_to_tuples('', 'date', params['date'])) + form_params.append(('date', params['date'])) if 'date_time' in params: - form_params.extend(self.api_client.parameter_to_tuples('', 'dateTime', params['date_time'])) + form_params.append(('dateTime', params['date_time'])) if 'password' in params: - form_params.extend(self.api_client.parameter_to_tuples('', 'password', params['password'])) + form_params.append(('password', params['password'])) body_params = None @@ -340,7 +347,8 @@ def test_endpoint_parameters_with_http_info(self, number, double, pattern_withou response_type=None, auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def test_enum_parameters(self, **kwargs): """ @@ -418,12 +426,16 @@ def test_enum_parameters_with_http_info(self, **kwargs): params[key] = val del params['kwargs'] + + collection_formats = {} + resource_path = '/fake'.replace('{format}', 'json') path_params = {} query_params = {} if 'enum_query_string_array' in params: query_params['enum_query_string_array'] = params['enum_query_string_array'] + collection_formats['enum_query_string_array'] = 'csv' if 'enum_query_string' in params: query_params['enum_query_string'] = params['enum_query_string'] if 'enum_query_integer' in params: @@ -432,17 +444,19 @@ def test_enum_parameters_with_http_info(self, **kwargs): header_params = {} if 'enum_header_string_array' in params: header_params['enum_header_string_array'] = params['enum_header_string_array'] + collection_formats['enum_header_string_array'] = 'csv' if 'enum_header_string' in params: header_params['enum_header_string'] = params['enum_header_string'] form_params = [] local_var_files = {} if 'enum_form_string_array' in params: - form_params.extend(self.api_client.parameter_to_tuples('csv', 'enum_form_string_array', params['enum_form_string_array'])) + form_params.append(('enum_form_string_array', params['enum_form_string_array'])) + collection_formats['enum_form_string_array'] = 'csv' if 'enum_form_string' in params: - form_params.extend(self.api_client.parameter_to_tuples('', 'enum_form_string', params['enum_form_string'])) + form_params.append(('enum_form_string', params['enum_form_string'])) if 'enum_query_double' in params: - form_params.extend(self.api_client.parameter_to_tuples('', 'enum_query_double', params['enum_query_double'])) + form_params.append(('enum_query_double', params['enum_query_double'])) body_params = None @@ -469,4 +483,5 @@ def test_enum_parameters_with_http_info(self, **kwargs): response_type=None, auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) diff --git a/samples/client/petstore/python/petstore_api/apis/pet_api.py b/samples/client/petstore/python/petstore_api/apis/pet_api.py index 9357e8e70e1..b0aa2d9a842 100644 --- a/samples/client/petstore/python/petstore_api/apis/pet_api.py +++ b/samples/client/petstore/python/petstore_api/apis/pet_api.py @@ -116,6 +116,9 @@ def add_pet_with_http_info(self, body, **kwargs): if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `add_pet`") + + collection_formats = {} + resource_path = '/pet'.replace('{format}', 'json') path_params = {} @@ -153,7 +156,8 @@ def add_pet_with_http_info(self, body, **kwargs): response_type=None, auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def delete_pet(self, pet_id, **kwargs): """ @@ -222,6 +226,9 @@ def delete_pet_with_http_info(self, pet_id, **kwargs): if ('pet_id' not in params) or (params['pet_id'] is None): raise ValueError("Missing the required parameter `pet_id` when calling `delete_pet`") + + collection_formats = {} + resource_path = '/pet/{petId}'.replace('{format}', 'json') path_params = {} if 'pet_id' in params: @@ -261,7 +268,8 @@ def delete_pet_with_http_info(self, pet_id, **kwargs): response_type=None, auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def find_pets_by_status(self, status, **kwargs): """ @@ -328,12 +336,16 @@ def find_pets_by_status_with_http_info(self, status, **kwargs): if ('status' not in params) or (params['status'] is None): raise ValueError("Missing the required parameter `status` when calling `find_pets_by_status`") + + collection_formats = {} + resource_path = '/pet/findByStatus'.replace('{format}', 'json') path_params = {} query_params = {} if 'status' in params: query_params['status'] = params['status'] + collection_formats['status'] = 'csv' header_params = {} @@ -365,7 +377,8 @@ def find_pets_by_status_with_http_info(self, status, **kwargs): response_type='list[Pet]', auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def find_pets_by_tags(self, tags, **kwargs): """ @@ -432,12 +445,16 @@ def find_pets_by_tags_with_http_info(self, tags, **kwargs): if ('tags' not in params) or (params['tags'] is None): raise ValueError("Missing the required parameter `tags` when calling `find_pets_by_tags`") + + collection_formats = {} + resource_path = '/pet/findByTags'.replace('{format}', 'json') path_params = {} query_params = {} if 'tags' in params: query_params['tags'] = params['tags'] + collection_formats['tags'] = 'csv' header_params = {} @@ -469,7 +486,8 @@ def find_pets_by_tags_with_http_info(self, tags, **kwargs): response_type='list[Pet]', auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def get_pet_by_id(self, pet_id, **kwargs): """ @@ -536,6 +554,9 @@ def get_pet_by_id_with_http_info(self, pet_id, **kwargs): if ('pet_id' not in params) or (params['pet_id'] is None): raise ValueError("Missing the required parameter `pet_id` when calling `get_pet_by_id`") + + collection_formats = {} + resource_path = '/pet/{petId}'.replace('{format}', 'json') path_params = {} if 'pet_id' in params: @@ -573,7 +594,8 @@ def get_pet_by_id_with_http_info(self, pet_id, **kwargs): response_type='Pet', auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def update_pet(self, body, **kwargs): """ @@ -640,6 +662,9 @@ def update_pet_with_http_info(self, body, **kwargs): if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `update_pet`") + + collection_formats = {} + resource_path = '/pet'.replace('{format}', 'json') path_params = {} @@ -677,7 +702,8 @@ def update_pet_with_http_info(self, body, **kwargs): response_type=None, auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def update_pet_with_form(self, pet_id, **kwargs): """ @@ -748,6 +774,9 @@ def update_pet_with_form_with_http_info(self, pet_id, **kwargs): if ('pet_id' not in params) or (params['pet_id'] is None): raise ValueError("Missing the required parameter `pet_id` when calling `update_pet_with_form`") + + collection_formats = {} + resource_path = '/pet/{petId}'.replace('{format}', 'json') path_params = {} if 'pet_id' in params: @@ -760,9 +789,9 @@ def update_pet_with_form_with_http_info(self, pet_id, **kwargs): form_params = [] local_var_files = {} if 'name' in params: - form_params.extend(self.api_client.parameter_to_tuples('', 'name', params['name'])) + form_params.append(('name', params['name'])) if 'status' in params: - form_params.extend(self.api_client.parameter_to_tuples('', 'status', params['status'])) + form_params.append(('status', params['status'])) body_params = None @@ -789,7 +818,8 @@ def update_pet_with_form_with_http_info(self, pet_id, **kwargs): response_type=None, auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def upload_file(self, pet_id, **kwargs): """ @@ -860,6 +890,9 @@ def upload_file_with_http_info(self, pet_id, **kwargs): if ('pet_id' not in params) or (params['pet_id'] is None): raise ValueError("Missing the required parameter `pet_id` when calling `upload_file`") + + collection_formats = {} + resource_path = '/pet/{petId}/uploadImage'.replace('{format}', 'json') path_params = {} if 'pet_id' in params: @@ -872,7 +905,7 @@ def upload_file_with_http_info(self, pet_id, **kwargs): form_params = [] local_var_files = {} if 'additional_metadata' in params: - form_params.extend(self.api_client.parameter_to_tuples('', 'additionalMetadata', params['additional_metadata'])) + form_params.append(('additionalMetadata', params['additional_metadata'])) if 'file' in params: local_var_files['file'] = params['file'] @@ -901,4 +934,5 @@ def upload_file_with_http_info(self, pet_id, **kwargs): response_type='ApiResponse', auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) diff --git a/samples/client/petstore/python/petstore_api/apis/store_api.py b/samples/client/petstore/python/petstore_api/apis/store_api.py index e5e972c7444..d9c505055e3 100644 --- a/samples/client/petstore/python/petstore_api/apis/store_api.py +++ b/samples/client/petstore/python/petstore_api/apis/store_api.py @@ -118,6 +118,9 @@ def delete_order_with_http_info(self, order_id, **kwargs): if 'order_id' in params and params['order_id'] < 1.0: raise ValueError("Invalid value for parameter `order_id` when calling `delete_order`, must be a value greater than or equal to `1.0`") + + collection_formats = {} + resource_path = '/store/order/{orderId}'.replace('{format}', 'json') path_params = {} if 'order_id' in params: @@ -155,7 +158,8 @@ def delete_order_with_http_info(self, order_id, **kwargs): response_type=None, auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def get_inventory(self, **kwargs): """ @@ -217,6 +221,9 @@ def get_inventory_with_http_info(self, **kwargs): params[key] = val del params['kwargs'] + + collection_formats = {} + resource_path = '/store/inventory'.replace('{format}', 'json') path_params = {} @@ -252,7 +259,8 @@ def get_inventory_with_http_info(self, **kwargs): response_type='dict(str, int)', auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def get_order_by_id(self, order_id, **kwargs): """ @@ -323,6 +331,9 @@ def get_order_by_id_with_http_info(self, order_id, **kwargs): raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value less than or equal to `5.0`") if 'order_id' in params and params['order_id'] < 1.0: raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value greater than or equal to `1.0`") + + collection_formats = {} + resource_path = '/store/order/{orderId}'.replace('{format}', 'json') path_params = {} if 'order_id' in params: @@ -360,7 +371,8 @@ def get_order_by_id_with_http_info(self, order_id, **kwargs): response_type='Order', auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def place_order(self, body, **kwargs): """ @@ -427,6 +439,9 @@ def place_order_with_http_info(self, body, **kwargs): if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `place_order`") + + collection_formats = {} + resource_path = '/store/order'.replace('{format}', 'json') path_params = {} @@ -464,4 +479,5 @@ def place_order_with_http_info(self, body, **kwargs): response_type='Order', auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) diff --git a/samples/client/petstore/python/petstore_api/apis/user_api.py b/samples/client/petstore/python/petstore_api/apis/user_api.py index 57e89ccca3d..cc7f2d35083 100644 --- a/samples/client/petstore/python/petstore_api/apis/user_api.py +++ b/samples/client/petstore/python/petstore_api/apis/user_api.py @@ -116,6 +116,9 @@ def create_user_with_http_info(self, body, **kwargs): if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `create_user`") + + collection_formats = {} + resource_path = '/user'.replace('{format}', 'json') path_params = {} @@ -153,7 +156,8 @@ def create_user_with_http_info(self, body, **kwargs): response_type=None, auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def create_users_with_array_input(self, body, **kwargs): """ @@ -220,6 +224,9 @@ def create_users_with_array_input_with_http_info(self, body, **kwargs): if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `create_users_with_array_input`") + + collection_formats = {} + resource_path = '/user/createWithArray'.replace('{format}', 'json') path_params = {} @@ -257,7 +264,8 @@ def create_users_with_array_input_with_http_info(self, body, **kwargs): response_type=None, auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def create_users_with_list_input(self, body, **kwargs): """ @@ -324,6 +332,9 @@ def create_users_with_list_input_with_http_info(self, body, **kwargs): if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `create_users_with_list_input`") + + collection_formats = {} + resource_path = '/user/createWithList'.replace('{format}', 'json') path_params = {} @@ -361,7 +372,8 @@ def create_users_with_list_input_with_http_info(self, body, **kwargs): response_type=None, auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def delete_user(self, username, **kwargs): """ @@ -428,6 +440,9 @@ def delete_user_with_http_info(self, username, **kwargs): if ('username' not in params) or (params['username'] is None): raise ValueError("Missing the required parameter `username` when calling `delete_user`") + + collection_formats = {} + resource_path = '/user/{username}'.replace('{format}', 'json') path_params = {} if 'username' in params: @@ -465,7 +480,8 @@ def delete_user_with_http_info(self, username, **kwargs): response_type=None, auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def get_user_by_name(self, username, **kwargs): """ @@ -532,6 +548,9 @@ def get_user_by_name_with_http_info(self, username, **kwargs): if ('username' not in params) or (params['username'] is None): raise ValueError("Missing the required parameter `username` when calling `get_user_by_name`") + + collection_formats = {} + resource_path = '/user/{username}'.replace('{format}', 'json') path_params = {} if 'username' in params: @@ -569,7 +588,8 @@ def get_user_by_name_with_http_info(self, username, **kwargs): response_type='User', auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def login_user(self, username, password, **kwargs): """ @@ -641,6 +661,9 @@ def login_user_with_http_info(self, username, password, **kwargs): if ('password' not in params) or (params['password'] is None): raise ValueError("Missing the required parameter `password` when calling `login_user`") + + collection_formats = {} + resource_path = '/user/login'.replace('{format}', 'json') path_params = {} @@ -680,7 +703,8 @@ def login_user_with_http_info(self, username, password, **kwargs): response_type='str', auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def logout_user(self, **kwargs): """ @@ -742,6 +766,9 @@ def logout_user_with_http_info(self, **kwargs): params[key] = val del params['kwargs'] + + collection_formats = {} + resource_path = '/user/logout'.replace('{format}', 'json') path_params = {} @@ -777,7 +804,8 @@ def logout_user_with_http_info(self, **kwargs): response_type=None, auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) def update_user(self, username, body, **kwargs): """ @@ -849,6 +877,9 @@ def update_user_with_http_info(self, username, body, **kwargs): if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `update_user`") + + collection_formats = {} + resource_path = '/user/{username}'.replace('{format}', 'json') path_params = {} if 'username' in params: @@ -888,4 +919,5 @@ def update_user_with_http_info(self, username, body, **kwargs): response_type=None, auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) From 8183d96088551d77e8db18cd7f92e7f96153b876 Mon Sep 17 00:00:00 2001 From: Neil O'Toole Date: Fri, 2 Sep 2016 06:49:39 -0600 Subject: [PATCH 323/470] #3690 adding RequestURL, Method, Operation and Payload fields to APIResponse --- .../codegen/languages/GoClientCodegen.java | 3 +- .../src/main/resources/go/api.mustache | 18 +- .../main/resources/go/api_response.mustache | 14 +- .../additional_properties_class.go | 30 ++ .../client/petstore/go/go-petstore/animal.go | 30 ++ .../petstore/go/go-petstore/animal_farm.go | 26 ++ .../petstore/go/go-petstore/api_response.go | 14 +- .../array_of_array_of_number_only.go | 28 ++ .../go/go-petstore/array_of_number_only.go | 28 ++ .../petstore/go/go-petstore/array_test.go | 32 ++ samples/client/petstore/go/go-petstore/cat.go | 32 ++ .../client/petstore/go/go-petstore/client.go | 28 ++ .../docs/AdditionalPropertiesClass.md | 11 + .../petstore/go/go-petstore/docs/Animal.md | 11 + .../go/go-petstore/docs/AnimalFarm.md | 9 + .../docs/ArrayOfArrayOfNumberOnly.md | 10 + .../go/go-petstore/docs/ArrayOfNumberOnly.md | 10 + .../petstore/go/go-petstore/docs/ArrayTest.md | 12 + .../petstore/go/go-petstore/docs/Cat.md | 12 + .../petstore/go/go-petstore/docs/Client.md | 10 + .../petstore/go/go-petstore/docs/Dog.md | 12 + .../go/go-petstore/docs/EnumArrays.md | 11 + .../petstore/go/go-petstore/docs/EnumClass.md | 9 + .../petstore/go/go-petstore/docs/EnumTest.md | 12 + .../petstore/go/go-petstore/docs/FakeApi.md | 113 +++++++ .../go/go-petstore/docs/FormatTest.md | 22 ++ .../go/go-petstore/docs/HasOnlyReadOnly.md | 11 + .../petstore/go/go-petstore/docs/List.md | 10 + .../petstore/go/go-petstore/docs/MapTest.md | 11 + ...dPropertiesAndAdditionalPropertiesClass.md | 12 + .../go/go-petstore/docs/Model200Response.md | 11 + .../go/go-petstore/docs/ModelReturn.md | 10 + .../petstore/go/go-petstore/docs/Name.md | 13 + .../go/go-petstore/docs/NumberOnly.md | 10 + .../go/go-petstore/docs/ReadOnlyFirst.md | 11 + .../go/go-petstore/docs/SpecialModelName.md | 10 + samples/client/petstore/go/go-petstore/dog.go | 32 ++ .../petstore/go/go-petstore/enum_arrays.go | 30 ++ .../petstore/go/go-petstore/enum_class.go | 26 ++ .../petstore/go/go-petstore/enum_test.go | 32 ++ .../petstore/go/go-petstore/fake_api.go | 294 ++++++++++++++++++ .../petstore/go/go-petstore/format_test.go | 56 ++++ .../go/go-petstore/has_only_read_only.go | 30 ++ .../client/petstore/go/go-petstore/list.go | 28 ++ .../petstore/go/go-petstore/map_test.go | 30 ++ ...perties_and_additional_properties_class.go | 36 +++ .../go/go-petstore/model_200_response.go | 31 ++ .../petstore/go/go-petstore/model_return.go | 29 ++ .../client/petstore/go/go-petstore/name.go | 35 +++ .../petstore/go/go-petstore/number_only.go | 28 ++ .../client/petstore/go/go-petstore/pet_api.go | 138 ++++++-- .../go/go-petstore/read_only_first.go | 30 ++ .../go/go-petstore/special_model_name.go | 28 ++ .../petstore/go/go-petstore/store_api.go | 70 ++++- .../petstore/go/go-petstore/user_api.go | 138 ++++++-- 55 files changed, 1686 insertions(+), 91 deletions(-) create mode 100644 samples/client/petstore/go/go-petstore/additional_properties_class.go create mode 100644 samples/client/petstore/go/go-petstore/animal.go create mode 100644 samples/client/petstore/go/go-petstore/animal_farm.go create mode 100644 samples/client/petstore/go/go-petstore/array_of_array_of_number_only.go create mode 100644 samples/client/petstore/go/go-petstore/array_of_number_only.go create mode 100644 samples/client/petstore/go/go-petstore/array_test.go create mode 100644 samples/client/petstore/go/go-petstore/cat.go create mode 100644 samples/client/petstore/go/go-petstore/client.go create mode 100644 samples/client/petstore/go/go-petstore/docs/AdditionalPropertiesClass.md create mode 100644 samples/client/petstore/go/go-petstore/docs/Animal.md create mode 100644 samples/client/petstore/go/go-petstore/docs/AnimalFarm.md create mode 100644 samples/client/petstore/go/go-petstore/docs/ArrayOfArrayOfNumberOnly.md create mode 100644 samples/client/petstore/go/go-petstore/docs/ArrayOfNumberOnly.md create mode 100644 samples/client/petstore/go/go-petstore/docs/ArrayTest.md create mode 100644 samples/client/petstore/go/go-petstore/docs/Cat.md create mode 100644 samples/client/petstore/go/go-petstore/docs/Client.md create mode 100644 samples/client/petstore/go/go-petstore/docs/Dog.md create mode 100644 samples/client/petstore/go/go-petstore/docs/EnumArrays.md create mode 100644 samples/client/petstore/go/go-petstore/docs/EnumClass.md create mode 100644 samples/client/petstore/go/go-petstore/docs/EnumTest.md create mode 100644 samples/client/petstore/go/go-petstore/docs/FakeApi.md create mode 100644 samples/client/petstore/go/go-petstore/docs/FormatTest.md create mode 100644 samples/client/petstore/go/go-petstore/docs/HasOnlyReadOnly.md create mode 100644 samples/client/petstore/go/go-petstore/docs/List.md create mode 100644 samples/client/petstore/go/go-petstore/docs/MapTest.md create mode 100644 samples/client/petstore/go/go-petstore/docs/MixedPropertiesAndAdditionalPropertiesClass.md create mode 100644 samples/client/petstore/go/go-petstore/docs/Model200Response.md create mode 100644 samples/client/petstore/go/go-petstore/docs/ModelReturn.md create mode 100644 samples/client/petstore/go/go-petstore/docs/Name.md create mode 100644 samples/client/petstore/go/go-petstore/docs/NumberOnly.md create mode 100644 samples/client/petstore/go/go-petstore/docs/ReadOnlyFirst.md create mode 100644 samples/client/petstore/go/go-petstore/docs/SpecialModelName.md create mode 100644 samples/client/petstore/go/go-petstore/dog.go create mode 100644 samples/client/petstore/go/go-petstore/enum_arrays.go create mode 100644 samples/client/petstore/go/go-petstore/enum_class.go create mode 100644 samples/client/petstore/go/go-petstore/enum_test.go create mode 100644 samples/client/petstore/go/go-petstore/fake_api.go create mode 100644 samples/client/petstore/go/go-petstore/format_test.go create mode 100644 samples/client/petstore/go/go-petstore/has_only_read_only.go create mode 100644 samples/client/petstore/go/go-petstore/list.go create mode 100644 samples/client/petstore/go/go-petstore/map_test.go create mode 100644 samples/client/petstore/go/go-petstore/mixed_properties_and_additional_properties_class.go create mode 100644 samples/client/petstore/go/go-petstore/model_200_response.go create mode 100644 samples/client/petstore/go/go-petstore/model_return.go create mode 100644 samples/client/petstore/go/go-petstore/name.go create mode 100644 samples/client/petstore/go/go-petstore/number_only.go create mode 100644 samples/client/petstore/go/go-petstore/read_only_first.go create mode 100644 samples/client/petstore/go/go-petstore/special_model_name.go diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java index 6bfd1df425f..9facbf6044b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java @@ -414,11 +414,10 @@ public Map postProcessOperations(Map objs) { } } - // this will only import "strings" "fmt" if there are items in pathParams + // this will only import "fmt" if there are items in pathParams for (CodegenOperation operation : operations) { if(operation.pathParams != null && operation.pathParams.size() > 0) { imports.add(createMapping("import", "fmt")); - imports.add(createMapping("import", "strings")); break; //just need to import once } } diff --git a/modules/swagger-codegen/src/main/resources/go/api.mustache b/modules/swagger-codegen/src/main/resources/go/api.mustache index 9165fb21e29..38c77384a7c 100644 --- a/modules/swagger-codegen/src/main/resources/go/api.mustache +++ b/modules/swagger-codegen/src/main/resources/go/api.mustache @@ -4,6 +4,7 @@ package {{packageName}} {{#operations}} import ( "net/url" + "strings" {{#imports}} "{{import}}" {{/imports}} ) @@ -38,7 +39,7 @@ func New{{classname}}WithBasePath(basePath string) *{{classname}} { */ func (a {{{classname}}}) {{{nickname}}}({{#allParams}}{{paramName}} {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) ({{#returnType}}{{^isListContainer}}*{{/isListContainer}}{{{returnType}}}, {{/returnType}}*APIResponse, error) { - var localVarHttpMethod = "{{httpMethod}}" + var localVarHttpMethod = strings.ToUpper("{{httpMethod}}") // create path and map variables localVarPath := a.Configuration.BasePath + "{{path}}"{{#pathParams}} localVarPath = strings.Replace(localVarPath, "{"+"{{baseName}}"+"}", fmt.Sprintf("%v", {{paramName}}), -1){{/pathParams}} @@ -135,11 +136,20 @@ func (a {{{classname}}}) {{{nickname}}}({{#allParams}}{{paramName}} {{{dataType} {{/bodyParams}}{{/hasBodyParam}} {{#returnType}} var successPayload = new({{returnType}}){{/returnType}} localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - if err != nil { - return {{#returnType}}{{#isListContainer}}*{{/isListContainer}}successPayload, {{/returnType}}NewAPIResponse(localVarHttpResponse.RawResponse), err + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "{{operationId}}", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + +if err != nil { + return {{#returnType}}{{#isListContainer}}*{{/isListContainer}}successPayload, {{/returnType}}localVarAPIResponse, err } {{#returnType}} err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload){{/returnType}} - return {{#returnType}}{{#isListContainer}}*{{/isListContainer}}successPayload, {{/returnType}}NewAPIResponse(localVarHttpResponse.RawResponse), err + return {{#returnType}}{{#isListContainer}}*{{/isListContainer}}successPayload, {{/returnType}}localVarAPIResponse, err } {{/operation}}{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/go/api_response.mustache b/modules/swagger-codegen/src/main/resources/go/api_response.mustache index 9bacc9578e4..00ab14a5124 100644 --- a/modules/swagger-codegen/src/main/resources/go/api_response.mustache +++ b/modules/swagger-codegen/src/main/resources/go/api_response.mustache @@ -6,8 +6,20 @@ import ( ) type APIResponse struct { - *http.Response + *http.Response `json:"-"` Message string `json:"message,omitempty"` + // Operation is the name of the swagger operation. + Operation string `json:"operation,omitempty"` + // RequestURL is the request URL. This value is always available, even if the + // embedded *http.Response is nil. + RequestURL string `json:"url,omitempty"` + // Method is the HTTP method used for the request. This value is always + // available, even if the embedded *http.Response is nil. + Method string `json:"method,omitempty"` + // Payload holds the contents of the response body (which may be nil or empty). + // This is provided here as the raw response.Body() reader will have already + // been drained. + Payload []byte `json:"-"` } func NewAPIResponse(r *http.Response) *APIResponse { diff --git a/samples/client/petstore/go/go-petstore/additional_properties_class.go b/samples/client/petstore/go/go-petstore/additional_properties_class.go new file mode 100644 index 00000000000..ad768d2e478 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/additional_properties_class.go @@ -0,0 +1,30 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type AdditionalPropertiesClass struct { + + MapProperty map[string]string `json:"map_property,omitempty"` + + MapOfMapProperty map[string]map[string]string `json:"map_of_map_property,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/animal.go b/samples/client/petstore/go/go-petstore/animal.go new file mode 100644 index 00000000000..bc9d8161db7 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/animal.go @@ -0,0 +1,30 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type Animal struct { + + ClassName string `json:"className,omitempty"` + + Color string `json:"color,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/animal_farm.go b/samples/client/petstore/go/go-petstore/animal_farm.go new file mode 100644 index 00000000000..a412cbcd450 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/animal_farm.go @@ -0,0 +1,26 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type AnimalFarm struct { +} diff --git a/samples/client/petstore/go/go-petstore/api_response.go b/samples/client/petstore/go/go-petstore/api_response.go index 0647a0d6b4d..2459f617a03 100644 --- a/samples/client/petstore/go/go-petstore/api_response.go +++ b/samples/client/petstore/go/go-petstore/api_response.go @@ -27,8 +27,20 @@ import ( ) type APIResponse struct { - *http.Response + *http.Response `json:"-"` Message string `json:"message,omitempty"` + // Operation is the name of the swagger operation. + Operation string `json:"operation,omitempty"` + // RequestURL is the request URL. This value is always available, even if the + // embedded *http.Response is nil. + RequestURL string `json:"url,omitempty"` + // Method is the HTTP method used for the request. This value is always + // available, even if the embedded *http.Response is nil. + Method string `json:"method,omitempty"` + // Payload holds the contents of the response body (which may be nil or empty). + // This is provided here as the raw response.Body() reader will have already + // been drained. + Payload []byte `json:"-"` } func NewAPIResponse(r *http.Response) *APIResponse { diff --git a/samples/client/petstore/go/go-petstore/array_of_array_of_number_only.go b/samples/client/petstore/go/go-petstore/array_of_array_of_number_only.go new file mode 100644 index 00000000000..8fc05e77a16 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/array_of_array_of_number_only.go @@ -0,0 +1,28 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type ArrayOfArrayOfNumberOnly struct { + + ArrayArrayNumber [][]float32 `json:"ArrayArrayNumber,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/array_of_number_only.go b/samples/client/petstore/go/go-petstore/array_of_number_only.go new file mode 100644 index 00000000000..d9ef9a4c6d9 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/array_of_number_only.go @@ -0,0 +1,28 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type ArrayOfNumberOnly struct { + + ArrayNumber []float32 `json:"ArrayNumber,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/array_test.go b/samples/client/petstore/go/go-petstore/array_test.go new file mode 100644 index 00000000000..251f0a88efb --- /dev/null +++ b/samples/client/petstore/go/go-petstore/array_test.go @@ -0,0 +1,32 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type ArrayTest struct { + + ArrayOfString []string `json:"array_of_string,omitempty"` + + ArrayArrayOfInteger [][]int64 `json:"array_array_of_integer,omitempty"` + + ArrayArrayOfModel [][]ReadOnlyFirst `json:"array_array_of_model,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/cat.go b/samples/client/petstore/go/go-petstore/cat.go new file mode 100644 index 00000000000..f8526999824 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/cat.go @@ -0,0 +1,32 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type Cat struct { + + ClassName string `json:"className,omitempty"` + + Color string `json:"color,omitempty"` + + Declawed bool `json:"declawed,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/client.go b/samples/client/petstore/go/go-petstore/client.go new file mode 100644 index 00000000000..e20c597d838 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/client.go @@ -0,0 +1,28 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type Client struct { + + Client string `json:"client,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/docs/AdditionalPropertiesClass.md b/samples/client/petstore/go/go-petstore/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..abdb42c8e01 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/AdditionalPropertiesClass.md @@ -0,0 +1,11 @@ +# AdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**MapProperty** | **map[string]string** | | [optional] [default to null] +**MapOfMapProperty** | [**map[string]map[string]string**](map.md) | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/Animal.md b/samples/client/petstore/go/go-petstore/docs/Animal.md new file mode 100644 index 00000000000..e7163af792c --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/Animal.md @@ -0,0 +1,11 @@ +# Animal + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **string** | | [default to null] +**Color** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/AnimalFarm.md b/samples/client/petstore/go/go-petstore/docs/AnimalFarm.md new file mode 100644 index 00000000000..df6bab21dae --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/AnimalFarm.md @@ -0,0 +1,9 @@ +# AnimalFarm + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/go/go-petstore/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 00000000000..495038e58e1 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/ArrayOfArrayOfNumberOnly.md @@ -0,0 +1,10 @@ +# ArrayOfArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ArrayArrayNumber** | [**[][]float32**](array.md) | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/ArrayOfNumberOnly.md b/samples/client/petstore/go/go-petstore/docs/ArrayOfNumberOnly.md new file mode 100644 index 00000000000..bd7a48160d2 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/ArrayOfNumberOnly.md @@ -0,0 +1,10 @@ +# ArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ArrayNumber** | **[]float32** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/ArrayTest.md b/samples/client/petstore/go/go-petstore/docs/ArrayTest.md new file mode 100644 index 00000000000..6cf88880292 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/ArrayTest.md @@ -0,0 +1,12 @@ +# ArrayTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ArrayOfString** | **[]string** | | [optional] [default to null] +**ArrayArrayOfInteger** | [**[][]int64**](array.md) | | [optional] [default to null] +**ArrayArrayOfModel** | [**[][]ReadOnlyFirst**](array.md) | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/Cat.md b/samples/client/petstore/go/go-petstore/docs/Cat.md new file mode 100644 index 00000000000..3a49c3ca62e --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/Cat.md @@ -0,0 +1,12 @@ +# Cat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **string** | | [default to null] +**Color** | **string** | | [optional] [default to null] +**Declawed** | **bool** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/Client.md b/samples/client/petstore/go/go-petstore/docs/Client.md new file mode 100644 index 00000000000..d8edb814853 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/Client.md @@ -0,0 +1,10 @@ +# Client + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Client** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/Dog.md b/samples/client/petstore/go/go-petstore/docs/Dog.md new file mode 100644 index 00000000000..7178972d5dc --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/Dog.md @@ -0,0 +1,12 @@ +# Dog + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **string** | | [default to null] +**Color** | **string** | | [optional] [default to null] +**Breed** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/EnumArrays.md b/samples/client/petstore/go/go-petstore/docs/EnumArrays.md new file mode 100644 index 00000000000..2ca85fdd1fb --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/EnumArrays.md @@ -0,0 +1,11 @@ +# EnumArrays + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**JustSymbol** | **string** | | [optional] [default to null] +**ArrayEnum** | **[]string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/EnumClass.md b/samples/client/petstore/go/go-petstore/docs/EnumClass.md new file mode 100644 index 00000000000..67f017becd0 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/EnumClass.md @@ -0,0 +1,9 @@ +# EnumClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/EnumTest.md b/samples/client/petstore/go/go-petstore/docs/EnumTest.md new file mode 100644 index 00000000000..fe6ca0cb32d --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/EnumTest.md @@ -0,0 +1,12 @@ +# EnumTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**EnumString** | **string** | | [optional] [default to null] +**EnumInteger** | **int32** | | [optional] [default to null] +**EnumNumber** | **float64** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/FakeApi.md b/samples/client/petstore/go/go-petstore/docs/FakeApi.md new file mode 100644 index 00000000000..63e7fb728fb --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/FakeApi.md @@ -0,0 +1,113 @@ +# \FakeApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**TestClientModel**](FakeApi.md#TestClientModel) | **Patch** /fake | To test \"client\" model +[**TestEndpointParameters**](FakeApi.md#TestEndpointParameters) | **Post** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**TestEnumParameters**](FakeApi.md#TestEnumParameters) | **Get** /fake | To test enum parameters + + +# **TestClientModel** +> Client TestClientModel($body) + +To test \"client\" model + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Client**](Client.md)| client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **TestEndpointParameters** +> TestEndpointParameters($number, $double, $patternWithoutDelimiter, $byte_, $integer, $int32_, $int64_, $float, $string_, $binary, $date, $dateTime, $password) + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **number** | **float32**| None | + **double** | **float64**| None | + **patternWithoutDelimiter** | **string**| None | + **byte_** | **string**| None | + **integer** | **int32**| None | [optional] + **int32_** | **int32**| None | [optional] + **int64_** | **int64**| None | [optional] + **float** | **float32**| None | [optional] + **string_** | **string**| None | [optional] + **binary** | **string**| None | [optional] + **date** | **time.Time**| None | [optional] + **dateTime** | **time.Time**| None | [optional] + **password** | **string**| None | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[http_basic_test](../README.md#http_basic_test) + +### HTTP request headers + + - **Content-Type**: application/xml; charset=utf-8, application/json; charset=utf-8 + - **Accept**: application/xml; charset=utf-8, application/json; charset=utf-8 + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **TestEnumParameters** +> TestEnumParameters($enumFormStringArray, $enumFormString, $enumHeaderStringArray, $enumHeaderString, $enumQueryStringArray, $enumQueryString, $enumQueryInteger, $enumQueryDouble) + +To test enum parameters + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **enumFormStringArray** | [**[]string**](string.md)| Form parameter enum test (string array) | [optional] + **enumFormString** | **string**| Form parameter enum test (string) | [optional] [default to -efg] + **enumHeaderStringArray** | [**[]string**](string.md)| Header parameter enum test (string array) | [optional] + **enumHeaderString** | **string**| Header parameter enum test (string) | [optional] [default to -efg] + **enumQueryStringArray** | [**[]string**](string.md)| Query parameter enum test (string array) | [optional] + **enumQueryString** | **string**| Query parameter enum test (string) | [optional] [default to -efg] + **enumQueryInteger** | **float32**| Query parameter enum test (double) | [optional] + **enumQueryDouble** | **float64**| Query parameter enum test (double) | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/go/go-petstore/docs/FormatTest.md b/samples/client/petstore/go/go-petstore/docs/FormatTest.md new file mode 100644 index 00000000000..05f41a8039f --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/FormatTest.md @@ -0,0 +1,22 @@ +# FormatTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Integer** | **int32** | | [optional] [default to null] +**Int32_** | **int32** | | [optional] [default to null] +**Int64_** | **int64** | | [optional] [default to null] +**Number** | **float32** | | [default to null] +**Float** | **float32** | | [optional] [default to null] +**Double** | **float64** | | [optional] [default to null] +**String_** | **string** | | [optional] [default to null] +**Byte_** | **string** | | [default to null] +**Binary** | **string** | | [optional] [default to null] +**Date** | [**time.Time**](time.Time.md) | | [default to null] +**DateTime** | [**time.Time**](time.Time.md) | | [optional] [default to null] +**Uuid** | **string** | | [optional] [default to null] +**Password** | **string** | | [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/HasOnlyReadOnly.md b/samples/client/petstore/go/go-petstore/docs/HasOnlyReadOnly.md new file mode 100644 index 00000000000..32dfdedcfe7 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/HasOnlyReadOnly.md @@ -0,0 +1,11 @@ +# HasOnlyReadOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Bar** | **string** | | [optional] [default to null] +**Foo** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/List.md b/samples/client/petstore/go/go-petstore/docs/List.md new file mode 100644 index 00000000000..54fd3876c26 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/List.md @@ -0,0 +1,10 @@ +# List + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Var123List** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/MapTest.md b/samples/client/petstore/go/go-petstore/docs/MapTest.md new file mode 100644 index 00000000000..6b70bf448e8 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/MapTest.md @@ -0,0 +1,11 @@ +# MapTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**MapMapOfString** | [**map[string]map[string]string**](map.md) | | [optional] [default to null] +**MapOfEnumString** | **map[string]string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/go/go-petstore/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..b4de97169dd --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,12 @@ +# MixedPropertiesAndAdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Uuid** | **string** | | [optional] [default to null] +**DateTime** | [**time.Time**](time.Time.md) | | [optional] [default to null] +**Map_** | [**map[string]Animal**](Animal.md) | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/Model200Response.md b/samples/client/petstore/go/go-petstore/docs/Model200Response.md new file mode 100644 index 00000000000..8b4bb38033d --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/Model200Response.md @@ -0,0 +1,11 @@ +# Model200Response + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Name** | **int32** | | [optional] [default to null] +**Class** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/ModelReturn.md b/samples/client/petstore/go/go-petstore/docs/ModelReturn.md new file mode 100644 index 00000000000..86350d4310c --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/ModelReturn.md @@ -0,0 +1,10 @@ +# ModelReturn + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Return_** | **int32** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/Name.md b/samples/client/petstore/go/go-petstore/docs/Name.md new file mode 100644 index 00000000000..d677e60263f --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/Name.md @@ -0,0 +1,13 @@ +# Name + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Name** | **int32** | | [default to null] +**SnakeCase** | **int32** | | [optional] [default to null] +**Property** | **string** | | [optional] [default to null] +**Var123Number** | **int32** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/NumberOnly.md b/samples/client/petstore/go/go-petstore/docs/NumberOnly.md new file mode 100644 index 00000000000..3ebbf2f0308 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/NumberOnly.md @@ -0,0 +1,10 @@ +# NumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**JustNumber** | **float32** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/ReadOnlyFirst.md b/samples/client/petstore/go/go-petstore/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..3ff591d7a74 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/ReadOnlyFirst.md @@ -0,0 +1,11 @@ +# ReadOnlyFirst + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Bar** | **string** | | [optional] [default to null] +**Baz** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/SpecialModelName.md b/samples/client/petstore/go/go-petstore/docs/SpecialModelName.md new file mode 100644 index 00000000000..dcf601a308d --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/SpecialModelName.md @@ -0,0 +1,10 @@ +# SpecialModelName + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**SpecialPropertyName** | **int64** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/dog.go b/samples/client/petstore/go/go-petstore/dog.go new file mode 100644 index 00000000000..acf4999618e --- /dev/null +++ b/samples/client/petstore/go/go-petstore/dog.go @@ -0,0 +1,32 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type Dog struct { + + ClassName string `json:"className,omitempty"` + + Color string `json:"color,omitempty"` + + Breed string `json:"breed,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/enum_arrays.go b/samples/client/petstore/go/go-petstore/enum_arrays.go new file mode 100644 index 00000000000..3b42ad142b5 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/enum_arrays.go @@ -0,0 +1,30 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type EnumArrays struct { + + JustSymbol string `json:"just_symbol,omitempty"` + + ArrayEnum []string `json:"array_enum,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/enum_class.go b/samples/client/petstore/go/go-petstore/enum_class.go new file mode 100644 index 00000000000..4a63f179dd3 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/enum_class.go @@ -0,0 +1,26 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type EnumClass struct { +} diff --git a/samples/client/petstore/go/go-petstore/enum_test.go b/samples/client/petstore/go/go-petstore/enum_test.go new file mode 100644 index 00000000000..c2be92c6246 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/enum_test.go @@ -0,0 +1,32 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type EnumTest struct { + + EnumString string `json:"enum_string,omitempty"` + + EnumInteger int32 `json:"enum_integer,omitempty"` + + EnumNumber float64 `json:"enum_number,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/fake_api.go b/samples/client/petstore/go/go-petstore/fake_api.go new file mode 100644 index 00000000000..3777a812813 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/fake_api.go @@ -0,0 +1,294 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +import ( + "net/url" + "strings" + "time" + "encoding/json" +) + +type FakeApi struct { + Configuration *Configuration +} + +func NewFakeApi() *FakeApi { + configuration := NewConfiguration() + return &FakeApi{ + Configuration: configuration, + } +} + +func NewFakeApiWithBasePath(basePath string) *FakeApi { + configuration := NewConfiguration() + configuration.BasePath = basePath + + return &FakeApi{ + Configuration: configuration, + } +} + +/** + * To test \"client\" model + * + * @param body client model + * @return *Client + */ +func (a FakeApi) TestClientModel(body Client) (*Client, *APIResponse, error) { + + var localVarHttpMethod = strings.ToUpper("Patch") + // create path and map variables + localVarPath := a.Configuration.BasePath + "/fake" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte + // add default headers if any + for key := range a.Configuration.DefaultHeader { + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] + } + + + // to determine the Content-Type header + localVarHttpContentTypes := []string{ "application/json", } + + // set Content-Type header + localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + // to determine the Accept header + localVarHttpHeaderAccepts := []string{ + "application/json", + } + + // set Accept header + localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + // body params + localVarPostBody = &body + + var successPayload = new(Client) + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "TestClientModel", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + +if err != nil { + return successPayload, localVarAPIResponse, err + } + err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) + return successPayload, localVarAPIResponse, err +} + +/** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * @param number None + * @param double None + * @param patternWithoutDelimiter None + * @param byte_ None + * @param integer None + * @param int32_ None + * @param int64_ None + * @param float None + * @param string_ None + * @param binary None + * @param date None + * @param dateTime None + * @param password None + * @return void + */ +func (a FakeApi) TestEndpointParameters(number float32, double float64, patternWithoutDelimiter string, byte_ string, integer int32, int32_ int32, int64_ int64, float float32, string_ string, binary string, date time.Time, dateTime time.Time, password string) (*APIResponse, error) { + + var localVarHttpMethod = strings.ToUpper("Post") + // create path and map variables + localVarPath := a.Configuration.BasePath + "/fake" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte + // authentication '(http_basic_test)' required + // http basic authentication required + if a.Configuration.UserName != "" || a.Configuration.Password != ""{ + localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString() + } + // add default headers if any + for key := range a.Configuration.DefaultHeader { + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] + } + + + // to determine the Content-Type header + localVarHttpContentTypes := []string{ "application/xml; charset=utf-8", "application/json; charset=utf-8", } + + // set Content-Type header + localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + // to determine the Accept header + localVarHttpHeaderAccepts := []string{ + "application/xml; charset=utf-8", +"application/json; charset=utf-8", + } + + // set Accept header + localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + localVarFormParams["integer"] = a.Configuration.APIClient.ParameterToString(integer, "") + localVarFormParams["int32_"] = a.Configuration.APIClient.ParameterToString(int32_, "") + localVarFormParams["int64_"] = a.Configuration.APIClient.ParameterToString(int64_, "") + localVarFormParams["number"] = a.Configuration.APIClient.ParameterToString(number, "") + localVarFormParams["float"] = a.Configuration.APIClient.ParameterToString(float, "") + localVarFormParams["double"] = a.Configuration.APIClient.ParameterToString(double, "") + localVarFormParams["string_"] = a.Configuration.APIClient.ParameterToString(string_, "") + localVarFormParams["patternWithoutDelimiter"] = a.Configuration.APIClient.ParameterToString(patternWithoutDelimiter, "") + localVarFormParams["byte_"] = a.Configuration.APIClient.ParameterToString(byte_, "") + localVarFormParams["binary"] = a.Configuration.APIClient.ParameterToString(binary, "") + localVarFormParams["date"] = a.Configuration.APIClient.ParameterToString(date, "") + localVarFormParams["dateTime"] = a.Configuration.APIClient.ParameterToString(dateTime, "") + localVarFormParams["password"] = a.Configuration.APIClient.ParameterToString(password, "") + + + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "TestEndpointParameters", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + +if err != nil { + return localVarAPIResponse, err + } + + return localVarAPIResponse, err +} + +/** + * To test enum parameters + * + * @param enumFormStringArray Form parameter enum test (string array) + * @param enumFormString Form parameter enum test (string) + * @param enumHeaderStringArray Header parameter enum test (string array) + * @param enumHeaderString Header parameter enum test (string) + * @param enumQueryStringArray Query parameter enum test (string array) + * @param enumQueryString Query parameter enum test (string) + * @param enumQueryInteger Query parameter enum test (double) + * @param enumQueryDouble Query parameter enum test (double) + * @return void + */ +func (a FakeApi) TestEnumParameters(enumFormStringArray []string, enumFormString string, enumHeaderStringArray []string, enumHeaderString string, enumQueryStringArray []string, enumQueryString string, enumQueryInteger float32, enumQueryDouble float64) (*APIResponse, error) { + + var localVarHttpMethod = strings.ToUpper("Get") + // create path and map variables + localVarPath := a.Configuration.BasePath + "/fake" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte + // add default headers if any + for key := range a.Configuration.DefaultHeader { + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] + } + var collectionFormat = "csv" + if collectionFormat == "multi" { + for _, value := range enumQueryStringArray { + localVarQueryParams.Add("enum_query_string_array", value) + } + } else { + localVarQueryParams.Add("enum_query_string_array", a.Configuration.APIClient.ParameterToString(enumQueryStringArray, collectionFormat)) + } + localVarQueryParams.Add("enum_query_string", a.Configuration.APIClient.ParameterToString(enumQueryString, "")) + localVarQueryParams.Add("enum_query_integer", a.Configuration.APIClient.ParameterToString(enumQueryInteger, "")) + + + // to determine the Content-Type header + localVarHttpContentTypes := []string{ "application/json", } + + // set Content-Type header + localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + // to determine the Accept header + localVarHttpHeaderAccepts := []string{ + "application/json", + } + + // set Accept header + localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + + // header params "enum_header_string_array" + localVarHeaderParams["enum_header_string_array"] = a.Configuration.APIClient.ParameterToString(enumHeaderStringArray, "") + // header params "enum_header_string" + localVarHeaderParams["enum_header_string"] = a.Configuration.APIClient.ParameterToString(enumHeaderString, "") + + localVarFormParams["enumFormStringArray"] = a.Configuration.APIClient.ParameterToString(enumFormStringArray, "") + localVarFormParams["enumFormString"] = a.Configuration.APIClient.ParameterToString(enumFormString, "") + localVarFormParams["enumQueryDouble"] = a.Configuration.APIClient.ParameterToString(enumQueryDouble, "") + + + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "TestEnumParameters", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + +if err != nil { + return localVarAPIResponse, err + } + + return localVarAPIResponse, err +} + diff --git a/samples/client/petstore/go/go-petstore/format_test.go b/samples/client/petstore/go/go-petstore/format_test.go new file mode 100644 index 00000000000..fa370de4d12 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/format_test.go @@ -0,0 +1,56 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +import ( + "time" +) + +type FormatTest struct { + + Integer int32 `json:"integer,omitempty"` + + Int32_ int32 `json:"int32,omitempty"` + + Int64_ int64 `json:"int64,omitempty"` + + Number float32 `json:"number,omitempty"` + + Float float32 `json:"float,omitempty"` + + Double float64 `json:"double,omitempty"` + + String_ string `json:"string,omitempty"` + + Byte_ string `json:"byte,omitempty"` + + Binary string `json:"binary,omitempty"` + + Date time.Time `json:"date,omitempty"` + + DateTime time.Time `json:"dateTime,omitempty"` + + Uuid string `json:"uuid,omitempty"` + + Password string `json:"password,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/has_only_read_only.go b/samples/client/petstore/go/go-petstore/has_only_read_only.go new file mode 100644 index 00000000000..f95600a35bc --- /dev/null +++ b/samples/client/petstore/go/go-petstore/has_only_read_only.go @@ -0,0 +1,30 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type HasOnlyReadOnly struct { + + Bar string `json:"bar,omitempty"` + + Foo string `json:"foo,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/list.go b/samples/client/petstore/go/go-petstore/list.go new file mode 100644 index 00000000000..7fcab1a6d84 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/list.go @@ -0,0 +1,28 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type List struct { + + Var123List string `json:"123-list,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/map_test.go b/samples/client/petstore/go/go-petstore/map_test.go new file mode 100644 index 00000000000..88b060ef3c4 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/map_test.go @@ -0,0 +1,30 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type MapTest struct { + + MapMapOfString map[string]map[string]string `json:"map_map_of_string,omitempty"` + + MapOfEnumString map[string]string `json:"map_of_enum_string,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/mixed_properties_and_additional_properties_class.go b/samples/client/petstore/go/go-petstore/mixed_properties_and_additional_properties_class.go new file mode 100644 index 00000000000..6a34a75cefc --- /dev/null +++ b/samples/client/petstore/go/go-petstore/mixed_properties_and_additional_properties_class.go @@ -0,0 +1,36 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +import ( + "time" +) + +type MixedPropertiesAndAdditionalPropertiesClass struct { + + Uuid string `json:"uuid,omitempty"` + + DateTime time.Time `json:"dateTime,omitempty"` + + Map_ map[string]Animal `json:"map,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/model_200_response.go b/samples/client/petstore/go/go-petstore/model_200_response.go new file mode 100644 index 00000000000..6fefe4b6ab7 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/model_200_response.go @@ -0,0 +1,31 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +// Model for testing model name starting with number +type Model200Response struct { + + Name int32 `json:"name,omitempty"` + + Class string `json:"class,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/model_return.go b/samples/client/petstore/go/go-petstore/model_return.go new file mode 100644 index 00000000000..a2f3244ebf5 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/model_return.go @@ -0,0 +1,29 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +// Model for testing reserved words +type ModelReturn struct { + + Return_ int32 `json:"return,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/name.go b/samples/client/petstore/go/go-petstore/name.go new file mode 100644 index 00000000000..6bde7a16d00 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/name.go @@ -0,0 +1,35 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +// Model for testing model name same as property name +type Name struct { + + Name int32 `json:"name,omitempty"` + + SnakeCase int32 `json:"snake_case,omitempty"` + + Property string `json:"property,omitempty"` + + Var123Number int32 `json:"123Number,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/number_only.go b/samples/client/petstore/go/go-petstore/number_only.go new file mode 100644 index 00000000000..96a0d7f2133 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/number_only.go @@ -0,0 +1,28 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type NumberOnly struct { + + JustNumber float32 `json:"JustNumber,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/pet_api.go b/samples/client/petstore/go/go-petstore/pet_api.go index 04cc352d2bb..23f0380de95 100644 --- a/samples/client/petstore/go/go-petstore/pet_api.go +++ b/samples/client/petstore/go/go-petstore/pet_api.go @@ -24,11 +24,11 @@ package petstore import ( "net/url" + "strings" "os" "io/ioutil" "encoding/json" "fmt" - "strings" ) type PetApi struct { @@ -60,7 +60,7 @@ func NewPetApiWithBasePath(basePath string) *PetApi { */ func (a PetApi) AddPet(body Pet) (*APIResponse, error) { - var localVarHttpMethod = "Post" + var localVarHttpMethod = strings.ToUpper("Post") // create path and map variables localVarPath := a.Configuration.BasePath + "/pet" @@ -105,11 +105,20 @@ func (a PetApi) AddPet(body Pet) (*APIResponse, error) { localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - if err != nil { - return NewAPIResponse(localVarHttpResponse.RawResponse), err + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "AddPet", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() } - return NewAPIResponse(localVarHttpResponse.RawResponse), err +if err != nil { + return localVarAPIResponse, err + } + + return localVarAPIResponse, err } /** @@ -122,7 +131,7 @@ func (a PetApi) AddPet(body Pet) (*APIResponse, error) { */ func (a PetApi) DeletePet(petId int64, apiKey string) (*APIResponse, error) { - var localVarHttpMethod = "Delete" + var localVarHttpMethod = strings.ToUpper("Delete") // create path and map variables localVarPath := a.Configuration.BasePath + "/pet/{petId}" localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", fmt.Sprintf("%v", petId), -1) @@ -170,11 +179,20 @@ func (a PetApi) DeletePet(petId int64, apiKey string) (*APIResponse, error) { localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - if err != nil { - return NewAPIResponse(localVarHttpResponse.RawResponse), err + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "DeletePet", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() } - return NewAPIResponse(localVarHttpResponse.RawResponse), err +if err != nil { + return localVarAPIResponse, err + } + + return localVarAPIResponse, err } /** @@ -186,7 +204,7 @@ func (a PetApi) DeletePet(petId int64, apiKey string) (*APIResponse, error) { */ func (a PetApi) FindPetsByStatus(status []string) ([]Pet, *APIResponse, error) { - var localVarHttpMethod = "Get" + var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables localVarPath := a.Configuration.BasePath + "/pet/findByStatus" @@ -237,11 +255,20 @@ func (a PetApi) FindPetsByStatus(status []string) ([]Pet, *APIResponse, error) { var successPayload = new([]Pet) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - if err != nil { - return *successPayload, NewAPIResponse(localVarHttpResponse.RawResponse), err + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "FindPetsByStatus", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + +if err != nil { + return *successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return *successPayload, NewAPIResponse(localVarHttpResponse.RawResponse), err + return *successPayload, localVarAPIResponse, err } /** @@ -253,7 +280,7 @@ func (a PetApi) FindPetsByStatus(status []string) ([]Pet, *APIResponse, error) { */ func (a PetApi) FindPetsByTags(tags []string) ([]Pet, *APIResponse, error) { - var localVarHttpMethod = "Get" + var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables localVarPath := a.Configuration.BasePath + "/pet/findByTags" @@ -304,11 +331,20 @@ func (a PetApi) FindPetsByTags(tags []string) ([]Pet, *APIResponse, error) { var successPayload = new([]Pet) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - if err != nil { - return *successPayload, NewAPIResponse(localVarHttpResponse.RawResponse), err + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "FindPetsByTags", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + +if err != nil { + return *successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return *successPayload, NewAPIResponse(localVarHttpResponse.RawResponse), err + return *successPayload, localVarAPIResponse, err } /** @@ -320,7 +356,7 @@ func (a PetApi) FindPetsByTags(tags []string) ([]Pet, *APIResponse, error) { */ func (a PetApi) GetPetById(petId int64) (*Pet, *APIResponse, error) { - var localVarHttpMethod = "Get" + var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables localVarPath := a.Configuration.BasePath + "/pet/{petId}" localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", fmt.Sprintf("%v", petId), -1) @@ -362,11 +398,20 @@ func (a PetApi) GetPetById(petId int64) (*Pet, *APIResponse, error) { var successPayload = new(Pet) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - if err != nil { - return successPayload, NewAPIResponse(localVarHttpResponse.RawResponse), err + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "GetPetById", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + +if err != nil { + return successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, NewAPIResponse(localVarHttpResponse.RawResponse), err + return successPayload, localVarAPIResponse, err } /** @@ -378,7 +423,7 @@ func (a PetApi) GetPetById(petId int64) (*Pet, *APIResponse, error) { */ func (a PetApi) UpdatePet(body Pet) (*APIResponse, error) { - var localVarHttpMethod = "Put" + var localVarHttpMethod = strings.ToUpper("Put") // create path and map variables localVarPath := a.Configuration.BasePath + "/pet" @@ -423,11 +468,20 @@ func (a PetApi) UpdatePet(body Pet) (*APIResponse, error) { localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - if err != nil { - return NewAPIResponse(localVarHttpResponse.RawResponse), err + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "UpdatePet", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + +if err != nil { + return localVarAPIResponse, err } - return NewAPIResponse(localVarHttpResponse.RawResponse), err + return localVarAPIResponse, err } /** @@ -441,7 +495,7 @@ func (a PetApi) UpdatePet(body Pet) (*APIResponse, error) { */ func (a PetApi) UpdatePetWithForm(petId int64, name string, status string) (*APIResponse, error) { - var localVarHttpMethod = "Post" + var localVarHttpMethod = strings.ToUpper("Post") // create path and map variables localVarPath := a.Configuration.BasePath + "/pet/{petId}" localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", fmt.Sprintf("%v", petId), -1) @@ -487,11 +541,20 @@ func (a PetApi) UpdatePetWithForm(petId int64, name string, status string) (*API localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - if err != nil { - return NewAPIResponse(localVarHttpResponse.RawResponse), err + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "UpdatePetWithForm", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + +if err != nil { + return localVarAPIResponse, err } - return NewAPIResponse(localVarHttpResponse.RawResponse), err + return localVarAPIResponse, err } /** @@ -505,7 +568,7 @@ func (a PetApi) UpdatePetWithForm(petId int64, name string, status string) (*API */ func (a PetApi) UploadFile(petId int64, additionalMetadata string, file *os.File) (*ModelApiResponse, *APIResponse, error) { - var localVarHttpMethod = "Post" + var localVarHttpMethod = strings.ToUpper("Post") // create path and map variables localVarPath := a.Configuration.BasePath + "/pet/{petId}/uploadImage" localVarPath = strings.Replace(localVarPath, "{"+"petId"+"}", fmt.Sprintf("%v", petId), -1) @@ -552,10 +615,19 @@ func (a PetApi) UploadFile(petId int64, additionalMetadata string, file *os.File var successPayload = new(ModelApiResponse) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - if err != nil { - return successPayload, NewAPIResponse(localVarHttpResponse.RawResponse), err + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "UploadFile", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + +if err != nil { + return successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, NewAPIResponse(localVarHttpResponse.RawResponse), err + return successPayload, localVarAPIResponse, err } diff --git a/samples/client/petstore/go/go-petstore/read_only_first.go b/samples/client/petstore/go/go-petstore/read_only_first.go new file mode 100644 index 00000000000..9d8e6351fdf --- /dev/null +++ b/samples/client/petstore/go/go-petstore/read_only_first.go @@ -0,0 +1,30 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type ReadOnlyFirst struct { + + Bar string `json:"bar,omitempty"` + + Baz string `json:"baz,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/special_model_name.go b/samples/client/petstore/go/go-petstore/special_model_name.go new file mode 100644 index 00000000000..7bbb2093ef4 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/special_model_name.go @@ -0,0 +1,28 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type SpecialModelName struct { + + SpecialPropertyName int64 `json:"$special[property.name],omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/store_api.go b/samples/client/petstore/go/go-petstore/store_api.go index 898dc59d264..9318add7d6c 100644 --- a/samples/client/petstore/go/go-petstore/store_api.go +++ b/samples/client/petstore/go/go-petstore/store_api.go @@ -24,9 +24,9 @@ package petstore import ( "net/url" + "strings" "encoding/json" "fmt" - "strings" ) type StoreApi struct { @@ -58,7 +58,7 @@ func NewStoreApiWithBasePath(basePath string) *StoreApi { */ func (a StoreApi) DeleteOrder(orderId string) (*APIResponse, error) { - var localVarHttpMethod = "Delete" + var localVarHttpMethod = strings.ToUpper("Delete") // create path and map variables localVarPath := a.Configuration.BasePath + "/store/order/{orderId}" localVarPath = strings.Replace(localVarPath, "{"+"orderId"+"}", fmt.Sprintf("%v", orderId), -1) @@ -97,11 +97,20 @@ func (a StoreApi) DeleteOrder(orderId string) (*APIResponse, error) { localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - if err != nil { - return NewAPIResponse(localVarHttpResponse.RawResponse), err + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "DeleteOrder", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() } - return NewAPIResponse(localVarHttpResponse.RawResponse), err +if err != nil { + return localVarAPIResponse, err + } + + return localVarAPIResponse, err } /** @@ -112,7 +121,7 @@ func (a StoreApi) DeleteOrder(orderId string) (*APIResponse, error) { */ func (a StoreApi) GetInventory() (*map[string]int32, *APIResponse, error) { - var localVarHttpMethod = "Get" + var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables localVarPath := a.Configuration.BasePath + "/store/inventory" @@ -152,11 +161,20 @@ func (a StoreApi) GetInventory() (*map[string]int32, *APIResponse, error) { var successPayload = new(map[string]int32) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - if err != nil { - return successPayload, NewAPIResponse(localVarHttpResponse.RawResponse), err + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "GetInventory", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + +if err != nil { + return successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, NewAPIResponse(localVarHttpResponse.RawResponse), err + return successPayload, localVarAPIResponse, err } /** @@ -168,7 +186,7 @@ func (a StoreApi) GetInventory() (*map[string]int32, *APIResponse, error) { */ func (a StoreApi) GetOrderById(orderId int64) (*Order, *APIResponse, error) { - var localVarHttpMethod = "Get" + var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables localVarPath := a.Configuration.BasePath + "/store/order/{orderId}" localVarPath = strings.Replace(localVarPath, "{"+"orderId"+"}", fmt.Sprintf("%v", orderId), -1) @@ -207,11 +225,20 @@ func (a StoreApi) GetOrderById(orderId int64) (*Order, *APIResponse, error) { var successPayload = new(Order) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - if err != nil { - return successPayload, NewAPIResponse(localVarHttpResponse.RawResponse), err + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "GetOrderById", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + +if err != nil { + return successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, NewAPIResponse(localVarHttpResponse.RawResponse), err + return successPayload, localVarAPIResponse, err } /** @@ -223,7 +250,7 @@ func (a StoreApi) GetOrderById(orderId int64) (*Order, *APIResponse, error) { */ func (a StoreApi) PlaceOrder(body Order) (*Order, *APIResponse, error) { - var localVarHttpMethod = "Post" + var localVarHttpMethod = strings.ToUpper("Post") // create path and map variables localVarPath := a.Configuration.BasePath + "/store/order" @@ -263,10 +290,19 @@ func (a StoreApi) PlaceOrder(body Order) (*Order, *APIResponse, error) { var successPayload = new(Order) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - if err != nil { - return successPayload, NewAPIResponse(localVarHttpResponse.RawResponse), err + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "PlaceOrder", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + +if err != nil { + return successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, NewAPIResponse(localVarHttpResponse.RawResponse), err + return successPayload, localVarAPIResponse, err } diff --git a/samples/client/petstore/go/go-petstore/user_api.go b/samples/client/petstore/go/go-petstore/user_api.go index 262312d986a..04f8fe4cfe6 100644 --- a/samples/client/petstore/go/go-petstore/user_api.go +++ b/samples/client/petstore/go/go-petstore/user_api.go @@ -24,9 +24,9 @@ package petstore import ( "net/url" + "strings" "encoding/json" "fmt" - "strings" ) type UserApi struct { @@ -58,7 +58,7 @@ func NewUserApiWithBasePath(basePath string) *UserApi { */ func (a UserApi) CreateUser(body User) (*APIResponse, error) { - var localVarHttpMethod = "Post" + var localVarHttpMethod = strings.ToUpper("Post") // create path and map variables localVarPath := a.Configuration.BasePath + "/user" @@ -98,11 +98,20 @@ func (a UserApi) CreateUser(body User) (*APIResponse, error) { localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - if err != nil { - return NewAPIResponse(localVarHttpResponse.RawResponse), err + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "CreateUser", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() } - return NewAPIResponse(localVarHttpResponse.RawResponse), err +if err != nil { + return localVarAPIResponse, err + } + + return localVarAPIResponse, err } /** @@ -114,7 +123,7 @@ func (a UserApi) CreateUser(body User) (*APIResponse, error) { */ func (a UserApi) CreateUsersWithArrayInput(body []User) (*APIResponse, error) { - var localVarHttpMethod = "Post" + var localVarHttpMethod = strings.ToUpper("Post") // create path and map variables localVarPath := a.Configuration.BasePath + "/user/createWithArray" @@ -154,11 +163,20 @@ func (a UserApi) CreateUsersWithArrayInput(body []User) (*APIResponse, error) { localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - if err != nil { - return NewAPIResponse(localVarHttpResponse.RawResponse), err + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "CreateUsersWithArrayInput", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() } - return NewAPIResponse(localVarHttpResponse.RawResponse), err +if err != nil { + return localVarAPIResponse, err + } + + return localVarAPIResponse, err } /** @@ -170,7 +188,7 @@ func (a UserApi) CreateUsersWithArrayInput(body []User) (*APIResponse, error) { */ func (a UserApi) CreateUsersWithListInput(body []User) (*APIResponse, error) { - var localVarHttpMethod = "Post" + var localVarHttpMethod = strings.ToUpper("Post") // create path and map variables localVarPath := a.Configuration.BasePath + "/user/createWithList" @@ -210,11 +228,20 @@ func (a UserApi) CreateUsersWithListInput(body []User) (*APIResponse, error) { localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - if err != nil { - return NewAPIResponse(localVarHttpResponse.RawResponse), err + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "CreateUsersWithListInput", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + +if err != nil { + return localVarAPIResponse, err } - return NewAPIResponse(localVarHttpResponse.RawResponse), err + return localVarAPIResponse, err } /** @@ -226,7 +253,7 @@ func (a UserApi) CreateUsersWithListInput(body []User) (*APIResponse, error) { */ func (a UserApi) DeleteUser(username string) (*APIResponse, error) { - var localVarHttpMethod = "Delete" + var localVarHttpMethod = strings.ToUpper("Delete") // create path and map variables localVarPath := a.Configuration.BasePath + "/user/{username}" localVarPath = strings.Replace(localVarPath, "{"+"username"+"}", fmt.Sprintf("%v", username), -1) @@ -265,11 +292,20 @@ func (a UserApi) DeleteUser(username string) (*APIResponse, error) { localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - if err != nil { - return NewAPIResponse(localVarHttpResponse.RawResponse), err + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "DeleteUser", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + +if err != nil { + return localVarAPIResponse, err } - return NewAPIResponse(localVarHttpResponse.RawResponse), err + return localVarAPIResponse, err } /** @@ -281,7 +317,7 @@ func (a UserApi) DeleteUser(username string) (*APIResponse, error) { */ func (a UserApi) GetUserByName(username string) (*User, *APIResponse, error) { - var localVarHttpMethod = "Get" + var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables localVarPath := a.Configuration.BasePath + "/user/{username}" localVarPath = strings.Replace(localVarPath, "{"+"username"+"}", fmt.Sprintf("%v", username), -1) @@ -320,11 +356,20 @@ func (a UserApi) GetUserByName(username string) (*User, *APIResponse, error) { var successPayload = new(User) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - if err != nil { - return successPayload, NewAPIResponse(localVarHttpResponse.RawResponse), err + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "GetUserByName", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + +if err != nil { + return successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, NewAPIResponse(localVarHttpResponse.RawResponse), err + return successPayload, localVarAPIResponse, err } /** @@ -337,7 +382,7 @@ func (a UserApi) GetUserByName(username string) (*User, *APIResponse, error) { */ func (a UserApi) LoginUser(username string, password string) (*string, *APIResponse, error) { - var localVarHttpMethod = "Get" + var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables localVarPath := a.Configuration.BasePath + "/user/login" @@ -377,11 +422,20 @@ func (a UserApi) LoginUser(username string, password string) (*string, *APIRespo var successPayload = new(string) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - if err != nil { - return successPayload, NewAPIResponse(localVarHttpResponse.RawResponse), err + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "LoginUser", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + +if err != nil { + return successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, NewAPIResponse(localVarHttpResponse.RawResponse), err + return successPayload, localVarAPIResponse, err } /** @@ -392,7 +446,7 @@ func (a UserApi) LoginUser(username string, password string) (*string, *APIRespo */ func (a UserApi) LogoutUser() (*APIResponse, error) { - var localVarHttpMethod = "Get" + var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables localVarPath := a.Configuration.BasePath + "/user/logout" @@ -430,11 +484,20 @@ func (a UserApi) LogoutUser() (*APIResponse, error) { localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - if err != nil { - return NewAPIResponse(localVarHttpResponse.RawResponse), err + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "LogoutUser", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + +if err != nil { + return localVarAPIResponse, err } - return NewAPIResponse(localVarHttpResponse.RawResponse), err + return localVarAPIResponse, err } /** @@ -447,7 +510,7 @@ func (a UserApi) LogoutUser() (*APIResponse, error) { */ func (a UserApi) UpdateUser(username string, body User) (*APIResponse, error) { - var localVarHttpMethod = "Put" + var localVarHttpMethod = strings.ToUpper("Put") // create path and map variables localVarPath := a.Configuration.BasePath + "/user/{username}" localVarPath = strings.Replace(localVarPath, "{"+"username"+"}", fmt.Sprintf("%v", username), -1) @@ -488,10 +551,19 @@ func (a UserApi) UpdateUser(username string, body User) (*APIResponse, error) { localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - if err != nil { - return NewAPIResponse(localVarHttpResponse.RawResponse), err + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "UpdateUser", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + +if err != nil { + return localVarAPIResponse, err } - return NewAPIResponse(localVarHttpResponse.RawResponse), err + return localVarAPIResponse, err } From 1539986984a78e083864c0fa5ee59b2af0d7d304 Mon Sep 17 00:00:00 2001 From: Kim Sondrup Date: Sat, 3 Sep 2016 10:06:07 +0200 Subject: [PATCH 324/470] [PHP] Corrected PHPDoc type declarations (#3710) * [PHP] Corrected PHPDoc type declarations * Update petstore PHP --- .../resources/php/ObjectSerializer.mustache | 23 ++++++++++--------- .../src/main/resources/php/api.mustache | 2 +- .../main/resources/php/configuration.mustache | 10 ++++---- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 6 ++--- .../php/SwaggerClient-php/lib/Api/PetApi.php | 16 ++++++------- .../SwaggerClient-php/lib/Api/StoreApi.php | 8 +++---- .../php/SwaggerClient-php/lib/Api/UserApi.php | 16 ++++++------- .../SwaggerClient-php/lib/Configuration.php | 10 ++++---- .../lib/ObjectSerializer.php | 23 ++++++++++--------- 9 files changed, 58 insertions(+), 56 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache index 4f99eaac4c3..10f94686507 100644 --- a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache @@ -37,7 +37,7 @@ class ObjectSerializer * * @param mixed $data the data to serialize * - * @return string serialized form of $data + * @return string|object serialized form of $data */ public static function sanitizeForSerialization($data) { @@ -100,7 +100,7 @@ class ObjectSerializer * If it's a string, pass through unchanged. It will be url-encoded * later. * - * @param object $object an object to be serialized to a string + * @param string[]|string|\DateTime $object an object to be serialized to a string * * @return string the serialized object */ @@ -132,7 +132,7 @@ class ObjectSerializer * the http body (form parameter). If it's a string, pass through unchanged * If it's a datetime object, format it in ISO8601 * - * @param string $value the value of the form parameter + * @param string|\SplFileObject $value the value of the form parameter * * @return string the form string */ @@ -150,7 +150,7 @@ class ObjectSerializer * the parameter. If it's a string, pass through unchanged * If it's a datetime object, format it in ISO8601 * - * @param string $value the value of the parameter + * @param string|\DateTime $value the value of the parameter * * @return string the header string */ @@ -166,9 +166,10 @@ class ObjectSerializer /** * Serialize an array to a string. * - * @param array $collection collection to serialize to a string - * @param string $collectionFormat the format use for serialization (csv, + * @param array $collection collection to serialize to a string + * @param string $collectionFormat the format use for serialization (csv, * ssv, tsv, pipes, multi) + * @param bool $allowCollectionFormatMulti allow collection format to be a multidimensional array * * @return string */ @@ -199,12 +200,12 @@ class ObjectSerializer /** * Deserialize a JSON string into an object * - * @param mixed $data object or primitive to be deserialized - * @param string $class class name is passed as a string - * @param string $httpHeaders HTTP headers - * @param string $discriminator discriminator if polymorphism is used + * @param mixed $data object or primitive to be deserialized + * @param string $class class name is passed as a string + * @param string[] $httpHeaders HTTP headers + * @param string $discriminator discriminator if polymorphism is used * - * @return object an instance of $class + * @return object|array|null an single or an array of $class instances */ public static function deserialize($data, $class, $httpHeaders = null, $discriminator = null) { diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index f039a6baa17..bb9f5e400d7 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -115,7 +115,7 @@ use \{{invokerPackage}}\ObjectSerializer; {{#allParams}} * @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} {{/allParams}} - * @return Array of {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}null{{/returnType}}, HTTP status code, HTTP response headers (array of strings) + * @return array of {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}null{{/returnType}}, HTTP status code, HTTP response headers (array of strings) * @throws \{{invokerPackage}}\ApiException on non-2xx response */ public function {{operationId}}WithHttpInfo({{#allParams}}${{paramName}}{{^required}} = null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/configuration.mustache index 7e3883cf9c4..ee8a83bde58 100644 --- a/modules/swagger-codegen/src/main/resources/php/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/configuration.mustache @@ -70,9 +70,9 @@ class Configuration protected $password = ''; /** - * The default instance of ApiClient + * The default header(s) * - * @var \{{invokerPackage}}\ApiClient + * @var array */ protected $defaultHeaders = array(); @@ -262,7 +262,7 @@ class Configuration * @param string $headerName header name (e.g. Token) * @param string $headerValue header value (e.g. 1z8wp3) * - * @return ApiClient + * @return Configuration */ public function addDefaultHeader($headerName, $headerValue) { @@ -324,7 +324,7 @@ class Configuration * * @param string $userAgent the user agent of the api client * - * @return ApiClient + * @return Configuration */ public function setUserAgent($userAgent) { @@ -351,7 +351,7 @@ class Configuration * * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] * - * @return ApiClient + * @return Configuration */ public function setCurlTimeout($seconds) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index 3635aebefe8..d0403636db5 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -123,7 +123,7 @@ public function testClientModel($body) * To test \"client\" model * * @param \Swagger\Client\Model\Client $body client model (required) - * @return Array of \Swagger\Client\Model\Client, HTTP status code, HTTP response headers (array of strings) + * @return array of \Swagger\Client\Model\Client, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ public function testClientModelWithHttpInfo($body) @@ -229,7 +229,7 @@ public function testEndpointParameters($number, $double, $pattern_without_delimi * @param \DateTime $date None (optional) * @param \DateTime $date_time None (optional) * @param string $password None (optional) - * @return Array of null, HTTP status code, HTTP response headers (array of strings) + * @return array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_without_delimiter, $byte, $integer = null, $int32 = null, $int64 = null, $float = null, $string = null, $binary = null, $date = null, $date_time = null, $password = null) @@ -431,7 +431,7 @@ public function testEnumParameters($enum_form_string_array = null, $enum_form_st * @param string $enum_query_string Query parameter enum test (string) (optional, default to -efg) * @param float $enum_query_integer Query parameter enum test (double) (optional) * @param double $enum_query_double Query parameter enum test (double) (optional) - * @return Array of null, HTTP status code, HTTP response headers (array of strings) + * @return array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $enum_form_string = null, $enum_header_string_array = null, $enum_header_string = null, $enum_query_string_array = null, $enum_query_string = null, $enum_query_integer = null, $enum_query_double = null) 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 98ebca4f6dd..53ee7866716 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -123,7 +123,7 @@ public function addPet($body) * Add a new pet to the store * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) - * @return Array of null, HTTP status code, HTTP response headers (array of strings) + * @return array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ public function addPetWithHttpInfo($body) @@ -207,7 +207,7 @@ public function deletePet($pet_id, $api_key = null) * * @param int $pet_id Pet id to delete (required) * @param string $api_key (optional) - * @return Array of null, HTTP status code, HTTP response headers (array of strings) + * @return array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ public function deletePetWithHttpInfo($pet_id, $api_key = null) @@ -296,7 +296,7 @@ public function findPetsByStatus($status) * Finds Pets by status * * @param string[] $status Status values that need to be considered for filter (required) - * @return Array of \Swagger\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) + * @return array of \Swagger\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ public function findPetsByStatusWithHttpInfo($status) @@ -384,7 +384,7 @@ public function findPetsByTags($tags) * Finds Pets by tags * * @param string[] $tags Tags to filter by (required) - * @return Array of \Swagger\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) + * @return array of \Swagger\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ public function findPetsByTagsWithHttpInfo($tags) @@ -472,7 +472,7 @@ public function getPetById($pet_id) * Find pet by ID * * @param int $pet_id ID of pet to return (required) - * @return Array of \Swagger\Client\Model\Pet, HTTP status code, HTTP response headers (array of strings) + * @return array of \Swagger\Client\Model\Pet, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ public function getPetByIdWithHttpInfo($pet_id) @@ -562,7 +562,7 @@ public function updatePet($body) * Update an existing pet * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) - * @return Array of null, HTTP status code, HTTP response headers (array of strings) + * @return array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ public function updatePetWithHttpInfo($body) @@ -648,7 +648,7 @@ public function updatePetWithForm($pet_id, $name = null, $status = null) * @param int $pet_id ID of pet that needs to be updated (required) * @param string $name Updated name of the pet (optional) * @param string $status Updated status of the pet (optional) - * @return Array of null, HTTP status code, HTTP response headers (array of strings) + * @return array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = null) @@ -745,7 +745,7 @@ public function uploadFile($pet_id, $additional_metadata = null, $file = null) * @param int $pet_id ID of pet to update (required) * @param string $additional_metadata Additional data to pass to server (optional) * @param \SplFileObject $file file to upload (optional) - * @return Array of \Swagger\Client\Model\ApiResponse, HTTP status code, HTTP response headers (array of strings) + * @return array of \Swagger\Client\Model\ApiResponse, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $file = null) 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 679d67b94ed..63ece203576 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -123,7 +123,7 @@ public function deleteOrder($order_id) * Delete purchase order by ID * * @param string $order_id ID of the order that needs to be deleted (required) - * @return Array of null, HTTP status code, HTTP response headers (array of strings) + * @return array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ public function deleteOrderWithHttpInfo($order_id) @@ -206,7 +206,7 @@ public function getInventory() * * Returns pet inventories by status * - * @return Array of map[string,int], HTTP status code, HTTP response headers (array of strings) + * @return array of map[string,int], HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ public function getInventoryWithHttpInfo() @@ -284,7 +284,7 @@ public function getOrderById($order_id) * Find purchase order by ID * * @param int $order_id ID of pet that needs to be fetched (required) - * @return Array of \Swagger\Client\Model\Order, HTTP status code, HTTP response headers (array of strings) + * @return array of \Swagger\Client\Model\Order, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ public function getOrderByIdWithHttpInfo($order_id) @@ -376,7 +376,7 @@ public function placeOrder($body) * Place an order for a pet * * @param \Swagger\Client\Model\Order $body order placed for purchasing the pet (required) - * @return Array of \Swagger\Client\Model\Order, HTTP status code, HTTP response headers (array of strings) + * @return array of \Swagger\Client\Model\Order, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ public function placeOrderWithHttpInfo($body) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index ac046ad5086..5d738494fc5 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -123,7 +123,7 @@ public function createUser($body) * Create user * * @param \Swagger\Client\Model\User $body Created user object (required) - * @return Array of null, HTTP status code, HTTP response headers (array of strings) + * @return array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ public function createUserWithHttpInfo($body) @@ -201,7 +201,7 @@ public function createUsersWithArrayInput($body) * Creates list of users with given input array * * @param \Swagger\Client\Model\User[] $body List of user object (required) - * @return Array of null, HTTP status code, HTTP response headers (array of strings) + * @return array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ public function createUsersWithArrayInputWithHttpInfo($body) @@ -279,7 +279,7 @@ public function createUsersWithListInput($body) * Creates list of users with given input array * * @param \Swagger\Client\Model\User[] $body List of user object (required) - * @return Array of null, HTTP status code, HTTP response headers (array of strings) + * @return array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ public function createUsersWithListInputWithHttpInfo($body) @@ -357,7 +357,7 @@ public function deleteUser($username) * Delete user * * @param string $username The name that needs to be deleted (required) - * @return Array of null, HTTP status code, HTTP response headers (array of strings) + * @return array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ public function deleteUserWithHttpInfo($username) @@ -438,7 +438,7 @@ public function getUserByName($username) * Get user by user name * * @param string $username The name that needs to be fetched. Use user1 for testing. (required) - * @return Array of \Swagger\Client\Model\User, HTTP status code, HTTP response headers (array of strings) + * @return array of \Swagger\Client\Model\User, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ public function getUserByNameWithHttpInfo($username) @@ -525,7 +525,7 @@ public function loginUser($username, $password) * * @param string $username The user name for login (required) * @param string $password The password for login in clear text (required) - * @return Array of string, HTTP status code, HTTP response headers (array of strings) + * @return array of string, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ public function loginUserWithHttpInfo($username, $password) @@ -612,7 +612,7 @@ public function logoutUser() * * Logs out current logged in user session * - * @return Array of null, HTTP status code, HTTP response headers (array of strings) + * @return array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ public function logoutUserWithHttpInfo() @@ -683,7 +683,7 @@ public function updateUser($username, $body) * * @param string $username name that need to be deleted (required) * @param \Swagger\Client\Model\User $body Updated user object (required) - * @return Array of null, HTTP status code, HTTP response headers (array of strings) + * @return array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ public function updateUserWithHttpInfo($username, $body) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index 98bb4ab2c17..20946f7bc5f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -91,9 +91,9 @@ class Configuration protected $password = ''; /** - * The default instance of ApiClient + * The default header(s) * - * @var \Swagger\Client\ApiClient + * @var array */ protected $defaultHeaders = array(); @@ -283,7 +283,7 @@ public function getPassword() * @param string $headerName header name (e.g. Token) * @param string $headerValue header value (e.g. 1z8wp3) * - * @return ApiClient + * @return Configuration */ public function addDefaultHeader($headerName, $headerValue) { @@ -345,7 +345,7 @@ public function getHost() * * @param string $userAgent the user agent of the api client * - * @return ApiClient + * @return Configuration */ public function setUserAgent($userAgent) { @@ -372,7 +372,7 @@ public function getUserAgent() * * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] * - * @return ApiClient + * @return Configuration */ public function setCurlTimeout($seconds) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php index f8c592c67cb..516ad2519cf 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -58,7 +58,7 @@ class ObjectSerializer * * @param mixed $data the data to serialize * - * @return string serialized form of $data + * @return string|object serialized form of $data */ public static function sanitizeForSerialization($data) { @@ -121,7 +121,7 @@ public function toPathValue($value) * If it's a string, pass through unchanged. It will be url-encoded * later. * - * @param object $object an object to be serialized to a string + * @param string[]|string|\DateTime $object an object to be serialized to a string * * @return string the serialized object */ @@ -153,7 +153,7 @@ public function toHeaderValue($value) * the http body (form parameter). If it's a string, pass through unchanged * If it's a datetime object, format it in ISO8601 * - * @param string $value the value of the form parameter + * @param string|\SplFileObject $value the value of the form parameter * * @return string the form string */ @@ -171,7 +171,7 @@ public function toFormValue($value) * the parameter. If it's a string, pass through unchanged * If it's a datetime object, format it in ISO8601 * - * @param string $value the value of the parameter + * @param string|\DateTime $value the value of the parameter * * @return string the header string */ @@ -187,9 +187,10 @@ public function toString($value) /** * Serialize an array to a string. * - * @param array $collection collection to serialize to a string - * @param string $collectionFormat the format use for serialization (csv, + * @param array $collection collection to serialize to a string + * @param string $collectionFormat the format use for serialization (csv, * ssv, tsv, pipes, multi) + * @param bool $allowCollectionFormatMulti allow collection format to be a multidimensional array * * @return string */ @@ -220,12 +221,12 @@ public function serializeCollection(array $collection, $collectionFormat, $allow /** * Deserialize a JSON string into an object * - * @param mixed $data object or primitive to be deserialized - * @param string $class class name is passed as a string - * @param string $httpHeaders HTTP headers - * @param string $discriminator discriminator if polymorphism is used + * @param mixed $data object or primitive to be deserialized + * @param string $class class name is passed as a string + * @param string[] $httpHeaders HTTP headers + * @param string $discriminator discriminator if polymorphism is used * - * @return object an instance of $class + * @return object|array|null an single or an array of $class instances */ public static function deserialize($data, $class, $httpHeaders = null, $discriminator = null) { From 92aa8ed767f8d442b7ccafdd6e884e3f8072f16a Mon Sep 17 00:00:00 2001 From: Masahiro Saito Date: Mon, 5 Sep 2016 16:37:54 +0900 Subject: [PATCH 325/470] [Ruby] Fix ambiguous regex (#3716) * ruby: Fix ambiguous regex * ruby: Add test for strict regex --- .../src/main/resources/ruby/base_object.mustache | 2 +- .../ruby/lib/petstore/models/additional_properties_class.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/animal.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/animal_farm.rb | 2 +- .../client/petstore/ruby/lib/petstore/models/api_response.rb | 2 +- .../ruby/lib/petstore/models/array_of_array_of_number_only.rb | 2 +- .../petstore/ruby/lib/petstore/models/array_of_number_only.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/array_test.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/cat.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/category.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/client.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/dog.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/enum_arrays.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/enum_test.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/format_test.rb | 2 +- .../petstore/ruby/lib/petstore/models/has_only_read_only.rb | 2 +- .../petstore/ruby/lib/petstore/models/inline_response_200.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/list.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/map_test.rb | 2 +- .../models/mixed_properties_and_additional_properties_class.rb | 2 +- .../petstore/ruby/lib/petstore/models/model_200_response.rb | 2 +- .../client/petstore/ruby/lib/petstore/models/model_return.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/name.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/number_only.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/order.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/pet.rb | 2 +- .../client/petstore/ruby/lib/petstore/models/read_only_first.rb | 2 +- .../petstore/ruby/lib/petstore/models/special_model_name.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/tag.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/user.rb | 2 +- samples/client/petstore/ruby/spec/base_object_spec.rb | 2 +- 31 files changed, 31 insertions(+), 31 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache index 0c15a9929f3..a28437fc695 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache @@ -35,7 +35,7 @@ when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false diff --git a/samples/client/petstore/ruby/lib/petstore/models/additional_properties_class.rb b/samples/client/petstore/ruby/lib/petstore/models/additional_properties_class.rb index 27bb91fea38..b9ee9a3693f 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/additional_properties_class.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/additional_properties_class.rb @@ -140,7 +140,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false diff --git a/samples/client/petstore/ruby/lib/petstore/models/animal.rb b/samples/client/petstore/ruby/lib/petstore/models/animal.rb index 692c736e98e..24b4788705a 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/animal.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/animal.rb @@ -139,7 +139,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false diff --git a/samples/client/petstore/ruby/lib/petstore/models/animal_farm.rb b/samples/client/petstore/ruby/lib/petstore/models/animal_farm.rb index 71a87330302..1966d1cb440 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/animal_farm.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/animal_farm.rb @@ -118,7 +118,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false diff --git a/samples/client/petstore/ruby/lib/petstore/models/api_response.rb b/samples/client/petstore/ruby/lib/petstore/models/api_response.rb index e8c413b5b4f..cf9f163d5b3 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/api_response.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/api_response.rb @@ -145,7 +145,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false diff --git a/samples/client/petstore/ruby/lib/petstore/models/array_of_array_of_number_only.rb b/samples/client/petstore/ruby/lib/petstore/models/array_of_array_of_number_only.rb index 779608824ad..fbc3f8df519 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/array_of_array_of_number_only.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/array_of_array_of_number_only.rb @@ -129,7 +129,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false diff --git a/samples/client/petstore/ruby/lib/petstore/models/array_of_number_only.rb b/samples/client/petstore/ruby/lib/petstore/models/array_of_number_only.rb index 6077f9a5584..2e8cc072211 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/array_of_number_only.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/array_of_number_only.rb @@ -129,7 +129,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false diff --git a/samples/client/petstore/ruby/lib/petstore/models/array_test.rb b/samples/client/petstore/ruby/lib/petstore/models/array_test.rb index 8a005f1c5cd..1e30d141430 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/array_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/array_test.rb @@ -151,7 +151,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false diff --git a/samples/client/petstore/ruby/lib/petstore/models/cat.rb b/samples/client/petstore/ruby/lib/petstore/models/cat.rb index 8eb06e9ee9f..ca5dfa12dae 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/cat.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/cat.rb @@ -148,7 +148,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false diff --git a/samples/client/petstore/ruby/lib/petstore/models/category.rb b/samples/client/petstore/ruby/lib/petstore/models/category.rb index 2edd8b0bbe2..849b0c96dd9 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/category.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/category.rb @@ -136,7 +136,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false diff --git a/samples/client/petstore/ruby/lib/petstore/models/client.rb b/samples/client/petstore/ruby/lib/petstore/models/client.rb index c7663e0d6c1..186894b8338 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/client.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/client.rb @@ -127,7 +127,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false diff --git a/samples/client/petstore/ruby/lib/petstore/models/dog.rb b/samples/client/petstore/ruby/lib/petstore/models/dog.rb index ceaeb2714e9..5a481c524a6 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/dog.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/dog.rb @@ -148,7 +148,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false diff --git a/samples/client/petstore/ruby/lib/petstore/models/enum_arrays.rb b/samples/client/petstore/ruby/lib/petstore/models/enum_arrays.rb index 1c56f3a2db2..194aa26460e 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/enum_arrays.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/enum_arrays.rb @@ -171,7 +171,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false diff --git a/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb b/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb index ab6e17324d4..f9c36700349 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb @@ -202,7 +202,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false diff --git a/samples/client/petstore/ruby/lib/petstore/models/format_test.rb b/samples/client/petstore/ruby/lib/petstore/models/format_test.rb index 2159b1ea656..4812b7a2cae 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/format_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/format_test.rb @@ -424,7 +424,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false diff --git a/samples/client/petstore/ruby/lib/petstore/models/has_only_read_only.rb b/samples/client/petstore/ruby/lib/petstore/models/has_only_read_only.rb index 046325dbced..06c66756d99 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/has_only_read_only.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/has_only_read_only.rb @@ -136,7 +136,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false diff --git a/samples/client/petstore/ruby/lib/petstore/models/inline_response_200.rb b/samples/client/petstore/ruby/lib/petstore/models/inline_response_200.rb index a3a44b28cfe..442a0e26ed8 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/inline_response_200.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/inline_response_200.rb @@ -159,7 +159,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false diff --git a/samples/client/petstore/ruby/lib/petstore/models/list.rb b/samples/client/petstore/ruby/lib/petstore/models/list.rb index f2f34430ce7..77045dc9f1a 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/list.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/list.rb @@ -127,7 +127,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false diff --git a/samples/client/petstore/ruby/lib/petstore/models/map_test.rb b/samples/client/petstore/ruby/lib/petstore/models/map_test.rb index e227c9c8cef..5204a2a2316 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/map_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/map_test.rb @@ -161,7 +161,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false diff --git a/samples/client/petstore/ruby/lib/petstore/models/mixed_properties_and_additional_properties_class.rb b/samples/client/petstore/ruby/lib/petstore/models/mixed_properties_and_additional_properties_class.rb index e87726056fe..4c7fbf2e790 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/mixed_properties_and_additional_properties_class.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/mixed_properties_and_additional_properties_class.rb @@ -147,7 +147,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false diff --git a/samples/client/petstore/ruby/lib/petstore/models/model_200_response.rb b/samples/client/petstore/ruby/lib/petstore/models/model_200_response.rb index 3a519731281..8e1660ed4b5 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/model_200_response.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/model_200_response.rb @@ -136,7 +136,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false diff --git a/samples/client/petstore/ruby/lib/petstore/models/model_return.rb b/samples/client/petstore/ruby/lib/petstore/models/model_return.rb index 448610807c6..4bd7d792af0 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/model_return.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/model_return.rb @@ -127,7 +127,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false diff --git a/samples/client/petstore/ruby/lib/petstore/models/name.rb b/samples/client/petstore/ruby/lib/petstore/models/name.rb index dd6978fec9a..5d72199e21e 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/name.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/name.rb @@ -155,7 +155,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false diff --git a/samples/client/petstore/ruby/lib/petstore/models/number_only.rb b/samples/client/petstore/ruby/lib/petstore/models/number_only.rb index 4b70b090df8..07267259fd7 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/number_only.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/number_only.rb @@ -127,7 +127,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false diff --git a/samples/client/petstore/ruby/lib/petstore/models/order.rb b/samples/client/petstore/ruby/lib/petstore/models/order.rb index 2b6aa895718..a07a4ba84c9 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/order.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/order.rb @@ -208,7 +208,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false diff --git a/samples/client/petstore/ruby/lib/petstore/models/pet.rb b/samples/client/petstore/ruby/lib/petstore/models/pet.rb index b74bba64192..428720d76fc 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/pet.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/pet.rb @@ -212,7 +212,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false diff --git a/samples/client/petstore/ruby/lib/petstore/models/read_only_first.rb b/samples/client/petstore/ruby/lib/petstore/models/read_only_first.rb index 3be06c72ffb..d4d36e85cba 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/read_only_first.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/read_only_first.rb @@ -136,7 +136,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false diff --git a/samples/client/petstore/ruby/lib/petstore/models/special_model_name.rb b/samples/client/petstore/ruby/lib/petstore/models/special_model_name.rb index 40e8f2ed692..0cf160271d9 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/special_model_name.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/special_model_name.rb @@ -127,7 +127,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false diff --git a/samples/client/petstore/ruby/lib/petstore/models/tag.rb b/samples/client/petstore/ruby/lib/petstore/models/tag.rb index d7a351d3dbe..0bc268c946a 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/tag.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/tag.rb @@ -136,7 +136,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false diff --git a/samples/client/petstore/ruby/lib/petstore/models/user.rb b/samples/client/petstore/ruby/lib/petstore/models/user.rb index 5d7467ad970..163874f6416 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/user.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/user.rb @@ -191,7 +191,7 @@ def _deserialize(type, value) when :Float value.to_f when :BOOLEAN - if value.to_s =~ /^(true|t|yes|y|1)$/i + if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false diff --git a/samples/client/petstore/ruby/spec/base_object_spec.rb b/samples/client/petstore/ruby/spec/base_object_spec.rb index 5b84351f7b8..115a1c0e040 100644 --- a/samples/client/petstore/ruby/spec/base_object_spec.rb +++ b/samples/client/petstore/ruby/spec/base_object_spec.rb @@ -51,7 +51,7 @@ def self.swagger_types int_arr_map: {'int_arr' => [123, 456]}, pet_arr_map: {'pet_arr' => [{name: 'Kitty'}]}, boolean_true_arr: [true, "true", "TruE", 1, "y", "yes", "1", "t", "T"], - boolean_false_arr: [false, "", 0, "0", "f", nil, "null"], + boolean_false_arr: [false, "", 0, "0", "f", nil, "null", "\ntrue\n"], } end From e68b3644798cda54f3a9d7242735163fe7353733 Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 5 Sep 2016 16:06:38 +0800 Subject: [PATCH 326/470] update ruby regular expression to use \A --- .../src/main/resources/ruby/base_object.mustache | 2 +- .../ruby/lib/petstore/models/additional_properties_class.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/animal.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/animal_farm.rb | 2 +- .../client/petstore/ruby/lib/petstore/models/api_response.rb | 2 +- .../ruby/lib/petstore/models/array_of_array_of_number_only.rb | 2 +- .../petstore/ruby/lib/petstore/models/array_of_number_only.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/array_test.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/cat.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/category.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/client.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/dog.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/enum_arrays.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/enum_test.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/format_test.rb | 2 +- .../petstore/ruby/lib/petstore/models/has_only_read_only.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/list.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/map_test.rb | 2 +- .../models/mixed_properties_and_additional_properties_class.rb | 2 +- .../petstore/ruby/lib/petstore/models/model_200_response.rb | 2 +- .../client/petstore/ruby/lib/petstore/models/model_return.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/name.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/number_only.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/order.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/pet.rb | 2 +- .../client/petstore/ruby/lib/petstore/models/read_only_first.rb | 2 +- .../petstore/ruby/lib/petstore/models/special_model_name.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/tag.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/user.rb | 2 +- 29 files changed, 29 insertions(+), 29 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache index a28437fc695..eb66ef6ff72 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache @@ -4,7 +4,7 @@ def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) diff --git a/samples/client/petstore/ruby/lib/petstore/models/additional_properties_class.rb b/samples/client/petstore/ruby/lib/petstore/models/additional_properties_class.rb index b9ee9a3693f..97c85707a45 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/additional_properties_class.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/additional_properties_class.rb @@ -109,7 +109,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) diff --git a/samples/client/petstore/ruby/lib/petstore/models/animal.rb b/samples/client/petstore/ruby/lib/petstore/models/animal.rb index 24b4788705a..d71a06a294c 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/animal.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/animal.rb @@ -108,7 +108,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) diff --git a/samples/client/petstore/ruby/lib/petstore/models/animal_farm.rb b/samples/client/petstore/ruby/lib/petstore/models/animal_farm.rb index 1966d1cb440..f86eb1b9eb1 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/animal_farm.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/animal_farm.rb @@ -87,7 +87,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) diff --git a/samples/client/petstore/ruby/lib/petstore/models/api_response.rb b/samples/client/petstore/ruby/lib/petstore/models/api_response.rb index cf9f163d5b3..7fcc61a148c 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/api_response.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/api_response.rb @@ -114,7 +114,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) diff --git a/samples/client/petstore/ruby/lib/petstore/models/array_of_array_of_number_only.rb b/samples/client/petstore/ruby/lib/petstore/models/array_of_array_of_number_only.rb index fbc3f8df519..d5fb71a5f35 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/array_of_array_of_number_only.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/array_of_array_of_number_only.rb @@ -98,7 +98,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) diff --git a/samples/client/petstore/ruby/lib/petstore/models/array_of_number_only.rb b/samples/client/petstore/ruby/lib/petstore/models/array_of_number_only.rb index 2e8cc072211..a6d5e081ae5 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/array_of_number_only.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/array_of_number_only.rb @@ -98,7 +98,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) diff --git a/samples/client/petstore/ruby/lib/petstore/models/array_test.rb b/samples/client/petstore/ruby/lib/petstore/models/array_test.rb index 1e30d141430..b9f784a59de 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/array_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/array_test.rb @@ -120,7 +120,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) diff --git a/samples/client/petstore/ruby/lib/petstore/models/cat.rb b/samples/client/petstore/ruby/lib/petstore/models/cat.rb index ca5dfa12dae..8d0d801fbc2 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/cat.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/cat.rb @@ -117,7 +117,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) diff --git a/samples/client/petstore/ruby/lib/petstore/models/category.rb b/samples/client/petstore/ruby/lib/petstore/models/category.rb index 849b0c96dd9..dc3fa09c4b1 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/category.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/category.rb @@ -105,7 +105,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) diff --git a/samples/client/petstore/ruby/lib/petstore/models/client.rb b/samples/client/petstore/ruby/lib/petstore/models/client.rb index 186894b8338..1931b314d12 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/client.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/client.rb @@ -96,7 +96,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) diff --git a/samples/client/petstore/ruby/lib/petstore/models/dog.rb b/samples/client/petstore/ruby/lib/petstore/models/dog.rb index 5a481c524a6..ff44da76a68 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/dog.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/dog.rb @@ -117,7 +117,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) diff --git a/samples/client/petstore/ruby/lib/petstore/models/enum_arrays.rb b/samples/client/petstore/ruby/lib/petstore/models/enum_arrays.rb index 194aa26460e..a437cfab42b 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/enum_arrays.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/enum_arrays.rb @@ -140,7 +140,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) diff --git a/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb b/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb index f9c36700349..8df4d2daad5 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb @@ -171,7 +171,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) diff --git a/samples/client/petstore/ruby/lib/petstore/models/format_test.rb b/samples/client/petstore/ruby/lib/petstore/models/format_test.rb index 4812b7a2cae..ba633d3c6ca 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/format_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/format_test.rb @@ -393,7 +393,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) diff --git a/samples/client/petstore/ruby/lib/petstore/models/has_only_read_only.rb b/samples/client/petstore/ruby/lib/petstore/models/has_only_read_only.rb index 06c66756d99..9721f6b7e65 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/has_only_read_only.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/has_only_read_only.rb @@ -105,7 +105,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) diff --git a/samples/client/petstore/ruby/lib/petstore/models/list.rb b/samples/client/petstore/ruby/lib/petstore/models/list.rb index 77045dc9f1a..a5804aac06d 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/list.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/list.rb @@ -96,7 +96,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) diff --git a/samples/client/petstore/ruby/lib/petstore/models/map_test.rb b/samples/client/petstore/ruby/lib/petstore/models/map_test.rb index 5204a2a2316..c9304f024c8 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/map_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/map_test.rb @@ -130,7 +130,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) diff --git a/samples/client/petstore/ruby/lib/petstore/models/mixed_properties_and_additional_properties_class.rb b/samples/client/petstore/ruby/lib/petstore/models/mixed_properties_and_additional_properties_class.rb index 4c7fbf2e790..0e49fd3e2a0 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/mixed_properties_and_additional_properties_class.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/mixed_properties_and_additional_properties_class.rb @@ -116,7 +116,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) diff --git a/samples/client/petstore/ruby/lib/petstore/models/model_200_response.rb b/samples/client/petstore/ruby/lib/petstore/models/model_200_response.rb index 8e1660ed4b5..9876e3dd3ea 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/model_200_response.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/model_200_response.rb @@ -105,7 +105,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) diff --git a/samples/client/petstore/ruby/lib/petstore/models/model_return.rb b/samples/client/petstore/ruby/lib/petstore/models/model_return.rb index 4bd7d792af0..7278d4171bd 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/model_return.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/model_return.rb @@ -96,7 +96,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) diff --git a/samples/client/petstore/ruby/lib/petstore/models/name.rb b/samples/client/petstore/ruby/lib/petstore/models/name.rb index 5d72199e21e..24d7e27aff2 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/name.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/name.rb @@ -124,7 +124,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) diff --git a/samples/client/petstore/ruby/lib/petstore/models/number_only.rb b/samples/client/petstore/ruby/lib/petstore/models/number_only.rb index 07267259fd7..1ac0f0217f5 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/number_only.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/number_only.rb @@ -96,7 +96,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) diff --git a/samples/client/petstore/ruby/lib/petstore/models/order.rb b/samples/client/petstore/ruby/lib/petstore/models/order.rb index a07a4ba84c9..802961e7a9a 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/order.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/order.rb @@ -177,7 +177,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) diff --git a/samples/client/petstore/ruby/lib/petstore/models/pet.rb b/samples/client/petstore/ruby/lib/petstore/models/pet.rb index 428720d76fc..88a3dc43aed 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/pet.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/pet.rb @@ -181,7 +181,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) diff --git a/samples/client/petstore/ruby/lib/petstore/models/read_only_first.rb b/samples/client/petstore/ruby/lib/petstore/models/read_only_first.rb index d4d36e85cba..b816c21633d 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/read_only_first.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/read_only_first.rb @@ -105,7 +105,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) diff --git a/samples/client/petstore/ruby/lib/petstore/models/special_model_name.rb b/samples/client/petstore/ruby/lib/petstore/models/special_model_name.rb index 0cf160271d9..6a31e57643b 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/special_model_name.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/special_model_name.rb @@ -96,7 +96,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) diff --git a/samples/client/petstore/ruby/lib/petstore/models/tag.rb b/samples/client/petstore/ruby/lib/petstore/models/tag.rb index 0bc268c946a..fa89d2c72a7 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/tag.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/tag.rb @@ -105,7 +105,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) diff --git a/samples/client/petstore/ruby/lib/petstore/models/user.rb b/samples/client/petstore/ruby/lib/petstore/models/user.rb index 163874f6416..92d335c68d0 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/user.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/user.rb @@ -160,7 +160,7 @@ def hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^Array<(.*)>/i + if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) From f751e50e2e09c8391709019e4a66e1ee79ff6395 Mon Sep 17 00:00:00 2001 From: Neil O'Toole Date: Mon, 5 Sep 2016 03:11:34 -0600 Subject: [PATCH 327/470] Issue #3687 silence resty logging [Go] (#3705) * disabling resty logger * #3687 updating go-petstore --- .../src/main/resources/go/api_client.mustache | 3 +- .../additional_properties_class.go | 30 ++ .../client/petstore/go/go-petstore/animal.go | 30 ++ .../petstore/go/go-petstore/animal_farm.go | 26 ++ .../petstore/go/go-petstore/api_client.go | 3 +- .../array_of_array_of_number_only.go | 28 ++ .../go/go-petstore/array_of_number_only.go | 28 ++ .../petstore/go/go-petstore/array_test.go | 32 +++ samples/client/petstore/go/go-petstore/cat.go | 32 +++ .../client/petstore/go/go-petstore/client.go | 28 ++ .../docs/AdditionalPropertiesClass.md | 11 + .../petstore/go/go-petstore/docs/Animal.md | 11 + .../go/go-petstore/docs/AnimalFarm.md | 9 + .../docs/ArrayOfArrayOfNumberOnly.md | 10 + .../go/go-petstore/docs/ArrayOfNumberOnly.md | 10 + .../petstore/go/go-petstore/docs/ArrayTest.md | 12 + .../petstore/go/go-petstore/docs/Cat.md | 12 + .../petstore/go/go-petstore/docs/Client.md | 10 + .../petstore/go/go-petstore/docs/Dog.md | 12 + .../go/go-petstore/docs/EnumArrays.md | 11 + .../petstore/go/go-petstore/docs/EnumClass.md | 9 + .../petstore/go/go-petstore/docs/EnumTest.md | 12 + .../petstore/go/go-petstore/docs/FakeApi.md | 113 ++++++++ .../go/go-petstore/docs/FormatTest.md | 22 ++ .../go/go-petstore/docs/HasOnlyReadOnly.md | 11 + .../petstore/go/go-petstore/docs/List.md | 10 + .../petstore/go/go-petstore/docs/MapTest.md | 11 + ...dPropertiesAndAdditionalPropertiesClass.md | 12 + .../go/go-petstore/docs/Model200Response.md | 11 + .../go/go-petstore/docs/ModelReturn.md | 10 + .../petstore/go/go-petstore/docs/Name.md | 13 + .../go/go-petstore/docs/NumberOnly.md | 10 + .../go/go-petstore/docs/ReadOnlyFirst.md | 11 + .../go/go-petstore/docs/SpecialModelName.md | 10 + samples/client/petstore/go/go-petstore/dog.go | 32 +++ .../petstore/go/go-petstore/enum_arrays.go | 30 ++ .../petstore/go/go-petstore/enum_class.go | 26 ++ .../petstore/go/go-petstore/enum_test.go | 32 +++ .../petstore/go/go-petstore/fake_api.go | 266 ++++++++++++++++++ .../petstore/go/go-petstore/format_test.go | 56 ++++ .../go/go-petstore/has_only_read_only.go | 30 ++ .../client/petstore/go/go-petstore/list.go | 28 ++ .../petstore/go/go-petstore/map_test.go | 30 ++ ...perties_and_additional_properties_class.go | 36 +++ .../go/go-petstore/model_200_response.go | 31 ++ .../petstore/go/go-petstore/model_return.go | 29 ++ .../client/petstore/go/go-petstore/name.go | 35 +++ .../petstore/go/go-petstore/number_only.go | 28 ++ .../go/go-petstore/read_only_first.go | 30 ++ .../go/go-petstore/special_model_name.go | 28 ++ 50 files changed, 1358 insertions(+), 2 deletions(-) create mode 100644 samples/client/petstore/go/go-petstore/additional_properties_class.go create mode 100644 samples/client/petstore/go/go-petstore/animal.go create mode 100644 samples/client/petstore/go/go-petstore/animal_farm.go create mode 100644 samples/client/petstore/go/go-petstore/array_of_array_of_number_only.go create mode 100644 samples/client/petstore/go/go-petstore/array_of_number_only.go create mode 100644 samples/client/petstore/go/go-petstore/array_test.go create mode 100644 samples/client/petstore/go/go-petstore/cat.go create mode 100644 samples/client/petstore/go/go-petstore/client.go create mode 100644 samples/client/petstore/go/go-petstore/docs/AdditionalPropertiesClass.md create mode 100644 samples/client/petstore/go/go-petstore/docs/Animal.md create mode 100644 samples/client/petstore/go/go-petstore/docs/AnimalFarm.md create mode 100644 samples/client/petstore/go/go-petstore/docs/ArrayOfArrayOfNumberOnly.md create mode 100644 samples/client/petstore/go/go-petstore/docs/ArrayOfNumberOnly.md create mode 100644 samples/client/petstore/go/go-petstore/docs/ArrayTest.md create mode 100644 samples/client/petstore/go/go-petstore/docs/Cat.md create mode 100644 samples/client/petstore/go/go-petstore/docs/Client.md create mode 100644 samples/client/petstore/go/go-petstore/docs/Dog.md create mode 100644 samples/client/petstore/go/go-petstore/docs/EnumArrays.md create mode 100644 samples/client/petstore/go/go-petstore/docs/EnumClass.md create mode 100644 samples/client/petstore/go/go-petstore/docs/EnumTest.md create mode 100644 samples/client/petstore/go/go-petstore/docs/FakeApi.md create mode 100644 samples/client/petstore/go/go-petstore/docs/FormatTest.md create mode 100644 samples/client/petstore/go/go-petstore/docs/HasOnlyReadOnly.md create mode 100644 samples/client/petstore/go/go-petstore/docs/List.md create mode 100644 samples/client/petstore/go/go-petstore/docs/MapTest.md create mode 100644 samples/client/petstore/go/go-petstore/docs/MixedPropertiesAndAdditionalPropertiesClass.md create mode 100644 samples/client/petstore/go/go-petstore/docs/Model200Response.md create mode 100644 samples/client/petstore/go/go-petstore/docs/ModelReturn.md create mode 100644 samples/client/petstore/go/go-petstore/docs/Name.md create mode 100644 samples/client/petstore/go/go-petstore/docs/NumberOnly.md create mode 100644 samples/client/petstore/go/go-petstore/docs/ReadOnlyFirst.md create mode 100644 samples/client/petstore/go/go-petstore/docs/SpecialModelName.md create mode 100644 samples/client/petstore/go/go-petstore/dog.go create mode 100644 samples/client/petstore/go/go-petstore/enum_arrays.go create mode 100644 samples/client/petstore/go/go-petstore/enum_class.go create mode 100644 samples/client/petstore/go/go-petstore/enum_test.go create mode 100644 samples/client/petstore/go/go-petstore/fake_api.go create mode 100644 samples/client/petstore/go/go-petstore/format_test.go create mode 100644 samples/client/petstore/go/go-petstore/has_only_read_only.go create mode 100644 samples/client/petstore/go/go-petstore/list.go create mode 100644 samples/client/petstore/go/go-petstore/map_test.go create mode 100644 samples/client/petstore/go/go-petstore/mixed_properties_and_additional_properties_class.go create mode 100644 samples/client/petstore/go/go-petstore/model_200_response.go create mode 100644 samples/client/petstore/go/go-petstore/model_return.go create mode 100644 samples/client/petstore/go/go-petstore/name.go create mode 100644 samples/client/petstore/go/go-petstore/number_only.go create mode 100644 samples/client/petstore/go/go-petstore/read_only_first.go create mode 100644 samples/client/petstore/go/go-petstore/special_model_name.go diff --git a/modules/swagger-codegen/src/main/resources/go/api_client.mustache b/modules/swagger-codegen/src/main/resources/go/api_client.mustache index c1f0841bffd..a92c7631202 100644 --- a/modules/swagger-codegen/src/main/resources/go/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/go/api_client.mustache @@ -8,6 +8,7 @@ import ( "reflect" "strings" "net/url" + "io/ioutil" "github.com/go-resty/resty" ) @@ -107,7 +108,7 @@ func (c *APIClient) prepareClient() *resty.Client { if c.config.Timeout != nil { rClient.SetTimeout(*c.config.Timeout) } - + rClient.SetLogger(ioutil.Discard) return rClient } diff --git a/samples/client/petstore/go/go-petstore/additional_properties_class.go b/samples/client/petstore/go/go-petstore/additional_properties_class.go new file mode 100644 index 00000000000..ad768d2e478 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/additional_properties_class.go @@ -0,0 +1,30 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type AdditionalPropertiesClass struct { + + MapProperty map[string]string `json:"map_property,omitempty"` + + MapOfMapProperty map[string]map[string]string `json:"map_of_map_property,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/animal.go b/samples/client/petstore/go/go-petstore/animal.go new file mode 100644 index 00000000000..bc9d8161db7 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/animal.go @@ -0,0 +1,30 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type Animal struct { + + ClassName string `json:"className,omitempty"` + + Color string `json:"color,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/animal_farm.go b/samples/client/petstore/go/go-petstore/animal_farm.go new file mode 100644 index 00000000000..a412cbcd450 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/animal_farm.go @@ -0,0 +1,26 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type AnimalFarm struct { +} diff --git a/samples/client/petstore/go/go-petstore/api_client.go b/samples/client/petstore/go/go-petstore/api_client.go index 5c66c5580e0..6196eb5a706 100644 --- a/samples/client/petstore/go/go-petstore/api_client.go +++ b/samples/client/petstore/go/go-petstore/api_client.go @@ -29,6 +29,7 @@ import ( "reflect" "strings" "net/url" + "io/ioutil" "github.com/go-resty/resty" ) @@ -128,7 +129,7 @@ func (c *APIClient) prepareClient() *resty.Client { if c.config.Timeout != nil { rClient.SetTimeout(*c.config.Timeout) } - + rClient.SetLogger(ioutil.Discard) return rClient } diff --git a/samples/client/petstore/go/go-petstore/array_of_array_of_number_only.go b/samples/client/petstore/go/go-petstore/array_of_array_of_number_only.go new file mode 100644 index 00000000000..8fc05e77a16 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/array_of_array_of_number_only.go @@ -0,0 +1,28 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type ArrayOfArrayOfNumberOnly struct { + + ArrayArrayNumber [][]float32 `json:"ArrayArrayNumber,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/array_of_number_only.go b/samples/client/petstore/go/go-petstore/array_of_number_only.go new file mode 100644 index 00000000000..d9ef9a4c6d9 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/array_of_number_only.go @@ -0,0 +1,28 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type ArrayOfNumberOnly struct { + + ArrayNumber []float32 `json:"ArrayNumber,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/array_test.go b/samples/client/petstore/go/go-petstore/array_test.go new file mode 100644 index 00000000000..251f0a88efb --- /dev/null +++ b/samples/client/petstore/go/go-petstore/array_test.go @@ -0,0 +1,32 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type ArrayTest struct { + + ArrayOfString []string `json:"array_of_string,omitempty"` + + ArrayArrayOfInteger [][]int64 `json:"array_array_of_integer,omitempty"` + + ArrayArrayOfModel [][]ReadOnlyFirst `json:"array_array_of_model,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/cat.go b/samples/client/petstore/go/go-petstore/cat.go new file mode 100644 index 00000000000..f8526999824 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/cat.go @@ -0,0 +1,32 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type Cat struct { + + ClassName string `json:"className,omitempty"` + + Color string `json:"color,omitempty"` + + Declawed bool `json:"declawed,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/client.go b/samples/client/petstore/go/go-petstore/client.go new file mode 100644 index 00000000000..e20c597d838 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/client.go @@ -0,0 +1,28 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type Client struct { + + Client string `json:"client,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/docs/AdditionalPropertiesClass.md b/samples/client/petstore/go/go-petstore/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..abdb42c8e01 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/AdditionalPropertiesClass.md @@ -0,0 +1,11 @@ +# AdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**MapProperty** | **map[string]string** | | [optional] [default to null] +**MapOfMapProperty** | [**map[string]map[string]string**](map.md) | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/Animal.md b/samples/client/petstore/go/go-petstore/docs/Animal.md new file mode 100644 index 00000000000..e7163af792c --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/Animal.md @@ -0,0 +1,11 @@ +# Animal + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **string** | | [default to null] +**Color** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/AnimalFarm.md b/samples/client/petstore/go/go-petstore/docs/AnimalFarm.md new file mode 100644 index 00000000000..df6bab21dae --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/AnimalFarm.md @@ -0,0 +1,9 @@ +# AnimalFarm + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/go/go-petstore/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 00000000000..495038e58e1 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/ArrayOfArrayOfNumberOnly.md @@ -0,0 +1,10 @@ +# ArrayOfArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ArrayArrayNumber** | [**[][]float32**](array.md) | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/ArrayOfNumberOnly.md b/samples/client/petstore/go/go-petstore/docs/ArrayOfNumberOnly.md new file mode 100644 index 00000000000..bd7a48160d2 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/ArrayOfNumberOnly.md @@ -0,0 +1,10 @@ +# ArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ArrayNumber** | **[]float32** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/ArrayTest.md b/samples/client/petstore/go/go-petstore/docs/ArrayTest.md new file mode 100644 index 00000000000..6cf88880292 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/ArrayTest.md @@ -0,0 +1,12 @@ +# ArrayTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ArrayOfString** | **[]string** | | [optional] [default to null] +**ArrayArrayOfInteger** | [**[][]int64**](array.md) | | [optional] [default to null] +**ArrayArrayOfModel** | [**[][]ReadOnlyFirst**](array.md) | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/Cat.md b/samples/client/petstore/go/go-petstore/docs/Cat.md new file mode 100644 index 00000000000..3a49c3ca62e --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/Cat.md @@ -0,0 +1,12 @@ +# Cat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **string** | | [default to null] +**Color** | **string** | | [optional] [default to null] +**Declawed** | **bool** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/Client.md b/samples/client/petstore/go/go-petstore/docs/Client.md new file mode 100644 index 00000000000..d8edb814853 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/Client.md @@ -0,0 +1,10 @@ +# Client + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Client** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/Dog.md b/samples/client/petstore/go/go-petstore/docs/Dog.md new file mode 100644 index 00000000000..7178972d5dc --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/Dog.md @@ -0,0 +1,12 @@ +# Dog + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **string** | | [default to null] +**Color** | **string** | | [optional] [default to null] +**Breed** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/EnumArrays.md b/samples/client/petstore/go/go-petstore/docs/EnumArrays.md new file mode 100644 index 00000000000..2ca85fdd1fb --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/EnumArrays.md @@ -0,0 +1,11 @@ +# EnumArrays + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**JustSymbol** | **string** | | [optional] [default to null] +**ArrayEnum** | **[]string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/EnumClass.md b/samples/client/petstore/go/go-petstore/docs/EnumClass.md new file mode 100644 index 00000000000..67f017becd0 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/EnumClass.md @@ -0,0 +1,9 @@ +# EnumClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/EnumTest.md b/samples/client/petstore/go/go-petstore/docs/EnumTest.md new file mode 100644 index 00000000000..fe6ca0cb32d --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/EnumTest.md @@ -0,0 +1,12 @@ +# EnumTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**EnumString** | **string** | | [optional] [default to null] +**EnumInteger** | **int32** | | [optional] [default to null] +**EnumNumber** | **float64** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/FakeApi.md b/samples/client/petstore/go/go-petstore/docs/FakeApi.md new file mode 100644 index 00000000000..63e7fb728fb --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/FakeApi.md @@ -0,0 +1,113 @@ +# \FakeApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**TestClientModel**](FakeApi.md#TestClientModel) | **Patch** /fake | To test \"client\" model +[**TestEndpointParameters**](FakeApi.md#TestEndpointParameters) | **Post** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**TestEnumParameters**](FakeApi.md#TestEnumParameters) | **Get** /fake | To test enum parameters + + +# **TestClientModel** +> Client TestClientModel($body) + +To test \"client\" model + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Client**](Client.md)| client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **TestEndpointParameters** +> TestEndpointParameters($number, $double, $patternWithoutDelimiter, $byte_, $integer, $int32_, $int64_, $float, $string_, $binary, $date, $dateTime, $password) + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **number** | **float32**| None | + **double** | **float64**| None | + **patternWithoutDelimiter** | **string**| None | + **byte_** | **string**| None | + **integer** | **int32**| None | [optional] + **int32_** | **int32**| None | [optional] + **int64_** | **int64**| None | [optional] + **float** | **float32**| None | [optional] + **string_** | **string**| None | [optional] + **binary** | **string**| None | [optional] + **date** | **time.Time**| None | [optional] + **dateTime** | **time.Time**| None | [optional] + **password** | **string**| None | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[http_basic_test](../README.md#http_basic_test) + +### HTTP request headers + + - **Content-Type**: application/xml; charset=utf-8, application/json; charset=utf-8 + - **Accept**: application/xml; charset=utf-8, application/json; charset=utf-8 + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **TestEnumParameters** +> TestEnumParameters($enumFormStringArray, $enumFormString, $enumHeaderStringArray, $enumHeaderString, $enumQueryStringArray, $enumQueryString, $enumQueryInteger, $enumQueryDouble) + +To test enum parameters + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **enumFormStringArray** | [**[]string**](string.md)| Form parameter enum test (string array) | [optional] + **enumFormString** | **string**| Form parameter enum test (string) | [optional] [default to -efg] + **enumHeaderStringArray** | [**[]string**](string.md)| Header parameter enum test (string array) | [optional] + **enumHeaderString** | **string**| Header parameter enum test (string) | [optional] [default to -efg] + **enumQueryStringArray** | [**[]string**](string.md)| Query parameter enum test (string array) | [optional] + **enumQueryString** | **string**| Query parameter enum test (string) | [optional] [default to -efg] + **enumQueryInteger** | **float32**| Query parameter enum test (double) | [optional] + **enumQueryDouble** | **float64**| Query parameter enum test (double) | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/go/go-petstore/docs/FormatTest.md b/samples/client/petstore/go/go-petstore/docs/FormatTest.md new file mode 100644 index 00000000000..05f41a8039f --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/FormatTest.md @@ -0,0 +1,22 @@ +# FormatTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Integer** | **int32** | | [optional] [default to null] +**Int32_** | **int32** | | [optional] [default to null] +**Int64_** | **int64** | | [optional] [default to null] +**Number** | **float32** | | [default to null] +**Float** | **float32** | | [optional] [default to null] +**Double** | **float64** | | [optional] [default to null] +**String_** | **string** | | [optional] [default to null] +**Byte_** | **string** | | [default to null] +**Binary** | **string** | | [optional] [default to null] +**Date** | [**time.Time**](time.Time.md) | | [default to null] +**DateTime** | [**time.Time**](time.Time.md) | | [optional] [default to null] +**Uuid** | **string** | | [optional] [default to null] +**Password** | **string** | | [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/HasOnlyReadOnly.md b/samples/client/petstore/go/go-petstore/docs/HasOnlyReadOnly.md new file mode 100644 index 00000000000..32dfdedcfe7 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/HasOnlyReadOnly.md @@ -0,0 +1,11 @@ +# HasOnlyReadOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Bar** | **string** | | [optional] [default to null] +**Foo** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/List.md b/samples/client/petstore/go/go-petstore/docs/List.md new file mode 100644 index 00000000000..54fd3876c26 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/List.md @@ -0,0 +1,10 @@ +# List + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Var123List** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/MapTest.md b/samples/client/petstore/go/go-petstore/docs/MapTest.md new file mode 100644 index 00000000000..6b70bf448e8 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/MapTest.md @@ -0,0 +1,11 @@ +# MapTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**MapMapOfString** | [**map[string]map[string]string**](map.md) | | [optional] [default to null] +**MapOfEnumString** | **map[string]string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/go/go-petstore/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..b4de97169dd --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,12 @@ +# MixedPropertiesAndAdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Uuid** | **string** | | [optional] [default to null] +**DateTime** | [**time.Time**](time.Time.md) | | [optional] [default to null] +**Map_** | [**map[string]Animal**](Animal.md) | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/Model200Response.md b/samples/client/petstore/go/go-petstore/docs/Model200Response.md new file mode 100644 index 00000000000..8b4bb38033d --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/Model200Response.md @@ -0,0 +1,11 @@ +# Model200Response + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Name** | **int32** | | [optional] [default to null] +**Class** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/ModelReturn.md b/samples/client/petstore/go/go-petstore/docs/ModelReturn.md new file mode 100644 index 00000000000..86350d4310c --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/ModelReturn.md @@ -0,0 +1,10 @@ +# ModelReturn + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Return_** | **int32** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/Name.md b/samples/client/petstore/go/go-petstore/docs/Name.md new file mode 100644 index 00000000000..d677e60263f --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/Name.md @@ -0,0 +1,13 @@ +# Name + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Name** | **int32** | | [default to null] +**SnakeCase** | **int32** | | [optional] [default to null] +**Property** | **string** | | [optional] [default to null] +**Var123Number** | **int32** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/NumberOnly.md b/samples/client/petstore/go/go-petstore/docs/NumberOnly.md new file mode 100644 index 00000000000..3ebbf2f0308 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/NumberOnly.md @@ -0,0 +1,10 @@ +# NumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**JustNumber** | **float32** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/ReadOnlyFirst.md b/samples/client/petstore/go/go-petstore/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..3ff591d7a74 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/ReadOnlyFirst.md @@ -0,0 +1,11 @@ +# ReadOnlyFirst + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Bar** | **string** | | [optional] [default to null] +**Baz** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/SpecialModelName.md b/samples/client/petstore/go/go-petstore/docs/SpecialModelName.md new file mode 100644 index 00000000000..dcf601a308d --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/SpecialModelName.md @@ -0,0 +1,10 @@ +# SpecialModelName + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**SpecialPropertyName** | **int64** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/dog.go b/samples/client/petstore/go/go-petstore/dog.go new file mode 100644 index 00000000000..acf4999618e --- /dev/null +++ b/samples/client/petstore/go/go-petstore/dog.go @@ -0,0 +1,32 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type Dog struct { + + ClassName string `json:"className,omitempty"` + + Color string `json:"color,omitempty"` + + Breed string `json:"breed,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/enum_arrays.go b/samples/client/petstore/go/go-petstore/enum_arrays.go new file mode 100644 index 00000000000..3b42ad142b5 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/enum_arrays.go @@ -0,0 +1,30 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type EnumArrays struct { + + JustSymbol string `json:"just_symbol,omitempty"` + + ArrayEnum []string `json:"array_enum,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/enum_class.go b/samples/client/petstore/go/go-petstore/enum_class.go new file mode 100644 index 00000000000..4a63f179dd3 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/enum_class.go @@ -0,0 +1,26 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type EnumClass struct { +} diff --git a/samples/client/petstore/go/go-petstore/enum_test.go b/samples/client/petstore/go/go-petstore/enum_test.go new file mode 100644 index 00000000000..c2be92c6246 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/enum_test.go @@ -0,0 +1,32 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type EnumTest struct { + + EnumString string `json:"enum_string,omitempty"` + + EnumInteger int32 `json:"enum_integer,omitempty"` + + EnumNumber float64 `json:"enum_number,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/fake_api.go b/samples/client/petstore/go/go-petstore/fake_api.go new file mode 100644 index 00000000000..5de90a7753a --- /dev/null +++ b/samples/client/petstore/go/go-petstore/fake_api.go @@ -0,0 +1,266 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +import ( + "net/url" + "time" + "encoding/json" +) + +type FakeApi struct { + Configuration *Configuration +} + +func NewFakeApi() *FakeApi { + configuration := NewConfiguration() + return &FakeApi{ + Configuration: configuration, + } +} + +func NewFakeApiWithBasePath(basePath string) *FakeApi { + configuration := NewConfiguration() + configuration.BasePath = basePath + + return &FakeApi{ + Configuration: configuration, + } +} + +/** + * To test \"client\" model + * + * @param body client model + * @return *Client + */ +func (a FakeApi) TestClientModel(body Client) (*Client, *APIResponse, error) { + + var localVarHttpMethod = "Patch" + // create path and map variables + localVarPath := a.Configuration.BasePath + "/fake" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte + // add default headers if any + for key := range a.Configuration.DefaultHeader { + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] + } + + + // to determine the Content-Type header + localVarHttpContentTypes := []string{ "application/json", } + + // set Content-Type header + localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + // to determine the Accept header + localVarHttpHeaderAccepts := []string{ + "application/json", + } + + // set Accept header + localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + // body params + localVarPostBody = &body + + var successPayload = new(Client) + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return successPayload, NewAPIResponse(localVarHttpResponse.RawResponse), err + } + err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) + return successPayload, NewAPIResponse(localVarHttpResponse.RawResponse), err +} + +/** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * @param number None + * @param double None + * @param patternWithoutDelimiter None + * @param byte_ None + * @param integer None + * @param int32_ None + * @param int64_ None + * @param float None + * @param string_ None + * @param binary None + * @param date None + * @param dateTime None + * @param password None + * @return void + */ +func (a FakeApi) TestEndpointParameters(number float32, double float64, patternWithoutDelimiter string, byte_ string, integer int32, int32_ int32, int64_ int64, float float32, string_ string, binary string, date time.Time, dateTime time.Time, password string) (*APIResponse, error) { + + var localVarHttpMethod = "Post" + // create path and map variables + localVarPath := a.Configuration.BasePath + "/fake" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte + // authentication '(http_basic_test)' required + // http basic authentication required + if a.Configuration.UserName != "" || a.Configuration.Password != ""{ + localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString() + } + // add default headers if any + for key := range a.Configuration.DefaultHeader { + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] + } + + + // to determine the Content-Type header + localVarHttpContentTypes := []string{ "application/xml; charset=utf-8", "application/json; charset=utf-8", } + + // set Content-Type header + localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + // to determine the Accept header + localVarHttpHeaderAccepts := []string{ + "application/xml; charset=utf-8", +"application/json; charset=utf-8", + } + + // set Accept header + localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + localVarFormParams["integer"] = a.Configuration.APIClient.ParameterToString(integer, "") + localVarFormParams["int32_"] = a.Configuration.APIClient.ParameterToString(int32_, "") + localVarFormParams["int64_"] = a.Configuration.APIClient.ParameterToString(int64_, "") + localVarFormParams["number"] = a.Configuration.APIClient.ParameterToString(number, "") + localVarFormParams["float"] = a.Configuration.APIClient.ParameterToString(float, "") + localVarFormParams["double"] = a.Configuration.APIClient.ParameterToString(double, "") + localVarFormParams["string_"] = a.Configuration.APIClient.ParameterToString(string_, "") + localVarFormParams["patternWithoutDelimiter"] = a.Configuration.APIClient.ParameterToString(patternWithoutDelimiter, "") + localVarFormParams["byte_"] = a.Configuration.APIClient.ParameterToString(byte_, "") + localVarFormParams["binary"] = a.Configuration.APIClient.ParameterToString(binary, "") + localVarFormParams["date"] = a.Configuration.APIClient.ParameterToString(date, "") + localVarFormParams["dateTime"] = a.Configuration.APIClient.ParameterToString(dateTime, "") + localVarFormParams["password"] = a.Configuration.APIClient.ParameterToString(password, "") + + + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return NewAPIResponse(localVarHttpResponse.RawResponse), err + } + + return NewAPIResponse(localVarHttpResponse.RawResponse), err +} + +/** + * To test enum parameters + * + * @param enumFormStringArray Form parameter enum test (string array) + * @param enumFormString Form parameter enum test (string) + * @param enumHeaderStringArray Header parameter enum test (string array) + * @param enumHeaderString Header parameter enum test (string) + * @param enumQueryStringArray Query parameter enum test (string array) + * @param enumQueryString Query parameter enum test (string) + * @param enumQueryInteger Query parameter enum test (double) + * @param enumQueryDouble Query parameter enum test (double) + * @return void + */ +func (a FakeApi) TestEnumParameters(enumFormStringArray []string, enumFormString string, enumHeaderStringArray []string, enumHeaderString string, enumQueryStringArray []string, enumQueryString string, enumQueryInteger float32, enumQueryDouble float64) (*APIResponse, error) { + + var localVarHttpMethod = "Get" + // create path and map variables + localVarPath := a.Configuration.BasePath + "/fake" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte + // add default headers if any + for key := range a.Configuration.DefaultHeader { + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] + } + var collectionFormat = "csv" + if collectionFormat == "multi" { + for _, value := range enumQueryStringArray { + localVarQueryParams.Add("enum_query_string_array", value) + } + } else { + localVarQueryParams.Add("enum_query_string_array", a.Configuration.APIClient.ParameterToString(enumQueryStringArray, collectionFormat)) + } + localVarQueryParams.Add("enum_query_string", a.Configuration.APIClient.ParameterToString(enumQueryString, "")) + localVarQueryParams.Add("enum_query_integer", a.Configuration.APIClient.ParameterToString(enumQueryInteger, "")) + + + // to determine the Content-Type header + localVarHttpContentTypes := []string{ "application/json", } + + // set Content-Type header + localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + // to determine the Accept header + localVarHttpHeaderAccepts := []string{ + "application/json", + } + + // set Accept header + localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + + // header params "enum_header_string_array" + localVarHeaderParams["enum_header_string_array"] = a.Configuration.APIClient.ParameterToString(enumHeaderStringArray, "") + // header params "enum_header_string" + localVarHeaderParams["enum_header_string"] = a.Configuration.APIClient.ParameterToString(enumHeaderString, "") + + localVarFormParams["enumFormStringArray"] = a.Configuration.APIClient.ParameterToString(enumFormStringArray, "") + localVarFormParams["enumFormString"] = a.Configuration.APIClient.ParameterToString(enumFormString, "") + localVarFormParams["enumQueryDouble"] = a.Configuration.APIClient.ParameterToString(enumQueryDouble, "") + + + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return NewAPIResponse(localVarHttpResponse.RawResponse), err + } + + return NewAPIResponse(localVarHttpResponse.RawResponse), err +} + diff --git a/samples/client/petstore/go/go-petstore/format_test.go b/samples/client/petstore/go/go-petstore/format_test.go new file mode 100644 index 00000000000..fa370de4d12 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/format_test.go @@ -0,0 +1,56 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +import ( + "time" +) + +type FormatTest struct { + + Integer int32 `json:"integer,omitempty"` + + Int32_ int32 `json:"int32,omitempty"` + + Int64_ int64 `json:"int64,omitempty"` + + Number float32 `json:"number,omitempty"` + + Float float32 `json:"float,omitempty"` + + Double float64 `json:"double,omitempty"` + + String_ string `json:"string,omitempty"` + + Byte_ string `json:"byte,omitempty"` + + Binary string `json:"binary,omitempty"` + + Date time.Time `json:"date,omitempty"` + + DateTime time.Time `json:"dateTime,omitempty"` + + Uuid string `json:"uuid,omitempty"` + + Password string `json:"password,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/has_only_read_only.go b/samples/client/petstore/go/go-petstore/has_only_read_only.go new file mode 100644 index 00000000000..f95600a35bc --- /dev/null +++ b/samples/client/petstore/go/go-petstore/has_only_read_only.go @@ -0,0 +1,30 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type HasOnlyReadOnly struct { + + Bar string `json:"bar,omitempty"` + + Foo string `json:"foo,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/list.go b/samples/client/petstore/go/go-petstore/list.go new file mode 100644 index 00000000000..7fcab1a6d84 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/list.go @@ -0,0 +1,28 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type List struct { + + Var123List string `json:"123-list,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/map_test.go b/samples/client/petstore/go/go-petstore/map_test.go new file mode 100644 index 00000000000..88b060ef3c4 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/map_test.go @@ -0,0 +1,30 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type MapTest struct { + + MapMapOfString map[string]map[string]string `json:"map_map_of_string,omitempty"` + + MapOfEnumString map[string]string `json:"map_of_enum_string,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/mixed_properties_and_additional_properties_class.go b/samples/client/petstore/go/go-petstore/mixed_properties_and_additional_properties_class.go new file mode 100644 index 00000000000..6a34a75cefc --- /dev/null +++ b/samples/client/petstore/go/go-petstore/mixed_properties_and_additional_properties_class.go @@ -0,0 +1,36 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +import ( + "time" +) + +type MixedPropertiesAndAdditionalPropertiesClass struct { + + Uuid string `json:"uuid,omitempty"` + + DateTime time.Time `json:"dateTime,omitempty"` + + Map_ map[string]Animal `json:"map,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/model_200_response.go b/samples/client/petstore/go/go-petstore/model_200_response.go new file mode 100644 index 00000000000..6fefe4b6ab7 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/model_200_response.go @@ -0,0 +1,31 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +// Model for testing model name starting with number +type Model200Response struct { + + Name int32 `json:"name,omitempty"` + + Class string `json:"class,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/model_return.go b/samples/client/petstore/go/go-petstore/model_return.go new file mode 100644 index 00000000000..a2f3244ebf5 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/model_return.go @@ -0,0 +1,29 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +// Model for testing reserved words +type ModelReturn struct { + + Return_ int32 `json:"return,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/name.go b/samples/client/petstore/go/go-petstore/name.go new file mode 100644 index 00000000000..6bde7a16d00 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/name.go @@ -0,0 +1,35 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +// Model for testing model name same as property name +type Name struct { + + Name int32 `json:"name,omitempty"` + + SnakeCase int32 `json:"snake_case,omitempty"` + + Property string `json:"property,omitempty"` + + Var123Number int32 `json:"123Number,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/number_only.go b/samples/client/petstore/go/go-petstore/number_only.go new file mode 100644 index 00000000000..96a0d7f2133 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/number_only.go @@ -0,0 +1,28 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type NumberOnly struct { + + JustNumber float32 `json:"JustNumber,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/read_only_first.go b/samples/client/petstore/go/go-petstore/read_only_first.go new file mode 100644 index 00000000000..9d8e6351fdf --- /dev/null +++ b/samples/client/petstore/go/go-petstore/read_only_first.go @@ -0,0 +1,30 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type ReadOnlyFirst struct { + + Bar string `json:"bar,omitempty"` + + Baz string `json:"baz,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/special_model_name.go b/samples/client/petstore/go/go-petstore/special_model_name.go new file mode 100644 index 00000000000..7bbb2093ef4 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/special_model_name.go @@ -0,0 +1,28 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package petstore + +type SpecialModelName struct { + + SpecialPropertyName int64 `json:"$special[property.name],omitempty"` +} From 59891c7f667d4f29317146d0a3cb6bcf7b4ae02a Mon Sep 17 00:00:00 2001 From: ataraxus Date: Tue, 6 Sep 2016 04:59:54 +0200 Subject: [PATCH 328/470] fix map usage in api generation #3694 (#3714) * fix map usage in api generation #3694 * fix map usage in api generation #3695 * close impl gap between queryParam and formParam, to be more consistent --- .../typescript-angular2/api.mustache | 16 +- .../typescript-angular2/default/api/PetApi.ts | 320 +++++++++++++----- .../default/api/StoreApi.ts | 157 ++++++--- .../default/api/UserApi.ts | 303 ++++++++++++----- .../typescript-angular2/default/index.ts | 3 +- .../default/model/Category.ts | 1 - .../default/model/Order.ts | 1 - .../typescript-angular2/default/model/Pet.ts | 1 - .../typescript-angular2/default/model/Tag.ts | 1 - .../typescript-angular2/default/model/User.ts | 1 - .../typescript-angular2/npm/README.md | 15 +- .../typescript-angular2/npm/api/PetApi.ts | 320 +++++++++++++----- .../typescript-angular2/npm/api/StoreApi.ts | 157 ++++++--- .../typescript-angular2/npm/api/UserApi.ts | 303 ++++++++++++----- .../petstore/typescript-angular2/npm/index.ts | 3 +- .../typescript-angular2/npm/model/Category.ts | 1 - .../typescript-angular2/npm/model/Order.ts | 1 - .../typescript-angular2/npm/model/Pet.ts | 1 - .../typescript-angular2/npm/model/Tag.ts | 1 - .../typescript-angular2/npm/model/User.ts | 1 - .../typescript-angular2/npm/package.json | 37 +- .../typescript-angular2/npm/typings.json | 6 +- 22 files changed, 1182 insertions(+), 468 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache index aadf38be181..f033a8a4b6c 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache @@ -55,10 +55,10 @@ export class {{classname}} { {{/allParams}} {{#queryParams}} if ({{paramName}} !== undefined) { - queryParameters.set('{{baseName}}', String({{paramName}})); + queryParameters.set('{{baseName}}', {{paramName}}); } - {{/queryParams}} + {{#headers}} headers.set('{{baseName}}', String({{paramName}})); @@ -80,16 +80,18 @@ export class {{classname}} { {{#hasFormParams}} headers.set('Content-Type', 'application/x-www-form-urlencoded'); - {{/hasFormParams}} + {{#bodyParam}} headers.set('Content-Type', 'application/json'); - {{/bodyParam}} -{{#formParams}} - formParams['{{baseName}}'] = {{paramName}}; +{{#formParams}} + if ({{paramName}} !== undefined) { + formParams.set('{{baseName}}', {{paramName}}); + } {{/formParams}} + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: {{httpMethod}}, headers: headers, @@ -115,4 +117,4 @@ export class {{classname}} { {{/operation}} } -{{/operations}} +{{/operations}} \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts index a217fbe8532..7159642a26a 100644 --- a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts @@ -22,22 +22,26 @@ * limitations under the License. */ -import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; -import {Injectable, Optional} from '@angular/core'; -import {Observable} from 'rxjs/Observable'; -import * as models from '../model/models'; -import 'rxjs/Rx'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { Http, Headers, URLSearchParams } from '@angular/http'; +import { RequestMethod, RequestOptions, RequestOptionsArgs } from '@angular/http'; +import { Response, ResponseContentType } from '@angular/http'; + +import { Observable } from 'rxjs/Observable'; +import 'rxjs/add/operator/map'; + +import * as models from '../model/models'; +import { BASE_PATH } from '../variables'; /* tslint:disable:no-unused-variable member-ordering */ -'use strict'; @Injectable() export class PetApi { protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : Headers = new Headers(); + public defaultHeaders: Headers = new Headers(); - constructor(protected http: Http, @Optional() basePath: string) { + constructor(protected http: Http, @Optional()@Inject(BASE_PATH) basePath: string) { if (basePath) { this.basePath = basePath; } @@ -48,17 +52,37 @@ export class PetApi { * * @param body Pet object that needs to be added to the store */ - public addPet (body?: models.Pet, extraHttpRequestParams?: any ) : Observable<{}> { - const path = this.basePath + '/pet'; + public addPet(body?: models.Pet, extraHttpRequestParams?: any): Observable<{}> { + const path = this.basePath + `/pet`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; - let requestOptions: RequestOptionsArgs = { - method: 'POST', - headers: headerParams, - search: queryParameters - }; - requestOptions.body = JSON.stringify(body); + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + + + // to determine the Content-Type header + let consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + headers.set('Content-Type', 'application/json'); + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Post, + headers: headers, + body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -76,23 +100,37 @@ export class PetApi { * @param petId Pet id to delete * @param apiKey */ - public deletePet (petId: number, apiKey?: string, extraHttpRequestParams?: any ) : Observable<{}> { - const path = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(petId)); + public deletePet(petId: number, apiKey?: string, extraHttpRequestParams?: any): Observable<{}> { + const path = this.basePath + `/pet/${petId}`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling deletePet.'); } - headerParams.set('api_key', String(apiKey)); - let requestOptions: RequestOptionsArgs = { - method: 'DELETE', - headers: headerParams, - search: queryParameters - }; + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Delete, + headers: headers, + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -109,20 +147,36 @@ export class PetApi { * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ - public findPetsByStatus (status?: Array, extraHttpRequestParams?: any ) : Observable> { - const path = this.basePath + '/pet/findByStatus'; + public findPetsByStatus(status?: Array, extraHttpRequestParams?: any): Observable> { + const path = this.basePath + `/pet/findByStatus`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 if (status !== undefined) { - queryParameters.set('status', String(status)); + queryParameters.set('status', status); } - let requestOptions: RequestOptionsArgs = { - method: 'GET', - headers: headerParams, - search: queryParameters - }; + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Get, + headers: headers, + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -139,20 +193,36 @@ export class PetApi { * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - public findPetsByTags (tags?: Array, extraHttpRequestParams?: any ) : Observable> { - const path = this.basePath + '/pet/findByTags'; + public findPetsByTags(tags?: Array, extraHttpRequestParams?: any): Observable> { + const path = this.basePath + `/pet/findByTags`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 if (tags !== undefined) { - queryParameters.set('tags', String(tags)); + queryParameters.set('tags', tags); } - let requestOptions: RequestOptionsArgs = { - method: 'GET', - headers: headerParams, - search: queryParameters - }; + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Get, + headers: headers, + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -169,21 +239,37 @@ export class PetApi { * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions * @param petId ID of pet that needs to be fetched */ - public getPetById (petId: number, extraHttpRequestParams?: any ) : Observable { - const path = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(petId)); + public getPetById(petId: number, extraHttpRequestParams?: any): Observable { + const path = this.basePath + `/pet/${petId}`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling getPetById.'); } - let requestOptions: RequestOptionsArgs = { - method: 'GET', - headers: headerParams, - search: queryParameters - }; + + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Get, + headers: headers, + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -200,17 +286,37 @@ export class PetApi { * * @param body Pet object that needs to be added to the store */ - public updatePet (body?: models.Pet, extraHttpRequestParams?: any ) : Observable<{}> { - const path = this.basePath + '/pet'; + public updatePet(body?: models.Pet, extraHttpRequestParams?: any): Observable<{}> { + const path = this.basePath + `/pet`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; - let requestOptions: RequestOptionsArgs = { - method: 'PUT', - headers: headerParams, - search: queryParameters - }; - requestOptions.body = JSON.stringify(body); + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + + + // to determine the Content-Type header + let consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + headers.set('Content-Type', 'application/json'); + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Put, + headers: headers, + body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -229,30 +335,48 @@ export class PetApi { * @param name Updated name of the pet * @param status Updated status of the pet */ - public updatePetWithForm (petId: string, name?: string, status?: string, extraHttpRequestParams?: any ) : Observable<{}> { - const path = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(petId)); + public updatePetWithForm(petId: string, name?: string, status?: string, extraHttpRequestParams?: any): Observable<{}> { + const path = this.basePath + `/pet/${petId}`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 let formParams = new URLSearchParams(); // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); } - headerParams.set('Content-Type', 'application/x-www-form-urlencoded'); - formParams['name'] = name; - formParams['status'] = status; + // to determine the Content-Type header + let consumes: string[] = [ + 'application/x-www-form-urlencoded' + ]; - let requestOptions: RequestOptionsArgs = { - method: 'POST', - headers: headerParams, - search: queryParameters - }; - requestOptions.body = formParams.toString(); + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + headers.set('Content-Type', 'application/x-www-form-urlencoded'); + + +// add form parameters if provided + if (name !== undefined) { + formParams.set('name', name); + } + if (status !== undefined) { + formParams.set('status', status); + } + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Post, + headers: headers, + body: formParams.toString(), + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -271,30 +395,48 @@ export class PetApi { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public uploadFile (petId: number, additionalMetadata?: string, file?: any, extraHttpRequestParams?: any ) : Observable<{}> { - const path = this.basePath + '/pet/{petId}/uploadImage' - .replace('{' + 'petId' + '}', String(petId)); + public uploadFile(petId: number, additionalMetadata?: string, file?: any, extraHttpRequestParams?: any): Observable<{}> { + const path = this.basePath + `/pet/${petId}/uploadImage`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 let formParams = new URLSearchParams(); // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); } - headerParams.set('Content-Type', 'application/x-www-form-urlencoded'); - formParams['additionalMetadata'] = additionalMetadata; - formParams['file'] = file; + // to determine the Content-Type header + let consumes: string[] = [ + 'multipart/form-data' + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + headers.set('Content-Type', 'application/x-www-form-urlencoded'); + + +// add form parameters if provided + if (additionalMetadata !== undefined) { + formParams.set('additionalMetadata', additionalMetadata); + } + if (file !== undefined) { + formParams.set('file', file); + } - let requestOptions: RequestOptionsArgs = { - method: 'POST', - headers: headerParams, - search: queryParameters - }; - requestOptions.body = formParams.toString(); + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Post, + headers: headers, + body: formParams.toString(), + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { diff --git a/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts b/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts index a16fbe4db1a..0987c9fb724 100644 --- a/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts @@ -22,22 +22,26 @@ * limitations under the License. */ -import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; -import {Injectable, Optional} from '@angular/core'; -import {Observable} from 'rxjs/Observable'; -import * as models from '../model/models'; -import 'rxjs/Rx'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { Http, Headers, URLSearchParams } from '@angular/http'; +import { RequestMethod, RequestOptions, RequestOptionsArgs } from '@angular/http'; +import { Response, ResponseContentType } from '@angular/http'; + +import { Observable } from 'rxjs/Observable'; +import 'rxjs/add/operator/map'; + +import * as models from '../model/models'; +import { BASE_PATH } from '../variables'; /* tslint:disable:no-unused-variable member-ordering */ -'use strict'; @Injectable() export class StoreApi { protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : Headers = new Headers(); + public defaultHeaders: Headers = new Headers(); - constructor(protected http: Http, @Optional() basePath: string) { + constructor(protected http: Http, @Optional()@Inject(BASE_PATH) basePath: string) { if (basePath) { this.basePath = basePath; } @@ -48,21 +52,37 @@ export class StoreApi { * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * @param orderId ID of the order that needs to be deleted */ - public deleteOrder (orderId: string, extraHttpRequestParams?: any ) : Observable<{}> { - const path = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(orderId)); + public deleteOrder(orderId: string, extraHttpRequestParams?: any): Observable<{}> { + const path = this.basePath + `/store/order/${orderId}`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); } - let requestOptions: RequestOptionsArgs = { - method: 'DELETE', - headers: headerParams, - search: queryParameters - }; + + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Delete, + headers: headers, + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -78,16 +98,33 @@ export class StoreApi { * Returns pet inventories by status * Returns a map of status codes to quantities */ - public getInventory (extraHttpRequestParams?: any ) : Observable<{ [key: string]: number; }> { - const path = this.basePath + '/store/inventory'; + public getInventory(extraHttpRequestParams?: any): Observable<{ [key: string]: number; }> { + const path = this.basePath + `/store/inventory`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; - let requestOptions: RequestOptionsArgs = { - method: 'GET', - headers: headerParams, - search: queryParameters - }; + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Get, + headers: headers, + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -104,21 +141,37 @@ export class StoreApi { * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * @param orderId ID of pet that needs to be fetched */ - public getOrderById (orderId: string, extraHttpRequestParams?: any ) : Observable { - const path = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(orderId)); + public getOrderById(orderId: string, extraHttpRequestParams?: any): Observable { + const path = this.basePath + `/store/order/${orderId}`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); } - let requestOptions: RequestOptionsArgs = { - method: 'GET', - headers: headerParams, - search: queryParameters - }; + + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Get, + headers: headers, + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -135,17 +188,35 @@ export class StoreApi { * * @param body order placed for purchasing the pet */ - public placeOrder (body?: models.Order, extraHttpRequestParams?: any ) : Observable { - const path = this.basePath + '/store/order'; + public placeOrder(body?: models.Order, extraHttpRequestParams?: any): Observable { + const path = this.basePath + `/store/order`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; - let requestOptions: RequestOptionsArgs = { - method: 'POST', - headers: headerParams, - search: queryParameters - }; - requestOptions.body = JSON.stringify(body); + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + headers.set('Content-Type', 'application/json'); + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Post, + headers: headers, + body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { diff --git a/samples/client/petstore/typescript-angular2/default/api/UserApi.ts b/samples/client/petstore/typescript-angular2/default/api/UserApi.ts index 385c0a03f03..bd7f09522f4 100644 --- a/samples/client/petstore/typescript-angular2/default/api/UserApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/UserApi.ts @@ -22,22 +22,26 @@ * limitations under the License. */ -import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; -import {Injectable, Optional} from '@angular/core'; -import {Observable} from 'rxjs/Observable'; -import * as models from '../model/models'; -import 'rxjs/Rx'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { Http, Headers, URLSearchParams } from '@angular/http'; +import { RequestMethod, RequestOptions, RequestOptionsArgs } from '@angular/http'; +import { Response, ResponseContentType } from '@angular/http'; + +import { Observable } from 'rxjs/Observable'; +import 'rxjs/add/operator/map'; + +import * as models from '../model/models'; +import { BASE_PATH } from '../variables'; /* tslint:disable:no-unused-variable member-ordering */ -'use strict'; @Injectable() export class UserApi { protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : Headers = new Headers(); + public defaultHeaders: Headers = new Headers(); - constructor(protected http: Http, @Optional() basePath: string) { + constructor(protected http: Http, @Optional()@Inject(BASE_PATH) basePath: string) { if (basePath) { this.basePath = basePath; } @@ -48,17 +52,35 @@ export class UserApi { * This can only be done by the logged in user. * @param body Created user object */ - public createUser (body?: models.User, extraHttpRequestParams?: any ) : Observable<{}> { - const path = this.basePath + '/user'; + public createUser(body?: models.User, extraHttpRequestParams?: any): Observable<{}> { + const path = this.basePath + `/user`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; - let requestOptions: RequestOptionsArgs = { - method: 'POST', - headers: headerParams, - search: queryParameters - }; - requestOptions.body = JSON.stringify(body); + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + headers.set('Content-Type', 'application/json'); + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Post, + headers: headers, + body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -75,17 +97,35 @@ export class UserApi { * * @param body List of user object */ - public createUsersWithArrayInput (body?: Array, extraHttpRequestParams?: any ) : Observable<{}> { - const path = this.basePath + '/user/createWithArray'; + public createUsersWithArrayInput(body?: Array, extraHttpRequestParams?: any): Observable<{}> { + const path = this.basePath + `/user/createWithArray`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; - let requestOptions: RequestOptionsArgs = { - method: 'POST', - headers: headerParams, - search: queryParameters - }; - requestOptions.body = JSON.stringify(body); + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + headers.set('Content-Type', 'application/json'); + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Post, + headers: headers, + body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -102,17 +142,35 @@ export class UserApi { * * @param body List of user object */ - public createUsersWithListInput (body?: Array, extraHttpRequestParams?: any ) : Observable<{}> { - const path = this.basePath + '/user/createWithList'; + public createUsersWithListInput(body?: Array, extraHttpRequestParams?: any): Observable<{}> { + const path = this.basePath + `/user/createWithList`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; - let requestOptions: RequestOptionsArgs = { - method: 'POST', - headers: headerParams, - search: queryParameters - }; - requestOptions.body = JSON.stringify(body); + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + headers.set('Content-Type', 'application/json'); + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Post, + headers: headers, + body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -129,21 +187,37 @@ export class UserApi { * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - public deleteUser (username: string, extraHttpRequestParams?: any ) : Observable<{}> { - const path = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(username)); + public deleteUser(username: string, extraHttpRequestParams?: any): Observable<{}> { + const path = this.basePath + `/user/${username}`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling deleteUser.'); } - let requestOptions: RequestOptionsArgs = { - method: 'DELETE', - headers: headerParams, - search: queryParameters - }; + + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Delete, + headers: headers, + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -160,21 +234,37 @@ export class UserApi { * * @param username The name that needs to be fetched. Use user1 for testing. */ - public getUserByName (username: string, extraHttpRequestParams?: any ) : Observable { - const path = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(username)); + public getUserByName(username: string, extraHttpRequestParams?: any): Observable { + const path = this.basePath + `/user/${username}`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling getUserByName.'); } - let requestOptions: RequestOptionsArgs = { - method: 'GET', - headers: headerParams, - search: queryParameters - }; + + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Get, + headers: headers, + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -192,24 +282,39 @@ export class UserApi { * @param username The user name for login * @param password The password for login in clear text */ - public loginUser (username?: string, password?: string, extraHttpRequestParams?: any ) : Observable { - const path = this.basePath + '/user/login'; + public loginUser(username?: string, password?: string, extraHttpRequestParams?: any): Observable { + const path = this.basePath + `/user/login`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 if (username !== undefined) { - queryParameters.set('username', String(username)); + queryParameters.set('username', username); } - if (password !== undefined) { - queryParameters.set('password', String(password)); + queryParameters.set('password', password); } - let requestOptions: RequestOptionsArgs = { - method: 'GET', - headers: headerParams, - search: queryParameters - }; + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Get, + headers: headers, + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -225,16 +330,33 @@ export class UserApi { * Logs out current logged in user session * */ - public logoutUser (extraHttpRequestParams?: any ) : Observable<{}> { - const path = this.basePath + '/user/logout'; + public logoutUser(extraHttpRequestParams?: any): Observable<{}> { + const path = this.basePath + `/user/logout`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; - let requestOptions: RequestOptionsArgs = { - method: 'GET', - headers: headerParams, - search: queryParameters - }; + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Get, + headers: headers, + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -252,22 +374,39 @@ export class UserApi { * @param username name that need to be deleted * @param body Updated user object */ - public updateUser (username: string, body?: models.User, extraHttpRequestParams?: any ) : Observable<{}> { - const path = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(username)); + public updateUser(username: string, body?: models.User, extraHttpRequestParams?: any): Observable<{}> { + const path = this.basePath + `/user/${username}`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling updateUser.'); } - let requestOptions: RequestOptionsArgs = { - method: 'PUT', - headers: headerParams, - search: queryParameters - }; - requestOptions.body = JSON.stringify(body); + + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + headers.set('Content-Type', 'application/json'); + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Put, + headers: headers, + body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { diff --git a/samples/client/petstore/typescript-angular2/default/index.ts b/samples/client/petstore/typescript-angular2/default/index.ts index 557365516ad..ec7dcae82b2 100644 --- a/samples/client/petstore/typescript-angular2/default/index.ts +++ b/samples/client/petstore/typescript-angular2/default/index.ts @@ -1,2 +1,3 @@ export * from './api/api'; -export * from './model/models'; \ No newline at end of file +export * from './model/models'; +export * from './variables'; \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular2/default/model/Category.ts b/samples/client/petstore/typescript-angular2/default/model/Category.ts index 32657b473c6..4ab562b6d3b 100644 --- a/samples/client/petstore/typescript-angular2/default/model/Category.ts +++ b/samples/client/petstore/typescript-angular2/default/model/Category.ts @@ -22,7 +22,6 @@ * limitations under the License. */ -'use strict'; import * as models from './models'; export interface Category { diff --git a/samples/client/petstore/typescript-angular2/default/model/Order.ts b/samples/client/petstore/typescript-angular2/default/model/Order.ts index 0d5ca98d914..8fdad0357f4 100644 --- a/samples/client/petstore/typescript-angular2/default/model/Order.ts +++ b/samples/client/petstore/typescript-angular2/default/model/Order.ts @@ -22,7 +22,6 @@ * limitations under the License. */ -'use strict'; import * as models from './models'; export interface Order { diff --git a/samples/client/petstore/typescript-angular2/default/model/Pet.ts b/samples/client/petstore/typescript-angular2/default/model/Pet.ts index b9557dfb4b3..8695a84774c 100644 --- a/samples/client/petstore/typescript-angular2/default/model/Pet.ts +++ b/samples/client/petstore/typescript-angular2/default/model/Pet.ts @@ -22,7 +22,6 @@ * limitations under the License. */ -'use strict'; import * as models from './models'; export interface Pet { diff --git a/samples/client/petstore/typescript-angular2/default/model/Tag.ts b/samples/client/petstore/typescript-angular2/default/model/Tag.ts index 6672611adfc..2e1bf1572e1 100644 --- a/samples/client/petstore/typescript-angular2/default/model/Tag.ts +++ b/samples/client/petstore/typescript-angular2/default/model/Tag.ts @@ -22,7 +22,6 @@ * limitations under the License. */ -'use strict'; import * as models from './models'; export interface Tag { diff --git a/samples/client/petstore/typescript-angular2/default/model/User.ts b/samples/client/petstore/typescript-angular2/default/model/User.ts index 11c5e587ee8..efb2351b234 100644 --- a/samples/client/petstore/typescript-angular2/default/model/User.ts +++ b/samples/client/petstore/typescript-angular2/default/model/User.ts @@ -22,7 +22,6 @@ * limitations under the License. */ -'use strict'; import * as models from './models'; export interface User { diff --git a/samples/client/petstore/typescript-angular2/npm/README.md b/samples/client/petstore/typescript-angular2/npm/README.md index b57ee5d3ac7..b688e462e7d 100644 --- a/samples/client/petstore/typescript-angular2/npm/README.md +++ b/samples/client/petstore/typescript-angular2/npm/README.md @@ -1,4 +1,4 @@ -## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201608052320 +## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201609051239 ### Building @@ -19,7 +19,7 @@ navigate to the folder of your consuming project and run one of next commando's. _published:_ ``` -npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201608052320 --save +npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201609051239 --save ``` _unPublished (not recommended):_ @@ -31,3 +31,14 @@ npm install PATH_TO_GENERATED_PACKAGE --save In your angular2 project: TODO: paste example. + +### Set service base path +If different than the generated base path, during app bootstrap, you can provide the base path to your service. + +``` +import { BASE_PATH } from './path-to-swagger-gen-service/index'; + +bootstrap(AppComponent, [ + { provide: BASE_PATH, useValue: 'https://your-web-service.com' }, +]); +``` \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts index a217fbe8532..7159642a26a 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts @@ -22,22 +22,26 @@ * limitations under the License. */ -import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; -import {Injectable, Optional} from '@angular/core'; -import {Observable} from 'rxjs/Observable'; -import * as models from '../model/models'; -import 'rxjs/Rx'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { Http, Headers, URLSearchParams } from '@angular/http'; +import { RequestMethod, RequestOptions, RequestOptionsArgs } from '@angular/http'; +import { Response, ResponseContentType } from '@angular/http'; + +import { Observable } from 'rxjs/Observable'; +import 'rxjs/add/operator/map'; + +import * as models from '../model/models'; +import { BASE_PATH } from '../variables'; /* tslint:disable:no-unused-variable member-ordering */ -'use strict'; @Injectable() export class PetApi { protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : Headers = new Headers(); + public defaultHeaders: Headers = new Headers(); - constructor(protected http: Http, @Optional() basePath: string) { + constructor(protected http: Http, @Optional()@Inject(BASE_PATH) basePath: string) { if (basePath) { this.basePath = basePath; } @@ -48,17 +52,37 @@ export class PetApi { * * @param body Pet object that needs to be added to the store */ - public addPet (body?: models.Pet, extraHttpRequestParams?: any ) : Observable<{}> { - const path = this.basePath + '/pet'; + public addPet(body?: models.Pet, extraHttpRequestParams?: any): Observable<{}> { + const path = this.basePath + `/pet`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; - let requestOptions: RequestOptionsArgs = { - method: 'POST', - headers: headerParams, - search: queryParameters - }; - requestOptions.body = JSON.stringify(body); + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + + + // to determine the Content-Type header + let consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + headers.set('Content-Type', 'application/json'); + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Post, + headers: headers, + body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -76,23 +100,37 @@ export class PetApi { * @param petId Pet id to delete * @param apiKey */ - public deletePet (petId: number, apiKey?: string, extraHttpRequestParams?: any ) : Observable<{}> { - const path = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(petId)); + public deletePet(petId: number, apiKey?: string, extraHttpRequestParams?: any): Observable<{}> { + const path = this.basePath + `/pet/${petId}`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling deletePet.'); } - headerParams.set('api_key', String(apiKey)); - let requestOptions: RequestOptionsArgs = { - method: 'DELETE', - headers: headerParams, - search: queryParameters - }; + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Delete, + headers: headers, + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -109,20 +147,36 @@ export class PetApi { * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ - public findPetsByStatus (status?: Array, extraHttpRequestParams?: any ) : Observable> { - const path = this.basePath + '/pet/findByStatus'; + public findPetsByStatus(status?: Array, extraHttpRequestParams?: any): Observable> { + const path = this.basePath + `/pet/findByStatus`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 if (status !== undefined) { - queryParameters.set('status', String(status)); + queryParameters.set('status', status); } - let requestOptions: RequestOptionsArgs = { - method: 'GET', - headers: headerParams, - search: queryParameters - }; + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Get, + headers: headers, + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -139,20 +193,36 @@ export class PetApi { * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - public findPetsByTags (tags?: Array, extraHttpRequestParams?: any ) : Observable> { - const path = this.basePath + '/pet/findByTags'; + public findPetsByTags(tags?: Array, extraHttpRequestParams?: any): Observable> { + const path = this.basePath + `/pet/findByTags`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 if (tags !== undefined) { - queryParameters.set('tags', String(tags)); + queryParameters.set('tags', tags); } - let requestOptions: RequestOptionsArgs = { - method: 'GET', - headers: headerParams, - search: queryParameters - }; + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Get, + headers: headers, + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -169,21 +239,37 @@ export class PetApi { * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions * @param petId ID of pet that needs to be fetched */ - public getPetById (petId: number, extraHttpRequestParams?: any ) : Observable { - const path = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(petId)); + public getPetById(petId: number, extraHttpRequestParams?: any): Observable { + const path = this.basePath + `/pet/${petId}`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling getPetById.'); } - let requestOptions: RequestOptionsArgs = { - method: 'GET', - headers: headerParams, - search: queryParameters - }; + + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Get, + headers: headers, + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -200,17 +286,37 @@ export class PetApi { * * @param body Pet object that needs to be added to the store */ - public updatePet (body?: models.Pet, extraHttpRequestParams?: any ) : Observable<{}> { - const path = this.basePath + '/pet'; + public updatePet(body?: models.Pet, extraHttpRequestParams?: any): Observable<{}> { + const path = this.basePath + `/pet`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; - let requestOptions: RequestOptionsArgs = { - method: 'PUT', - headers: headerParams, - search: queryParameters - }; - requestOptions.body = JSON.stringify(body); + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + + + // to determine the Content-Type header + let consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + headers.set('Content-Type', 'application/json'); + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Put, + headers: headers, + body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -229,30 +335,48 @@ export class PetApi { * @param name Updated name of the pet * @param status Updated status of the pet */ - public updatePetWithForm (petId: string, name?: string, status?: string, extraHttpRequestParams?: any ) : Observable<{}> { - const path = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(petId)); + public updatePetWithForm(petId: string, name?: string, status?: string, extraHttpRequestParams?: any): Observable<{}> { + const path = this.basePath + `/pet/${petId}`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 let formParams = new URLSearchParams(); // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); } - headerParams.set('Content-Type', 'application/x-www-form-urlencoded'); - formParams['name'] = name; - formParams['status'] = status; + // to determine the Content-Type header + let consumes: string[] = [ + 'application/x-www-form-urlencoded' + ]; - let requestOptions: RequestOptionsArgs = { - method: 'POST', - headers: headerParams, - search: queryParameters - }; - requestOptions.body = formParams.toString(); + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + headers.set('Content-Type', 'application/x-www-form-urlencoded'); + + +// add form parameters if provided + if (name !== undefined) { + formParams.set('name', name); + } + if (status !== undefined) { + formParams.set('status', status); + } + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Post, + headers: headers, + body: formParams.toString(), + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -271,30 +395,48 @@ export class PetApi { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public uploadFile (petId: number, additionalMetadata?: string, file?: any, extraHttpRequestParams?: any ) : Observable<{}> { - const path = this.basePath + '/pet/{petId}/uploadImage' - .replace('{' + 'petId' + '}', String(petId)); + public uploadFile(petId: number, additionalMetadata?: string, file?: any, extraHttpRequestParams?: any): Observable<{}> { + const path = this.basePath + `/pet/${petId}/uploadImage`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 let formParams = new URLSearchParams(); // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); } - headerParams.set('Content-Type', 'application/x-www-form-urlencoded'); - formParams['additionalMetadata'] = additionalMetadata; - formParams['file'] = file; + // to determine the Content-Type header + let consumes: string[] = [ + 'multipart/form-data' + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + headers.set('Content-Type', 'application/x-www-form-urlencoded'); + + +// add form parameters if provided + if (additionalMetadata !== undefined) { + formParams.set('additionalMetadata', additionalMetadata); + } + if (file !== undefined) { + formParams.set('file', file); + } - let requestOptions: RequestOptionsArgs = { - method: 'POST', - headers: headerParams, - search: queryParameters - }; - requestOptions.body = formParams.toString(); + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Post, + headers: headers, + body: formParams.toString(), + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { diff --git a/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts b/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts index a16fbe4db1a..0987c9fb724 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts @@ -22,22 +22,26 @@ * limitations under the License. */ -import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; -import {Injectable, Optional} from '@angular/core'; -import {Observable} from 'rxjs/Observable'; -import * as models from '../model/models'; -import 'rxjs/Rx'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { Http, Headers, URLSearchParams } from '@angular/http'; +import { RequestMethod, RequestOptions, RequestOptionsArgs } from '@angular/http'; +import { Response, ResponseContentType } from '@angular/http'; + +import { Observable } from 'rxjs/Observable'; +import 'rxjs/add/operator/map'; + +import * as models from '../model/models'; +import { BASE_PATH } from '../variables'; /* tslint:disable:no-unused-variable member-ordering */ -'use strict'; @Injectable() export class StoreApi { protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : Headers = new Headers(); + public defaultHeaders: Headers = new Headers(); - constructor(protected http: Http, @Optional() basePath: string) { + constructor(protected http: Http, @Optional()@Inject(BASE_PATH) basePath: string) { if (basePath) { this.basePath = basePath; } @@ -48,21 +52,37 @@ export class StoreApi { * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * @param orderId ID of the order that needs to be deleted */ - public deleteOrder (orderId: string, extraHttpRequestParams?: any ) : Observable<{}> { - const path = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(orderId)); + public deleteOrder(orderId: string, extraHttpRequestParams?: any): Observable<{}> { + const path = this.basePath + `/store/order/${orderId}`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); } - let requestOptions: RequestOptionsArgs = { - method: 'DELETE', - headers: headerParams, - search: queryParameters - }; + + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Delete, + headers: headers, + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -78,16 +98,33 @@ export class StoreApi { * Returns pet inventories by status * Returns a map of status codes to quantities */ - public getInventory (extraHttpRequestParams?: any ) : Observable<{ [key: string]: number; }> { - const path = this.basePath + '/store/inventory'; + public getInventory(extraHttpRequestParams?: any): Observable<{ [key: string]: number; }> { + const path = this.basePath + `/store/inventory`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; - let requestOptions: RequestOptionsArgs = { - method: 'GET', - headers: headerParams, - search: queryParameters - }; + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Get, + headers: headers, + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -104,21 +141,37 @@ export class StoreApi { * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * @param orderId ID of pet that needs to be fetched */ - public getOrderById (orderId: string, extraHttpRequestParams?: any ) : Observable { - const path = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(orderId)); + public getOrderById(orderId: string, extraHttpRequestParams?: any): Observable { + const path = this.basePath + `/store/order/${orderId}`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); } - let requestOptions: RequestOptionsArgs = { - method: 'GET', - headers: headerParams, - search: queryParameters - }; + + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Get, + headers: headers, + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -135,17 +188,35 @@ export class StoreApi { * * @param body order placed for purchasing the pet */ - public placeOrder (body?: models.Order, extraHttpRequestParams?: any ) : Observable { - const path = this.basePath + '/store/order'; + public placeOrder(body?: models.Order, extraHttpRequestParams?: any): Observable { + const path = this.basePath + `/store/order`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; - let requestOptions: RequestOptionsArgs = { - method: 'POST', - headers: headerParams, - search: queryParameters - }; - requestOptions.body = JSON.stringify(body); + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + headers.set('Content-Type', 'application/json'); + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Post, + headers: headers, + body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { diff --git a/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts b/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts index 385c0a03f03..bd7f09522f4 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts @@ -22,22 +22,26 @@ * limitations under the License. */ -import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; -import {Injectable, Optional} from '@angular/core'; -import {Observable} from 'rxjs/Observable'; -import * as models from '../model/models'; -import 'rxjs/Rx'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { Http, Headers, URLSearchParams } from '@angular/http'; +import { RequestMethod, RequestOptions, RequestOptionsArgs } from '@angular/http'; +import { Response, ResponseContentType } from '@angular/http'; + +import { Observable } from 'rxjs/Observable'; +import 'rxjs/add/operator/map'; + +import * as models from '../model/models'; +import { BASE_PATH } from '../variables'; /* tslint:disable:no-unused-variable member-ordering */ -'use strict'; @Injectable() export class UserApi { protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : Headers = new Headers(); + public defaultHeaders: Headers = new Headers(); - constructor(protected http: Http, @Optional() basePath: string) { + constructor(protected http: Http, @Optional()@Inject(BASE_PATH) basePath: string) { if (basePath) { this.basePath = basePath; } @@ -48,17 +52,35 @@ export class UserApi { * This can only be done by the logged in user. * @param body Created user object */ - public createUser (body?: models.User, extraHttpRequestParams?: any ) : Observable<{}> { - const path = this.basePath + '/user'; + public createUser(body?: models.User, extraHttpRequestParams?: any): Observable<{}> { + const path = this.basePath + `/user`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; - let requestOptions: RequestOptionsArgs = { - method: 'POST', - headers: headerParams, - search: queryParameters - }; - requestOptions.body = JSON.stringify(body); + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + headers.set('Content-Type', 'application/json'); + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Post, + headers: headers, + body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -75,17 +97,35 @@ export class UserApi { * * @param body List of user object */ - public createUsersWithArrayInput (body?: Array, extraHttpRequestParams?: any ) : Observable<{}> { - const path = this.basePath + '/user/createWithArray'; + public createUsersWithArrayInput(body?: Array, extraHttpRequestParams?: any): Observable<{}> { + const path = this.basePath + `/user/createWithArray`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; - let requestOptions: RequestOptionsArgs = { - method: 'POST', - headers: headerParams, - search: queryParameters - }; - requestOptions.body = JSON.stringify(body); + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + headers.set('Content-Type', 'application/json'); + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Post, + headers: headers, + body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -102,17 +142,35 @@ export class UserApi { * * @param body List of user object */ - public createUsersWithListInput (body?: Array, extraHttpRequestParams?: any ) : Observable<{}> { - const path = this.basePath + '/user/createWithList'; + public createUsersWithListInput(body?: Array, extraHttpRequestParams?: any): Observable<{}> { + const path = this.basePath + `/user/createWithList`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; - let requestOptions: RequestOptionsArgs = { - method: 'POST', - headers: headerParams, - search: queryParameters - }; - requestOptions.body = JSON.stringify(body); + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + headers.set('Content-Type', 'application/json'); + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Post, + headers: headers, + body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -129,21 +187,37 @@ export class UserApi { * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - public deleteUser (username: string, extraHttpRequestParams?: any ) : Observable<{}> { - const path = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(username)); + public deleteUser(username: string, extraHttpRequestParams?: any): Observable<{}> { + const path = this.basePath + `/user/${username}`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling deleteUser.'); } - let requestOptions: RequestOptionsArgs = { - method: 'DELETE', - headers: headerParams, - search: queryParameters - }; + + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Delete, + headers: headers, + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -160,21 +234,37 @@ export class UserApi { * * @param username The name that needs to be fetched. Use user1 for testing. */ - public getUserByName (username: string, extraHttpRequestParams?: any ) : Observable { - const path = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(username)); + public getUserByName(username: string, extraHttpRequestParams?: any): Observable { + const path = this.basePath + `/user/${username}`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling getUserByName.'); } - let requestOptions: RequestOptionsArgs = { - method: 'GET', - headers: headerParams, - search: queryParameters - }; + + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Get, + headers: headers, + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -192,24 +282,39 @@ export class UserApi { * @param username The user name for login * @param password The password for login in clear text */ - public loginUser (username?: string, password?: string, extraHttpRequestParams?: any ) : Observable { - const path = this.basePath + '/user/login'; + public loginUser(username?: string, password?: string, extraHttpRequestParams?: any): Observable { + const path = this.basePath + `/user/login`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 if (username !== undefined) { - queryParameters.set('username', String(username)); + queryParameters.set('username', username); } - if (password !== undefined) { - queryParameters.set('password', String(password)); + queryParameters.set('password', password); } - let requestOptions: RequestOptionsArgs = { - method: 'GET', - headers: headerParams, - search: queryParameters - }; + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Get, + headers: headers, + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -225,16 +330,33 @@ export class UserApi { * Logs out current logged in user session * */ - public logoutUser (extraHttpRequestParams?: any ) : Observable<{}> { - const path = this.basePath + '/user/logout'; + public logoutUser(extraHttpRequestParams?: any): Observable<{}> { + const path = this.basePath + `/user/logout`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; - let requestOptions: RequestOptionsArgs = { - method: 'GET', - headers: headerParams, - search: queryParameters - }; + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Get, + headers: headers, + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { @@ -252,22 +374,39 @@ export class UserApi { * @param username name that need to be deleted * @param body Updated user object */ - public updateUser (username: string, body?: models.User, extraHttpRequestParams?: any ) : Observable<{}> { - const path = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(username)); + public updateUser(username: string, body?: models.User, extraHttpRequestParams?: any): Observable<{}> { + const path = this.basePath + `/user/${username}`; let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; + let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling updateUser.'); } - let requestOptions: RequestOptionsArgs = { - method: 'PUT', - headers: headerParams, - search: queryParameters - }; - requestOptions.body = JSON.stringify(body); + + + // to determine the Content-Type header + let consumes: string[] = [ + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + 'application/xml' + ]; + + + headers.set('Content-Type', 'application/json'); + +// add form parameters if provided + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Put, + headers: headers, + body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 + search: queryParameters, + responseType: ResponseContentType.Json + }); return this.http.request(path, requestOptions) .map((response: Response) => { diff --git a/samples/client/petstore/typescript-angular2/npm/index.ts b/samples/client/petstore/typescript-angular2/npm/index.ts index 557365516ad..ec7dcae82b2 100644 --- a/samples/client/petstore/typescript-angular2/npm/index.ts +++ b/samples/client/petstore/typescript-angular2/npm/index.ts @@ -1,2 +1,3 @@ export * from './api/api'; -export * from './model/models'; \ No newline at end of file +export * from './model/models'; +export * from './variables'; \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular2/npm/model/Category.ts b/samples/client/petstore/typescript-angular2/npm/model/Category.ts index 32657b473c6..4ab562b6d3b 100644 --- a/samples/client/petstore/typescript-angular2/npm/model/Category.ts +++ b/samples/client/petstore/typescript-angular2/npm/model/Category.ts @@ -22,7 +22,6 @@ * limitations under the License. */ -'use strict'; import * as models from './models'; export interface Category { diff --git a/samples/client/petstore/typescript-angular2/npm/model/Order.ts b/samples/client/petstore/typescript-angular2/npm/model/Order.ts index 0d5ca98d914..8fdad0357f4 100644 --- a/samples/client/petstore/typescript-angular2/npm/model/Order.ts +++ b/samples/client/petstore/typescript-angular2/npm/model/Order.ts @@ -22,7 +22,6 @@ * limitations under the License. */ -'use strict'; import * as models from './models'; export interface Order { diff --git a/samples/client/petstore/typescript-angular2/npm/model/Pet.ts b/samples/client/petstore/typescript-angular2/npm/model/Pet.ts index b9557dfb4b3..8695a84774c 100644 --- a/samples/client/petstore/typescript-angular2/npm/model/Pet.ts +++ b/samples/client/petstore/typescript-angular2/npm/model/Pet.ts @@ -22,7 +22,6 @@ * limitations under the License. */ -'use strict'; import * as models from './models'; export interface Pet { diff --git a/samples/client/petstore/typescript-angular2/npm/model/Tag.ts b/samples/client/petstore/typescript-angular2/npm/model/Tag.ts index 6672611adfc..2e1bf1572e1 100644 --- a/samples/client/petstore/typescript-angular2/npm/model/Tag.ts +++ b/samples/client/petstore/typescript-angular2/npm/model/Tag.ts @@ -22,7 +22,6 @@ * limitations under the License. */ -'use strict'; import * as models from './models'; export interface Tag { diff --git a/samples/client/petstore/typescript-angular2/npm/model/User.ts b/samples/client/petstore/typescript-angular2/npm/model/User.ts index 11c5e587ee8..efb2351b234 100644 --- a/samples/client/petstore/typescript-angular2/npm/model/User.ts +++ b/samples/client/petstore/typescript-angular2/npm/model/User.ts @@ -22,7 +22,6 @@ * limitations under the License. */ -'use strict'; import * as models from './models'; export interface User { diff --git a/samples/client/petstore/typescript-angular2/npm/package.json b/samples/client/petstore/typescript-angular2/npm/package.json index 7279d56588d..8a6efafddf9 100644 --- a/samples/client/petstore/typescript-angular2/npm/package.json +++ b/samples/client/petstore/typescript-angular2/npm/package.json @@ -1,6 +1,6 @@ { "name": "@swagger/angular2-typescript-petstore", - "version": "0.0.1-SNAPSHOT.201608052320", + "version": "0.0.1-SNAPSHOT.201609051239", "description": "swagger client for @swagger/angular2-typescript-petstore", "author": "Swagger Codegen Contributors", "keywords": [ @@ -13,26 +13,31 @@ "main": "./lib/index.js", "typings": "./lib/index.d.ts", "scripts": { - "build": "typings install && tsc" + "build": "typings install && tsc", + "postinstall": "npm run build" }, "peerDependencies": { - "@angular/core": "^2.0.0-rc.1", - "@angular/http": "^2.0.0-rc.1" + "@angular/core": "^2.0.0-rc.5", + "@angular/http": "^2.0.0-rc.5", + "@angular/common": "^2.0.0-rc.5", + "@angular/compiler": "^2.0.0-rc.5", + "core-js": "^2.4.0", + "reflect-metadata": "^0.1.3", + "rxjs": "5.0.0-beta.6", + "zone.js": "^0.6.17" }, "devDependencies": { - "@angular/common": "^2.0.0-rc.1", - "@angular/compiler": "^2.0.0-rc.1", - "@angular/core": "^2.0.0-rc.1", - "@angular/http": "^2.0.0-rc.1", - "@angular/platform-browser": "^2.0.0-rc.1", - "@angular/platform-browser-dynamic": "^2.0.0-rc.1", - "core-js": "^2.3.0", - "rxjs": "^5.0.0-beta.6", - "zone.js": "^0.6.12", + "@angular/core": "^2.0.0-rc.5", + "@angular/http": "^2.0.0-rc.5", + "@angular/common": "^2.0.0-rc.5", + "@angular/compiler": "^2.0.0-rc.5", + "@angular/platform-browser": "^2.0.0-rc.5", + "core-js": "^2.4.0", + "reflect-metadata": "^0.1.3", + "rxjs": "5.0.0-beta.6", + "zone.js": "^0.6.17", "typescript": "^1.8.10", - "typings": "^0.8.1", - "es6-shim": "^0.35.0", - "es7-reflect-metadata": "^1.6.0" + "typings": "^1.3.2" }, "publishConfig":{ "registry":"https://skimdb.npmjs.com/registry" diff --git a/samples/client/petstore/typescript-angular2/npm/typings.json b/samples/client/petstore/typescript-angular2/npm/typings.json index 0848dcffe31..507c40e5cbe 100644 --- a/samples/client/petstore/typescript-angular2/npm/typings.json +++ b/samples/client/petstore/typescript-angular2/npm/typings.json @@ -1,5 +1,5 @@ { - "ambientDependencies": { - "core-js": "registry:dt/core-js#0.0.0+20160317120654" + "globalDependencies": { + "core-js": "registry:dt/core-js#0.0.0+20160725163759" } -} \ No newline at end of file +} From ddc5b8043845c8923d5b42397de5dd09d206b476 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Tue, 6 Sep 2016 09:57:35 +0300 Subject: [PATCH 329/470] [Lumen, PHP, Python, Ruby] Implement exclusiveMinimum/Maximum (#3717) * Ignore exclusiveMinimum/Maximum in setting hasValidation * python: Implement exclusiveMinimum/Maximum * ruby: Implement exclusiveMinimum/Maximum * lumen: Implement exclusiveMinimum/Maximum * php: Implement exclusiveMinimum/Maximum --- .../io/swagger/codegen/DefaultCodegen.java | 7 ++++--- .../src/main/resources/lumen/api.mustache | 16 +++++++-------- .../src/main/resources/php/api.mustache | 8 ++++---- .../main/resources/php/model_generic.mustache | 20 +++++++++---------- .../src/main/resources/python/api.mustache | 8 ++++---- .../src/main/resources/python/model.mustache | 8 ++++---- .../src/main/resources/ruby/api.mustache | 8 ++++---- .../ruby/partial_model_generic.mustache | 20 +++++++++---------- .../python/petstore_api/apis/fake_api.py | 10 +++++----- .../python/petstore_api/apis/store_api.py | 2 +- 10 files changed, 54 insertions(+), 53 deletions(-) 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 7ba6dff419d..64506e2a209 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 @@ -1403,7 +1403,8 @@ public CodegenProperty fromProperty(String name, Property p) { property.exclusiveMaximum = np.getExclusiveMaximum(); // check if any validation rule defined - if (property.minimum != null || property.maximum != null || property.exclusiveMinimum != null || property.exclusiveMaximum != null) + // exclusive* are noop without corresponding min/max + if (property.minimum != null || property.maximum != null) property.hasValidation = true; // legacy support @@ -2270,8 +2271,8 @@ public CodegenParameter fromParameter(Parameter param, Set imports) { p.uniqueItems = qp.isUniqueItems(); p.multipleOf = qp.getMultipleOf(); - if (p.maximum != null || p.exclusiveMaximum != null || - p.minimum != null || p.exclusiveMinimum != null || + // exclusive* are noop without corresponding min/max + if (p.maximum != null || p.minimum != null || p.maxLength != null || p.minLength != null || p.maxItems != null || p.minItems != null || p.pattern != null) { diff --git a/modules/swagger-codegen/src/main/resources/lumen/api.mustache b/modules/swagger-codegen/src/main/resources/lumen/api.mustache index 34ce7b64955..c6b6561624b 100644 --- a/modules/swagger-codegen/src/main/resources/lumen/api.mustache +++ b/modules/swagger-codegen/src/main/resources/lumen/api.mustache @@ -43,13 +43,13 @@ use Illuminate\Support\Facades\Request; } {{/minLength}} {{#maximum}} - if (${{paramName}}] > {{maximum}}) { - throw new \InvalidArgumentException('invalid value for ${{paramName}} when calling {{classname}}.{{operationId}}, must be smaller than or equal to {{maximum}}.'); + if (${{paramName}}] >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}}) { + throw new \InvalidArgumentException('invalid value for ${{paramName}} when calling {{classname}}.{{operationId}}, must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{maximum}}.'); } {{/maximum}} {{#minimum}} - if (${{paramName}}] < {{minimum}}) { - throw new \InvalidArgumentException('invalid value for ${{paramName}} when calling {{classname}}.{{operationId}}, must be bigger than or equal to {{minimum}}.'); + if (${{paramName}}] <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}}) { + throw new \InvalidArgumentException('invalid value for ${{paramName}} when calling {{classname}}.{{operationId}}, must be bigger than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{minimum}}.'); } {{/minimum}} {{#pattern}} @@ -81,13 +81,13 @@ use Illuminate\Support\Facades\Request; } {{/minLength}} {{#maximum}} - if ($input['{{paramName}}'] > {{maximum}}) { - throw new \InvalidArgumentException('invalid value for ${{paramName}} when calling {{classname}}.{{operationId}}, must be smaller than or equal to {{maximum}}.'); + if ($input['{{paramName}}'] >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}}) { + throw new \InvalidArgumentException('invalid value for ${{paramName}} when calling {{classname}}.{{operationId}}, must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{maximum}}.'); } {{/maximum}} {{#minimum}} - if ($input['{{paramName}}'] < {{minimum}}) { - throw new \InvalidArgumentException('invalid value for ${{paramName}} when calling {{classname}}.{{operationId}}, must be bigger than or equal to {{minimum}}.'); + if ($input['{{paramName}}'] <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}}) { + throw new \InvalidArgumentException('invalid value for ${{paramName}} when calling {{classname}}.{{operationId}}, must be bigger than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{minimum}}.'); } {{/minimum}} {{#pattern}} diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 0d3394d42e7..c6148ae251d 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -139,13 +139,13 @@ use \{{invokerPackage}}\ObjectSerializer; } {{/minLength}} {{#maximum}} - if ({{^required}}!is_null(${{paramName}}) && {{/required}}(${{paramName}} > {{maximum}})) { - throw new \InvalidArgumentException('invalid value for "${{paramName}}" when calling {{classname}}.{{operationId}}, must be smaller than or equal to {{maximum}}.'); + if ({{^required}}!is_null(${{paramName}}) && {{/required}}(${{paramName}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}})) { + throw new \InvalidArgumentException('invalid value for "${{paramName}}" when calling {{classname}}.{{operationId}}, must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{maximum}}.'); } {{/maximum}} {{#minimum}} - if ({{^required}}!is_null(${{paramName}}) && {{/required}}(${{paramName}} < {{minimum}})) { - throw new \InvalidArgumentException('invalid value for "${{paramName}}" when calling {{classname}}.{{operationId}}, must be bigger than or equal to {{minimum}}.'); + if ({{^required}}!is_null(${{paramName}}) && {{/required}}(${{paramName}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}})) { + throw new \InvalidArgumentException('invalid value for "${{paramName}}" when calling {{classname}}.{{operationId}}, must be bigger than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{minimum}}.'); } {{/minimum}} {{#pattern}} diff --git a/modules/swagger-codegen/src/main/resources/php/model_generic.mustache b/modules/swagger-codegen/src/main/resources/php/model_generic.mustache index 8286a9b9f4d..372af3af6cc 100644 --- a/modules/swagger-codegen/src/main/resources/php/model_generic.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model_generic.mustache @@ -143,14 +143,14 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple {{/minLength}} {{#maximum}} - if ({{^required}}!is_null($this->container['{{name}}']) && {{/required}}($this->container['{{name}}'] > {{maximum}})) { - $invalid_properties[] = "invalid value for '{{name}}', must be smaller than or equal to {{maximum}}."; + if ({{^required}}!is_null($this->container['{{name}}']) && {{/required}}($this->container['{{name}}'] >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}})) { + $invalid_properties[] = "invalid value for '{{name}}', must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{maximum}}."; } {{/maximum}} {{#minimum}} - if ({{^required}}!is_null($this->container['{{name}}']) && {{/required}}($this->container['{{name}}'] < {{minimum}})) { - $invalid_properties[] = "invalid value for '{{name}}', must be bigger than or equal to {{minimum}}."; + if ({{^required}}!is_null($this->container['{{name}}']) && {{/required}}($this->container['{{name}}'] <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}})) { + $invalid_properties[] = "invalid value for '{{name}}', must be bigger than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{minimum}}."; } {{/minimum}} @@ -199,12 +199,12 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple } {{/minLength}} {{#maximum}} - if ($this->container['{{name}}'] > {{maximum}}) { + if ($this->container['{{name}}'] >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}}) { return false; } {{/maximum}} {{#minimum}} - if ($this->container['{{name}}'] < {{minimum}}) { + if ($this->container['{{name}}'] <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}}) { return false; } {{/minimum}} @@ -260,13 +260,13 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple } {{/minLength}} {{#maximum}} - if (${{name}} > {{maximum}}) { - throw new \InvalidArgumentException('invalid value for ${{name}} when calling {{classname}}.{{operationId}}, must be smaller than or equal to {{maximum}}.'); + if (${{name}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}}) { + throw new \InvalidArgumentException('invalid value for ${{name}} when calling {{classname}}.{{operationId}}, must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{maximum}}.'); } {{/maximum}} {{#minimum}} - if (${{name}} < {{minimum}}) { - throw new \InvalidArgumentException('invalid value for ${{name}} when calling {{classname}}.{{operationId}}, must be bigger than or equal to {{minimum}}.'); + if (${{name}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}}) { + throw new \InvalidArgumentException('invalid value for ${{name}} when calling {{classname}}.{{operationId}}, must be bigger than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{minimum}}.'); } {{/minimum}} {{#pattern}} diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index 9b355a32fba..34ae38fc615 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -127,12 +127,12 @@ class {{classname}}(object): raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, length must be greater than or equal to `{{minLength}}`") {{/minLength}} {{#maximum}} - if '{{paramName}}' in params and params['{{paramName}}'] > {{maximum}}: - raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must be a value less than or equal to `{{maximum}}`") + if '{{paramName}}' in params and params['{{paramName}}'] >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}}: + raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must be a value less than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}`{{maximum}}`") {{/maximum}} {{#minimum}} - if '{{paramName}}' in params and params['{{paramName}}'] < {{minimum}}: - raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must be a value greater than or equal to `{{minimum}}`") + if '{{paramName}}' in params and params['{{paramName}}'] <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}}: + raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must be a value greater than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}`{{minimum}}`") {{/minimum}} {{#pattern}} if '{{paramName}}' in params and not re.search('{{{vendorExtensions.x-regex}}}', params['{{paramName}}']{{#vendorExtensions.x-modifiers}}{{#-first}}, flags={{/-first}}re.{{.}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}): diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index 59dc13b83ce..9b51612a8a5 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -81,12 +81,12 @@ class {{classname}}(object): raise ValueError("Invalid value for `{{name}}`, length must be greater than or equal to `{{minLength}}`") {{/minLength}} {{#maximum}} - if {{name}} > {{maximum}}: - raise ValueError("Invalid value for `{{name}}`, must be a value less than or equal to `{{maximum}}`") + if {{name}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}}: + raise ValueError("Invalid value for `{{name}}`, must be a value less than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}`{{maximum}}`") {{/maximum}} {{#minimum}} - if {{name}} < {{minimum}}: - raise ValueError("Invalid value for `{{name}}`, must be a value greater than or equal to `{{minimum}}`") + if {{name}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}}: + raise ValueError("Invalid value for `{{name}}`, must be a value greater than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}`{{minimum}}`") {{/minimum}} {{#pattern}} if not re.search('{{{vendorExtensions.x-regex}}}', {{name}}{{#vendorExtensions.x-modifiers}}{{#-first}}, flags={{/-first}}re.{{.}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}): diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index e69765707d2..dc44728259d 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -69,14 +69,14 @@ module {{moduleName}} {{/minLength}} {{#maximum}} - if {{^required}}!opts[:'{{{paramName}}}'].nil? && {{/required}}{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}} > {{{maximum}}} - fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, must be smaller than or equal to {{{maximum}}}.' + if {{^required}}!opts[:'{{{paramName}}}'].nil? && {{/required}}{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{{maximum}}} + fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{{maximum}}}.' end {{/maximum}} {{#minimum}} - if {{^required}}!opts[:'{{{paramName}}}'].nil? && {{/required}}{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}} < {{{minimum}}} - fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, must be greater than or equal to {{{minimum}}}.' + if {{^required}}!opts[:'{{{paramName}}}'].nil? && {{/required}}{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{{minimum}}} + fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, must be greater than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{{minimum}}}.' end {{/minimum}} diff --git a/modules/swagger-codegen/src/main/resources/ruby/partial_model_generic.mustache b/modules/swagger-codegen/src/main/resources/ruby/partial_model_generic.mustache index 6416ada91f1..8463120c7da 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/partial_model_generic.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/partial_model_generic.mustache @@ -98,14 +98,14 @@ {{/minLength}} {{#maximum}} - if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}} > {{{maximum}}} - invalid_properties.push("invalid value for '{{{name}}}', must be smaller than or equal to {{{maximum}}}.") + if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{{maximum}}} + invalid_properties.push("invalid value for '{{{name}}}', must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{{maximum}}}.") end {{/maximum}} {{#minimum}} - if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}} < {{{minimum}}} - invalid_properties.push("invalid value for '{{{name}}}', must be greater than or equal to {{{minimum}}}.") + if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{{minimum}}} + invalid_properties.push("invalid value for '{{{name}}}', must be greater than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{{minimum}}}.") end {{/minimum}} @@ -141,10 +141,10 @@ return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.to_s.length < {{{minLength}}} {{/minLength}} {{#maximum}} - return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}} > {{{maximum}}} + return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{{maximum}}} {{/maximum}} {{#minimum}} - return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}} < {{{minimum}}} + return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{{minimum}}} {{/minimum}} {{#pattern}} return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}} !~ Regexp.new({{{pattern}}}) @@ -193,14 +193,14 @@ {{/minLength}} {{#maximum}} - if {{^required}}!{{{name}}}.nil? && {{/required}}{{{name}}} > {{{maximum}}} - fail ArgumentError, "invalid value for '{{{name}}}', must be smaller than or equal to {{{maximum}}}." + if {{^required}}!{{{name}}}.nil? && {{/required}}{{{name}}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{{maximum}}} + fail ArgumentError, "invalid value for '{{{name}}}', must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{{maximum}}}." end {{/maximum}} {{#minimum}} - if {{^required}}!{{{name}}}.nil? && {{/required}}{{{name}}} < {{{minimum}}} - fail ArgumentError, "invalid value for '{{{name}}}', must be greater than or equal to {{{minimum}}}." + if {{^required}}!{{{name}}}.nil? && {{/required}}{{{name}}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{{minimum}}} + fail ArgumentError, "invalid value for '{{{name}}}', must be greater than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{{minimum}}}." end {{/minimum}} diff --git a/samples/client/petstore/python/petstore_api/apis/fake_api.py b/samples/client/petstore/python/petstore_api/apis/fake_api.py index 5ed13ee9c2a..dd8873cc0f9 100644 --- a/samples/client/petstore/python/petstore_api/apis/fake_api.py +++ b/samples/client/petstore/python/petstore_api/apis/fake_api.py @@ -258,25 +258,25 @@ def test_endpoint_parameters_with_http_info(self, number, double, pattern_withou raise ValueError("Missing the required parameter `byte` when calling `test_endpoint_parameters`") if 'number' in params and params['number'] > 543.2: - raise ValueError("Invalid value for parameter `number` when calling `test_endpoint_parameters`, must be a value less than or equal to `543.2`") + raise ValueError("Invalid value for parameter `number` when calling `test_endpoint_parameters`, must be a value less than or equal to `543.2`") if 'number' in params and params['number'] < 32.1: raise ValueError("Invalid value for parameter `number` when calling `test_endpoint_parameters`, must be a value greater than or equal to `32.1`") if 'double' in params and params['double'] > 123.4: - raise ValueError("Invalid value for parameter `double` when calling `test_endpoint_parameters`, must be a value less than or equal to `123.4`") + raise ValueError("Invalid value for parameter `double` when calling `test_endpoint_parameters`, must be a value less than or equal to `123.4`") if 'double' in params and params['double'] < 67.8: raise ValueError("Invalid value for parameter `double` when calling `test_endpoint_parameters`, must be a value greater than or equal to `67.8`") if 'pattern_without_delimiter' in params and not re.search('^[A-Z].*', params['pattern_without_delimiter']): raise ValueError("Invalid value for parameter `pattern_without_delimiter` when calling `test_endpoint_parameters`, must conform to the pattern `/^[A-Z].*/`") if 'integer' in params and params['integer'] > 100.0: - raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value less than or equal to `100.0`") + raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value less than or equal to `100.0`") if 'integer' in params and params['integer'] < 10.0: raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value greater than or equal to `10.0`") if 'int32' in params and params['int32'] > 200.0: - raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value less than or equal to `200.0`") + raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value less than or equal to `200.0`") if 'int32' in params and params['int32'] < 20.0: raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value greater than or equal to `20.0`") if 'float' in params and params['float'] > 987.6: - raise ValueError("Invalid value for parameter `float` when calling `test_endpoint_parameters`, must be a value less than or equal to `987.6`") + raise ValueError("Invalid value for parameter `float` when calling `test_endpoint_parameters`, must be a value less than or equal to `987.6`") if 'string' in params and not re.search('[a-z]', params['string'], flags=re.IGNORECASE): raise ValueError("Invalid value for parameter `string` when calling `test_endpoint_parameters`, must conform to the pattern `/[a-z]/i`") if 'password' in params and len(params['password']) > 64: diff --git a/samples/client/petstore/python/petstore_api/apis/store_api.py b/samples/client/petstore/python/petstore_api/apis/store_api.py index d9c505055e3..c7f37de09e8 100644 --- a/samples/client/petstore/python/petstore_api/apis/store_api.py +++ b/samples/client/petstore/python/petstore_api/apis/store_api.py @@ -328,7 +328,7 @@ def get_order_by_id_with_http_info(self, order_id, **kwargs): raise ValueError("Missing the required parameter `order_id` when calling `get_order_by_id`") if 'order_id' in params and params['order_id'] > 5.0: - raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value less than or equal to `5.0`") + raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value less than or equal to `5.0`") if 'order_id' in params and params['order_id'] < 1.0: raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value greater than or equal to `1.0`") From fb3b91550cfe37abdc24d7322c3bbca1d3959382 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 6 Sep 2016 18:51:28 +0800 Subject: [PATCH 330/470] add back test cases for java jersey1 client --- .gitignore | 1 + .../java/io/swagger/PetstoreProfiling.java | 106 +++++ .../src/test/java/io/swagger/TestUtils.java | 17 + .../java/io/swagger/client/ApiClientTest.java | 239 ++++++++++ .../io/swagger/client/ConfigurationTest.java | 15 + .../io/swagger/client/StringUtilTest.java | 33 ++ .../io/swagger/client/api/FakeApiTest.java | 50 +- .../io/swagger/client/api/PetApiTest.java | 444 +++++++++++------- .../io/swagger/client/api/StoreApiTest.java | 171 ++++--- .../io/swagger/client/api/UserApiTest.java | 210 +++------ .../swagger/client/auth/ApiKeyAuthTest.java | 47 ++ .../client/auth/HttpBasicAuthTest.java | 52 ++ 12 files changed, 943 insertions(+), 442 deletions(-) create mode 100644 samples/client/petstore/java/jersey1/src/test/java/io/swagger/PetstoreProfiling.java create mode 100644 samples/client/petstore/java/jersey1/src/test/java/io/swagger/TestUtils.java create mode 100644 samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/ApiClientTest.java create mode 100644 samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/ConfigurationTest.java create mode 100644 samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/StringUtilTest.java create mode 100644 samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java create mode 100644 samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java diff --git a/.gitignore b/.gitignore index adea0e97125..ddef98a2b72 100644 --- a/.gitignore +++ b/.gitignore @@ -57,6 +57,7 @@ samples/client/petstore/qt5cpp/PetStore/Makefile **/.gradle samples/client/petstore/java/hello.txt samples/client/petstore/java/okhttp-gson/hello.txt +samples/client/petstore/java/jersey1/hello.txt samples/client/petstore/java/jersey2-java8/hello.txt samples/client/petstore/android/default/hello.txt samples/client/petstore/android/volley/.gradle/ diff --git a/samples/client/petstore/java/jersey1/src/test/java/io/swagger/PetstoreProfiling.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/PetstoreProfiling.java new file mode 100644 index 00000000000..d0be1523e45 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/PetstoreProfiling.java @@ -0,0 +1,106 @@ +package io.swagger; + +import java.io.*; +import java.util.*; + +import io.swagger.client.*; +import io.swagger.client.api.*; +import io.swagger.client.model.*; + +public class PetstoreProfiling { + public int total = 5; + public Long newPetId = 50003L; + public String outputFile = "./petstore_profiling.output"; + + public void callApis(int index, List> results) { + long start; + + try { + PetApi petApi = new PetApi(); + + /* ADD PET */ + Pet pet = new Pet(); + pet.setId(newPetId); + pet.setName("profiler"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + pet.setPhotoUrls(Arrays.asList("http://profiler.com")); + // new tag + Tag tag = new Tag(); + tag.setId(newPetId); // use the same id as pet + tag.setName("profile tag 1"); + // new category + Category category = new Category(); + category.setId(newPetId); // use the same id as pet + category.setName("profile category 1"); + + pet.setTags(Arrays.asList(tag)); + pet.setCategory(category); + + /* ADD PET */ + start = System.nanoTime(); + petApi.addPet(pet); + results.add(buildResult(index, "ADD PET", System.nanoTime() - start)); + + /* GET PET */ + start = System.nanoTime(); + pet = petApi.getPetById(newPetId); + results.add(buildResult(index, "GET PET", System.nanoTime() - start)); + + /* UPDATE PET WITH FORM */ + start = System.nanoTime(); + petApi.updatePetWithForm(newPetId, "new profiler", "sold"); + results.add(buildResult(index, "UPDATE PET", System.nanoTime() - start)); + + /* DELETE PET */ + start = System.nanoTime(); + petApi.deletePet(newPetId, "special-key"); + results.add(buildResult(index, "DELETE PET", System.nanoTime() - start)); + } catch (ApiException e) { + System.out.println("Caught error: " + e.getMessage()); + System.out.println("HTTP response headers: " + e.getResponseHeaders()); + System.out.println("HTTP response body: " + e.getResponseBody()); + System.out.println("HTTP status code: " + e.getCode()); + } + } + + public void run() { + System.out.printf("Running profiling... (total: %s)\n", total); + + List> results = new ArrayList>(); + for (int i = 0; i < total; i++) { + callApis(i, results); + } + writeResultsToFile(results); + + System.out.printf("Profiling results written to %s\n", outputFile); + } + + private Map buildResult(int index, String name, long time) { + Map result = new HashMap(); + result.put("index", String.valueOf(index)); + result.put("name", name); + result.put("time", String.valueOf(time / 1000000000.0)); + return result; + } + + private void writeResultsToFile(List> results) { + try { + java.io.File file = new java.io.File(outputFile); + PrintWriter writer = new PrintWriter(file); + String command = "mvn compile test-compile exec:java -Dexec.classpathScope=test -Dexec.mainClass=\"io.swagger.PetstoreProfiling\""; + writer.println("# To run the profiling:"); + writer.printf("# %s\n\n", command); + for (Map result : results) { + writer.printf("%s: %s => %s\n", result.get("index"), result.get("name"), result.get("time")); + } + writer.close(); + } catch (FileNotFoundException e) { + throw new RuntimeException(e); + } + } + + public static void main(String[] args) { + final PetstoreProfiling profiling = new PetstoreProfiling(); + profiling.run(); + } +} diff --git a/samples/client/petstore/java/jersey1/src/test/java/io/swagger/TestUtils.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/TestUtils.java new file mode 100644 index 00000000000..7ddf142426e --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/TestUtils.java @@ -0,0 +1,17 @@ +package io.swagger; + +import java.util.Random; +import java.util.concurrent.atomic.AtomicLong; + +public class TestUtils { + private static final AtomicLong atomicId = createAtomicId(); + + public static long nextId() { + return atomicId.getAndIncrement(); + } + + private static AtomicLong createAtomicId() { + int baseId = new Random(System.currentTimeMillis()).nextInt(1000000) + 20000; + return new AtomicLong((long) baseId); + } +} diff --git a/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/ApiClientTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/ApiClientTest.java new file mode 100644 index 00000000000..19b55257d0c --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/ApiClientTest.java @@ -0,0 +1,239 @@ +package io.swagger.client; + +import io.swagger.client.auth.*; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.*; + +import org.junit.*; +import static org.junit.Assert.*; + + +public class ApiClientTest { + ApiClient apiClient = null; + + @Before + public void setup() { + apiClient = new ApiClient(); + } + + @Test + public void testParseAndFormatDate() { + // default date format + String dateStr = "2015-11-07T03:49:09.356Z"; + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356+00:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356Z"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T05:49:09.356+02:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T02:49:09.356-01:00"))); + + // custom date format: without milli-seconds, custom time zone + DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); + format.setTimeZone(TimeZone.getTimeZone("GMT+10")); + apiClient.setDateFormat(format); + dateStr = "2015-11-07T13:49:09+10:00"; + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09+00:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09Z"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T00:49:09-03:00"))); + 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"}; + 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)); + + accepts = new String[]{}; + assertNull(apiClient.selectHeaderAccept(accepts)); + } + + @Test + public void testSelectHeaderContentType() { + 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/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)); + + contentTypes = new String[]{}; + assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + } + + @Test + public void testGetAuthentications() { + Map auths = apiClient.getAuthentications(); + + Authentication auth = auths.get("api_key"); + assertNotNull(auth); + assertTrue(auth instanceof ApiKeyAuth); + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) auth; + assertEquals("header", apiKeyAuth.getLocation()); + assertEquals("api_key", apiKeyAuth.getParamName()); + + auth = auths.get("petstore_auth"); + assertTrue(auth instanceof OAuth); + assertSame(auth, apiClient.getAuthentication("petstore_auth")); + + assertNull(auths.get("unknown")); + + try { + auths.put("my_auth", new HttpBasicAuth()); + fail("the authentications returned should not be modifiable"); + } catch (UnsupportedOperationException e) { + } + } + + @Ignore("There is no more basic auth in petstore security definitions") + @Test + public void testSetUsernameAndPassword() { + HttpBasicAuth auth = null; + for (Authentication _auth : apiClient.getAuthentications().values()) { + if (_auth instanceof HttpBasicAuth) { + auth = (HttpBasicAuth) _auth; + break; + } + } + auth.setUsername(null); + auth.setPassword(null); + + apiClient.setUsername("my-username"); + apiClient.setPassword("my-password"); + assertEquals("my-username", auth.getUsername()); + assertEquals("my-password", auth.getPassword()); + + // reset values + auth.setUsername(null); + auth.setPassword(null); + } + + @Test + public void testSetApiKeyAndPrefix() { + ApiKeyAuth auth = null; + for (Authentication _auth : apiClient.getAuthentications().values()) { + if (_auth instanceof ApiKeyAuth) { + auth = (ApiKeyAuth) _auth; + break; + } + } + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + + apiClient.setApiKey("my-api-key"); + apiClient.setApiKeyPrefix("Token"); + assertEquals("my-api-key", auth.getApiKey()); + assertEquals("Token", auth.getApiKeyPrefix()); + + // reset values + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + } + + @Test + public void testParameterToPairsWhenNameIsInvalid() throws Exception { + List pairs_a = apiClient.parameterToPairs("csv", null, new Integer(1)); + List pairs_b = apiClient.parameterToPairs("csv", "", new Integer(1)); + + assertTrue(pairs_a.isEmpty()); + assertTrue(pairs_b.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsNull() throws Exception { + List pairs = apiClient.parameterToPairs("csv", "param-a", null); + + assertTrue(pairs.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsEmptyStrings() throws Exception { + + // single empty string + List pairs = apiClient.parameterToPairs("csv", "param-a", " "); + assertEquals(1, pairs.size()); + + // list of empty strings + List strs = new ArrayList(); + strs.add(" "); + strs.add(" "); + strs.add(" "); + + List concatStrings = apiClient.parameterToPairs("csv", "param-a", strs); + + assertEquals(1, concatStrings.size()); + assertFalse(concatStrings.get(0).getValue().isEmpty()); // should contain some delimiters + } + + @Test + public void testParameterToPairsWhenValueIsNotCollection() throws Exception { + String name = "param-a"; + Integer value = 1; + + List pairs = apiClient.parameterToPairs("csv", name, value); + + assertEquals(1, pairs.size()); + assertEquals(value, Integer.valueOf(pairs.get(0).getValue())); + } + + @Test + public void testParameterToPairsWhenValueIsCollection() throws Exception { + Map collectionFormatMap = new HashMap(); + collectionFormatMap.put("csv", ","); + collectionFormatMap.put("tsv", "\t"); + collectionFormatMap.put("ssv", " "); + collectionFormatMap.put("pipes", "\\|"); + collectionFormatMap.put("", ","); // no format, must default to csv + collectionFormatMap.put("unknown", ","); // all other formats, must default to csv + + String name = "param-a"; + + List values = new ArrayList(); + values.add("value-a"); + values.add(123); + values.add(new Date()); + + // check for multi separately + List multiPairs = apiClient.parameterToPairs("multi", name, values); + assertEquals(values.size(), multiPairs.size()); + + // all other formats + for (String collectionFormat : collectionFormatMap.keySet()) { + List pairs = apiClient.parameterToPairs(collectionFormat, name, values); + + assertEquals(1, pairs.size()); + + String delimiter = collectionFormatMap.get(collectionFormat); + String[] pairValueSplit = pairs.get(0).getValue().split(delimiter); + + // must equal input values + assertEquals(values.size(), pairValueSplit.length); + } + } +} diff --git a/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/ConfigurationTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/ConfigurationTest.java new file mode 100644 index 00000000000..b95eb74605e --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/ConfigurationTest.java @@ -0,0 +1,15 @@ +package io.swagger.client; + +import org.junit.*; +import static org.junit.Assert.*; + + +public class ConfigurationTest { + @Test + public void testDefaultApiClient() { + ApiClient apiClient = Configuration.getDefaultApiClient(); + assertNotNull(apiClient); + assertEquals("http://petstore.swagger.io/v2", apiClient.getBasePath()); + assertFalse(apiClient.isDebugging()); + } +} diff --git a/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/StringUtilTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/StringUtilTest.java new file mode 100644 index 00000000000..4b03c7a9812 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/StringUtilTest.java @@ -0,0 +1,33 @@ +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"}, ",")); + } +} diff --git a/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/FakeApiTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/FakeApiTest.java index 5a7d2e5aa80..c564001ad70 100644 --- a/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/FakeApiTest.java +++ b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/FakeApiTest.java @@ -1,34 +1,8 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - package io.swagger.client.api; import io.swagger.client.ApiException; -import org.joda.time.LocalDate; -import org.joda.time.DateTime; import java.math.BigDecimal; +import java.util.Date; import org.junit.Test; import java.util.ArrayList; @@ -63,30 +37,12 @@ public void testEndpointParametersTest() throws ApiException { Long int64 = null; Float _float = null; byte[] binary = null; - LocalDate date = null; - DateTime dateTime = null; + Date date = null; + Date dateTime = null; String password = null; // api.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); // TODO: test validations } - /** - * To test enum query parameters - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void testEnumQueryParametersTest() throws ApiException { - String enumQueryString = null; - BigDecimal enumQueryInteger = null; - Double enumQueryDouble = null; - // api.testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); - - // TODO: test validations - } - } diff --git a/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/PetApiTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/PetApiTest.java index 373f7d287ad..e75a9c7e7da 100644 --- a/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/PetApiTest.java +++ b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/PetApiTest.java @@ -1,180 +1,306 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +package io.swagger.client.api; +import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.datatype.joda.*; -package io.swagger.client.api; +import io.swagger.TestUtils; -import io.swagger.client.ApiException; -import io.swagger.client.model.Pet; -import java.io.File; -import io.swagger.client.model.ModelApiResponse; -import org.junit.Test; +import io.swagger.client.*; +import io.swagger.client.api.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; import java.util.ArrayList; -import java.util.HashMap; +import java.util.Arrays; import java.util.List; import java.util.Map; -/** - * API tests for PetApi - */ +import org.junit.*; +import static org.junit.Assert.*; + public class PetApiTest { + private PetApi api; + private ObjectMapper mapper; + + @Before + public void setup() { + api = new PetApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); + } - private final PetApi api = new PetApi(); - - - /** - * Add a new pet to the store - * - * - * - * @throws ApiException - * if the Api call fails - */ @Test - public void addPetTest() throws ApiException { - Pet body = null; - // api.addPet(body); - - // TODO: test validations - } - - /** - * Deletes a pet - * - * - * - * @throws ApiException - * if the Api call fails - */ + public void testApiClient() { + // the default api client is used + assertEquals(Configuration.getDefaultApiClient(), api.getApiClient()); + assertNotNull(api.getApiClient()); + assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath()); + assertFalse(api.getApiClient().isDebugging()); + + ApiClient oldClient = api.getApiClient(); + + ApiClient newClient = new ApiClient(); + newClient.setBasePath("http://example.com"); + newClient.setDebugging(true); + + // set api client via constructor + api = new PetApi(newClient); + assertNotNull(api.getApiClient()); + assertEquals("http://example.com", api.getApiClient().getBasePath()); + assertTrue(api.getApiClient().isDebugging()); + + // set api client via setter method + api.setApiClient(oldClient); + assertNotNull(api.getApiClient()); + assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath()); + assertFalse(api.getApiClient().isDebugging()); + } + @Test - public void deletePetTest() throws ApiException { - Long petId = null; - String apiKey = null; - // api.deletePet(petId, apiKey); - - // TODO: test validations - } - - /** - * Finds Pets by status - * - * Multiple status values can be provided with comma separated strings - * - * @throws ApiException - * if the Api call fails - */ + 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 findPetsByStatusTest() throws ApiException { - List status = null; - // List response = api.findPetsByStatus(status); - - // TODO: test validations - } - - /** - * Finds Pets by tags - * - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * - * @throws ApiException - * if the Api call fails - */ + public void testCreateAndGetPetWithByteArray() throws Exception { + Pet pet = createRandomPet(); + byte[] bytes = serializeJson(pet).getBytes(); + api.addPetUsingByteArray(bytes); + + byte[] fetchedBytes = api.petPetIdtestingByteArraytrueGet(pet.getId()); + Pet fetched = deserializeJson(new String(fetchedBytes), Pet.class); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + @Test - public void findPetsByTagsTest() throws ApiException { - List tags = null; - // List response = api.findPetsByTags(tags); - - // TODO: test validations - } - - /** - * Find pet by ID - * - * Returns a single pet - * - * @throws ApiException - * if the Api call fails - */ + public void testGetPetByIdInObject() throws Exception { + Pet pet = new Pet(); + pet.setId(TestUtils.nextId()); + pet.setName("pet " + pet.getId()); + + Category category = new Category(); + category.setId(TestUtils.nextId()); + category.setName("category " + category.getId()); + pet.setCategory(category); + + pet.setStatus(Pet.StatusEnum.PENDING); + List photos = Arrays.asList(new String[]{"http://foo.bar.com/1"}); + pet.setPhotoUrls(photos); + + api.addPet(pet); + + InlineResponse200 fetched = api.getPetByIdInObject(pet.getId()); + assertEquals(pet.getId(), fetched.getId()); + assertEquals(pet.getName(), fetched.getName()); + + Object categoryObj = fetched.getCategory(); + assertNotNull(categoryObj); + assertTrue(categoryObj instanceof Map); + + Map categoryMap = (Map) categoryObj; + Object categoryIdObj = categoryMap.get("id"); + assertTrue(categoryIdObj instanceof Integer); + Integer categoryIdInt = (Integer) categoryIdObj; + assertEquals(category.getId(), Long.valueOf(categoryIdInt)); + assertEquals(category.getName(), categoryMap.get("name")); + } + */ + @Test - public void getPetByIdTest() throws ApiException { - Long petId = null; - // Pet response = api.getPetById(petId); - - // TODO: test validations - } - - /** - * Update an existing pet - * - * - * - * @throws ApiException - * if the Api call fails - */ + 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 updatePetTest() throws ApiException { - Pet body = null; - // api.updatePet(body); - - // TODO: test validations - } - - /** - * Updates a pet in the store with form data - * - * - * - * @throws ApiException - * if the Api call fails - */ + public void testFindPetsByStatus() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + api.updatePet(pet); + + List pets = api.findPetsByStatus(Arrays.asList(new String[]{"available"})); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + + assertTrue(found); + } + + @Test + public void testFindPetsByTags() throws Exception { + Pet pet = createRandomPet(); + pet.setName("monster"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + List tags = new ArrayList(); + Tag tag1 = new Tag(); + tag1.setName("friendly"); + tags.add(tag1); + pet.setTags(tags); + + api.updatePet(pet); + + List pets = api.findPetsByTags(Arrays.asList(new String[]{"friendly"})); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + assertTrue(found); + } + + @Test + public void testUpdatePetWithForm() throws Exception { + Pet pet = createRandomPet(); + pet.setName("frank"); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + + api.updatePetWithForm(fetched.getId(), "furt", null); + Pet updated = api.getPetById(fetched.getId()); + + assertEquals(updated.getName(), "furt"); + } + @Test - public void updatePetWithFormTest() throws ApiException { - Long petId = null; - String name = null; - String status = null; - // api.updatePetWithForm(petId, name, status); - - // TODO: test validations - } - - /** - * uploads an image - * - * - * - * @throws ApiException - * if the Api call fails - */ + 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 uploadFileTest() throws ApiException { - Long petId = null; - String additionalMetadata = null; - File file = null; - // ModelApiResponse response = api.uploadFile(petId, additionalMetadata, file); + public void testUploadFile() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + File file = new File("hello.txt"); + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + writer.write("Hello world!"); + writer.close(); + + api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath())); + } + + @Test + public void testEqualsAndHashCode() { + Pet pet1 = new Pet(); + Pet pet2 = new Pet(); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + + pet2.setName("really-happy"); + pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertFalse(pet1.equals(pet2)); + assertFalse(pet2.equals(pet1)); + assertFalse(pet1.hashCode() == (pet2.hashCode())); + assertTrue(pet2.equals(pet2)); + assertTrue(pet2.hashCode() == pet2.hashCode()); + + pet1.setName("really-happy"); + pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + } + + private Pet createRandomPet() { + Pet pet = new Pet(); + pet.setId(TestUtils.nextId()); + pet.setName("gorilla"); + + Category category = new Category(); + category.setName("really-happy"); + + pet.setCategory(category); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); + pet.setPhotoUrls(photos); + + return pet; + } + + private String serializeJson(Object o) { + if (mapper == null) { + mapper = createObjectMapper(); + } + try { + return mapper.writeValueAsString(o); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private T deserializeJson(String json, Class klass) { + if (mapper == null) { + mapper = createObjectMapper(); + } + try { + return mapper.readValue(json, klass); + } catch (Exception e) { + throw new RuntimeException(e); + } + } - // TODO: test validations + private ObjectMapper createObjectMapper() { + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + mapper.registerModule(new JodaModule()); + return mapper; } - } diff --git a/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/StoreApiTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/StoreApiTest.java index 4bcdcbf8338..51779f265f0 100644 --- a/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/StoreApiTest.java +++ b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/StoreApiTest.java @@ -1,108 +1,103 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - package io.swagger.client.api; +import io.swagger.TestUtils; + import io.swagger.client.ApiException; -import io.swagger.client.model.Order; -import org.junit.Test; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; +import io.swagger.client.*; +import io.swagger.client.api.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; + +import java.lang.reflect.Field; import java.util.Map; +import java.text.SimpleDateFormat; + +import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; +import org.junit.*; +import static org.junit.Assert.*; -/** - * API tests for StoreApi - */ public class StoreApiTest { + StoreApi api = null; - private final StoreApi api = new StoreApi(); - - - /** - * Delete purchase order by ID - * - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void deleteOrderTest() throws ApiException { - String orderId = null; - // api.deleteOrder(orderId); + @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")); + } - // TODO: test validations + @Test + public void testGetInventory() throws Exception { + Map inventory = api.getInventory(); + assertTrue(inventory.keySet().size() > 0); } - - /** - * Returns pet inventories by status - * - * Returns a map of status codes to quantities - * - * @throws ApiException - * if the Api call fails - */ + + /* @Test - public void getInventoryTest() throws ApiException { - // Map response = api.getInventory(); + public void testGetInventoryInObject() throws Exception { + Object inventoryObj = api.getInventoryInObject(); + assertTrue(inventoryObj instanceof Map); - // TODO: test validations + Map inventoryMap = (Map) inventoryObj; + assertTrue(inventoryMap.keySet().size() > 0); + + Map.Entry firstEntry = (Map.Entry) inventoryMap.entrySet().iterator().next(); + assertTrue(firstEntry.getKey() instanceof String); + assertTrue(firstEntry.getValue() instanceof Integer); } - - /** - * Find purchase order by ID - * - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * - * @throws ApiException - * if the Api call fails - */ + */ + @Test - public void getOrderByIdTest() throws ApiException { - Long orderId = null; - // Order response = api.getOrderById(orderId); + public void testPlaceOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); - // TODO: test validations + Order fetched = api.getOrderById(order.getId()); + assertEquals(order.getId(), fetched.getId()); + assertEquals(order.getPetId(), fetched.getPetId()); + assertEquals(order.getQuantity(), fetched.getQuantity()); + assertEquals(order.getShipDate().withZone(DateTimeZone.UTC), fetched.getShipDate().withZone(DateTimeZone.UTC)); } - - /** - * Place an order for a pet - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void placeOrderTest() throws ApiException { - Order body = null; - // Order response = api.placeOrder(body); + public void testDeleteOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); + + Order fetched = api.getOrderById(order.getId()); + assertEquals(fetched.getId(), order.getId()); + + api.deleteOrder(String.valueOf(order.getId())); + + try { + api.getOrderById(order.getId()); + // fail("expected an error"); + } catch (ApiException e) { + // ok + } + } + + private Order createOrder() { + Order order = new Order(); + order.setPetId(new Long(200)); + order.setQuantity(new Integer(13)); + order.setShipDate(DateTime.now()); + order.setStatus(Order.StatusEnum.PLACED); + order.setComplete(true); + + try { + Field idField = Order.class.getDeclaredField("id"); + idField.setAccessible(true); + idField.set(order, TestUtils.nextId()); + } catch (Exception e) { + throw new RuntimeException(e); + } - // TODO: test validations + return order; } - } diff --git a/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/UserApiTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/UserApiTest.java index 832748dbb45..c7fb92d2552 100644 --- a/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/UserApiTest.java +++ b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/UserApiTest.java @@ -1,174 +1,88 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +package io.swagger.client.api; +import io.swagger.TestUtils; -package io.swagger.client.api; +import io.swagger.client.api.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; -import io.swagger.client.ApiException; -import io.swagger.client.model.User; -import org.junit.Test; +import java.util.Arrays; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import org.junit.*; +import static org.junit.Assert.*; -/** - * API tests for UserApi - */ public class UserApiTest { + UserApi api = null; - private final UserApi api = new UserApi(); - - - /** - * Create user - * - * This can only be done by the logged in user. - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void createUserTest() throws ApiException { - User body = null; - // api.createUser(body); - - // TODO: test validations + @Before + public void setup() { + api = new UserApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); } - - /** - * Creates list of users with given input array - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void createUsersWithArrayInputTest() throws ApiException { - List body = null; - // api.createUsersWithArrayInput(body); - // TODO: test validations - } - - /** - * Creates list of users with given input array - * - * - * - * @throws ApiException - * if the Api call fails - */ @Test - public void createUsersWithListInputTest() throws ApiException { - List body = null; - // api.createUsersWithListInput(body); + public void testCreateUser() throws Exception { + User user = createUser(); - // TODO: test validations - } - - /** - * Delete user - * - * This can only be done by the logged in user. - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void deleteUserTest() throws ApiException { - String username = null; - // api.deleteUser(username); + api.createUser(user); - // TODO: test validations + User fetched = api.getUserByName(user.getUsername()); + assertEquals(user.getId(), fetched.getId()); } - - /** - * Get user by user name - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void getUserByNameTest() throws ApiException { - String username = null; - // User response = api.getUserByName(username); + public void testCreateUsersWithArray() throws Exception { + User user1 = createUser(); + user1.setUsername("user" + user1.getId()); + User user2 = createUser(); + user2.setUsername("user" + user2.getId()); + + api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); - // TODO: test validations + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); } - - /** - * Logs user into the system - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void loginUserTest() throws ApiException { - String username = null; - String password = null; - // String response = api.loginUser(username, password); + public void testCreateUsersWithList() throws Exception { + User user1 = createUser(); + user1.setUsername("user" + user1.getId()); + User user2 = createUser(); + user2.setUsername("user" + user2.getId()); + + api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); - // TODO: test validations + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); } - - /** - * Logs out current logged in user session - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void logoutUserTest() throws ApiException { - // api.logoutUser(); + public void testLoginUser() throws Exception { + User user = createUser(); + api.createUser(user); - // TODO: test validations + String token = api.loginUser(user.getUsername(), user.getPassword()); + assertTrue(token.startsWith("logged in user session:")); } - - /** - * Updated user - * - * This can only be done by the logged in user. - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void updateUserTest() throws ApiException { - String username = null; - User body = null; - // api.updateUser(username, body); + public void logoutUser() throws Exception { + api.logoutUser(); + } + + private User createUser() { + User user = new User(); + user.setId(TestUtils.nextId()); + user.setUsername("fred" + user.getId()); + user.setFirstName("Fred"); + user.setLastName("Meyer"); + user.setEmail("fred@fredmeyer.com"); + user.setPassword("xxXXxx"); + user.setPhone("408-867-5309"); + user.setUserStatus(123); - // TODO: test validations + return user; } - } diff --git a/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java new file mode 100644 index 00000000000..5bdb4fb78fb --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java @@ -0,0 +1,47 @@ +package io.swagger.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import io.swagger.client.Pair; +import org.junit.*; +import static org.junit.Assert.*; + + +public class ApiKeyAuthTest { + @Test + public void testApplyToParamsInQuery() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("query", "api_key"); + auth.setApiKey("my-api-key"); + auth.applyToParams(queryParams, headerParams); + + assertEquals(1, queryParams.size()); + for (Pair queryParam : queryParams) { + assertEquals("my-api-key", queryParam.getValue()); + } + + // no changes to header parameters + assertEquals(0, headerParams.size()); + } + + @Test + public void testApplyToParamsInHeaderWithPrefix() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN"); + auth.setApiKey("my-api-token"); + auth.setApiKeyPrefix("Token"); + auth.applyToParams(queryParams, headerParams); + + // no changes to query parameters + assertEquals(0, queryParams.size()); + assertEquals(1, headerParams.size()); + assertEquals("Token my-api-token", headerParams.get("X-API-TOKEN")); + } +} diff --git a/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java new file mode 100644 index 00000000000..52c5497ba83 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java @@ -0,0 +1,52 @@ +package io.swagger.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import io.swagger.client.Pair; +import org.junit.*; +import static org.junit.Assert.*; + + +public class HttpBasicAuthTest { + HttpBasicAuth auth = null; + + @Before + public void setup() { + auth = new HttpBasicAuth(); + } + + @Test + public void testApplyToParams() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + auth.setUsername("my-username"); + auth.setPassword("my-password"); + auth.applyToParams(queryParams, headerParams); + + // no changes to query parameters + assertEquals(0, queryParams.size()); + assertEquals(1, headerParams.size()); + // the string below is base64-encoded result of "my-username:my-password" with the "Basic " prefix + String expected = "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ="; + assertEquals(expected, headerParams.get("Authorization")); + + // null username should be treated as empty string + auth.setUsername(null); + auth.applyToParams(queryParams, headerParams); + // the string below is base64-encoded result of ":my-password" with the "Basic " prefix + expected = "Basic Om15LXBhc3N3b3Jk"; + assertEquals(expected, headerParams.get("Authorization")); + + // null password should be treated as empty string + auth.setUsername("my-username"); + auth.setPassword(null); + auth.applyToParams(queryParams, headerParams); + // the string below is base64-encoded result of "my-username:" with the "Basic " prefix + expected = "Basic bXktdXNlcm5hbWU6"; + assertEquals(expected, headerParams.get("Authorization")); + } +} From 91b7494e3e7d8b7f2e448d32410c2c85caf00880 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Tue, 6 Sep 2016 14:45:04 +0300 Subject: [PATCH 331/470] Spelling fixes --- .../swagger-codegen/src/main/resources/php/ApiClient.mustache | 4 ++-- .../src/main/resources/php/ApiException.mustache | 4 ++-- .../src/main/resources/php/ObjectSerializer.mustache | 4 ++-- modules/swagger-codegen/src/main/resources/php/api.mustache | 4 ++-- .../swagger-codegen/src/main/resources/php/api_test.mustache | 4 ++-- .../src/main/resources/php/configuration.mustache | 4 ++-- modules/swagger-codegen/src/main/resources/php/model.mustache | 4 ++-- .../src/main/resources/php/model_test.mustache | 4 ++-- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 4 ++-- .../php/SwaggerClient-php/lib/ApiClient.php | 4 ++-- .../php/SwaggerClient-php/lib/ApiException.php | 4 ++-- .../php/SwaggerClient-php/lib/Configuration.php | 4 ++-- .../php/SwaggerClient-php/lib/Model/ModelReturn.php | 4 ++-- .../php/SwaggerClient-php/lib/ObjectSerializer.php | 4 ++-- .../php/SwaggerClient-php/test/Api/FakeApiTest.php | 4 ++-- .../php/SwaggerClient-php/test/Model/ModelReturnTest.php | 4 ++-- .../client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php | 4 ++-- .../client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php | 4 ++-- .../petstore/php/SwaggerClient-php/lib/Api/StoreApi.php | 4 ++-- .../client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php | 4 ++-- .../client/petstore/php/SwaggerClient-php/lib/ApiClient.php | 4 ++-- .../petstore/php/SwaggerClient-php/lib/ApiException.php | 4 ++-- .../petstore/php/SwaggerClient-php/lib/Configuration.php | 4 ++-- .../SwaggerClient-php/lib/Model/AdditionalPropertiesClass.php | 4 ++-- .../petstore/php/SwaggerClient-php/lib/Model/Animal.php | 4 ++-- .../petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php | 4 ++-- .../petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php | 4 ++-- .../SwaggerClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php | 4 ++-- .../php/SwaggerClient-php/lib/Model/ArrayOfNumberOnly.php | 4 ++-- .../petstore/php/SwaggerClient-php/lib/Model/ArrayTest.php | 4 ++-- .../client/petstore/php/SwaggerClient-php/lib/Model/Cat.php | 4 ++-- .../petstore/php/SwaggerClient-php/lib/Model/Category.php | 4 ++-- .../petstore/php/SwaggerClient-php/lib/Model/Client.php | 4 ++-- .../client/petstore/php/SwaggerClient-php/lib/Model/Dog.php | 4 ++-- .../petstore/php/SwaggerClient-php/lib/Model/EnumArrays.php | 4 ++-- .../petstore/php/SwaggerClient-php/lib/Model/EnumClass.php | 4 ++-- .../petstore/php/SwaggerClient-php/lib/Model/EnumTest.php | 4 ++-- .../petstore/php/SwaggerClient-php/lib/Model/FormatTest.php | 4 ++-- .../php/SwaggerClient-php/lib/Model/HasOnlyReadOnly.php | 4 ++-- .../petstore/php/SwaggerClient-php/lib/Model/MapTest.php | 4 ++-- .../lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php | 4 ++-- .../php/SwaggerClient-php/lib/Model/Model200Response.php | 4 ++-- .../petstore/php/SwaggerClient-php/lib/Model/ModelList.php | 4 ++-- .../petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php | 4 ++-- .../client/petstore/php/SwaggerClient-php/lib/Model/Name.php | 4 ++-- .../petstore/php/SwaggerClient-php/lib/Model/NumberOnly.php | 4 ++-- .../client/petstore/php/SwaggerClient-php/lib/Model/Order.php | 4 ++-- .../client/petstore/php/SwaggerClient-php/lib/Model/Pet.php | 4 ++-- .../php/SwaggerClient-php/lib/Model/ReadOnlyFirst.php | 4 ++-- .../php/SwaggerClient-php/lib/Model/SpecialModelName.php | 4 ++-- .../client/petstore/php/SwaggerClient-php/lib/Model/Tag.php | 4 ++-- .../client/petstore/php/SwaggerClient-php/lib/Model/User.php | 4 ++-- .../petstore/php/SwaggerClient-php/lib/ObjectSerializer.php | 4 ++-- .../petstore/php/SwaggerClient-php/test/Api/FakeApiTest.php | 4 ++-- .../petstore/php/SwaggerClient-php/test/Api/PetApiTest.php | 4 ++-- .../petstore/php/SwaggerClient-php/test/Api/StoreApiTest.php | 4 ++-- .../petstore/php/SwaggerClient-php/test/Api/UserApiTest.php | 4 ++-- .../php/SwaggerClient-php/test/Client/ApiClientTest.php | 4 ++-- .../SwaggerClient-php/test/Client/ObjectSerializerTest.php | 4 ++-- .../test/Model/AdditionalPropertiesClassTest.php | 4 ++-- .../php/SwaggerClient-php/test/Model/AnimalFarmTest.php | 4 ++-- .../petstore/php/SwaggerClient-php/test/Model/AnimalTest.php | 4 ++-- .../php/SwaggerClient-php/test/Model/ApiResponseTest.php | 4 ++-- .../test/Model/ArrayOfArrayOfNumberOnlyTest.php | 4 ++-- .../SwaggerClient-php/test/Model/ArrayOfNumberOnlyTest.php | 4 ++-- .../php/SwaggerClient-php/test/Model/ArrayTestTest.php | 4 ++-- .../petstore/php/SwaggerClient-php/test/Model/CatTest.php | 4 ++-- .../php/SwaggerClient-php/test/Model/CategoryTest.php | 4 ++-- .../petstore/php/SwaggerClient-php/test/Model/ClientTest.php | 4 ++-- .../petstore/php/SwaggerClient-php/test/Model/DogTest.php | 4 ++-- .../php/SwaggerClient-php/test/Model/EnumArraysTest.php | 4 ++-- .../php/SwaggerClient-php/test/Model/EnumClassTest.php | 4 ++-- .../php/SwaggerClient-php/test/Model/EnumTestTest.php | 4 ++-- .../php/SwaggerClient-php/test/Model/FormatTestTest.php | 4 ++-- .../php/SwaggerClient-php/test/Model/HasOnlyReadOnlyTest.php | 4 ++-- .../petstore/php/SwaggerClient-php/test/Model/MapTestTest.php | 4 ++-- .../Model/MixedPropertiesAndAdditionalPropertiesClassTest.php | 4 ++-- .../php/SwaggerClient-php/test/Model/Model200ResponseTest.php | 4 ++-- .../php/SwaggerClient-php/test/Model/ModelListTest.php | 4 ++-- .../php/SwaggerClient-php/test/Model/ModelReturnTest.php | 4 ++-- .../petstore/php/SwaggerClient-php/test/Model/NameTest.php | 4 ++-- .../php/SwaggerClient-php/test/Model/NumberOnlyTest.php | 4 ++-- .../petstore/php/SwaggerClient-php/test/Model/OrderTest.php | 4 ++-- .../petstore/php/SwaggerClient-php/test/Model/PetTest.php | 4 ++-- .../php/SwaggerClient-php/test/Model/ReadOnlyFirstTest.php | 4 ++-- .../php/SwaggerClient-php/test/Model/SpecialModelNameTest.php | 4 ++-- .../petstore/php/SwaggerClient-php/test/Model/TagTest.php | 4 ++-- .../petstore/php/SwaggerClient-php/test/Model/UserTest.php | 4 ++-- 88 files changed, 176 insertions(+), 176 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index 59cde85cea6..fc0060adf9d 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -7,7 +7,7 @@ * @category Class * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -26,7 +26,7 @@ namespace {{invokerPackage}}; * @category Class * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ApiClient diff --git a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache index 2cffdea5ccf..f99a793fbc6 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache @@ -6,7 +6,7 @@ * @category Class * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -27,7 +27,7 @@ use \Exception; * @category Class * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ApiException extends Exception diff --git a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache index 10f94686507..ca9ad1d80ec 100644 --- a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache @@ -7,7 +7,7 @@ * @category Class * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -26,7 +26,7 @@ namespace {{invokerPackage}}; * @category Class * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ObjectSerializer diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index c6148ae251d..33059da83b8 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -6,7 +6,7 @@ * @category Class * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -30,7 +30,7 @@ use \{{invokerPackage}}\ObjectSerializer; * @category Class * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ {{#operations}}class {{classname}} diff --git a/modules/swagger-codegen/src/main/resources/php/api_test.mustache b/modules/swagger-codegen/src/main/resources/php/api_test.mustache index 4b961b3236b..99ad7065c9b 100644 --- a/modules/swagger-codegen/src/main/resources/php/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api_test.mustache @@ -6,7 +6,7 @@ * @category Class * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -30,7 +30,7 @@ use \{{invokerPackage}}\ObjectSerializer; * @category Class * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ {{#operations}}class {{classname}}Test extends \PHPUnit_Framework_TestCase diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/configuration.mustache index ee8a83bde58..df8269907bd 100644 --- a/modules/swagger-codegen/src/main/resources/php/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/configuration.mustache @@ -6,7 +6,7 @@ * @category Class * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -26,7 +26,7 @@ namespace {{invokerPackage}}; * @category Class * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class Configuration diff --git a/modules/swagger-codegen/src/main/resources/php/model.mustache b/modules/swagger-codegen/src/main/resources/php/model.mustache index d80f5d0f485..d747db88b7c 100644 --- a/modules/swagger-codegen/src/main/resources/php/model.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model.mustache @@ -9,7 +9,7 @@ * @category Class * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -34,7 +34,7 @@ use \ArrayAccess; /** * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ {{#isEnum}}{{>model_enum}}{{/isEnum}}{{^isEnum}}{{>model_generic}}{{/isEnum}} diff --git a/modules/swagger-codegen/src/main/resources/php/model_test.mustache b/modules/swagger-codegen/src/main/resources/php/model_test.mustache index 52e0d830a23..4bd8f1d3dba 100644 --- a/modules/swagger-codegen/src/main/resources/php/model_test.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model_test.mustache @@ -9,7 +9,7 @@ * @category Class * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -30,7 +30,7 @@ namespace {{invokerPackage}}; /** * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class {{classname}}Test extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php index 4d22ab3e5bd..5ce09b9a7ec 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -6,7 +6,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -51,7 +51,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class FakeApi diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiClient.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiClient.php index d009534a757..5f774a834d3 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiClient.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiClient.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -47,7 +47,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ApiClient diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiException.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiException.php index a88687b0b8f..2e320f1bba5 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiException.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiException.php @@ -6,7 +6,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -48,7 +48,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ApiException extends Exception diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php index 4f7815f162c..12c2b9b0ea2 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php @@ -6,7 +6,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -47,7 +47,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class Configuration diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Model/ModelReturn.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Model/ModelReturn.php index 1676ca46f8a..c4baed23baa 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Model/ModelReturn.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Model/ModelReturn.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -51,7 +51,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ModelReturn implements ArrayAccess diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php index 03502e3dae3..f5ce9361286 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -47,7 +47,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ObjectSerializer diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/test/Api/FakeApiTest.php b/samples/client/petstore-security-test/php/SwaggerClient-php/test/Api/FakeApiTest.php index 6e96b079929..732f8487b59 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/test/Api/FakeApiTest.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/test/Api/FakeApiTest.php @@ -6,7 +6,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -51,7 +51,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class FakeApiTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/test/Model/ModelReturnTest.php b/samples/client/petstore-security-test/php/SwaggerClient-php/test/Model/ModelReturnTest.php index a97d6a39873..c4c8dbe6dd7 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/test/Model/ModelReturnTest.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/test/Model/ModelReturnTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -49,7 +49,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ModelReturnTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index 4b0a732228e..8e339dc2aa0 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -6,7 +6,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -51,7 +51,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class FakeApi 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 53ee7866716..1dcd53a9811 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -6,7 +6,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -51,7 +51,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class PetApi 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 63ece203576..8086abea950 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -6,7 +6,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -51,7 +51,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class StoreApi diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index 5d738494fc5..17dbfd78f0b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -6,7 +6,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -51,7 +51,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class UserApi diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php index 45f83859de4..a28d9840e0f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -47,7 +47,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ApiClient diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php index 48551429c7f..de692b68b96 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php @@ -6,7 +6,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -48,7 +48,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ApiException extends Exception diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index 20946f7bc5f..2678530e46a 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -6,7 +6,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -47,7 +47,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class Configuration diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AdditionalPropertiesClass.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AdditionalPropertiesClass.php index 32f33b0fda2..3167f7b2739 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AdditionalPropertiesClass.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AdditionalPropertiesClass.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -50,7 +50,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class AdditionalPropertiesClass implements ArrayAccess diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php index 3f1b303817e..a2fec72d3d5 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -50,7 +50,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class Animal implements ArrayAccess diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php index 05ded47d5e5..9bcfa87c49f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -50,7 +50,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class AnimalFarm implements ArrayAccess diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php index eeccb4b25d3..106e917400e 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -50,7 +50,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ApiResponse implements ArrayAccess diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php index 43c4c6291cb..3b2375cf14d 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -50,7 +50,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ArrayOfArrayOfNumberOnly implements ArrayAccess diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfNumberOnly.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfNumberOnly.php index 63aa548fc4c..98ba2ab632f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfNumberOnly.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfNumberOnly.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -50,7 +50,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ArrayOfNumberOnly implements ArrayAccess diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayTest.php index efa14332750..1a9a646c11e 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -50,7 +50,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ArrayTest implements ArrayAccess diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php index 46cdad4d91c..349ac54deb6 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -50,7 +50,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class Cat extends Animal implements ArrayAccess diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php index 873589afdb4..c175e72cf8c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -50,7 +50,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class Category implements ArrayAccess diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Client.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Client.php index 5452d61cdf1..cd77d1a33e9 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Client.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Client.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -50,7 +50,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class Client implements ArrayAccess diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php index dbee0bd23cb..6063cb34f0c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -50,7 +50,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class Dog extends Animal implements ArrayAccess diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumArrays.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumArrays.php index 2fc2c3605ff..9b9e6f999be 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumArrays.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumArrays.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -50,7 +50,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class EnumArrays implements ArrayAccess diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php index 61014fa3959..2bee3c3960b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -50,7 +50,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class EnumClass { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php index 5079dcd362e..758c953f4c3 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -50,7 +50,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class EnumTest implements ArrayAccess diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php index 819f3a5013d..88327ba7195 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -50,7 +50,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class FormatTest implements ArrayAccess diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/HasOnlyReadOnly.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/HasOnlyReadOnly.php index 15262d99cb2..e099dd19137 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/HasOnlyReadOnly.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/HasOnlyReadOnly.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -50,7 +50,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class HasOnlyReadOnly implements ArrayAccess diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/MapTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/MapTest.php index 4d8372d7654..a66e65b72ae 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/MapTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/MapTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -50,7 +50,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class MapTest implements ArrayAccess diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php index 97d3394bac2..7fe26b551a8 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -50,7 +50,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class MixedPropertiesAndAdditionalPropertiesClass implements ArrayAccess diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php index 699f20048f2..d4d5fe73302 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -51,7 +51,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class Model200Response implements ArrayAccess diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelList.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelList.php index 9009470c98b..e298fad6faa 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelList.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelList.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -50,7 +50,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ModelList implements ArrayAccess diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php index f36b12dae60..2fee28c2c55 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -51,7 +51,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ModelReturn implements ArrayAccess diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php index a5c9f9696a2..68f53478a0d 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -51,7 +51,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class Name implements ArrayAccess diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/NumberOnly.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/NumberOnly.php index 387b53c1898..629b6b406c1 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/NumberOnly.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/NumberOnly.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -50,7 +50,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class NumberOnly implements ArrayAccess diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php index 9e7d3642320..a91971f18a6 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -50,7 +50,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class Order implements ArrayAccess diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php index 2ef11c3f961..493ef0be3c5 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -50,7 +50,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class Pet implements ArrayAccess diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ReadOnlyFirst.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ReadOnlyFirst.php index ab4a4899e71..07d09f264ab 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ReadOnlyFirst.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ReadOnlyFirst.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -50,7 +50,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ReadOnlyFirst implements ArrayAccess diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php index f4443fa322c..9f638160b87 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -50,7 +50,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class SpecialModelName implements ArrayAccess diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php index 2e75cf94493..bcf4cad8840 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -50,7 +50,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class Tag implements ArrayAccess diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php index cb812f55334..0f07b84c954 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -50,7 +50,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class User implements ArrayAccess diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php index 516ad2519cf..6a74bf2e072 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -47,7 +47,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ObjectSerializer diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Api/FakeApiTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Api/FakeApiTest.php index 3432b185096..c1ba9f2e8d6 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Api/FakeApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Api/FakeApiTest.php @@ -6,7 +6,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -51,7 +51,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class FakeApiTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Api/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Api/PetApiTest.php index ab80903b4bc..afc781e543b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Api/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Api/PetApiTest.php @@ -6,7 +6,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -51,7 +51,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class PetApiTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Api/StoreApiTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Api/StoreApiTest.php index 18146bf0591..c89ff1d23e3 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Api/StoreApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Api/StoreApiTest.php @@ -6,7 +6,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -51,7 +51,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class StoreApiTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Api/UserApiTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Api/UserApiTest.php index def54fa6580..40259040623 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Api/UserApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Api/UserApiTest.php @@ -6,7 +6,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -51,7 +51,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class UserApiTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Client/ApiClientTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Client/ApiClientTest.php index 5d4028ecf92..c7c90b115d7 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Client/ApiClientTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Client/ApiClientTest.php @@ -6,7 +6,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ /** @@ -44,7 +44,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ApiClientTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Client/ObjectSerializerTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Client/ObjectSerializerTest.php index 00e17895164..1b008fbb62a 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Client/ObjectSerializerTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Client/ObjectSerializerTest.php @@ -6,7 +6,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ /** @@ -44,7 +44,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ObjectSerializerTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/AdditionalPropertiesClassTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/AdditionalPropertiesClassTest.php index d5150f44b8d..d1b55c88a9d 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/AdditionalPropertiesClassTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/AdditionalPropertiesClassTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ /** @@ -40,7 +40,7 @@ * @description AdditionalPropertiesClass * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class AdditionalPropertiesClassTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/AnimalFarmTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/AnimalFarmTest.php index 683e9e5d220..37e736a5d2d 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/AnimalFarmTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/AnimalFarmTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -48,7 +48,7 @@ * @description AnimalFarm * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class AnimalFarmTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/AnimalTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/AnimalTest.php index 4890e367f51..c63b5ff4918 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/AnimalTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/AnimalTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ /** @@ -40,7 +40,7 @@ * @description Animal * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class AnimalTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/ApiResponseTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/ApiResponseTest.php index 8032f2d9149..083f9dcecfd 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/ApiResponseTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/ApiResponseTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ /** @@ -40,7 +40,7 @@ * @description ApiResponse * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ApiResponseTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/ArrayOfArrayOfNumberOnlyTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/ArrayOfArrayOfNumberOnlyTest.php index d7c1ddb9cfd..561a8551d1c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/ArrayOfArrayOfNumberOnlyTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/ArrayOfArrayOfNumberOnlyTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -48,7 +48,7 @@ * @description ArrayOfArrayOfNumberOnly * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ArrayOfArrayOfNumberOnlyTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/ArrayOfNumberOnlyTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/ArrayOfNumberOnlyTest.php index 75da7f819ea..f9c9847ad5b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/ArrayOfNumberOnlyTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/ArrayOfNumberOnlyTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -48,7 +48,7 @@ * @description ArrayOfNumberOnly * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ArrayOfNumberOnlyTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/ArrayTestTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/ArrayTestTest.php index 245abb7641e..1632ff9397f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/ArrayTestTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/ArrayTestTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -48,7 +48,7 @@ * @description ArrayTest * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ArrayTestTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/CatTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/CatTest.php index 0d0a876c1a3..ef9f5072fe2 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/CatTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/CatTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ /** @@ -40,7 +40,7 @@ * @description Cat * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class CatTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/CategoryTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/CategoryTest.php index 80394da3493..8a5c3cc8296 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/CategoryTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/CategoryTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ /** @@ -40,7 +40,7 @@ * @description Category * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class CategoryTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/ClientTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/ClientTest.php index 3871e02c455..412bd23450d 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/ClientTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/ClientTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -49,7 +49,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ClientTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/DogTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/DogTest.php index fe47efdd26d..3cdf56fcf50 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/DogTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/DogTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ /** @@ -40,7 +40,7 @@ * @description Dog * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class DogTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/EnumArraysTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/EnumArraysTest.php index df5d48f2cbb..beb363891bb 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/EnumArraysTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/EnumArraysTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -49,7 +49,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class EnumArraysTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/EnumClassTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/EnumClassTest.php index e3f1f8eddd8..23180be95b0 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/EnumClassTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/EnumClassTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ /** @@ -40,7 +40,7 @@ * @description EnumClass * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class EnumClassTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/EnumTestTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/EnumTestTest.php index 2f6b656ba06..79ba379f540 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/EnumTestTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/EnumTestTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ /** @@ -40,7 +40,7 @@ * @description EnumTest * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class EnumTestTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/FormatTestTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/FormatTestTest.php index 57675f2eada..70ad2086372 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/FormatTestTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/FormatTestTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ /** @@ -40,7 +40,7 @@ * @description FormatTest * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class FormatTestTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/HasOnlyReadOnlyTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/HasOnlyReadOnlyTest.php index 63d58ddb48e..e3f66a652f6 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/HasOnlyReadOnlyTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/HasOnlyReadOnlyTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -48,7 +48,7 @@ * @description HasOnlyReadOnly * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class HasOnlyReadOnlyTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/MapTestTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/MapTestTest.php index 68ccdf85945..b68cd027a2c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/MapTestTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/MapTestTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -48,7 +48,7 @@ * @description MapTest * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class MapTestTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/MixedPropertiesAndAdditionalPropertiesClassTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/MixedPropertiesAndAdditionalPropertiesClassTest.php index cd70c290959..3130b6291a7 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/MixedPropertiesAndAdditionalPropertiesClassTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/MixedPropertiesAndAdditionalPropertiesClassTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ /** @@ -40,7 +40,7 @@ * @description MixedPropertiesAndAdditionalPropertiesClass * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class MixedPropertiesAndAdditionalPropertiesClassTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/Model200ResponseTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/Model200ResponseTest.php index 20d6e492686..0e02c83a9cd 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/Model200ResponseTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/Model200ResponseTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ /** @@ -40,7 +40,7 @@ * @description Model for testing model name starting with number * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class Model200ResponseTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/ModelListTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/ModelListTest.php index 0ac755a1469..bab7bcc0362 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/ModelListTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/ModelListTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -49,7 +49,7 @@ /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ModelListTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/ModelReturnTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/ModelReturnTest.php index 80e692dd61a..4eea89ddbb2 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/ModelReturnTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/ModelReturnTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ /** @@ -40,7 +40,7 @@ * @description Model for testing reserved words * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ModelReturnTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/NameTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/NameTest.php index 81397cab0cd..350eb311ebd 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/NameTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/NameTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ /** @@ -40,7 +40,7 @@ * @description Model for testing model name same as property name * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class NameTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/NumberOnlyTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/NumberOnlyTest.php index 5ced13727b7..11c580d16f4 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/NumberOnlyTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/NumberOnlyTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -48,7 +48,7 @@ * @description NumberOnly * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class NumberOnlyTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/OrderTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/OrderTest.php index fe2bf25ef46..d197cffa653 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/OrderTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/OrderTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -48,7 +48,7 @@ * @description Order * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class OrderTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/PetTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/PetTest.php index 7c079f09a11..b40d6c35e3e 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/PetTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/PetTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ @@ -48,7 +48,7 @@ * @description Pet * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class PetTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/ReadOnlyFirstTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/ReadOnlyFirstTest.php index a048de72f22..38d936db03d 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/ReadOnlyFirstTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/ReadOnlyFirstTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ /** @@ -40,7 +40,7 @@ * @description ReadOnlyFirst * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class ReadOnlyFirstTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/SpecialModelNameTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/SpecialModelNameTest.php index 0b5eff62e3c..100fdb79789 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/SpecialModelNameTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/SpecialModelNameTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ /** @@ -40,7 +40,7 @@ * @description SpecialModelName * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class SpecialModelNameTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/TagTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/TagTest.php index 7360c3f7bb5..78b9abcc462 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/TagTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/TagTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ /** @@ -40,7 +40,7 @@ * @description Tag * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class TagTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/UserTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/UserTest.php index f6a6edc8208..b8746208f5c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/UserTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/UserTest.php @@ -7,7 +7,7 @@ * @category Class * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ /** @@ -40,7 +40,7 @@ * @description User * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 * @link https://github.com/swagger-api/swagger-codegen */ class UserTest extends \PHPUnit_Framework_TestCase From f436f0eee2f46f9745d91ac057d7be47020fc11b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Tue, 6 Sep 2016 14:49:00 +0300 Subject: [PATCH 332/470] python: Fix model maxLength validation error message --- .../swagger-codegen/src/main/resources/python/model.mustache | 2 +- .../client/petstore/python/petstore_api/models/format_test.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index 9b51612a8a5..3f5c717b0ec 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -74,7 +74,7 @@ class {{classname}}(object): raise ValueError("Invalid value for `{{name}}`, must not be `None`") {{#maxLength}} if len({{name}}) > {{maxLength}}: - raise ValueError("Invalid value for `{{name}}`, length must be less than `{{maxLength}}`") + raise ValueError("Invalid value for `{{name}}`, length must be less than or equal to `{{maxLength}}`") {{/maxLength}} {{#minLength}} if len({{name}}) < {{minLength}}: diff --git a/samples/client/petstore/python/petstore_api/models/format_test.py b/samples/client/petstore/python/petstore_api/models/format_test.py index bbc14daa13c..d36ba498de6 100644 --- a/samples/client/petstore/python/petstore_api/models/format_test.py +++ b/samples/client/petstore/python/petstore_api/models/format_test.py @@ -428,7 +428,7 @@ def password(self, password): if not password: raise ValueError("Invalid value for `password`, must not be `None`") if len(password) > 64: - raise ValueError("Invalid value for `password`, length must be less than `64`") + raise ValueError("Invalid value for `password`, length must be less than or equal to `64`") if len(password) < 10: raise ValueError("Invalid value for `password`, length must be greater than or equal to `10`") From 92eb722cedc33e2e6f24bc32928459f9b0bb7246 Mon Sep 17 00:00:00 2001 From: Cliffano Subagio Date: Wed, 7 Sep 2016 00:25:39 +1000 Subject: [PATCH 333/470] [ruby] Add gemspec required_ruby_version setting. (#3718) * [ruby] Add gemspec required_ruby_version setting. * [ruby] Add gemspec required_ruby_version setting. * Add gemRequiredRubyVersion option to Ruby client code generator. --- .../codegen/languages/RubyClientCodegen.java | 13 +++++++++++++ .../src/main/resources/ruby/gemspec.mustache | 1 + .../codegen/options/RubyClientOptionsProvider.java | 2 ++ .../swagger/codegen/ruby/RubyClientOptionsTest.java | 2 ++ samples/client/petstore/ruby/README.md | 1 + samples/client/petstore/ruby/petstore.gemspec | 1 + 6 files changed, 20 insertions(+) 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 5ccdf19cbdb..1bcadeef9ef 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 @@ -30,6 +30,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { public static final String MODULE_NAME = "moduleName"; public static final String GEM_VERSION = "gemVersion"; public static final String GEM_LICENSE = "gemLicense"; + public static final String GEM_REQUIRED_RUBY_VERSION = "gemRequiredRubyVersion"; public static final String GEM_HOMEPAGE = "gemHomepage"; public static final String GEM_SUMMARY = "gemSummary"; public static final String GEM_DESCRIPTION = "gemDescription"; @@ -42,6 +43,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { protected String specFolder = "spec"; protected String libFolder = "lib"; protected String gemLicense = "Apache-2.0"; + protected String gemRequiredRubyVersion = ">= 1.9"; protected String gemHomepage = "http://swagger.io"; protected String gemSummary = "A ruby wrapper for the swagger APIs"; protected String gemDescription = "This gem maps to a swagger API"; @@ -143,6 +145,9 @@ public RubyClientCodegen() { cliOptions.add(new CliOption(GEM_LICENSE, "gem license. "). defaultValue("Apache-2.0")); + cliOptions.add(new CliOption(GEM_REQUIRED_RUBY_VERSION, "gem required Ruby version. "). + defaultValue(">= 1.9")); + cliOptions.add(new CliOption(GEM_HOMEPAGE, "gem homepage. "). defaultValue("http://swagger.io")); @@ -203,6 +208,10 @@ public void processOpts() { setGemLicense((String) additionalProperties.get(GEM_LICENSE)); } + if (additionalProperties.containsKey(GEM_REQUIRED_RUBY_VERSION)) { + setGemRequiredRubyVersion((String) additionalProperties.get(GEM_REQUIRED_RUBY_VERSION)); + } + if (additionalProperties.containsKey(GEM_HOMEPAGE)) { setGemHomepage((String) additionalProperties.get(GEM_HOMEPAGE)); } @@ -708,6 +717,10 @@ public void setGemLicense(String gemLicense) { this.gemLicense = gemLicense; } + public void setGemRequiredRubyVersion(String gemRequiredRubyVersion) { + this.gemRequiredRubyVersion = gemRequiredRubyVersion; + } + public void setGemHomepage(String gemHomepage) { this.gemHomepage = gemHomepage; } diff --git a/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache b/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache index 86d9a6e55d8..935fad7f61b 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache @@ -17,6 +17,7 @@ Gem::Specification.new do |s| s.summary = "{{gemSummary}}{{^gemSummary}}{{{appName}}} Ruby Gem{{/gemSummary}}" s.description = "{{gemDescription}}{{^gemDescription}}{{{appDescription}}}{{^appDescription}}{{{appName}}} Ruby Gem{{/appDescription}}{{/gemDescription}}" s.license = "{{gemLicense}}{{^gemLicense}}{{{licenseInfo}}}{{^licenseInfo}}Apache 2.0{{/licenseInfo}}{{/gemLicense}}" + s.required_ruby_version = "{{{gemRequiredRubyVersion}}}{{^gemRequiredRubyVersion}}>= 1.9{{/gemRequiredRubyVersion}}" s.add_runtime_dependency 'typhoeus', '~> 1.0', '>= 1.0.1' s.add_runtime_dependency 'json', '~> 1.8', '>= 1.8.3' diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java index 55c81e6fdc4..34a36534a31 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java @@ -14,6 +14,7 @@ public class RubyClientOptionsProvider implements OptionsProvider { public static final String SORT_PARAMS_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final String GEM_LICENSE_VALUE = "MIT"; + public static final String GEM_REQUIRED_RUBY_VERSION_VALUE = ">= 1.9"; public static final String GEM_HOMEPAGE_VALUE = "homepage"; public static final String GEM_SUMMARY_VALUE = "summary"; public static final String GEM_DESCRIPTION_VALUE = "description"; @@ -32,6 +33,7 @@ public Map createOptions() { .put(RubyClientCodegen.MODULE_NAME, MODULE_NAME_VALUE) .put(RubyClientCodegen.GEM_VERSION, GEM_VERSION_VALUE) .put(RubyClientCodegen.GEM_LICENSE, GEM_LICENSE_VALUE) + .put(RubyClientCodegen.GEM_REQUIRED_RUBY_VERSION, GEM_REQUIRED_RUBY_VERSION_VALUE) .put(RubyClientCodegen.GEM_DESCRIPTION, GEM_DESCRIPTION_VALUE) .put(RubyClientCodegen.GEM_HOMEPAGE, GEM_HOMEPAGE_VALUE) .put(RubyClientCodegen.GEM_SUMMARY, GEM_SUMMARY_VALUE) diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientOptionsTest.java index f61367e8220..9bf7eea4c94 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientOptionsTest.java @@ -34,6 +34,8 @@ protected void setExpectations() { times = 1; clientCodegen.setGemLicense(RubyClientOptionsProvider.GEM_LICENSE_VALUE); times = 1; + clientCodegen.setGemRequiredRubyVersion(RubyClientOptionsProvider.GEM_REQUIRED_RUBY_VERSION_VALUE); + times = 1; clientCodegen.setGemHomepage(RubyClientOptionsProvider.GEM_HOMEPAGE_VALUE); times = 1; clientCodegen.setGemDescription(RubyClientOptionsProvider.GEM_DESCRIPTION_VALUE); diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index 188335045f6..1aa8be7831a 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -8,6 +8,7 @@ This SDK is automatically generated by the [Swagger Codegen](https://github.com/ - API version: 1.0.0 - Package version: 1.0.0 +- Build date: 2016-09-04T00:22:35.922+10:00 - Build package: class io.swagger.codegen.languages.RubyClientCodegen ## Installation diff --git a/samples/client/petstore/ruby/petstore.gemspec b/samples/client/petstore/ruby/petstore.gemspec index 4075ba0fc2d..9d4aa367b9c 100644 --- a/samples/client/petstore/ruby/petstore.gemspec +++ b/samples/client/petstore/ruby/petstore.gemspec @@ -36,6 +36,7 @@ Gem::Specification.new do |s| s.summary = "Swagger Petstore Ruby Gem" s.description = "This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\" s.license = "Apache 2.0" + s.required_ruby_version = ">= 1.9" s.add_runtime_dependency 'typhoeus', '~> 1.0', '>= 1.0.1' s.add_runtime_dependency 'json', '~> 1.8', '>= 1.8.3' From b8e8c7cdb5a064ee5136f55e07b334855f0e0925 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Wed, 7 Sep 2016 11:41:51 +0300 Subject: [PATCH 334/470] Various code cleanups (#3709) * For/while to foreach loop conversions * Don't instantiate Booleans * Remove redundant String.toString calls * Remove redundant String instantiations * Don't concatenate StringBuilder.append args * Replace dangling javadoc comments with blocks * Combine identical catch branches * Remove redundant catch branch * Remove unnecessary boxing * Remove redundant casts * Remove redundant null checks --- .../src/main/java/config/ConfigParser.java | 2 +- .../main/java/io/swagger/codegen/Codegen.java | 6 +-- .../swagger/codegen/CodegenModelFactory.java | 4 +- .../io/swagger/codegen/CodegenOperation.java | 2 +- .../io/swagger/codegen/CodegenResponse.java | 4 +- .../io/swagger/codegen/DefaultCodegen.java | 37 +++++++++---------- .../io/swagger/codegen/DefaultGenerator.java | 2 +- .../io/swagger/codegen/MetaGenerator.java | 6 +-- .../codegen/config/CodegenConfigurator.java | 4 +- .../codegen/examples/ExampleGenerator.java | 8 ++-- .../io/swagger/codegen/ignore/rules/Rule.java | 6 +-- .../languages/AbstractCSharpCodegen.java | 2 +- .../languages/AbstractJavaCodegen.java | 2 +- .../codegen/languages/AbstractPhpCodegen.java | 4 +- .../languages/CSharpClientCodegen.java | 2 +- .../languages/FlaskConnexionCodegen.java | 6 +-- .../codegen/languages/GoClientCodegen.java | 4 +- .../codegen/languages/GoServerCodegen.java | 12 +++--- .../codegen/languages/JMeterCodegen.java | 12 +++--- .../languages/JavaJAXRSSpecServerCodegen.java | 3 -- .../languages/JavascriptClientCodegen.java | 2 +- .../codegen/languages/LumenServerCodegen.java | 10 ++--- .../languages/NodeJSServerCodegen.java | 12 +++--- .../codegen/languages/ObjcClientCodegen.java | 8 ++-- .../codegen/languages/PerlClientCodegen.java | 6 +-- .../codegen/languages/PhpClientCodegen.java | 6 +-- .../languages/PythonClientCodegen.java | 4 +- .../codegen/languages/Qt5CPPGenerator.java | 12 +++--- .../codegen/languages/RubyClientCodegen.java | 4 +- .../codegen/languages/SpringCodegen.java | 2 +- .../codegen/languages/SwiftCodegen.java | 4 +- .../swagger/codegen/testutils/AssertFile.java | 6 +-- 32 files changed, 96 insertions(+), 108 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/config/ConfigParser.java b/modules/swagger-codegen/src/main/java/config/ConfigParser.java index 68cbb613f3a..0cd2558e266 100644 --- a/modules/swagger-codegen/src/main/java/config/ConfigParser.java +++ b/modules/swagger-codegen/src/main/java/config/ConfigParser.java @@ -27,7 +27,7 @@ public static Config read(String location) { Iterator> optionNodes = rootNode.fields(); while (optionNodes.hasNext()) { - Map.Entry optionNode = (Map.Entry) optionNodes.next(); + Map.Entry optionNode = optionNodes.next(); if (optionNode.getValue().isValueNode()) { config.setOption(optionNode.getKey(), optionNode.getValue().asText()); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/Codegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/Codegen.java index 649f068d16c..c4f0dc1ce7a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/Codegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/Codegen.java @@ -2,7 +2,6 @@ import java.util.ArrayList; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.ServiceLoader; @@ -124,9 +123,8 @@ public static void main(String[] args) { public static List getExtensions() { ServiceLoader loader = ServiceLoader.load(CodegenConfig.class); List output = new ArrayList(); - Iterator itr = loader.iterator(); - while (itr.hasNext()) { - output.add(itr.next()); + for (CodegenConfig aLoader : loader) { + output.add(aLoader); } return output; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModelFactory.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModelFactory.java index 4c2b4d4eb87..d0a93731a30 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModelFactory.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModelFactory.java @@ -30,9 +30,7 @@ public static T newInstance(CodegenModelType type) { Class classType = typeMapping.get(type); try { return (T) (classType != null ? classType : type.getDefaultImplementation()).newInstance(); - } catch (InstantiationException e) { - throw new RuntimeException(e); - } catch (IllegalAccessException e) { + } catch (IllegalAccessException | InstantiationException e) { throw new RuntimeException(e); } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java index e92e8aeb1d1..501479955fd 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java @@ -281,7 +281,7 @@ public boolean equals(Object o) { @Override public int hashCode() { - int result = responseHeaders != null ? responseHeaders.hashCode() : 0; + int result = responseHeaders.hashCode(); result = 31 * result + (hasAuthMethods != null ? hasAuthMethods.hashCode() : 0); result = 31 * result + (hasConsumes != null ? hasConsumes.hashCode() : 0); result = 31 * result + (hasProduces != null ? hasProduces.hashCode() : 0); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java index 746f65cea38..a8a2117a31e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java @@ -35,7 +35,7 @@ public boolean equals(Object o) { CodegenResponse that = (CodegenResponse) o; - if (headers != null ? !headers.equals(that.headers) : that.headers != null) + if (!headers.equals(that.headers)) return false; if (code != null ? !code.equals(that.code) : that.code != null) return false; @@ -71,7 +71,7 @@ public boolean equals(Object o) { @Override public int hashCode() { - int result = headers != null ? headers.hashCode() : 0; + int result = headers.hashCode(); result = 31 * result + (code != null ? code.hashCode() : 0); result = 31 * result + (message != null ? message.hashCode() : 0); result = 31 * result + (hasMore != null ? hasMore.hashCode() : 0); 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 64506e2a209..8695f7e6fff 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 @@ -886,7 +886,7 @@ public String generateExamplePath(String path, Operation operation) { paramPart.append(param.getName()).append("="); paramPart.append("{"); if (qp.getCollectionFormat() != null) { - paramPart.append(param.getName() + "1"); + paramPart.append(param.getName()).append("1"); if ("csv".equals(qp.getCollectionFormat())) { paramPart.append(","); } else if ("pipes".equals(qp.getCollectionFormat())) { @@ -895,7 +895,7 @@ public String generateExamplePath(String path, Operation operation) { paramPart.append("\t"); } else if ("multi".equals(qp.getCollectionFormat())) { paramPart.append("&").append(param.getName()).append("="); - paramPart.append(param.getName() + "2"); + paramPart.append(param.getName()).append("2"); } } else { paramPart.append(param.getName()); @@ -1574,7 +1574,7 @@ public CodegenProperty fromProperty(String name, Property p) { List _enum = sp.getEnum(); property._enum = new ArrayList(); for(String i : _enum) { - property._enum.add(i.toString()); + property._enum.add(i); } property.isEnum = true; @@ -1592,7 +1592,7 @@ public CodegenProperty fromProperty(String name, Property p) { List _enum = sp.getEnum(); property._enum = new ArrayList(); for(String i : _enum) { - property._enum.add(i.toString()); + property._enum.add(i); } property.isEnum = true; @@ -2355,28 +2355,28 @@ public CodegenParameter fromParameter(Parameter param, Set imports) { } else if (Boolean.TRUE.equals(p.isString)) { p.example = p.paramName + "_example"; } else if (Boolean.TRUE.equals(p.isBoolean)) { - p.example = new String("true"); + p.example = "true"; } else if (Boolean.TRUE.equals(p.isLong)) { - p.example = new String("789"); + p.example = "789"; } else if (Boolean.TRUE.equals(p.isInteger)) { - p.example = new String("56"); + p.example = "56"; } else if (Boolean.TRUE.equals(p.isFloat)) { - p.example = new String("3.4"); + p.example = "3.4"; } else if (Boolean.TRUE.equals(p.isDouble)) { - p.example = new String("1.2"); + p.example = "1.2"; } else if (Boolean.TRUE.equals(p.isBinary)) { - p.example = new String("BINARY_DATA_HERE"); + p.example = "BINARY_DATA_HERE"; } else if (Boolean.TRUE.equals(p.isByteArray)) { - p.example = new String("B"); + p.example = "B"; } else if (Boolean.TRUE.equals(p.isDate)) { - p.example = new String("2013-10-20"); + p.example = "2013-10-20"; } else if (Boolean.TRUE.equals(p.isDateTime)) { - p.example = new String("2013-10-20T19:20:30+01:00"); + p.example = "2013-10-20T19:20:30+01:00"; } else if (param instanceof FormParameter && ("file".equalsIgnoreCase(((FormParameter) param).getType()) || "file".equals(p.baseType))) { p.isFile = true; - p.example = new String("/path/to/file.txt"); + p.example = "/path/to/file.txt"; } // set the parameter excample value @@ -2531,8 +2531,7 @@ protected String getOrGenerateOperationId(Operation operation, String path, Stri // must be root tmpPath builder.append("root"); } - for (int i = 0; i < parts.length; i++) { - String part = parts[i]; + for (String part : parts) { if (part.length() > 0) { if (builder.toString().length() == 0) { part = Character.toLowerCase(part.charAt(0)) + part.substring(1); @@ -2587,10 +2586,10 @@ private static List addHasMore(List objs) { if (objs != null) { for (int i = 0; i < objs.size(); i++) { if (i > 0) { - objs.get(i).secondaryParam = new Boolean(true); + objs.get(i).secondaryParam = true; } if (i < objs.size() - 1) { - objs.get(i).hasMore = new Boolean(true); + objs.get(i).hasMore = true; } } } @@ -2601,7 +2600,7 @@ private static Map addHasMore(Map objs) { if (objs != null) { for (int i = 0; i < objs.size() - 1; i++) { if (i > 0) { - objs.put("secondaryParam", new Boolean(true)); + objs.put("secondaryParam", true); } if (i < objs.size() - 1) { objs.put("hasMore", true); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index 664d70d46c4..fd893f5d52f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -413,7 +413,7 @@ public int compare(CodegenOperation one, CodegenOperation another) { // Pass sortParamsByRequiredFlag through to the Mustache template... boolean sortParamsByRequiredFlag = true; if (this.config.additionalProperties().containsKey(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG)) { - sortParamsByRequiredFlag = Boolean.valueOf((String)this.config.additionalProperties().get(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG).toString()); + sortParamsByRequiredFlag = Boolean.valueOf(this.config.additionalProperties().get(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG).toString()); } operation.put("sortParamsByRequiredFlag", sortParamsByRequiredFlag); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/MetaGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/MetaGenerator.java index 6bbc02130c7..45eb05e56fb 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/MetaGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/MetaGenerator.java @@ -16,7 +16,6 @@ import java.io.Reader; import java.util.ArrayList; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.ServiceLoader; @@ -40,9 +39,8 @@ public static void main(String[] args) { public static List getExtensions() { ServiceLoader loader = ServiceLoader.load(CodegenConfig.class); List output = new ArrayList(); - Iterator itr = loader.iterator(); - while (itr.hasNext()) { - output.add(itr.next()); + for (CodegenConfig config : loader) { + output.add(config); } return output; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java index 5b572645513..1dd1ced4d74 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java @@ -151,7 +151,7 @@ public CodegenConfigurator setTemplateDir(String templateDir) { File f = new File(templateDir); // check to see if the folder exists - if (!(f != null && f.exists() && f.isDirectory())) { + if (!(f.exists() && f.isDirectory())) { throw new IllegalArgumentException("Template directory " + templateDir + " does not exist."); } @@ -414,7 +414,7 @@ private void handleDynamicProperties(CodegenConfig codegenConfig) { codegenConfig.additionalProperties().put(opt, dynamicProperties.get(opt)); } else if(systemProperties.containsKey(opt)) { - codegenConfig.additionalProperties().put(opt, systemProperties.get(opt).toString()); + codegenConfig.additionalProperties().put(opt, systemProperties.get(opt)); } } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/ExampleGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/ExampleGenerator.java index 5c373607d53..228e5afb90d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/ExampleGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/ExampleGenerator.java @@ -99,15 +99,15 @@ protected Object resolvePropertyToExample(String mediaType, Property property, S } else if (property instanceof DecimalProperty) { return new BigDecimal(1.3579); } else if (property instanceof DoubleProperty) { - return new Double(3.149); + return 3.149; } else if (property instanceof FileProperty) { return ""; // TODO } else if (property instanceof FloatProperty) { - return new Float(1.23); + return 1.23f; } else if (property instanceof IntegerProperty) { - return new Integer(123); + return 123; } else if (property instanceof LongProperty) { - return new Long(123456789); + return 123456789L; } else if (property instanceof MapProperty) { Map mp = new HashMap(); if (property.getName() != null) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/Rule.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/Rule.java index 8d199cba763..137cb071cab 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/Rule.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/Rule.java @@ -26,10 +26,8 @@ protected String getPattern() { if(syntax == null) return this.definition; StringBuilder sb = new StringBuilder(); - for (int i = 0; i < syntax.size(); i++) { - Part current = syntax.get(i); - - switch(current.getToken()){ + for (Part current : syntax) { + switch (current.getToken()) { case MATCH_ALL: case MATCH_ANY: case ESCAPED_EXCLAMATION: diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java index ad28fe98783..51dc81f46e0 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java @@ -466,7 +466,7 @@ public String toDefaultValue(Property p) { if (p instanceof StringProperty) { StringProperty dp = (StringProperty) p; if (dp.getDefault() != null) { - return "\"" + dp.getDefault().toString() + "\""; + return "\"" + dp.getDefault() + "\""; } } else if (p instanceof BooleanProperty) { BooleanProperty dp = (BooleanProperty) p; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java index 4565eafd4da..cabd2910353 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java @@ -602,7 +602,7 @@ public CodegenModel fromModel(String name, Model model, Map allDe if(codegenModel.description != null) { codegenModel.imports.add("ApiModel"); } - if (allDefinitions != null && codegenModel != null && codegenModel.parentSchema != null && codegenModel.hasEnums) { + if (allDefinitions != null && codegenModel.parentSchema != null && codegenModel.hasEnums) { final Model parentModel = allDefinitions.get(codegenModel.parentSchema); final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel); codegenModel = AbstractJavaCodegen.reconcileInlineEnums(codegenModel, parentCodegenModel); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractPhpCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractPhpCodegen.java index fd2ab974a6c..ff51beaef7f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractPhpCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractPhpCodegen.java @@ -462,7 +462,7 @@ public String toDefaultValue(Property p) { if (p instanceof StringProperty) { StringProperty dp = (StringProperty) p; if (dp.getDefault() != null) { - return "'" + dp.getDefault().toString() + "'"; + return "'" + dp.getDefault() + "'"; } } else if (p instanceof BooleanProperty) { BooleanProperty dp = (BooleanProperty) p; @@ -586,7 +586,7 @@ public String toEnumVarName(String name, String datatype) { // number if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) { - String varName = new String(name); + String varName = name; varName = varName.replaceAll("-", "MINUS_"); varName = varName.replaceAll("\\+", "PLUS_"); varName = varName.replaceAll("\\.", "_DOT_"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java index bc61b839009..3aead1ab93a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java @@ -144,7 +144,7 @@ public void processOpts() { additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); } else { additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf((String)additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); } Boolean excludeTests = false; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java index 153d85f1596..75dac2e4d98 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java @@ -67,7 +67,7 @@ public FlaskConnexionCodegen() { apiTemplateFiles.clear(); - /** + /* * 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. */ @@ -81,14 +81,14 @@ public FlaskConnexionCodegen() { "print", "class", "exec", "in", "raise", "continue", "finally", "is", "return", "def", "for", "lambda", "try")); - /** + /* * Additional Properties. These values can be passed to the templates and * are available in models, apis, and supporting files */ additionalProperties.put("apiVersion", apiVersion); additionalProperties.put("serverPort", serverPort); - /** + /* * Supporting Files. You can write single files for the generator with the * entire object tree available. If the input file has a suffix of `.mustache * it will be processed by the template engine. Otherwise, it will be copied diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java index 6bfd1df425f..ccc712dde60 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java @@ -132,7 +132,7 @@ public void processOpts() { additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); } else { additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf((String)additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); } if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { @@ -373,7 +373,7 @@ public String getSwaggerType(Property p) { @Override public String toOperationId(String operationId) { - String sanitizedOperationId = new String(sanitizeName(operationId)); + String sanitizedOperationId = sanitizeName(operationId); // method name cannot use reserved keyword, e.g. return if (isReservedWord(sanitizedOperationId)) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoServerCodegen.java index b8ce2247652..39c544fba42 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoServerCodegen.java @@ -36,7 +36,7 @@ public GoServerCodegen() { // set the output folder here outputFolder = "generated-code/go"; - /** + /* * Models. You can write model files using the modelTemplateFiles map. * if you want to create one template for file, you can do so here. * for multiple files for model, just put another entry in the `modelTemplateFiles` with @@ -44,7 +44,7 @@ public GoServerCodegen() { */ modelTemplateFiles.clear(); - /** + /* * 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 @@ -53,13 +53,13 @@ public GoServerCodegen() { "controller.mustache", // the template to use ".go"); // the extension for each file to write - /** + /* * 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. */ embeddedTemplateDir = templateDir = "go-server"; - /** + /* * Reserved words. Override this with reserved words specific to your language */ setReservedWordsLowerCase( @@ -126,14 +126,14 @@ public GoServerCodegen() { cliOptions.clear(); cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Go package name (convention: lowercase).") .defaultValue("swagger")); - /** + /* * Additional Properties. These values can be passed to the templates and * are available in models, apis, and supporting files */ additionalProperties.put("apiVersion", apiVersion); additionalProperties.put("serverPort", serverPort); additionalProperties.put("apiPath", apiPath); - /** + /* * Supporting Files. You can write single files for the generator with the * entire object tree available. If the input file has a suffix of `.mustache * it will be processed by the template engine. Otherwise, it will be copied diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java index 394e7122a04..89893176493 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java @@ -53,7 +53,7 @@ public JMeterCodegen() { // 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 @@ -64,23 +64,23 @@ public JMeterCodegen() { 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 ( @@ -89,7 +89,7 @@ public JMeterCodegen() { "sample2") ); - /** + /* * Additional Properties. These values can be passed to the templates and * are available in models, apis, and supporting files */ diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSSpecServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSSpecServerCodegen.java index 33320612505..4e1f388e8a4 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSSpecServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSSpecServerCodegen.java @@ -18,7 +18,6 @@ import io.swagger.models.Swagger; import io.swagger.util.Json; import org.apache.commons.io.FileUtils; -import com.fasterxml.jackson.core.JsonProcessingException; public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen { @@ -135,8 +134,6 @@ public void preprocessSwagger(Swagger swagger) { try { String swaggerJson = Json.pretty(swagger); FileUtils.writeStringToFile(new File(outputFolder + File.separator + "swagger.json"), swaggerJson); - } catch (JsonProcessingException e) { - throw new RuntimeException(e.getMessage(), e.getCause()); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e.getCause()); } 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 d26f18ceaa6..5db91f2600c 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 @@ -199,7 +199,7 @@ public void processOpts() { additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); } else { additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf((String)additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/LumenServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/LumenServerCodegen.java index b2a2db3def3..5dd35ba1b0f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/LumenServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/LumenServerCodegen.java @@ -50,18 +50,18 @@ public LumenServerCodegen() { embeddedTemplateDir = templateDir = "lumen"; - /** + /* * packPath */ invokerPackage = "lumen"; packagePath = ""; - /** + /* * Api Package. Optional, if needed, this can be used in templates */ apiPackage = "app.Http.Controllers"; - /** + /* * Model Package. Optional, if needed, this can be used in templates */ modelPackage = "models"; @@ -72,13 +72,13 @@ public LumenServerCodegen() { apiDocTemplateFiles.clear(); modelDocTemplateFiles.clear(); - /** + /* * Additional Properties. These values can be passed to the templates and * are available in models, apis, and supporting files */ additionalProperties.put("apiVersion", apiVersion); - /** + /* * Supporting Files. You can write single files for the generator with the * entire object tree available. If the input file has a suffix of `.mustache * it will be processed by the template engine. Otherwise, it will be copied diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java index 97aaef4cfcb..184027dd42b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java @@ -34,7 +34,7 @@ public NodeJSServerCodegen() { // set the output folder here outputFolder = "generated-code/nodejs"; - /** + /* * Models. You can write model files using the modelTemplateFiles map. * if you want to create one template for file, you can do so here. * for multiple files for model, just put another entry in the `modelTemplateFiles` with @@ -42,7 +42,7 @@ public NodeJSServerCodegen() { */ modelTemplateFiles.clear(); - /** + /* * 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 @@ -51,13 +51,13 @@ public NodeJSServerCodegen() { "controller.mustache", // the template to use ".js"); // the extension for each file to write - /** + /* * 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. */ embeddedTemplateDir = templateDir = "nodejs"; - /** + /* * Reserved words. Override this with reserved words specific to your language */ setReservedWordsLowerCase( @@ -69,14 +69,14 @@ public NodeJSServerCodegen() { "void", "while", "with", "yield") ); - /** + /* * Additional Properties. These values can be passed to the templates and * are available in models, apis, and supporting files */ additionalProperties.put("apiVersion", apiVersion); additionalProperties.put("serverPort", serverPort); - /** + /* * Supporting Files. You can write single files for the generator with the * entire object tree available. If the input file has a suffix of `.mustache * it will be processed by the template engine. Otherwise, it will be copied 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 c48974aa579..46732703c34 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 @@ -195,7 +195,7 @@ public void processOpts() { additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); } else { additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf((String)additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); } if (additionalProperties.containsKey(POD_NAME)) { @@ -514,8 +514,8 @@ public String toVarName(String name) { } // if name starting with special word, escape with '_' - for(int i =0; i < specialWords.length; i++) { - if (name.matches("(?i:^" + specialWords[i] + ".*)")) + for (String specialWord : specialWords) { + if (name.matches("(?i:^" + specialWord + ".*)")) name = escapeSpecialWord(name); } @@ -624,7 +624,7 @@ public String toDefaultValue(Property p) { if (p instanceof StringProperty) { StringProperty dp = (StringProperty) p; if (dp.getDefault() != null) { - return "@\"" + dp.getDefault().toString() + "\""; + return "@\"" + dp.getDefault() + "\""; } } else if (p instanceof BooleanProperty) { BooleanProperty dp = (BooleanProperty) p; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java index 00fbf9e651f..db892f8a7ff 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java @@ -232,7 +232,7 @@ public String toDefaultValue(Property p) { if (p instanceof StringProperty) { StringProperty dp = (StringProperty) p; if (dp.getDefault() != null) { - return "'" + dp.getDefault().toString() + "'"; + return "'" + dp.getDefault() + "'"; } } else if (p instanceof BooleanProperty) { BooleanProperty dp = (BooleanProperty) p; @@ -401,9 +401,9 @@ public void setParameterExampleValue(CodegenParameter p) { p.example = "'" + p.example + "'"; } else if (Boolean.TRUE.equals(p.isBoolean)) { if (Boolean.parseBoolean(p.example)) - p.example = new String("1"); + p.example = "1"; else - p.example = new String("0"); + p.example = "0"; } else if (Boolean.TRUE.equals(p.isDateTime) || Boolean.TRUE.equals(p.isDate)) { p.example = "DateTime->from_epoch(epoch => str2time('" + p.example + "'))"; } 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 a3296170e1f..9d3a12c8279 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 @@ -211,7 +211,7 @@ public void processOpts() { additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); } else { additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf((String)additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); } if (additionalProperties.containsKey(PACKAGE_PATH)) { @@ -517,7 +517,7 @@ public String toDefaultValue(Property p) { if (p instanceof StringProperty) { StringProperty dp = (StringProperty) p; if (dp.getDefault() != null) { - return "'" + dp.getDefault().toString() + "'"; + return "'" + dp.getDefault() + "'"; } } else if (p instanceof BooleanProperty) { BooleanProperty dp = (BooleanProperty) p; @@ -636,7 +636,7 @@ public String toEnumDefaultValue(String value, String datatype) { public String toEnumVarName(String name, String datatype) { // number if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) { - String varName = new String(name); + String varName = name; varName = varName.replaceAll("-", "MINUS_"); varName = varName.replaceAll("\\+", "PLUS_"); varName = varName.replaceAll("\\.", "_DOT_"); 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 54c6febbf88..568ad8165c8 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 @@ -146,7 +146,7 @@ public void processOpts() { additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); } else { additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf((String)additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); } additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); @@ -500,7 +500,7 @@ public String toDefaultValue(Property p) { if (p instanceof StringProperty) { StringProperty dp = (StringProperty) p; if (dp.getDefault() != null) { - return "'" + dp.getDefault().toString() + "'"; + return "'" + dp.getDefault() + "'"; } } else if (p instanceof BooleanProperty) { BooleanProperty dp = (BooleanProperty) p; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java index 9cfdc0c143b..f3179688c32 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java @@ -41,7 +41,7 @@ public Qt5CPPGenerator() { // set the output folder here outputFolder = "generated-code/qt5cpp"; - /** + /* * Models. You can write model files using the modelTemplateFiles map. * if you want to create one template for file, you can do so here. * for multiple files for model, just put another entry in the `modelTemplateFiles` with @@ -55,7 +55,7 @@ public Qt5CPPGenerator() { "model-body.mustache", ".cpp"); - /** + /* * 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 @@ -68,13 +68,13 @@ public Qt5CPPGenerator() { "api-body.mustache", // the template to use ".cpp"); // the extension for each file to write - /** + /* * 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. */ embeddedTemplateDir = templateDir = "qt5cpp"; - /** + /* * Reserved words. Override this with reserved words specific to your language */ setReservedWordsLowerCase( @@ -83,14 +83,14 @@ public Qt5CPPGenerator() { "sample2") ); - /** + /* * Additional Properties. These values can be passed to the templates and * are available in models, apis, and supporting files */ additionalProperties.put("apiVersion", apiVersion); additionalProperties().put("prefix", PREFIX); - /** + /* * Language Specific Primitives. These types will not trigger imports by * the client generator */ 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 1bcadeef9ef..f67b928f870 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 @@ -175,7 +175,7 @@ public void processOpts() { additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); } else { additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf((String)additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); } if (additionalProperties.containsKey(GEM_NAME)) { @@ -568,7 +568,7 @@ public String toEnumValue(String value, String datatype) { public String toEnumVarName(String name, String datatype) { // number if ("Integer".equals(datatype) || "Float".equals(datatype)) { - String varName = new String(name); + String varName = name; varName = varName.replaceAll("-", "MINUS_"); varName = varName.replaceAll("\\+", "PLUS_"); varName = varName.replaceAll("\\.", "_DOT_"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java index 5cf8b65c5ff..348f6cec727 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java @@ -233,7 +233,7 @@ public void preprocessSwagger(Swagger swagger) { } this.additionalProperties.put("serverPort", port); - if (swagger != null && swagger.getPaths() != null) { + if (swagger.getPaths() != null) { for (String pathname : swagger.getPaths().keySet()) { Path path = swagger.getPath(pathname); if (path.getOperations() != null) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java index 287afba9372..c775c8ec8f2 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java @@ -167,7 +167,7 @@ public void processOpts() { additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); } else { additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, - Boolean.valueOf((String)additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); } // Setup project name @@ -538,7 +538,7 @@ public String toEnumVarName(String name, String datatype) { // TODO: this code is probably useless, because the var name is computed from the value in map.put("enum", toSwiftyEnumName(value)); // number if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) { - String varName = new String(name); + String varName = name; varName = varName.replaceAll("-", "MINUS_"); varName = varName.replaceAll("\\+", "PLUS_"); varName = varName.replaceAll("\\.", "_DOT_"); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/testutils/AssertFile.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/testutils/AssertFile.java index f810e20eb0a..aca2beb2dc5 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/testutils/AssertFile.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/testutils/AssertFile.java @@ -113,12 +113,12 @@ public static void assertFilesAreEqual(final Path expected, final Path actual) { if(!deltas.isEmpty()) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("files diff:\n"); - stringBuilder.append("\tfile: '" + expected.toAbsolutePath().toString() + "' \n"); - stringBuilder.append("\tfile: '" + actual.toAbsolutePath().toString() + "' \n"); + stringBuilder.append("\tfile: '").append(expected.toAbsolutePath().toString()).append("' \n"); + stringBuilder.append("\tfile: '").append(actual.toAbsolutePath().toString()).append("' \n"); stringBuilder.append("\tdiffs:\n"); for (Delta delta: deltas) { - stringBuilder.append(delta.toString() + "\n"); + stringBuilder.append(delta.toString()).append("\n"); } fail(stringBuilder.toString()); From 326b8020d20bd793736bb3cde683d085d8d333b7 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 7 Sep 2016 18:55:19 +0800 Subject: [PATCH 335/470] fix property name 'result' for android using "this" --- .../android/libraries/volley/model.mustache | 2 +- .../src/main/resources/android/model.mustache | 2 +- .../httpclient/.swagger-codegen-ignore | 23 ++ .../petstore/android/httpclient/LICENSE | 201 ++++++++++++++++++ .../io/swagger/client/model/Category.java | 4 +- .../java/io/swagger/client/model/Order.java | 12 +- .../java/io/swagger/client/model/Pet.java | 12 +- .../java/io/swagger/client/model/Tag.java | 4 +- .../java/io/swagger/client/model/User.java | 16 +- .../client/petstore/android/volley/README.md | 12 +- .../petstore/android/volley/docs/PetApi.md | 2 +- .../java/io/swagger/client/ApiInvoker.java | 2 +- .../java/io/swagger/client/api/PetApi.java | 4 +- .../io/swagger/client/model/Category.java | 4 +- .../java/io/swagger/client/model/Order.java | 12 +- .../java/io/swagger/client/model/Pet.java | 12 +- .../java/io/swagger/client/model/Tag.java | 4 +- .../java/io/swagger/client/model/User.java | 16 +- 18 files changed, 284 insertions(+), 60 deletions(-) create mode 100644 samples/client/petstore/android/httpclient/.swagger-codegen-ignore create mode 100644 samples/client/petstore/android/httpclient/LICENSE diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/model.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/model.mustache index 0eb066cb6f2..22d7435b325 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/model.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/model.mustache @@ -57,7 +57,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { public int hashCode() { int result = 17; {{#vars}} - result = 31 * result + ({{name}} == null ? 0: {{name}}.hashCode());{{#hasMore}}{{/hasMore}} + result = 31 * result + (this.{{name}} == null ? 0: this.{{name}}.hashCode()); {{/vars}} return result; } diff --git a/modules/swagger-codegen/src/main/resources/android/model.mustache b/modules/swagger-codegen/src/main/resources/android/model.mustache index 701af6de43b..1b4d62b4468 100644 --- a/modules/swagger-codegen/src/main/resources/android/model.mustache +++ b/modules/swagger-codegen/src/main/resources/android/model.mustache @@ -56,7 +56,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { public int hashCode() { int result = 17; {{#vars}} - result = 31 * result + ({{name}} == null ? 0: {{name}}.hashCode());{{#hasMore}}{{/hasMore}} + result = 31 * result + (this.{{name}} == null ? 0: this.{{name}}.hashCode()); {{/vars}} return result; } diff --git a/samples/client/petstore/android/httpclient/.swagger-codegen-ignore b/samples/client/petstore/android/httpclient/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore/android/httpclient/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/android/httpclient/LICENSE b/samples/client/petstore/android/httpclient/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/android/httpclient/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Category.java index eb8367eb21b..eb9f643efe0 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Category.java @@ -50,8 +50,8 @@ public boolean equals(Object o) { @Override public int hashCode() { int result = 17; - result = 31 * result + (id == null ? 0: id.hashCode()); - result = 31 * result + (name == null ? 0: name.hashCode()); + result = 31 * result + (this.id == null ? 0: this.id.hashCode()); + result = 31 * result + (this.name == null ? 0: this.name.hashCode()); return result; } diff --git a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Order.java index bd92826b56b..5fe60f1bf56 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Order.java @@ -107,12 +107,12 @@ public boolean equals(Object o) { @Override public int hashCode() { int result = 17; - result = 31 * result + (id == null ? 0: id.hashCode()); - result = 31 * result + (petId == null ? 0: petId.hashCode()); - result = 31 * result + (quantity == null ? 0: quantity.hashCode()); - result = 31 * result + (shipDate == null ? 0: shipDate.hashCode()); - result = 31 * result + (status == null ? 0: status.hashCode()); - result = 31 * result + (complete == null ? 0: complete.hashCode()); + result = 31 * result + (this.id == null ? 0: this.id.hashCode()); + result = 31 * result + (this.petId == null ? 0: this.petId.hashCode()); + result = 31 * result + (this.quantity == null ? 0: this.quantity.hashCode()); + result = 31 * result + (this.shipDate == null ? 0: this.shipDate.hashCode()); + result = 31 * result + (this.status == null ? 0: this.status.hashCode()); + result = 31 * result + (this.complete == null ? 0: this.complete.hashCode()); return result; } diff --git a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Pet.java index 26662c6cfd6..8795964a6b3 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Pet.java @@ -109,12 +109,12 @@ public boolean equals(Object o) { @Override public int hashCode() { int result = 17; - result = 31 * result + (id == null ? 0: id.hashCode()); - result = 31 * result + (category == null ? 0: category.hashCode()); - result = 31 * result + (name == null ? 0: name.hashCode()); - result = 31 * result + (photoUrls == null ? 0: photoUrls.hashCode()); - result = 31 * result + (tags == null ? 0: tags.hashCode()); - result = 31 * result + (status == null ? 0: status.hashCode()); + result = 31 * result + (this.id == null ? 0: this.id.hashCode()); + result = 31 * result + (this.category == null ? 0: this.category.hashCode()); + result = 31 * result + (this.name == null ? 0: this.name.hashCode()); + result = 31 * result + (this.photoUrls == null ? 0: this.photoUrls.hashCode()); + result = 31 * result + (this.tags == null ? 0: this.tags.hashCode()); + result = 31 * result + (this.status == null ? 0: this.status.hashCode()); return result; } diff --git a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Tag.java index d6c78a74629..3729c3674fb 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Tag.java @@ -50,8 +50,8 @@ public boolean equals(Object o) { @Override public int hashCode() { int result = 17; - result = 31 * result + (id == null ? 0: id.hashCode()); - result = 31 * result + (name == null ? 0: name.hashCode()); + result = 31 * result + (this.id == null ? 0: this.id.hashCode()); + result = 31 * result + (this.name == null ? 0: this.name.hashCode()); return result; } diff --git a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/User.java index ea7018078dd..4f789b5e359 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/User.java @@ -129,14 +129,14 @@ public boolean equals(Object o) { @Override public int hashCode() { int result = 17; - result = 31 * result + (id == null ? 0: id.hashCode()); - result = 31 * result + (username == null ? 0: username.hashCode()); - result = 31 * result + (firstName == null ? 0: firstName.hashCode()); - result = 31 * result + (lastName == null ? 0: lastName.hashCode()); - result = 31 * result + (email == null ? 0: email.hashCode()); - result = 31 * result + (password == null ? 0: password.hashCode()); - result = 31 * result + (phone == null ? 0: phone.hashCode()); - result = 31 * result + (userStatus == null ? 0: userStatus.hashCode()); + result = 31 * result + (this.id == null ? 0: this.id.hashCode()); + result = 31 * result + (this.username == null ? 0: this.username.hashCode()); + result = 31 * result + (this.firstName == null ? 0: this.firstName.hashCode()); + result = 31 * result + (this.lastName == null ? 0: this.lastName.hashCode()); + result = 31 * result + (this.email == null ? 0: this.email.hashCode()); + result = 31 * result + (this.password == null ? 0: this.password.hashCode()); + result = 31 * result + (this.phone == null ? 0: this.phone.hashCode()); + result = 31 * result + (this.userStatus == null ? 0: this.userStatus.hashCode()); return result; } diff --git a/samples/client/petstore/android/volley/README.md b/samples/client/petstore/android/volley/README.md index 7693866ff60..c92f468b12b 100644 --- a/samples/client/petstore/android/volley/README.md +++ b/samples/client/petstore/android/volley/README.md @@ -116,6 +116,12 @@ Class | Method | HTTP request | Description ## Documentation for Authorization Authentication schemes defined for the API: +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + ### petstore_auth - **Type**: OAuth @@ -125,12 +131,6 @@ Authentication schemes defined for the API: - write:pets: modify pets in your account - read:pets: read your pets -### api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - ## Recommendation diff --git a/samples/client/petstore/android/volley/docs/PetApi.md b/samples/client/petstore/android/volley/docs/PetApi.md index ff596b3d918..e7b393c8ea7 100644 --- a/samples/client/petstore/android/volley/docs/PetApi.md +++ b/samples/client/petstore/android/volley/docs/PetApi.md @@ -222,7 +222,7 @@ Name | Type | Description | Notes ### Authorization -[petstore_auth](../README.md#petstore_auth), [api_key](../README.md#api_key) +[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) ### HTTP request headers diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiInvoker.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiInvoker.java index ec17f4582d4..b68e7e0ebfb 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiInvoker.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiInvoker.java @@ -214,9 +214,9 @@ public static void initializeInstance(Cache cache, Network network, int threadPo // Setup authentications (key: authentication name, value: authentication). INSTANCE.authentications = new HashMap(); + INSTANCE.authentications.put("api_key", new ApiKeyAuth("header", "api_key")); // TODO: comment out below as OAuth does not exist //INSTANCE.authentications.put("petstore_auth", new OAuth()); - INSTANCE.authentications.put("api_key", new ApiKeyAuth("header", "api_key")); // Prevent the authentications from being modified. INSTANCE.authentications = Collections.unmodifiableMap(INSTANCE.authentications); } diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/PetApi.java index 5ef1079981a..ae9bcead7c5 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/PetApi.java @@ -623,7 +623,7 @@ public Pet getPetById (Long petId) throws TimeoutException, ExecutionException, // normal form params } - String[] authNames = new String[] { "petstore_auth", "api_key" }; + String[] authNames = new String[] { "api_key", "petstore_auth" }; try { String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); @@ -693,7 +693,7 @@ public void getPetById (Long petId, final Response.Listener responseListene // normal form params } - String[] authNames = new String[] { "petstore_auth", "api_key" }; + String[] authNames = new String[] { "api_key", "petstore_auth" }; try { apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames, diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Category.java index 70342c4d4fd..6e2348fa509 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Category.java @@ -74,8 +74,8 @@ public boolean equals(Object o) { @Override public int hashCode() { int result = 17; - result = 31 * result + (id == null ? 0: id.hashCode()); - result = 31 * result + (name == null ? 0: name.hashCode()); + result = 31 * result + (this.id == null ? 0: this.id.hashCode()); + result = 31 * result + (this.name == null ? 0: this.name.hashCode()); return result; } diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Order.java index dae063be65a..50809231d23 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Order.java @@ -131,12 +131,12 @@ public boolean equals(Object o) { @Override public int hashCode() { int result = 17; - result = 31 * result + (id == null ? 0: id.hashCode()); - result = 31 * result + (petId == null ? 0: petId.hashCode()); - result = 31 * result + (quantity == null ? 0: quantity.hashCode()); - result = 31 * result + (shipDate == null ? 0: shipDate.hashCode()); - result = 31 * result + (status == null ? 0: status.hashCode()); - result = 31 * result + (complete == null ? 0: complete.hashCode()); + result = 31 * result + (this.id == null ? 0: this.id.hashCode()); + result = 31 * result + (this.petId == null ? 0: this.petId.hashCode()); + result = 31 * result + (this.quantity == null ? 0: this.quantity.hashCode()); + result = 31 * result + (this.shipDate == null ? 0: this.shipDate.hashCode()); + result = 31 * result + (this.status == null ? 0: this.status.hashCode()); + result = 31 * result + (this.complete == null ? 0: this.complete.hashCode()); return result; } diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Pet.java index dd9db9ae4c0..7a505ec4e70 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Pet.java @@ -133,12 +133,12 @@ public boolean equals(Object o) { @Override public int hashCode() { int result = 17; - result = 31 * result + (id == null ? 0: id.hashCode()); - result = 31 * result + (category == null ? 0: category.hashCode()); - result = 31 * result + (name == null ? 0: name.hashCode()); - result = 31 * result + (photoUrls == null ? 0: photoUrls.hashCode()); - result = 31 * result + (tags == null ? 0: tags.hashCode()); - result = 31 * result + (status == null ? 0: status.hashCode()); + result = 31 * result + (this.id == null ? 0: this.id.hashCode()); + result = 31 * result + (this.category == null ? 0: this.category.hashCode()); + result = 31 * result + (this.name == null ? 0: this.name.hashCode()); + result = 31 * result + (this.photoUrls == null ? 0: this.photoUrls.hashCode()); + result = 31 * result + (this.tags == null ? 0: this.tags.hashCode()); + result = 31 * result + (this.status == null ? 0: this.status.hashCode()); return result; } diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Tag.java index 92401c61c39..d75041a573c 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Tag.java @@ -74,8 +74,8 @@ public boolean equals(Object o) { @Override public int hashCode() { int result = 17; - result = 31 * result + (id == null ? 0: id.hashCode()); - result = 31 * result + (name == null ? 0: name.hashCode()); + result = 31 * result + (this.id == null ? 0: this.id.hashCode()); + result = 31 * result + (this.name == null ? 0: this.name.hashCode()); return result; } diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/User.java index 2e24880b456..fbaec6578dd 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/User.java @@ -153,14 +153,14 @@ public boolean equals(Object o) { @Override public int hashCode() { int result = 17; - result = 31 * result + (id == null ? 0: id.hashCode()); - result = 31 * result + (username == null ? 0: username.hashCode()); - result = 31 * result + (firstName == null ? 0: firstName.hashCode()); - result = 31 * result + (lastName == null ? 0: lastName.hashCode()); - result = 31 * result + (email == null ? 0: email.hashCode()); - result = 31 * result + (password == null ? 0: password.hashCode()); - result = 31 * result + (phone == null ? 0: phone.hashCode()); - result = 31 * result + (userStatus == null ? 0: userStatus.hashCode()); + result = 31 * result + (this.id == null ? 0: this.id.hashCode()); + result = 31 * result + (this.username == null ? 0: this.username.hashCode()); + result = 31 * result + (this.firstName == null ? 0: this.firstName.hashCode()); + result = 31 * result + (this.lastName == null ? 0: this.lastName.hashCode()); + result = 31 * result + (this.email == null ? 0: this.email.hashCode()); + result = 31 * result + (this.password == null ? 0: this.password.hashCode()); + result = 31 * result + (this.phone == null ? 0: this.phone.hashCode()); + result = 31 * result + (this.userStatus == null ? 0: this.userStatus.hashCode()); return result; } From 4f0f128ddbc6dcb11454c3e72ad78b952d12a660 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 8 Sep 2016 17:30:20 +0800 Subject: [PATCH 336/470] fix enum value issue for jaxrs cxf --- .../languages/JavaCXFServerCodegen.java | 3 + .../JavaJaxRS/cxf/enumClass.mustache | 4 +- .../java/io/swagger/model/ApiResponse.java | 78 ------ .../gen/java/io/swagger/model/Order.java | 3 +- .../gen/java/io/swagger/model/Pet.java | 3 +- samples/server/petstore/jaxrs-cxf/pom.xml | 265 ++++++++++++++++++ 6 files changed, 274 insertions(+), 82 deletions(-) delete mode 100644 samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/ApiResponse.java create mode 100644 samples/server/petstore/jaxrs-cxf/pom.xml diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java index f11821ef2b0..35fae461666 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java @@ -19,6 +19,9 @@ public JavaCXFServerCodegen() outputFolder = "generated-code/JavaJaxRS-CXF"; apiTestTemplateFiles.clear(); // TODO: add test template + //TODO add auto-generated pom.xml for maven + //apiTemplateFiles.put("pom.mustache", "pom.xml"); + // clear model and api doc template as this codegen // does not support auto-generated markdown doc at the moment //TODO: add doc templates diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/enumClass.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/enumClass.mustache index 5d6d4805f8a..94212231156 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/enumClass.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/enumClass.mustache @@ -3,7 +3,7 @@ public enum {{datatypeWithEnum}} { {{#allowableValues}} - {{#enumVars}}{{name}}({{datatype}}.valueOf("{{value}}")){{^-last}}, {{/-last}}{{#-last}};{{/-last}}{{/enumVars}} + {{#enumVars}}{{name}}({{datatype}}.valueOf({{{value}}})){{^-last}}, {{/-last}}{{#-last}};{{/-last}}{{/enumVars}} {{/allowableValues}} @@ -20,4 +20,4 @@ public enum {{datatypeWithEnum}} { public static {{datatypeWithEnum}} fromValue(String v) { return valueOf(v); } -} \ No newline at end of file +} diff --git a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/ApiResponse.java b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/ApiResponse.java deleted file mode 100644 index e6100b2fc6a..00000000000 --- a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/ApiResponse.java +++ /dev/null @@ -1,78 +0,0 @@ -package io.swagger.model; - - - - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlType; - -@XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = - { "code", "type", "message" -}) - -@XmlRootElement(name="ApiResponse") -public class ApiResponse { - - - private Integer code = null; - - private String type = null; - - private String message = null; - - /** - **/ - - public Integer getCode() { - return code; - } - public void setCode(Integer code) { - this.code = code; - } - /** - **/ - - public String getType() { - return type; - } - public void setType(String type) { - this.type = type; - } - /** - **/ - - public String getMessage() { - return message; - } - public void setMessage(String message) { - this.message = message; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ApiResponse {\n"); - - sb.append(" code: ").append(toIndentedString(code)).append("\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" message: ").append(toIndentedString(message)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private static String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - diff --git a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Order.java index 7c6356ec4b5..ef8d3dbfb73 100644 --- a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Order.java @@ -35,7 +35,7 @@ public class Order { @XmlEnum public enum StatusEnum { - PLACED(String.valueOf(""placed"")), APPROVED(String.valueOf(""approved"")), DELIVERED(String.valueOf(""delivered"")); + PLACED(String.valueOf("placed")), APPROVED(String.valueOf("approved")), DELIVERED(String.valueOf("delivered")); private String value; @@ -53,6 +53,7 @@ public static StatusEnum fromValue(String v) { } } + @XmlElement(name="status") private StatusEnum status = null; diff --git a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Pet.java index 52682bcdd0a..dd008ebe5a6 100644 --- a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Pet.java @@ -42,7 +42,7 @@ public class Pet { @XmlEnum public enum StatusEnum { - AVAILABLE(String.valueOf(""available"")), PENDING(String.valueOf(""pending"")), SOLD(String.valueOf(""sold"")); + AVAILABLE(String.valueOf("available")), PENDING(String.valueOf("pending")), SOLD(String.valueOf("sold")); private String value; @@ -60,6 +60,7 @@ public static StatusEnum fromValue(String v) { } } + @XmlElement(name="status") private StatusEnum status = null; diff --git a/samples/server/petstore/jaxrs-cxf/pom.xml b/samples/server/petstore/jaxrs-cxf/pom.xml new file mode 100644 index 00000000000..6b0b2318022 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/pom.xml @@ -0,0 +1,265 @@ + + 4.0.0 + io.swagger + swagger-jaxrs-cxf-server + jar + swagger-jaxrs-cxf-server + 1.0.0 + + gen/main/java + + + org.apache.maven.plugins + maven-war-plugin + 2.1.1 + + + maven-failsafe-plugin + 2.6 + + + + integration-test + verify + + + + + + org.eclipse.jetty + jetty-maven-plugin + ${jetty-version} + + + / + + target/${project.artifactId}-${project.version} + 8079 + stopit + 10 + + 8080 + 60000 + + + + + start-jetty + pre-integration-test + + start + + + 0 + true + + + + stop-jetty + post-integration-test + + stop + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.9.1 + + + add-source + generate-sources + + add-source + + + + gen/java + + + + + + + + + + + + org.springframework + spring-context + ${springframework-version} + + + org.springframework + spring-context-support + ${springframework-version} + + + org.springframework + spring-web + ${springframework-version} + + + + + org.apache.cxf + cxf-rt-frontend-jaxrs + ${cxf-version} + + + + org.apache.cxf + cxf-rt-transports-http + ${cxf-version} + + + + org.apache.cxf + cxf-rt-rs-extension-providers + ${cxf-version} + + + + javax.ws.rs + jsr311-api + 1.1.1 + + + + + org.slf4j + slf4j-api + ${slf4j-version} + + + + + org.slf4j + log4j-over-slf4j + ${slf4j-version} + runtime + + + + org.slf4j + jcl-over-slf4j + ${slf4j-version} + + + + org.slf4j + jul-to-slf4j + ${slf4j-version} + + + + ch.qos.logback + logback-classic + 1.0.9 + runtime + + + + + + + + javax.servlet + servlet-api + ${servlet-api-version} + provided + + + + + org.scala-lang + scala-library + ${scala-version} + + + + org.springframework + spring-test + ${springframework-version} + test + + + + org.apache.cxf + cxf-rt-transports-http-jetty + ${cxf-version} + test + + + + org.scalatest + scalatest_2.10 + ${scala-test-version} + test + + + + junit + junit + ${junit-version} + test + + + + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + true + + + + + 1.7 + ${java.version} + ${java.version} + 1.5.9 + 9.2.9.v20150224 + 1.19.1 + 1.7.21 + 4.12 + 2.5 + UTF-8 + 3.2.1.RELEASE + 2.7.15 + + 1.2 + 2.2 + 1.5.10 + 2.1.4 + 2.10.4 + 2.3.4 + 2.5 + 1.13 + 2.1 + 2.4.2 + 2.4.2 + 1.0.1 + + 4.8.1 + 1.0.0 + 3.2.1 + 1.6.3 + 2.1.3 + 8.1.11.v20130520 + 3.1.5 + 0.90 + 0.90 + 0 + + + From 735390f63366691e8c9029a204d6c838c7b305c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Thu, 8 Sep 2016 12:33:59 +0300 Subject: [PATCH 337/470] [Python, Ruby, PHP] Validate min/maxItems (#3734) * python: Validate min/maxItems * ruby: Validate min/maxItems * lumen: Validate min/maxItems * php: Validate min/maxItems --- .../src/main/resources/lumen/api.mustache | 20 ++++++++++++ .../src/main/resources/php/api.mustache | 10 ++++++ .../main/resources/php/model_generic.mustache | 31 +++++++++++++++++++ .../src/main/resources/python/api.mustache | 8 +++++ .../src/main/resources/python/model.mustache | 8 +++++ .../src/main/resources/ruby/api.mustache | 12 +++++++ .../ruby/partial_model_generic.mustache | 30 ++++++++++++++++++ .../lib/Model/FormatTest.php | 7 +++++ samples/client/petstore/ruby/README.md | 1 - 9 files changed, 126 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/lumen/api.mustache b/modules/swagger-codegen/src/main/resources/lumen/api.mustache index c6b6561624b..277bbcd3df3 100644 --- a/modules/swagger-codegen/src/main/resources/lumen/api.mustache +++ b/modules/swagger-codegen/src/main/resources/lumen/api.mustache @@ -57,6 +57,16 @@ use Illuminate\Support\Facades\Request; throw new \InvalidArgumentException('invalid value for ${{paramName}} when calling {{classname}}.{{operationId}}, must conform to the pattern {{{pattern}}}.'); } {{/pattern}} + {{#maxItems}} + if (count(${{paramName}}]) > {{maxItems}}) { + throw new \InvalidArgumentException('invalid length for ${{paramName}} when calling {{classname}}.{{operationId}}, number of items must be less than or equal to {{maxItems}}.'); + } + {{/maxItems}} + {{#minItems}} + if (count(${{paramName}}]) < {{minItems}}) { + throw new \InvalidArgumentException('invalid length for ${{paramName}} when calling {{classname}}.{{operationId}}, number of items must be greater than or equal to {{minItems}}.'); + } + {{/minItems}} {{/hasValidation}} {{/pathParams}} @@ -95,6 +105,16 @@ use Illuminate\Support\Facades\Request; throw new \InvalidArgumentException('invalid value for ${{paramName}} when calling {{classname}}.{{operationId}}, must conform to the pattern {{{pattern}}}.'); } {{/pattern}} + {{#maxItems}} + if (count($input['{{paramName}}']) > {{maxItems}}) { + throw new \InvalidArgumentException('invalid length for ${{paramName}} when calling {{classname}}.{{operationId}}, number of items must be less than or equal to {{maxItems}}.'); + } + {{/maxItems}} + {{#minItems}} + if (count($input['{{paramName}}']) < {{minItems}}) { + throw new \InvalidArgumentException('invalid length for ${{paramName}} when calling {{classname}}.{{operationId}}, number of items must be greater than or equal to {{minItems}}.'); + } + {{/minItems}} {{/hasValidation}} ${{paramName}} = $input['{{paramName}}']; diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 33059da83b8..b98d1f2db55 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -153,6 +153,16 @@ use \{{invokerPackage}}\ObjectSerializer; throw new \InvalidArgumentException("invalid value for \"{{paramName}}\" when calling {{classname}}.{{operationId}}, must conform to the pattern {{{pattern}}}."); } {{/pattern}} + {{#maxItems}} + if ({{^required}}!is_null(${{paramName}}) && {{/required}}(count(${{paramName}}) > {{maxItems}})) { + throw new \InvalidArgumentException('invalid value for "${{paramName}}" when calling {{classname}}.{{operationId}}, number of items must be less than or equal to {{maxItems}}.'); + } + {{/maxItems}} + {{#minItems}} + if ({{^required}}!is_null(${{paramName}}) && {{/required}}(count(${{paramName}}) < {{minItems}})) { + throw new \InvalidArgumentException('invalid value for "${{paramName}}" when calling {{classname}}.{{operationId}}, number of items must be greater than or equal to {{minItems}}.'); + } + {{/minItems}} {{/hasValidation}} {{/allParams}} diff --git a/modules/swagger-codegen/src/main/resources/php/model_generic.mustache b/modules/swagger-codegen/src/main/resources/php/model_generic.mustache index 372af3af6cc..47f79771a61 100644 --- a/modules/swagger-codegen/src/main/resources/php/model_generic.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model_generic.mustache @@ -160,6 +160,18 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple } {{/pattern}} + {{#maxItems}} + if ({{^required}}!is_null($this->container['{{name}}']) && {{/required}}(count($this->container['{{name}}']) > {{maxItems}})) { + $invalid_properties[] = "invalid value for '{{name}}', number of items must be less than or equal to {{{maxItems}}}."; + } + + {{/maxItems}} + {{#minItems}} + if ({{^required}}!is_null($this->container['{{name}}']) && {{/required}}(count($this->container['{{name}}']) < {{minItems}})) { + $invalid_properties[] = "invalid value for '{{name}}', number of items must be greater than or equal to {{{minItems}}}."; + } + + {{/minItems}} {{/hasValidation}} {{/vars}} return $invalid_properties; @@ -213,6 +225,16 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple return false; } {{/pattern}} + {{#maxItems}} + if (count($this->container['{{name}}']) > {{maxItems}}) { + return false; + } + {{/maxItems}} + {{#minItems}} + if (count($this->container['{{name}}']) < {{minItems}}) { + return false; + } + {{/minItems}} {{/hasValidation}} {{/vars}} return true; @@ -274,6 +296,15 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple throw new \InvalidArgumentException("invalid value for ${{name}} when calling {{classname}}.{{operationId}}, must conform to the pattern {{{pattern}}}."); } {{/pattern}} + {{#maxItems}} + if (count(${{name}}) > {{maxItems}}) { + throw new \InvalidArgumentException('invalid value for ${{name}} when calling {{classname}}.{{operationId}}, number of items must be less than or equal to {{maxItems}}.'); + }{{/maxItems}} + {{#minItems}} + if (count(${{name}}) < {{minItems}}) { + throw new \InvalidArgumentException('invalid length for ${{name}} when calling {{classname}}.{{operationId}}, number of items must be greater than or equal to {{minItems}}.'); + } + {{/minItems}} {{/hasValidation}} $this->container['{{name}}'] = ${{name}}; diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index 34ae38fc615..2d86c9de66c 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -138,6 +138,14 @@ class {{classname}}(object): if '{{paramName}}' in params and not re.search('{{{vendorExtensions.x-regex}}}', params['{{paramName}}']{{#vendorExtensions.x-modifiers}}{{#-first}}, flags={{/-first}}re.{{.}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}): raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must conform to the pattern `{{{pattern}}}`") {{/pattern}} + {{#maxItems}} + if '{{paramName}}' in params and len(params['{{paramName}}']) > {{maxItems}}: + raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, number of items must be less than or equal to `{{maxItems}}`") + {{/maxItems}} + {{#minItems}} + if '{{paramName}}' in params and len(params['{{paramName}}']) < {{minItems}}: + raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, number of items must be greater than or equal to `{{minItems}}`") + {{/minItems}} {{/hasValidation}} {{/allParams}} diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index 3f5c717b0ec..1569b3d37c9 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -92,6 +92,14 @@ class {{classname}}(object): if not re.search('{{{vendorExtensions.x-regex}}}', {{name}}{{#vendorExtensions.x-modifiers}}{{#-first}}, flags={{/-first}}re.{{.}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}): raise ValueError("Invalid value for `{{name}}`, must be a follow pattern or equal to `{{{pattern}}}`") {{/pattern}} +{{#maxItems}} + if len({{name}}) > {{maxItems}}: + raise ValueError("Invalid value for `{{name}}`, number of items must be less than or equal to `{{maxItems}}`") +{{/maxItems}} +{{#minItems}} + if len({{name}}) < {{minItems}}: + raise ValueError("Invalid value for `{{name}}`, number of items must be greater than or equal to `{{minItems}}`") +{{/minItems}} {{/hasValidation}} {{/isEnum}} diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index dc44728259d..7071e72e849 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -86,6 +86,18 @@ module {{moduleName}} end {{/pattern}} + {{#maxItems}} + if {{^required}}!opts[:'{{{paramName}}}'].nil? && {{/required}}{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}}.length > {{{maxItems}}} + fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, number of items must be less than or equal to {{{maxItems}}}.' + end + + {{/maxItems}} + {{#minItems}} + if {{^required}}!opts[:'{{{paramName}}}'].nil? && {{/required}}{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}}.length < {{{minItems}}} + fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, number of items must be greater than or equal to {{{minItems}}}.' + end + + {{/minItems}} {{/hasValidation}} {{/allParams}} # resource path diff --git a/modules/swagger-codegen/src/main/resources/ruby/partial_model_generic.mustache b/modules/swagger-codegen/src/main/resources/ruby/partial_model_generic.mustache index 8463120c7da..20662ae9771 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/partial_model_generic.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/partial_model_generic.mustache @@ -115,6 +115,18 @@ end {{/pattern}} + {{#maxItems}} + if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.length > {{{maxItems}}} + invalid_properties.push("invalid value for '{{{name}}}', number of items must be less than or equal to {{{maxItems}}}." + end + + {{/maxItems}} + {{#minItems}} + if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.length < {{{minItems}}} + invalid_properties.push("invalid value for '{{{name}}}', number of items must be greater than or equal to {{{minItems}}}." + end + + {{/minItems}} {{/hasValidation}} {{/vars}} return invalid_properties @@ -149,6 +161,12 @@ {{#pattern}} return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}} !~ Regexp.new({{{pattern}}}) {{/pattern}} + {{#maxItems}} + return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.length > {{{maxItems}}} + {{/maxItems}} + {{#minItems}} + return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.length < {{{minItems}}} + {{/minItems}} {{/hasValidation}} {{/vars}} return true @@ -210,6 +228,18 @@ end {{/pattern}} + {{#maxItems}} + if {{^required}}!{{{name}}}.nil? && {{/required}}{{{name}}}.length > {{{maxItems}}} + fail ArgumentError, "invalid value for '{{{name}}}', number of items must be less than or equal to {{{maxItems}}}." + end + + {{/maxItems}} + {{#minItems}} + if {{^required}}!{{{name}}}.nil? && {{/required}}{{{name}}}.length < {{{minItems}}} + fail ArgumentError, "invalid value for '{{{name}}}', number of items must be greater than or equal to {{{minItems}}}." + end + + {{/minItems}} @{{{name}}} = {{{name}}} end diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php index 88327ba7195..9fd635feb00 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php @@ -353,6 +353,7 @@ public function setInteger($integer) if ($integer < 10.0) { throw new \InvalidArgumentException('invalid value for $integer when calling FormatTest., must be bigger than or equal to 10.0.'); } + $this->container['integer'] = $integer; return $this; @@ -381,6 +382,7 @@ public function setInt32($int32) if ($int32 < 20.0) { throw new \InvalidArgumentException('invalid value for $int32 when calling FormatTest., must be bigger than or equal to 20.0.'); } + $this->container['int32'] = $int32; return $this; @@ -430,6 +432,7 @@ public function setNumber($number) if ($number < 32.1) { throw new \InvalidArgumentException('invalid value for $number when calling FormatTest., must be bigger than or equal to 32.1.'); } + $this->container['number'] = $number; return $this; @@ -458,6 +461,7 @@ public function setFloat($float) if ($float < 54.3) { throw new \InvalidArgumentException('invalid value for $float when calling FormatTest., must be bigger than or equal to 54.3.'); } + $this->container['float'] = $float; return $this; @@ -486,6 +490,7 @@ public function setDouble($double) if ($double < 67.8) { throw new \InvalidArgumentException('invalid value for $double when calling FormatTest., must be bigger than or equal to 67.8.'); } + $this->container['double'] = $double; return $this; @@ -511,6 +516,7 @@ public function setString($string) if (!preg_match("/[a-z]/i", $string)) { throw new \InvalidArgumentException("invalid value for $string when calling FormatTest., must conform to the pattern /[a-z]/i."); } + $this->container['string'] = $string; return $this; @@ -643,6 +649,7 @@ public function setPassword($password) if (strlen($password) < 10) { throw new \InvalidArgumentException('invalid length for $password when calling FormatTest., must be bigger than or equal to 10.'); } + $this->container['password'] = $password; return $this; diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index 1aa8be7831a..188335045f6 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -8,7 +8,6 @@ This SDK is automatically generated by the [Swagger Codegen](https://github.com/ - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-09-04T00:22:35.922+10:00 - Build package: class io.swagger.codegen.languages.RubyClientCodegen ## Installation From 65ca059221c108bd6a41c24faddd198959167433 Mon Sep 17 00:00:00 2001 From: Paul Ebermann Date: Thu, 8 Sep 2016 12:53:32 +0200 Subject: [PATCH 338/470] Issue #3738: regenerate Scala samples (no code changes). --- .../akka-scala/.swagger-codegen-ignore | 23 + samples/client/petstore/akka-scala/LICENSE | 201 +++++++ .../scala/io/swagger/client/api/PetApi.scala | 2 +- .../async-scala/.swagger-codegen-ignore | 23 + samples/client/petstore/async-scala/LICENSE | 201 +++++++ .../scala/io/swagger/client/api/PetApi.scala | 2 +- samples/server/petstore/scalatra/sbt | 525 ++++++++++++++++++ .../scala/com/wordnik/client/api/PetApi.scala | 2 +- 8 files changed, 976 insertions(+), 3 deletions(-) create mode 100644 samples/client/petstore/akka-scala/.swagger-codegen-ignore create mode 100644 samples/client/petstore/akka-scala/LICENSE create mode 100644 samples/client/petstore/async-scala/.swagger-codegen-ignore create mode 100644 samples/client/petstore/async-scala/LICENSE create mode 100644 samples/server/petstore/scalatra/sbt diff --git a/samples/client/petstore/akka-scala/.swagger-codegen-ignore b/samples/client/petstore/akka-scala/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore/akka-scala/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/akka-scala/LICENSE b/samples/client/petstore/akka-scala/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/akka-scala/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/PetApi.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/PetApi.scala index b59e7f912b4..d6c0d9c08b4 100644 --- a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/PetApi.scala +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/PetApi.scala @@ -6,8 +6,8 @@ package io.swagger.client.api import io.swagger.client.model.Pet -import io.swagger.client.model.ApiResponse import java.io.File +import io.swagger.client.model.ApiResponse import io.swagger.client.core._ import io.swagger.client.core.CollectionFormats._ import io.swagger.client.core.ApiKeyLocations._ diff --git a/samples/client/petstore/async-scala/.swagger-codegen-ignore b/samples/client/petstore/async-scala/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore/async-scala/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/async-scala/LICENSE b/samples/client/petstore/async-scala/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/async-scala/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/PetApi.scala b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/PetApi.scala index b918b0c55f8..3f9576fa8a8 100644 --- a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/PetApi.scala +++ b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/PetApi.scala @@ -1,8 +1,8 @@ package io.swagger.client.api import io.swagger.client.model.Pet -import io.swagger.client.model.ApiResponse import java.io.File +import io.swagger.client.model.ApiResponse import com.wordnik.swagger.client._ import scala.concurrent.Future import collection.mutable diff --git a/samples/server/petstore/scalatra/sbt b/samples/server/petstore/scalatra/sbt new file mode 100644 index 00000000000..08e58821219 --- /dev/null +++ b/samples/server/petstore/scalatra/sbt @@ -0,0 +1,525 @@ +#!/usr/bin/env bash +# +# A more capable sbt runner, coincidentally also called sbt. +# Author: Paul Phillips + +# todo - make this dynamic +declare -r sbt_release_version="0.13.6" +declare -r sbt_unreleased_version="0.13.6" +declare -r buildProps="project/build.properties" + +declare sbt_jar sbt_dir sbt_create sbt_version +declare scala_version sbt_explicit_version +declare verbose noshare batch trace_level log_level +declare sbt_saved_stty debugUs + +echoerr () { echo >&2 "$@"; } +vlog () { [[ -n "$verbose" ]] && echoerr "$@"; } + +# spaces are possible, e.g. sbt.version = 0.13.0 +build_props_sbt () { + [[ -r "$buildProps" ]] && \ + grep '^sbt\.version' "$buildProps" | tr '=' ' ' | awk '{ print $2; }' +} + +update_build_props_sbt () { + local ver="$1" + local old="$(build_props_sbt)" + + [[ -r "$buildProps" ]] && [[ "$ver" != "$old" ]] && { + perl -pi -e "s/^sbt\.version\b.*\$/sbt.version=${ver}/" "$buildProps" + grep -q '^sbt.version[ =]' "$buildProps" || printf "\nsbt.version=%s\n" "$ver" >> "$buildProps" + + vlog "!!!" + vlog "!!! Updated file $buildProps setting sbt.version to: $ver" + vlog "!!! Previous value was: $old" + vlog "!!!" + } +} + +set_sbt_version () { + sbt_version="${sbt_explicit_version:-$(build_props_sbt)}" + [[ -n "$sbt_version" ]] || sbt_version=$sbt_release_version + export sbt_version +} + +# restore stty settings (echo in particular) +onSbtRunnerExit() { + [[ -n "$sbt_saved_stty" ]] || return + vlog "" + vlog "restoring stty: $sbt_saved_stty" + stty "$sbt_saved_stty" + unset sbt_saved_stty +} + +# save stty and trap exit, to ensure echo is reenabled if we are interrupted. +trap onSbtRunnerExit EXIT +sbt_saved_stty="$(stty -g 2>/dev/null)" +vlog "Saved stty: $sbt_saved_stty" + +# this seems to cover the bases on OSX, and someone will +# have to tell me about the others. +get_script_path () { + local path="$1" + [[ -L "$path" ]] || { echo "$path" ; return; } + + local target="$(readlink "$path")" + if [[ "${target:0:1}" == "/" ]]; then + echo "$target" + else + echo "${path%/*}/$target" + fi +} + +die() { + echo "Aborting: $@" + exit 1 +} + +make_url () { + version="$1" + + case "$version" in + 0.7.*) echo "http://simple-build-tool.googlecode.com/files/sbt-launch-0.7.7.jar" ;; + 0.10.* ) echo "$sbt_launch_repo/org.scala-tools.sbt/sbt-launch/$version/sbt-launch.jar" ;; + 0.11.[12]) echo "$sbt_launch_repo/org.scala-tools.sbt/sbt-launch/$version/sbt-launch.jar" ;; + *) echo "$sbt_launch_repo/org.scala-sbt/sbt-launch/$version/sbt-launch.jar" ;; + esac +} + +init_default_option_file () { + local overriding_var="${!1}" + local default_file="$2" + if [[ ! -r "$default_file" && "$overriding_var" =~ ^@(.*)$ ]]; then + local envvar_file="${BASH_REMATCH[1]}" + if [[ -r "$envvar_file" ]]; then + default_file="$envvar_file" + fi + fi + echo "$default_file" +} + +declare -r cms_opts="-XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC" +declare -r jit_opts="-XX:ReservedCodeCacheSize=256m -XX:+TieredCompilation" +declare -r default_jvm_opts_common="-Xms512m -Xmx1536m -Xss2m $jit_opts $cms_opts" +declare -r noshare_opts="-Dsbt.global.base=project/.sbtboot -Dsbt.boot.directory=project/.boot -Dsbt.ivy.home=project/.ivy" +declare -r latest_28="2.8.2" +declare -r latest_29="2.9.3" +declare -r latest_210="2.10.4" +declare -r latest_211="2.11.2" + +declare -r script_path="$(get_script_path "$BASH_SOURCE")" +declare -r script_name="${script_path##*/}" + +# some non-read-onlies set with defaults +declare java_cmd="java" +declare sbt_opts_file="$(init_default_option_file SBT_OPTS .sbtopts)" +declare jvm_opts_file="$(init_default_option_file JVM_OPTS .jvmopts)" +declare sbt_launch_repo="http://typesafe.artifactoryonline.com/typesafe/ivy-releases" + +# pull -J and -D options to give to java. +declare -a residual_args +declare -a java_args +declare -a scalac_args +declare -a sbt_commands + +# args to jvm/sbt via files or environment variables +declare -a extra_jvm_opts extra_sbt_opts + +# if set, use JAVA_HOME over java found in path +[[ -e "$JAVA_HOME/bin/java" ]] && java_cmd="$JAVA_HOME/bin/java" + +# directory to store sbt launchers +declare sbt_launch_dir="$HOME/.sbt/launchers" +[[ -d "$sbt_launch_dir" ]] || mkdir -p "$sbt_launch_dir" +[[ -w "$sbt_launch_dir" ]] || sbt_launch_dir="$(mktemp -d -t sbt_extras_launchers.XXXXXX)" + +java_version () { + local version=$("$java_cmd" -version 2>&1 | grep -e 'java version' | awk '{ print $3 }' | tr -d \") + vlog "Detected Java version: $version" + echo "${version:2:1}" +} + +# MaxPermSize critical on pre-8 jvms but incurs noisy warning on 8+ +default_jvm_opts () { + local v="$(java_version)" + if [[ $v -ge 8 ]]; then + echo "$default_jvm_opts_common" + else + echo "-XX:MaxPermSize=384m $default_jvm_opts_common" + fi +} + +build_props_scala () { + if [[ -r "$buildProps" ]]; then + versionLine="$(grep '^build.scala.versions' "$buildProps")" + versionString="${versionLine##build.scala.versions=}" + echo "${versionString%% .*}" + fi +} + +execRunner () { + # print the arguments one to a line, quoting any containing spaces + vlog "# Executing command line:" && { + for arg; do + if [[ -n "$arg" ]]; then + if printf "%s\n" "$arg" | grep -q ' '; then + printf >&2 "\"%s\"\n" "$arg" + else + printf >&2 "%s\n" "$arg" + fi + fi + done + vlog "" + } + + [[ -n "$batch" ]] && exec /dev/null; then + curl --fail --silent "$url" --output "$jar" + elif which wget >/dev/null; then + wget --quiet -O "$jar" "$url" + fi + } && [[ -r "$jar" ]] +} + +acquire_sbt_jar () { + sbt_url="$(jar_url "$sbt_version")" + sbt_jar="$(jar_file "$sbt_version")" + + [[ -r "$sbt_jar" ]] || download_url "$sbt_url" "$sbt_jar" +} + +usage () { + cat < display stack traces with a max of frames (default: -1, traces suppressed) + -debug-inc enable debugging log for the incremental compiler + -no-colors disable ANSI color codes + -sbt-create start sbt even if current directory contains no sbt project + -sbt-dir path to global settings/plugins directory (default: ~/.sbt/) + -sbt-boot path to shared boot directory (default: ~/.sbt/boot in 0.11+) + -ivy path to local Ivy repository (default: ~/.ivy2) + -no-share use all local caches; no sharing + -offline put sbt in offline mode + -jvm-debug Turn on JVM debugging, open at the given port. + -batch Disable interactive mode + -prompt Set the sbt prompt; in expr, 's' is the State and 'e' is Extracted + + # sbt version (default: sbt.version from $buildProps if present, otherwise $sbt_release_version) + -sbt-force-latest force the use of the latest release of sbt: $sbt_release_version + -sbt-version use the specified version of sbt (default: $sbt_release_version) + -sbt-dev use the latest pre-release version of sbt: $sbt_unreleased_version + -sbt-jar use the specified jar as the sbt launcher + -sbt-launch-dir directory to hold sbt launchers (default: ~/.sbt/launchers) + -sbt-launch-repo repo url for downloading sbt launcher jar (default: $sbt_launch_repo) + + # scala version (default: as chosen by sbt) + -28 use $latest_28 + -29 use $latest_29 + -210 use $latest_210 + -211 use $latest_211 + -scala-home use the scala build at the specified directory + -scala-version use the specified version of scala + -binary-version use the specified scala version when searching for dependencies + + # java version (default: java from PATH, currently $(java -version 2>&1 | grep version)) + -java-home alternate JAVA_HOME + + # passing options to the jvm - note it does NOT use JAVA_OPTS due to pollution + # The default set is used if JVM_OPTS is unset and no -jvm-opts file is found + $(default_jvm_opts) + JVM_OPTS environment variable holding either the jvm args directly, or + the reference to a file containing jvm args if given path is prepended by '@' (e.g. '@/etc/jvmopts') + Note: "@"-file is overridden by local '.jvmopts' or '-jvm-opts' argument. + -jvm-opts file containing jvm args (if not given, .jvmopts in project root is used if present) + -Dkey=val pass -Dkey=val directly to the jvm + -J-X pass option -X directly to the jvm (-J is stripped) + + # passing options to sbt, OR to this runner + SBT_OPTS environment variable holding either the sbt args directly, or + the reference to a file containing sbt args if given path is prepended by '@' (e.g. '@/etc/sbtopts') + Note: "@"-file is overridden by local '.sbtopts' or '-sbt-opts' argument. + -sbt-opts file containing sbt args (if not given, .sbtopts in project root is used if present) + -S-X add -X to sbt's scalacOptions (-S is stripped) +EOM +} + +addJava () { + vlog "[addJava] arg = '$1'" + java_args=( "${java_args[@]}" "$1" ) +} +addSbt () { + vlog "[addSbt] arg = '$1'" + sbt_commands=( "${sbt_commands[@]}" "$1" ) +} +setThisBuild () { + vlog "[addBuild] args = '$@'" + local key="$1" && shift + addSbt "set $key in ThisBuild := $@" +} + +addScalac () { + vlog "[addScalac] arg = '$1'" + scalac_args=( "${scalac_args[@]}" "$1" ) +} +addResidual () { + vlog "[residual] arg = '$1'" + residual_args=( "${residual_args[@]}" "$1" ) +} +addResolver () { + addSbt "set resolvers += $1" +} +addDebugger () { + addJava "-Xdebug" + addJava "-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=$1" +} +setScalaVersion () { + [[ "$1" == *"-SNAPSHOT" ]] && addResolver 'Resolver.sonatypeRepo("snapshots")' + addSbt "++ $1" +} + +process_args () +{ + require_arg () { + local type="$1" + local opt="$2" + local arg="$3" + + if [[ -z "$arg" ]] || [[ "${arg:0:1}" == "-" ]]; then + die "$opt requires <$type> argument" + fi + } + while [[ $# -gt 0 ]]; do + case "$1" in + -h|-help) usage; exit 1 ;; + -v) verbose=true && shift ;; + -d) addSbt "--debug" && shift ;; + -w) addSbt "--warn" && shift ;; + -q) addSbt "--error" && shift ;; + -x) debugUs=true && shift ;; + -trace) require_arg integer "$1" "$2" && trace_level="$2" && shift 2 ;; + -ivy) require_arg path "$1" "$2" && addJava "-Dsbt.ivy.home=$2" && shift 2 ;; + -no-colors) addJava "-Dsbt.log.noformat=true" && shift ;; + -no-share) noshare=true && shift ;; + -sbt-boot) require_arg path "$1" "$2" && addJava "-Dsbt.boot.directory=$2" && shift 2 ;; + -sbt-dir) require_arg path "$1" "$2" && sbt_dir="$2" && shift 2 ;; + -debug-inc) addJava "-Dxsbt.inc.debug=true" && shift ;; + -offline) addSbt "set offline := true" && shift ;; + -jvm-debug) require_arg port "$1" "$2" && addDebugger "$2" && shift 2 ;; + -batch) batch=true && shift ;; + -prompt) require_arg "expr" "$1" "$2" && setThisBuild shellPrompt "(s => { val e = Project.extract(s) ; $2 })" && shift 2 ;; + + -sbt-create) sbt_create=true && shift ;; + -sbt-jar) require_arg path "$1" "$2" && sbt_jar="$2" && shift 2 ;; + -sbt-version) require_arg version "$1" "$2" && sbt_explicit_version="$2" && shift 2 ;; + -sbt-force-latest) sbt_explicit_version="$sbt_release_version" && shift ;; + -sbt-dev) sbt_explicit_version="$sbt_unreleased_version" && shift ;; + -sbt-launch-dir) require_arg path "$1" "$2" && sbt_launch_dir="$2" && shift 2 ;; + -sbt-launch-repo) require_arg path "$1" "$2" && sbt_launch_repo="$2" && shift 2 ;; + -scala-version) require_arg version "$1" "$2" && setScalaVersion "$2" && shift 2 ;; + -binary-version) require_arg version "$1" "$2" && setThisBuild scalaBinaryVersion "\"$2\"" && shift 2 ;; + -scala-home) require_arg path "$1" "$2" && setThisBuild scalaHome "Some(file(\"$2\"))" && shift 2 ;; + -java-home) require_arg path "$1" "$2" && java_cmd="$2/bin/java" && shift 2 ;; + -sbt-opts) require_arg path "$1" "$2" && sbt_opts_file="$2" && shift 2 ;; + -jvm-opts) require_arg path "$1" "$2" && jvm_opts_file="$2" && shift 2 ;; + + -D*) addJava "$1" && shift ;; + -J*) addJava "${1:2}" && shift ;; + -S*) addScalac "${1:2}" && shift ;; + -28) setScalaVersion "$latest_28" && shift ;; + -29) setScalaVersion "$latest_29" && shift ;; + -210) setScalaVersion "$latest_210" && shift ;; + -211) setScalaVersion "$latest_211" && shift ;; + + *) addResidual "$1" && shift ;; + esac + done +} + +# process the direct command line arguments +process_args "$@" + +# skip #-styled comments and blank lines +readConfigFile() { + while read line; do + [[ $line =~ ^# ]] || [[ -z $line ]] || echo "$line" + done < "$1" +} + +# if there are file/environment sbt_opts, process again so we +# can supply args to this runner +if [[ -r "$sbt_opts_file" ]]; then + vlog "Using sbt options defined in file $sbt_opts_file" + while read opt; do extra_sbt_opts+=("$opt"); done < <(readConfigFile "$sbt_opts_file") +elif [[ -n "$SBT_OPTS" && ! ("$SBT_OPTS" =~ ^@.*) ]]; then + vlog "Using sbt options defined in variable \$SBT_OPTS" + extra_sbt_opts=( $SBT_OPTS ) +else + vlog "No extra sbt options have been defined" +fi + +[[ -n "${extra_sbt_opts[*]}" ]] && process_args "${extra_sbt_opts[@]}" + +# reset "$@" to the residual args +set -- "${residual_args[@]}" +argumentCount=$# + +# set sbt version +set_sbt_version + +# only exists in 0.12+ +setTraceLevel() { + case "$sbt_version" in + "0.7."* | "0.10."* | "0.11."* ) echoerr "Cannot set trace level in sbt version $sbt_version" ;; + *) setThisBuild traceLevel $trace_level ;; + esac +} + +# set scalacOptions if we were given any -S opts +[[ ${#scalac_args[@]} -eq 0 ]] || addSbt "set scalacOptions in ThisBuild += \"${scalac_args[@]}\"" + +# Update build.properties on disk to set explicit version - sbt gives us no choice +[[ -n "$sbt_explicit_version" ]] && update_build_props_sbt "$sbt_explicit_version" +vlog "Detected sbt version $sbt_version" + +[[ -n "$scala_version" ]] && vlog "Overriding scala version to $scala_version" + +# no args - alert them there's stuff in here +(( argumentCount > 0 )) || { + vlog "Starting $script_name: invoke with -help for other options" + residual_args=( shell ) +} + +# verify this is an sbt dir or -create was given +[[ -r ./build.sbt || -d ./project || -n "$sbt_create" ]] || { + cat < Date: Thu, 8 Sep 2016 18:01:18 +0200 Subject: [PATCH 339/470] Added anchor tag in README.mustache issue #3748. --- .../swagger-codegen/src/main/resources/csharp/README.mustache | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/swagger-codegen/src/main/resources/csharp/README.mustache b/modules/swagger-codegen/src/main/resources/csharp/README.mustache index 7c8a3df52df..89af5dd54cc 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/README.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/README.mustache @@ -139,6 +139,7 @@ Authentication schemes defined for the API: {{/last}} {{/authMethods}} {{#authMethods}} + ### {{name}} {{#isApiKey}}- **Type**: API key From f90626ac818aebca9838d397e40482425619728c Mon Sep 17 00:00:00 2001 From: Artem Ocheredko Date: Fri, 9 Sep 2016 10:44:54 +0300 Subject: [PATCH 340/470] [Erlang] Add Erlang server generator (#3758) * Initial erlang generation * Recfactor erlang codegen to make a minimal working example * ft/erlang_codegen Separate handlers by resourse, add minor codegen fixes and refactoring * Test commit * ft/erlang_codegen Modify reouting generation * ft/erlang_codegen Remove parsed request concept. Add minor refactoring and bugfixes * ft/erlang_codegen Use swagger spec from an internal directory instead of a provided path * ft/erlang_codegen Add basic response validation * ft/erlang_codegen Moved all the req validators to a separate file for test needs * ft/erlang_codegen Add basic param validation * Add refactoring: OperationIDs are atoms now Fix schema validation Add todo list * CAPI-23 Add auth context to request handling (#2) * CAPI-23 Fix routing to support different paths in one handler. Add auth context to request handling. Add an opportunity to pass custom middlewares to the server * CAPI-31 Add enum validation and some minor fixes (#4) * CAPI-31 Fix turbo fuck up with additional params (#5) * Capi 23/fix/basic logging (#6) * CAPI-23 Add understandable messages in case of bad requests. Add specs to shut up dialyzer and add some minor code refactoring * CAPI-23 Fix missed bracket in auth module (#7) --- .../languages/ErlangServerCodegen.java | 267 ++++++++++++++ .../services/io.swagger.codegen.CodegenConfig | 1 + .../resources/erlang-server/README.mustache | 12 + .../main/resources/erlang-server/api.mustache | 345 ++++++++++++++++++ .../resources/erlang-server/app.src.mustache | 19 + .../resources/erlang-server/auth.mustache | 50 +++ .../default_logic_handler.mustache | 32 ++ .../resources/erlang-server/handler.mustache | 230 ++++++++++++ .../erlang-server/logic_handler.mustache | 50 +++ .../erlang-server/rebar.config.mustache | 4 + .../resources/erlang-server/router.mustache | 74 ++++ .../resources/erlang-server/server.mustache | 64 ++++ .../resources/erlang-server/swagger.mustache | 1 + .../resources/erlang-server/utils.mustache | 173 +++++++++ 14 files changed, 1322 insertions(+) create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ErlangServerCodegen.java create mode 100644 modules/swagger-codegen/src/main/resources/erlang-server/README.mustache create mode 100644 modules/swagger-codegen/src/main/resources/erlang-server/api.mustache create mode 100644 modules/swagger-codegen/src/main/resources/erlang-server/app.src.mustache create mode 100644 modules/swagger-codegen/src/main/resources/erlang-server/auth.mustache create mode 100644 modules/swagger-codegen/src/main/resources/erlang-server/default_logic_handler.mustache create mode 100644 modules/swagger-codegen/src/main/resources/erlang-server/handler.mustache create mode 100644 modules/swagger-codegen/src/main/resources/erlang-server/logic_handler.mustache create mode 100644 modules/swagger-codegen/src/main/resources/erlang-server/rebar.config.mustache create mode 100644 modules/swagger-codegen/src/main/resources/erlang-server/router.mustache create mode 100644 modules/swagger-codegen/src/main/resources/erlang-server/server.mustache create mode 100644 modules/swagger-codegen/src/main/resources/erlang-server/swagger.mustache create mode 100644 modules/swagger-codegen/src/main/resources/erlang-server/utils.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ErlangServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ErlangServerCodegen.java new file mode 100644 index 00000000000..d510b42fac2 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ErlangServerCodegen.java @@ -0,0 +1,267 @@ +package io.swagger.codegen.languages; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.module.SimpleModule; +import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.Lists; +import com.google.common.collect.Multimap; +import io.swagger.codegen.*; +import io.swagger.models.*; +import io.swagger.util.Json; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.*; +import java.util.Map.Entry; +import org.apache.commons.lang3.StringUtils; + +public class ErlangServerCodegen extends DefaultCodegen implements CodegenConfig { + + private static final Logger LOGGER = LoggerFactory.getLogger(ErlangServerCodegen.class); + + protected String apiVersion = "1.0.0"; + protected String apiPath = "src"; + protected String packageName = "swagger"; + + public ErlangServerCodegen() { + super(); + + // set the output folder here + outputFolder = "generated-code/erlang-server"; + + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { + setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); + } else { + additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); + }; + + /** + * Models. You can write model files using the modelTemplateFiles map. + * if you want to create one template for file, you can do so here. + * for multiple files for model, just put another entry in the `modelTemplateFiles` with + * a different extension + */ + modelTemplateFiles.clear(); + + /** + * 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( + "handler.mustache", // the template to use + ".erl"); // the extension for each file to write + + /** + * 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. + */ + embeddedTemplateDir = templateDir = "erlang-server"; + + /** + * Reserved words. Override this with reserved words specific to your language + */ + setReservedWordsLowerCase( + Arrays.asList( + "after","and","andalso","band","begin","bnot","bor","bsl","bsr","bxor","case", + "catch","cond","div","end","fun","if","let","not","of","or","orelse","receive", + "rem","try","when","xor" + ) + ); + + instantiationTypes.clear(); + + typeMapping.clear(); + typeMapping.put("enum", "binary"); + typeMapping.put("date", "date"); + typeMapping.put("datetime", "datetime"); + typeMapping.put("boolean", "boolean"); + typeMapping.put("string", "binary"); + typeMapping.put("integer", "integer"); + typeMapping.put("int", "integer"); + typeMapping.put("float", "integer"); + typeMapping.put("long", "integer"); + typeMapping.put("double", "float"); + typeMapping.put("array", "list"); + typeMapping.put("map", "map"); + typeMapping.put("number", "integer"); + typeMapping.put("bigdecimal", "float"); + typeMapping.put("List", "list"); + typeMapping.put("object", "object"); + typeMapping.put("file", "file"); + typeMapping.put("binary", "binary"); + typeMapping.put("bytearray", "binary"); + typeMapping.put("byte", "binary"); + typeMapping.put("uuid", "binary"); + typeMapping.put("password", "binary"); + + cliOptions.clear(); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Erlang package name (convention: lowercase).") + .defaultValue(this.packageName)); + /** + * Additional Properties. These values can be passed to the templates and + * are available in models, apis, and supporting files + */ + additionalProperties.put("apiVersion", apiVersion); + additionalProperties.put("apiPath", apiPath); + /** + * Supporting Files. You can write single files for the generator with the + * entire object tree available. If the input file has a suffix of `.mustache + * it will be processed by the template engine. Otherwise, it will be copied + */ + supportingFiles.add(new SupportingFile("rebar.config.mustache","", "rebar.config")); + supportingFiles.add(new SupportingFile("app.src.mustache", "", "src" + File.separator + this.packageName + ".app.src")); + supportingFiles.add(new SupportingFile("router.mustache", "", toSourceFilePath("router", "erl"))); + supportingFiles.add(new SupportingFile("api.mustache", "", toSourceFilePath("api", "erl"))); + supportingFiles.add(new SupportingFile("server.mustache", "", toSourceFilePath("server", "erl"))); + supportingFiles.add(new SupportingFile("utils.mustache", "", toSourceFilePath("utils", "erl"))); + supportingFiles.add(new SupportingFile("auth.mustache", "", toSourceFilePath("auth", "erl"))); + supportingFiles.add(new SupportingFile("swagger.mustache", "", toPrivFilePath("swagger", "json"))); + supportingFiles.add(new SupportingFile("default_logic_handler.mustache", "", toSourceFilePath("default_logic_handler", "erl"))); + supportingFiles.add(new SupportingFile("logic_handler.mustache", "", toSourceFilePath("logic_handler", "erl"))); + writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md")); + } + + @Override + public String apiPackage() { + return apiPath; + } + + /** + * Configures the type of generator. + * + * @return the CodegenType for this generator + * @see io.swagger.codegen.CodegenType + */ + @Override + public CodegenType getTag() { + return CodegenType.SERVER; + } + + /** + * 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 + */ + @Override + public String getName() { + return "erlang-server"; + } + + /** + * Returns human-friendly help for the generator. Provide the consumer with help + * tips, parameters here + * + * @return A string value for the help message + */ + @Override + public String getHelp() { + return "Generates an Erlang server library using the swagger-tools project. By default, " + + "it will also generate service classes--which you can disable with the `-Dnoservice` environment variable."; + } + + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return this.packageName + "_default_handler"; + } + return this.packageName + "_" + underscore(name) + "_handler"; + } + + /** + * 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 api files. You can use the apiPackage() as defined when the class is + * instantiated + */ + @Override + public String apiFileFolder() { + return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar); + } + + @Override + public String toModelName(String name) { + return camelize(toModelFilename(name)); + } + + @Override + public String toOperationId(String operationId) { + // method name cannot use reserved keyword, e.g. return + if (isReservedWord(operationId)) { + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId))); + operationId = "call_" + operationId; + } + + return camelize(operationId); + } + + @Override + public String toApiFilename(String name) { + return toHandlerName(name); + } + + @Override + public Map postProcessOperations(Map objs) { + Map operations = (Map) objs.get("operations"); + List operationList = (List) operations.get("operation"); + for (CodegenOperation op : operationList) { + if (op.path != null) { + op.path = op.path.replaceAll("\\{(.*?)\\}", ":$1"); + } + } + return objs; + } + + @Override + public Map postProcessSupportingFileData(Map objs) { + Swagger swagger = (Swagger)objs.get("swagger"); + if(swagger != null) { + try { + objs.put("swagger-json", Json.mapper().writeValueAsString(swagger)); + } catch (JsonProcessingException e) { + LOGGER.error(e.getMessage(), e); + } + } + return super.postProcessSupportingFileData(objs); + } + + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + protected String toHandlerName(String name) { + return toModuleName(name) + "_handler"; + } + + protected String toModuleName(String name) { + return this.packageName + "_" + underscore(name.replaceAll("-", "_")); + } + + protected String toSourceFilePath(String name, String extension) { + return "src" + File.separator + toModuleName(name) + "." + extension; + } + + protected String toIncludeFilePath(String name, String extension) { + return "include" + File.separator + toModuleName(name) + "." + extension; + } + + protected String toPrivFilePath(String name, String extension) { + return "priv" + File.separator + name + "." + extension; + } +} 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 9d512284bda..764b4b26b53 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 @@ -51,3 +51,4 @@ io.swagger.codegen.languages.ClojureClientCodegen io.swagger.codegen.languages.HaskellServantCodegen io.swagger.codegen.languages.LumenServerCodegen io.swagger.codegen.languages.GoServerCodegen +io.swagger.codegen.languages.ErlangServerCodegen diff --git a/modules/swagger-codegen/src/main/resources/erlang-server/README.mustache b/modules/swagger-codegen/src/main/resources/erlang-server/README.mustache new file mode 100644 index 00000000000..d9858d4cc03 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/erlang-server/README.mustache @@ -0,0 +1,12 @@ +# Swagger rest server library for Erlang + +## TODO +- [ ] Write specs for static exported fuctions +- [ ] Write specs for generated exported fuctions +- [ ] Add datetime/date validation +- [ ] Separate gigantic `api` to submodules and refactor the routing +- [ ] Add tests for the validators +- [ ] Add integrational test for the whole cycle +- [ ] Add validations of definitions with inheritance +- [ ] Add proper response validation (this `list` hack is so weird) +- [ ] Fix enum validation. It doesn't work correctly when the parans is in qs/header diff --git a/modules/swagger-codegen/src/main/resources/erlang-server/api.mustache b/modules/swagger-codegen/src/main/resources/erlang-server/api.mustache new file mode 100644 index 00000000000..355cfad6dae --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/erlang-server/api.mustache @@ -0,0 +1,345 @@ +-module({{packageName}}_api). + +-export([request_params/1]). +-export([request_param_info/2]). +-export([populate_request/3]). +-export([validate_response/4]). + +-type operation_id() :: atom(). +-type request_param() :: atom(). + +-export_type([operation_id/0]). + +-spec request_params(OperationID :: operation_id()) -> [Param :: request_param()]. +{{#apiInfo}}{{#apis}} +{{#operations}}{{#operation}} +request_params('{{operationId}}') -> + [{{#allParams}}{{^isBodyParam}} + '{{baseName}}'{{/isBodyParam}}{{#isBodyParam}} + '{{dataType}}'{{/isBodyParam}}{{#hasMore}},{{/hasMore}}{{/allParams}} + ]; +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} +request_params(_) -> + error(unknown_operation). + +-type rule() :: + {type, 'binary'} | + {type, 'integer'} | + {type, 'float'} | + {type, 'binary'} | + {type, 'boolean'} | + {type, 'date'} | + {type, 'datetime'} | + {enum, [atom()]} | + {max, Max :: number()} | + {exclusive_max, Max :: number()} | + {min, Min :: number()} | + {exclusive_min, Min :: number()} | + {max_length, MaxLength :: integer()} | + {min_length, MaxLength :: integer()} | + {pattern, Pattern :: string()} | + schema | + required | + not_required. + +-spec request_param_info(OperationID :: operation_id(), Name :: request_param()) -> #{ + source => qs_val | binding | header | body, + rules => [rule()] +}. + +{{#apiInfo}}{{#apis}} +{{#operations}}{{#operation}}{{#allParams}} +request_param_info('{{operationId}}', {{^isBodyParam}}'{{baseName}}'{{/isBodyParam}}{{#isBodyParam}}'{{dataType}}'{{/isBodyParam}}) -> + #{ + source => {{#isQueryParam}}qs_val{{/isQueryParam}} {{#isPathParam}}binding{{/isPathParam}} {{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}, + rules => [{{#isString}} + {type, 'binary'},{{/isString}}{{#isInteger}} + {type, 'integer'},{{/isInteger}}{{#isLong}} + {type, 'integer'},{{/isLong}}{{#isFloat}} + {type, 'float'},{{/isFloat}}{{#isDouble}} + {type, 'float'},{{/isDouble}}{{#isByteArray}} + {type, 'binary'},{{/isByteArray}}{{#isBinary}} + {type, 'binary'},{{/isBinary}}{{#isBoolean}} + {type, 'boolean'},{{/isBoolean}}{{#isDate}} + {type, 'date'},{{/isDate}}{{#isDateTime}} + {type, 'datetime'},{{/isDateTime}}{{#isEnum}} + {enum, [{{#allowableValues}}{{#values}}'{{.}}'{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}] },{{/isEnum}}{{#maximum}} + {max, {{maximum}} }, {{/maximum}}{{#exclusiveMaximum}} + {exclusive_max, {{exclusiveMaximum}} },{{/exclusiveMaximum}}{{#minimum}} + {min, {{minimum}} },{{/minimum}}{{#exclusiveMinimum}} + {exclusive_min, {{exclusiveMinimum}} },{{/exclusiveMinimum}}{{#maxLength}} + {max_length, {{maxLength}} },{{/maxLength}}{{#minLength}} + {min_length, {{minLength}} },{{/minLength}}{{#pattern}} + {pattern, "{{pattern}}" },{{/pattern}}{{#isBodyParam}} + schema,{{/isBodyParam}}{{#required}} + required{{/required}}{{^required}} + not_required{{/required}} + ] + }; +{{/allParams}}{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} +request_param_info(OperationID, Name) -> + error({unknown_param, OperationID, Name}). + +-spec populate_request( + OperationID :: operation_id(), + Req :: cowboy_req:req(), + ValidatorState :: jesse_state:state() +) -> + {ok, Model :: #{}, Req :: cowboy_req:req()} | + {error, Reason :: any(), Req :: cowboy_req:req()}. + +populate_request(OperationID, Req, ValidatorState) -> + Params = request_params(OperationID), + populate_request_params(OperationID, Params, Req, ValidatorState, #{}). + +populate_request_params(_, [], Req, _, Model) -> + {ok, Model, Req}; + +populate_request_params(OperationID, [FieldParams | T], Req0, ValidatorState, Model) -> + case populate_request_param(OperationID, FieldParams, Req0, ValidatorState) of + {ok, K, V, Req} -> + populate_request_params(OperationID, T, Req, ValidatorState, maps:put(K, V, Model)); + Error -> + Error + end. + +populate_request_param(OperationID, Name, Req0, ValidatorState) -> + #{rules := Rules, source := Source} = request_param_info(OperationID, Name), + {Value, Req} = get_value(Source, Name, Req0), + case prepare_param(Rules, Name, Value, ValidatorState) of + {ok, Result} -> {ok, Name, Result, Req}; + {error, Reason} -> + {error, Reason, Req} + end. + +-spec validate_response( + OperationID :: operation_id(), + Code :: 200..599, + Body :: jesse:json_term(), + ValidatorState :: jesse_state:state() +) -> ok | no_return(). +{{#apiInfo}}{{#apis}} +{{#operations}}{{#operation}} +{{#responses}} +validate_response('{{operationId}}', {{code}}, Body, ValidatorState) -> + validate_response_body('{{dataType}}', '{{baseType}}', Body, ValidatorState); +{{/responses}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + +validate_response(_OperationID, _Code, _Body, _ValidatorState) -> + ok. + +validate_response_body('list', ReturnBaseType, Body, ValidatorState) -> + [ + validate(schema, ReturnBaseType, Item, ValidatorState) + || Item <- Body]; + +validate_response_body(_, ReturnBaseType, Body, ValidatorState) -> + validate(schema, ReturnBaseType, Body, ValidatorState). + +%%% +validate(Rule = required, Name, Value, _ValidatorState) -> + case Value of + undefined -> validation_error(Rule, Name); + _ -> ok + end; + +validate(not_required, _Name, _Value, _ValidatorState) -> + ok; + +validate(_, _Name, undefined, _ValidatorState) -> + ok; + +validate(Rule = {type, 'integer'}, Name, Value, _ValidatorState) -> + try + {ok, {{packageName}}_utils:to_int(Value)} + catch + error:badarg -> + validation_error(Rule, Name) + end; + +validate(Rule = {type, 'float'}, Name, Value, _ValidatorState) -> + try + {ok, {{packageName}}_utils:to_float(Value)} + catch + error:badarg -> + validation_error(Rule, Name) + end; + +validate(Rule = {type, 'binary'}, Name, Value, _ValidatorState) -> + case is_binary(Value) of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(_Rule = {type, 'boolean'}, _Name, Value, _ValidatorState) when is_boolean(Value) -> + {ok, Value}; + +validate(Rule = {type, 'boolean'}, Name, Value, _ValidatorState) -> + V = binary_to_lower(Value), + try + case binary_to_existing_atom(V, utf8) of + B when is_boolean(B) -> {ok, B}; + _ -> validation_error(Rule, Name) + end + catch + error:badarg -> + validation_error(Rule, Name) + end; + +validate(Rule = {type, 'date'}, Name, Value, _ValidatorState) -> + case is_binary(Value) of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {type, 'datetime'}, Name, Value, _ValidatorState) -> + case is_binary(Value) of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {enum, Values}, Name, Value, _ValidatorState) -> + try + FormattedValue = erlang:binary_to_existing_atom(Value, utf8), + case lists:member(FormattedValue, Values) of + true -> {ok, FormattedValue}; + false -> validation_error(Rule, Name) + end + catch + error:badarg -> + validation_error(Rule, Name) + end; + +validate(Rule = {max, Max}, Name, Value, _ValidatorState) -> + case Value >= Max of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {exclusive_max, ExclusiveMax}, Name, Value, _ValidatorState) -> + case Value > ExclusiveMax of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {min, Min}, Name, Value, _ValidatorState) -> + case Value =< Min of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {exclusive_min, ExclusiveMin}, Name, Value, _ValidatorState) -> + case Value =< ExclusiveMin of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {max_length, MaxLength}, Name, Value, _ValidatorState) -> + case size(Value) =< MaxLength of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {min_length, MinLength}, Name, Value, _ValidatorState) -> + case size(Value) >= MinLength of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {pattern, Pattern}, Name, Value, _ValidatorState) -> + {ok, MP} = re:compile(Pattern), + case re:run(Value, MP) of + {match, _} -> ok; + _ -> validation_error(Rule, Name) + end; + +validate(Rule = schema, Name, Value, ValidatorState) -> + Definition = list_to_binary("#/definitions/" ++ {{packageName}}_utils:to_list(Name)), + try + _ = validate_with_schema(Value, Definition, ValidatorState), + ok + catch + throw:[{schema_invalid, _, Error} | _] -> + Info = #{ + type => schema_invalid, + error => Error + }, + validation_error(Rule, Name, Info); + throw:[{data_invalid, Schema, Error, _, Path} | _] -> + Info = #{ + type => data_invalid, + error => Error, + schema => Schema, + path => Path + }, + validation_error(Rule, Name, Info) + end; + +validate(Rule, Name, _Value, _ValidatorState) -> + error_logger:info_msg("Can't validate ~p with ~p", [Name, Rule]), + error({unknown_validation_rule, Rule}). + +-spec validation_error(Rule :: any(), Name :: any()) -> no_return(). + +validation_error(ViolatedRule, Name) -> + validation_error(ViolatedRule, Name, #{}). + +-spec validation_error(Rule :: any(), Name :: any(), Info :: #{}) -> no_return(). + +validation_error(ViolatedRule, Name, Info) -> + throw({wrong_param, Name, ViolatedRule, Info}). + +get_value(body, _Name, Req0) -> + {ok, Body, Req} = cowboy_req:body(Req0), + Value = prepare_body(Body), + {Value, Req}; + +get_value(qs_val, Name, Req0) -> + {QS, Req} = cowboy_req:qs_vals(Req0), + Value = {{packageName}}_utils:get_opt({{packageName}}_utils:to_qs(Name), QS), + {Value, Req}; + +get_value(header, Name, Req0) -> + {Headers, Req} = cowboy_req:headers(Req0), + Value = {{packageName}}_utils:get_opt({{packageName}}_utils:to_header(Name), Headers), + {Value, Req}; + +get_value(binding, Name, Req0) -> + {Bindings, Req} = cowboy_req:bindings(Req0), + Value = {{packageName}}_utils:get_opt({{packageName}}_utils:to_binding(Name), Bindings), + {Value, Req}. + +prepare_body(Body) -> + case Body of + <<"">> -> <<"">>; + _ -> jsx:decode(Body, [return_maps]) + end. + +validate_with_schema(Body, Definition, ValidatorState) -> + jesse_schema_validator:validate_with_state( + [{<<"$ref">>, Definition}], + Body, + ValidatorState + ). + +prepare_param(Rules, Name, Value, ValidatorState) -> + try + Result = lists:foldl( + fun(Rule, Acc) -> + case validate(Rule, Name, Acc, ValidatorState) of + ok -> Acc; + {ok, Prepared} -> Prepared + end + end, + Value, + Rules + ), + {ok, Result} + catch + throw:Reason -> + {error, Reason} + end. + +binary_to_lower(V) when is_binary(V) -> + list_to_binary(string:to_lower({{packageName}}_utils:to_list(V))). diff --git a/modules/swagger-codegen/src/main/resources/erlang-server/app.src.mustache b/modules/swagger-codegen/src/main/resources/erlang-server/app.src.mustache new file mode 100644 index 00000000000..0bc22f45743 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/erlang-server/app.src.mustache @@ -0,0 +1,19 @@ +{application, {{packageName}}, [ + {description, {{#appDescription}}"{{appDescription}}"{{/appDescription}}{{^appDescription}}"Swagger rest server library"{{/appDescription}}}, + {vsn, "{{apiVersion}}"}, + {registered, []}, + {applications, [ + kernel, + stdlib, + ssl, + inets, + jsx, + jesse, + cowboy + ]}, + {env, [ + ]}, + {modules, []}, + {licenses, [{{#licenseInfo}}"{{licenseInfo}}"{{/licenseInfo}}]}, + {links, [{{#infoUrl}}"{{infoUrl}}"{{/infoUrl}}]} +]}. diff --git a/modules/swagger-codegen/src/main/resources/erlang-server/auth.mustache b/modules/swagger-codegen/src/main/resources/erlang-server/auth.mustache new file mode 100644 index 00000000000..bf988fac348 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/erlang-server/auth.mustache @@ -0,0 +1,50 @@ +-module({{packageName}}_auth). + +-export([authorize_api_key/5]). + +-spec authorize_api_key( + LogicHandler :: atom(), + OperationID :: {{packageName}}_api:operation_id(), + From :: header | qs_val, + KeyParam :: iodata() | atom(), + Req ::cowboy_req:req() +)-> {true, Context :: #{binary() => any()}, Req ::cowboy_req:req()} | + {false, AuthHeader :: binary(), Req ::cowboy_req:req()}. + +authorize_api_key(LogicHandler, OperationID, From, KeyParam, Req0) -> + {ApiKey, Req} = get_api_key(From, KeyParam, Req0), + case ApiKey of + undefined -> + AuthHeader = <<"">>, + {false, AuthHeader, Req}; + _ -> + Result = {{packageName}}_logic_handler:authorize_api_key( + LogicHandler, + OperationID, + ApiKey + ), + case Result of + {true, Context} -> + {true, Context, Req}; + false -> + AuthHeader = <<"">>, + {false, AuthHeader, Req} + end + end. + +get_api_key(header, KeyParam, Req0) -> + {Headers, Req} = cowboy_req:headers(Req0), + { + swagger_utils:get_opt( + {{packageName}}_utils:to_header(KeyParam), + Headers + ), + Req + }; + +get_api_key(qs_val, KeyParam, Req0) -> + {QS, Req} = cowboy_req:qs_vals(Req0), + { {{packageName}}_utils:get_opt(KeyParam, QS), Req}. + + + diff --git a/modules/swagger-codegen/src/main/resources/erlang-server/default_logic_handler.mustache b/modules/swagger-codegen/src/main/resources/erlang-server/default_logic_handler.mustache new file mode 100644 index 00000000000..3be26911c74 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/erlang-server/default_logic_handler.mustache @@ -0,0 +1,32 @@ +-module({{packageName}}_default_logic_handler). + +-behaviour({{packageName}}_logic_handler). + +-export([handle_request/3]). +{{#authMethods}} + {{#isApiKey}} +-export([authorize_api_key/2]). + {{/isApiKey}} +{{/authMethods}} + +{{#authMethods}} + {{#isApiKey}} +-spec authorize_api_key(OperationID :: {{packageName}}_api:operation_id(), ApiKey :: binary()) -> {true, #{}}. + +authorize_api_key(_, _) -> {true, #{}}. + {{/isApiKey}} +{{/authMethods}} + +-spec handle_request( + OperationID :: {{packageName}}_api:operation_id(), + Req :: cowboy_req:req(), + Context :: #{} +) -> + {Status :: cowboy:http_status(), Headers :: cowboy:http_headers(), Body :: #{}}. + +handle_request(OperationID, Req, Context) -> + error_logger:error_msg( + "Got not implemented request to process: ~p~n", + [{OperationID, Req, Context}] + ), + {501, [], #{}}. diff --git a/modules/swagger-codegen/src/main/resources/erlang-server/handler.mustache b/modules/swagger-codegen/src/main/resources/erlang-server/handler.mustache new file mode 100644 index 00000000000..4559bc2962a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/erlang-server/handler.mustache @@ -0,0 +1,230 @@ +%% basic handler +-module({{classname}}). + +%% Cowboy REST callbacks +-export([allowed_methods/2]). +-export([init/3]). +-export([rest_init/2]). +-export([allow_missing_post/2]). +-export([content_types_accepted/2]). +-export([content_types_provided/2]). +-export([delete_resource/2]). +-export([is_authorized/2]). +-export([known_content_type/2]). +-export([malformed_request/2]). +-export([valid_content_headers/2]). +-export([valid_entity_length/2]). + +%% Handlers +-export([handle_request_json/2]). + +-record(state, { + operation_id :: {{packageName}}_api:operation_id(), + logic_handler :: atom(), + validator_state :: jesse_state:state(), + context=#{} :: #{} +}). + +-type state() :: state(). + +-spec init(TransportName :: atom(), Req :: cowboy_req:req(), Opts :: {{packageName}}_router:init_opts()) -> + {upgrade, protocol, cowboy_rest, Req :: cowboy_req:req(), Opts :: {{packageName}}_router:init_opts()}. + +init(_Transport, Req, Opts) -> + {upgrade, protocol, cowboy_rest, Req, Opts}. + +-spec rest_init(Req :: cowboy_req:req(), Opts :: {{packageName}}_router:init_opts()) -> + {ok, Req :: cowboy_req:req(), State :: state()}. + +rest_init(Req0, {Operations, LogicHandler, ValidatorState}) -> + {Method, Req} = cowboy_req:method(Req0), + OperationID = maps:get(Method, Operations, undefined), + + error_logger:info_msg("Attempt to process operation: ~p", [OperationID]), + + State = #state{ + operation_id = OperationID, + logic_handler = LogicHandler, + validator_state = ValidatorState + }, + {ok, Req, State}. + +-spec allowed_methods(Req :: cowboy_req:req(), State :: state()) -> + {Value :: [binary()], Req :: cowboy_req:req(), State :: state()}. + +{{#operations}}{{#operation}} +allowed_methods( + Req, + State = #state{ + operation_id = '{{operationId}}' + } +) -> + {[<<"{{httpMethod}}">>], Req, State}; +{{/operation}}{{/operations}} +allowed_methods(Req, State) -> + {[], Req, State}. + +-spec is_authorized(Req :: cowboy_req:req(), State :: state()) -> + { + Value :: true | {false, AuthHeader :: iodata()}, + Req :: cowboy_req:req(), + State :: state() + }. +{{#operations}}{{#operation}} +is_authorized( + Req0, + State = #state{ + operation_id = '{{operationId}}' = OperationID, + logic_handler = LogicHandler + } +) -> +{{#authMethods}} + {{#isApiKey}} + From = {{#isKeyInQuery}}qs_val{{/isKeyInQuery}}{{#isKeyInHeader}}header{{/isKeyInHeader}}, + Result = {{packageName}}_auth:authorize_api_key( + LogicHandler, + OperationID, + From, + "{{keyParamName}}", + Req0 + ), + case Result of + {true, Context, Req} -> {true, Req, State#state{context = Context}}; + {false, AuthHeader, Req} -> {{false, AuthHeader}, Req, State} + end; + {{/isApiKey}} +{{/authMethods}} +{{/operation}}{{/operations}} +is_authorized(Req, State) -> + {{false, <<"">>}, Req, State}. + +-spec content_types_accepted(Req :: cowboy_req:req(), State :: state()) -> + { + Value :: [{binary(), AcceptResource :: atom()}], + Req :: cowboy_req:req(), + State :: state() + }. + +content_types_accepted(Req, State) -> + {[ + {<<"application/json">>, handle_request_json} + ], Req, State}. + +-spec valid_content_headers(Req :: cowboy_req:req(), State :: state()) -> + {Value :: boolean(), Req :: cowboy_req:req(), State :: state()}. +{{#operations}}{{#operation}} +valid_content_headers( + Req0, + State = #state{ + operation_id = '{{operationId}}' + } +) -> + Headers = [{{#headerParams}}"{{baseName}}"{{#hasMore}},{{/hasMore}}{{/headerParams}}], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; +{{/operation}}{{/operations}} +valid_content_headers(Req, State) -> + {false, Req, State}. + +-spec content_types_provided(Req :: cowboy_req:req(), State :: state()) -> + { + Value :: [{binary(), ProvideResource :: atom()}], + Req :: cowboy_req:req(), + State :: state() + }. + +content_types_provided(Req, State) -> + {[ + {<<"application/json">>, handle_request_json} + ], Req, State}. + +-spec malformed_request(Req :: cowboy_req:req(), State :: state()) -> + {Value :: false, Req :: cowboy_req:req(), State :: state()}. + +malformed_request(Req, State) -> + {false, Req, State}. + +-spec allow_missing_post(Req :: cowboy_req:req(), State :: state()) -> + {Value :: false, Req :: cowboy_req:req(), State :: state()}. + +allow_missing_post(Req, State) -> + {false, Req, State}. + +-spec delete_resource(Req :: cowboy_req:req(), State :: state()) -> + processed_response(). + +delete_resource(Req, State) -> + handle_request_json(Req, State). + +-spec known_content_type(Req :: cowboy_req:req(), State :: state()) -> + {Value :: true, Req :: cowboy_req:req(), State :: state()}. + +known_content_type(Req, State) -> + {true, Req, State}. + +-spec valid_entity_length(Req :: cowboy_req:req(), State :: state()) -> + {Value :: true, Req :: cowboy_req:req(), State :: state()}. + +valid_entity_length(Req, State) -> + %% @TODO check the length + {true, Req, State}. + +%%%% + +-type result_ok() :: { + ok, + {Status :: cowboy:http_status(), Headers :: cowboy:http_headers(), Body :: iodata()} +}. + +-type result_error() :: {error, Reason :: any()}. + +-type processed_response() :: {halt, cowboy_req:req(), state()}. + +-spec process_response(result_ok() | result_error(), cowboy_req:req(), state()) -> + processed_response(). + +process_response(Response, Req0, State = #state{operation_id = OperationID}) -> + case Response of + {ok, {Code, Headers, Body}} -> + {ok, Req} = cowboy_req:reply(Code, Headers, Body, Req0), + {halt, Req, State}; + {error, Message} -> + error_logger:error_msg("Unable to process request for ~p: ~p", [OperationID, Message]), + + {ok, Req} = cowboy_req:reply(400, Req0), + {halt, Req, State} + end. + +-spec handle_request_json(cowboy_req:req(), state()) -> {halt, cowboy_req:req(), state()}. + +handle_request_json( + Req0, + State = #state{ + operation_id = OperationID, + logic_handler = LogicHandler, + validator_state = ValidatorState, + context = Context + } +) -> + case {{packageName}}_api:populate_request(OperationID, Req0, ValidatorState) of + {ok, Populated, Req1} -> + {Code, Headers, Body} = {{packageName}}_logic_handler:handle_request( + LogicHandler, + OperationID, + Populated, + Context + ), + _ = {{packageName}}_api:validate_response( + OperationID, + Code, + Body, + ValidatorState + ), + PreparedBody = jsx:encode(Body), + Response = {ok, {Code, Headers, PreparedBody}}, + process_response(Response, Req1, State); + {error, Reason, Req1} -> + process_response({error, Reason}, Req1, State) + end. + +validate_headers(_, Req) -> {true, Req}. diff --git a/modules/swagger-codegen/src/main/resources/erlang-server/logic_handler.mustache b/modules/swagger-codegen/src/main/resources/erlang-server/logic_handler.mustache new file mode 100644 index 00000000000..cb4ba201bf4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/erlang-server/logic_handler.mustache @@ -0,0 +1,50 @@ +-module({{packageName}}_logic_handler). + +-export([handle_request/4]). +{{#authMethods}} + {{#isApiKey}} +-export([authorize_api_key/3]). + {{/isApiKey}} +{{/authMethods}} +-type context() :: #{binary() => any()}. +-type handler_response() ::{ + Status :: cowboy:http_status(), + Headers :: cowboy:http_headers(), + Body :: #{} +}. + +-export_type([handler_response/0]). + +{{#authMethods}} + {{#isApiKey}} +-callback authorize_api_key( + OperationID :: {{packageName}}_api:operation_id(), + ApiKey :: binary() +) -> + Result :: boolean() | {boolean(), context()}. + {{/isApiKey}} +{{/authMethods}} + + +-callback handle_request(OperationID :: {{packageName}}_api:operation_id(), Request :: any(), Context :: context()) -> + handler_response(). + +-spec handle_request( + Handler :: atom(), + OperationID :: {{packageName}}_api:operation_id(), + Request :: any(), + Context :: context() +) -> + handler_response(). + +handle_request(Handler, OperationID, Req, Context) -> + Handler:handle_request(OperationID, Req, Context). + +{{#authMethods}} + {{#isApiKey}} +-spec authorize_api_key(Handler :: atom(), OperationID :: {{packageName}}_api:operation_id(), ApiKey :: binary()) -> + Result :: false | {true, context()}. +authorize_api_key(Handler, OperationID, ApiKey) -> + Handler:authorize_api_key(OperationID, ApiKey). + {{/isApiKey}} +{{/authMethods}} diff --git a/modules/swagger-codegen/src/main/resources/erlang-server/rebar.config.mustache b/modules/swagger-codegen/src/main/resources/erlang-server/rebar.config.mustache new file mode 100644 index 00000000000..1c7f7d922e9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/erlang-server/rebar.config.mustache @@ -0,0 +1,4 @@ +{deps, [ + {jsx, {git, "https://github.com/talentdeficit/jsx.git", {branch, "v2.8.0"}}}, + {jesse, {git, "https://github.com/for-GET/jesse.git", {tag, "1.4.0"}}} +]}. diff --git a/modules/swagger-codegen/src/main/resources/erlang-server/router.mustache b/modules/swagger-codegen/src/main/resources/erlang-server/router.mustache new file mode 100644 index 00000000000..9c5ff89b229 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/erlang-server/router.mustache @@ -0,0 +1,74 @@ +-module({{packageName}}_router). + +-export([get_paths/1]). + +-type operations() :: #{ + Method :: binary() => {{packageName}}_api:operation_id() +}. + +-type init_opts() :: { + Operations :: operations(), + LogicHandler :: atom(), + ValidatorState :: jesse_state:state() +}. + +-export_type([init_opts/0]). + +-spec get_paths(LogicHandler :: atom()) -> [{'_',[{ + Path :: string(), + Handler :: atom(), + InitOpts :: init_opts() +}]}]. + +get_paths(LogicHandler) -> + ValidatorState = prepare_validator(), + PreparedPaths = maps:fold( + fun(Path, #{operations := Operations, handler := Handler}, Acc) -> + [{Path, Handler, Operations} | Acc] + end, + [], + group_paths() + ), + [ + {'_', + [{P, H, {O, LogicHandler, ValidatorState}} || {P, H, O} <- PreparedPaths] + } + ]. + +group_paths() -> + maps:fold( + fun(OperationID, #{path := Path, method := Method, handler := Handler}, Acc) -> + case maps:find(Path, Acc) of + {ok, PathInfo0 = #{operations := Operations0}} -> + Operations = Operations0#{Method => OperationID}, + PathInfo = PathInfo0#{operations => Operations}, + Acc#{Path => PathInfo}; + error -> + Operations = #{Method => OperationID}, + PathInfo = #{handler => Handler, operations => Operations}, + Acc#{Path => PathInfo} + end + end, + #{}, + get_operations() + ). + +get_operations() -> + #{ {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} + '{{operationId}}' => #{ + path => "{{basePathWithoutHost}}{{path}}", + method => <<"{{httpMethod}}">>, + handler => '{{classname}}' + }{{#hasMore}},{{/hasMore}}{{/operation}}{{#hasMore}},{{/hasMore}}{{/operations}}{{/apis}}{{/apiInfo}} + }. + +prepare_validator() -> + R = jsx:decode(element(2, file:read_file(get_swagger_path()))), + jesse_state:new(R, [{default_schema_ver, <<"http://json-schema.org/draft-04/schema#">>}]). + + +get_swagger_path() -> + {ok, AppName} = application:get_application(?MODULE), + filename:join({{packageName}}_utils:priv_dir(AppName), "swagger.json"). + + diff --git a/modules/swagger-codegen/src/main/resources/erlang-server/server.mustache b/modules/swagger-codegen/src/main/resources/erlang-server/server.mustache new file mode 100644 index 00000000000..90a6388ea5d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/erlang-server/server.mustache @@ -0,0 +1,64 @@ +-module({{packageName}}_server). + + +-define(DEFAULT_ACCEPTORS_POOLSIZE, 100). +-define(DEFAULT_LOGIC_HANDLER, {{packageName}}_default_logic_handler). + +-export([child_spec/2]). + +-spec child_spec( ID :: any(), #{ + ip => inet:ip_address(), + port => inet:port_number(), + net_opts => [] +}) -> supervisor:child_spec(). + +child_spec(ID, #{ + ip := IP , + port := Port, + net_opts := NetOpts +} = Params) -> + AcceptorsPool = ?DEFAULT_ACCEPTORS_POOLSIZE, + {Transport, TransportOpts} = get_socket_transport(IP, Port, NetOpts), + LogicHandler = maps:get(logic_handler, Params, ?DEFAULT_LOGIC_HANDLER), + ExtraOpts = maps:get(cowboy_extra_opts, Params, []), + CowboyOpts = get_cowboy_config(LogicHandler, ExtraOpts), + ranch:child_spec({?MODULE, ID}, AcceptorsPool, + Transport, TransportOpts, cowboy_protocol, CowboyOpts). + +get_socket_transport(IP, Port, Options) -> + Opts = [ + {ip, IP}, + {port, Port} + ], + case {{packageName}}_utils:get_opt(ssl, Options) of + SslOpts = [_|_] -> + {ranch_ssl, Opts ++ SslOpts}; + undefined -> + {ranch_tcp, Opts} + end. + +get_cowboy_config(LogicHandler, ExtraOpts) -> + get_cowboy_config(LogicHandler, ExtraOpts, get_default_opts(LogicHandler)). + +get_cowboy_config(_LogicHandler, [], Opts) -> + Opts; + +get_cowboy_config(LogicHandler, [{env, Env} | Rest], Opts) -> + NewEnv = case proplists:get_value(dispatch, Env) of + undefined -> [get_default_dispatch(LogicHandler) | Env]; + _ -> Env + end, + get_cowboy_config(LogicHandler, Rest, store_key(env, NewEnv, Opts)); + +get_cowboy_config(LogicHandler, [{Key, Value}| Rest], Opts) -> + get_cowboy_config(LogicHandler, Rest, store_key(Key, Value, Opts)). + +get_default_dispatch(LogicHandler) -> + Paths = {{packageName}}_router:get_paths(LogicHandler), + {dispatch, cowboy_router:compile(Paths)}. + +get_default_opts(LogicHandler) -> + [{env, [get_default_dispatch(LogicHandler)]}]. + +store_key(Key, Value, Opts) -> + lists:keystore(Key, 1, Opts, {Key, Value}). diff --git a/modules/swagger-codegen/src/main/resources/erlang-server/swagger.mustache b/modules/swagger-codegen/src/main/resources/erlang-server/swagger.mustache new file mode 100644 index 00000000000..9bf6bbcffba --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/erlang-server/swagger.mustache @@ -0,0 +1 @@ +{{{swagger-json}}} diff --git a/modules/swagger-codegen/src/main/resources/erlang-server/utils.mustache b/modules/swagger-codegen/src/main/resources/erlang-server/utils.mustache new file mode 100644 index 00000000000..b6701add7fc --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/erlang-server/utils.mustache @@ -0,0 +1,173 @@ +-module({{packageName}}_utils). + +-export([to_binary/1]). +-export([to_list/1]). +-export([to_float/1]). +-export([to_int/1]). +-export([to_lower/1]). +-export([to_upper/1]). +-export([set_resp_headers/2]). +-export([to_header/1]). +-export([to_qs/1]). +-export([to_binding/1]). +-export([get_opt/2]). +-export([get_opt/3]). +-export([priv_dir/0]). +-export([priv_dir/1]). +-export([priv_path/1]). + + +-spec to_binary(iodata() | atom() | number()) -> binary(). + +to_binary(V) when is_binary(V) -> V; +to_binary(V) when is_list(V) -> iolist_to_binary(V); +to_binary(V) when is_atom(V) -> atom_to_binary(V, utf8); +to_binary(V) when is_integer(V) -> integer_to_binary(V); +to_binary(V) when is_float(V) -> float_to_binary(V). + +-spec to_list(iodata() | atom() | number()) -> string(). + +to_list(V) when is_list(V) -> V; +to_list(V) -> binary_to_list(to_binary(V)). + +-spec to_float(iodata()) -> number(). + +to_float(V) -> + Data = iolist_to_binary([V]), + case binary:split(Data, <<$.>>) of + [Data] -> + binary_to_integer(Data); + [<<>>, _] -> + binary_to_float(<<$0, Data/binary>>); + _ -> + binary_to_float(Data) + end. + +%% + +-spec to_int(integer() | binary() | list()) -> integer(). + +to_int(Data) when is_integer(Data) -> + Data; +to_int(Data) when is_binary(Data) -> + binary_to_integer(Data); +to_int(Data) when is_list(Data) -> + list_to_integer(Data). + +-spec set_resp_headers([{binary(), iodata()}], cowboy_req:req()) -> cowboy_req:req(). + +set_resp_headers([], Req) -> + Req; +set_resp_headers([{K, V} | T], Req0) -> + Req = cowboy_req:set_resp_header(K, V, Req0), + set_resp_headers(T, Req). + +-spec to_header(iodata() | atom() | number()) -> binary(). + +to_header(Name) -> + Prepared = to_binary(Name), + to_lower(Prepared). + +-spec to_qs(iodata() | atom() | number()) -> binary(). + +to_qs(Name) -> + to_binary(Name). + +-spec to_binding(iodata() | atom() | number()) -> atom(). + +to_binding(Name) -> + Prepared = to_binary(Name), + binary_to_atom(Prepared, utf8). + +-spec get_opt(any(), []) -> any(). + +get_opt(Key, Opts) -> + get_opt(Key, Opts, undefined). + +-spec get_opt(any(), [], any()) -> any(). + +get_opt(Key, Opts, Default) -> + case lists:keyfind(Key, 1, Opts) of + {_, Value} -> Value; + false -> Default + end. + +-spec priv_dir() -> file:filename(). + +priv_dir() -> + {ok, AppName} = application:get_application(), + priv_dir(AppName). + +-spec priv_dir(Application :: atom()) -> file:filename(). + +priv_dir(AppName) -> + case code:priv_dir(AppName) of + Value when is_list(Value) -> + Value ++ "/"; + _Error -> + select_priv_dir([filename:join(["apps", atom_to_list(AppName), "priv"]), "priv"]) + end. + +-spec priv_path(Relative :: file:filename()) -> file:filename(). + +priv_path(Relative) -> + filename:join(priv_dir(), Relative). + +-include_lib("kernel/include/file.hrl"). + +select_priv_dir(Paths) -> + case lists:dropwhile(fun test_priv_dir/1, Paths) of + [Path | _] -> Path; + _ -> exit(no_priv_dir) + end. + +test_priv_dir(Path) -> + case file:read_file_info(Path) of + {ok, #file_info{type = directory}} -> + false; + _ -> + true + end. + + +%% + +-spec to_lower(binary()) -> binary(). + +to_lower(S) -> + to_case(lower, S, <<>>). + +-spec to_upper(binary()) -> binary(). + +to_upper(S) -> + to_case(upper, S, <<>>). + +to_case(_Case, <<>>, Acc) -> + Acc; + +to_case(_Case, <>, _Acc) when C > 127 -> + error(badarg); + +to_case(Case = lower, <>, Acc) -> + to_case(Case, Rest, <>); + +to_case(Case = upper, <>, Acc) -> + to_case(Case, Rest, <>). + +to_lower_char(C) when is_integer(C), $A =< C, C =< $Z -> + C + 32; +to_lower_char(C) when is_integer(C), 16#C0 =< C, C =< 16#D6 -> + C + 32; +to_lower_char(C) when is_integer(C), 16#D8 =< C, C =< 16#DE -> + C + 32; +to_lower_char(C) -> + C. + +to_upper_char(C) when is_integer(C), $a =< C, C =< $z -> + C - 32; +to_upper_char(C) when is_integer(C), 16#E0 =< C, C =< 16#F6 -> + C - 32; +to_upper_char(C) when is_integer(C), 16#F8 =< C, C =< 16#FE -> + C - 32; +to_upper_char(C) -> + C. From f05c7aa8d3479d588956c1a02cbfc3c01b2eb5b6 Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 9 Sep 2016 15:46:06 +0800 Subject: [PATCH 341/470] add Erlang Server | @galaxie --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 0dac8820469..fa294158083 100644 --- a/README.md +++ b/README.md @@ -874,6 +874,7 @@ Here is a list of template creators: * TypeScript (Angular2): @roni-frantchi * Server Stubs * C# ASP.NET5: @jimschubert + * Erlang Server: @galaxie * C# NancyFX: @mstefaniuk * Go Server: @guohuang * Haskell Servant: @algas From 7850ecd76728ef53e7d1fa97844943fd89c5bcbf Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 9 Sep 2016 15:49:27 +0800 Subject: [PATCH 342/470] rearrange erlang server --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index fa294158083..ce865a03ce2 100644 --- a/README.md +++ b/README.md @@ -874,8 +874,8 @@ Here is a list of template creators: * TypeScript (Angular2): @roni-frantchi * Server Stubs * C# ASP.NET5: @jimschubert - * Erlang Server: @galaxie * C# NancyFX: @mstefaniuk + * Erlang Server: @galaxie * Go Server: @guohuang * Haskell Servant: @algas * Java Spring Boot: @diyfr From dcdea19cb888a5c45cd5d1809ed3c5f270a9c43a Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 9 Sep 2016 16:42:26 +0800 Subject: [PATCH 343/470] erlang update readme, add petstore samples --- bin/erlang-petstore-server.sh | 31 + .../languages/ErlangServerCodegen.java | 17 +- .../resources/erlang-server/README.mustache | 24 +- .../erlang-server/.swagger-codegen-ignore | 23 + samples/server/petstore/erlang-server/LICENSE | 201 +++++ .../server/petstore/erlang-server/README.md | 16 + .../petstore/erlang-server/priv/swagger.json | 1 + .../petstore/erlang-server/rebar.config | 4 + .../erlang-server/src/swagger.app.src | 19 + .../erlang-server/src/swagger_api.erl | 733 ++++++++++++++++++ .../erlang-server/src/swagger_auth.erl | 50 ++ .../src/swagger_default_logic_handler.erl | 24 + .../src/swagger_logic_handler.erl | 38 + .../erlang-server/src/swagger_pet_handler.erl | 408 ++++++++++ .../erlang-server/src/swagger_router.erl | 169 ++++ .../erlang-server/src/swagger_server.erl | 64 ++ .../src/swagger_store_handler.erl | 304 ++++++++ .../src/swagger_user_handler.erl | 396 ++++++++++ .../erlang-server/src/swagger_utils.erl | 173 +++++ 19 files changed, 2683 insertions(+), 12 deletions(-) create mode 100755 bin/erlang-petstore-server.sh create mode 100644 samples/server/petstore/erlang-server/.swagger-codegen-ignore create mode 100644 samples/server/petstore/erlang-server/LICENSE create mode 100644 samples/server/petstore/erlang-server/README.md create mode 100644 samples/server/petstore/erlang-server/priv/swagger.json create mode 100644 samples/server/petstore/erlang-server/rebar.config create mode 100644 samples/server/petstore/erlang-server/src/swagger.app.src create mode 100644 samples/server/petstore/erlang-server/src/swagger_api.erl create mode 100644 samples/server/petstore/erlang-server/src/swagger_auth.erl create mode 100644 samples/server/petstore/erlang-server/src/swagger_default_logic_handler.erl create mode 100644 samples/server/petstore/erlang-server/src/swagger_logic_handler.erl create mode 100644 samples/server/petstore/erlang-server/src/swagger_pet_handler.erl create mode 100644 samples/server/petstore/erlang-server/src/swagger_router.erl create mode 100644 samples/server/petstore/erlang-server/src/swagger_server.erl create mode 100644 samples/server/petstore/erlang-server/src/swagger_store_handler.erl create mode 100644 samples/server/petstore/erlang-server/src/swagger_user_handler.erl create mode 100644 samples/server/petstore/erlang-server/src/swagger_utils.erl diff --git a/bin/erlang-petstore-server.sh b/bin/erlang-petstore-server.sh new file mode 100755 index 00000000000..1fcbc2f3bfd --- /dev/null +++ b/bin/erlang-petstore-server.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/erlang-server -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l erlang-server -o samples/server/petstore/erlang-server" + +java $JAVA_OPTS -jar $executable $ags diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ErlangServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ErlangServerCodegen.java index d510b42fac2..65162cdd228 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ErlangServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ErlangServerCodegen.java @@ -163,8 +163,8 @@ public String getName() { */ @Override public String getHelp() { - return "Generates an Erlang server library using the swagger-tools project. By default, " + - "it will also generate service classes--which you can disable with the `-Dnoservice` environment variable."; + return "Generates an Erlang server library (beta) using the Swagger Codegen project. By default, " + + "it will also generate service classes, which can be disabled with the `-Dnoservice` environment variable."; } @Override @@ -264,4 +264,17 @@ protected String toIncludeFilePath(String name, String extension) { protected String toPrivFilePath(String name, String extension) { return "priv" + File.separator + name + "." + extension; } + + @Override + public String escapeQuotationMark(String input) { + // remove ' to avoid code injection + return input.replace("'", ""); + } + + @Override + public String escapeUnsafeCharacters(String input) { + // ref: http://stackoverflow.com/a/30421295/677735 + return input.replace("-ifdef", "- if def").replace("-endif", "- end if"); + } + } diff --git a/modules/swagger-codegen/src/main/resources/erlang-server/README.mustache b/modules/swagger-codegen/src/main/resources/erlang-server/README.mustache index d9858d4cc03..af53effabc7 100644 --- a/modules/swagger-codegen/src/main/resources/erlang-server/README.mustache +++ b/modules/swagger-codegen/src/main/resources/erlang-server/README.mustache @@ -1,12 +1,16 @@ # Swagger rest server library for Erlang -## TODO -- [ ] Write specs for static exported fuctions -- [ ] Write specs for generated exported fuctions -- [ ] Add datetime/date validation -- [ ] Separate gigantic `api` to submodules and refactor the routing -- [ ] Add tests for the validators -- [ ] Add integrational test for the whole cycle -- [ ] Add validations of definitions with inheritance -- [ ] Add proper response validation (this `list` hack is so weird) -- [ ] Fix enum validation. It doesn't work correctly when the parans is in qs/header +## Overview + +An Erlang server stub generated by [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) given an OpenAPI/Swagger spec. + +Dependency: [Cowboy](https://github.com/ninenines/cowboy) + +## Prerequisites + +TODO + +## Getting started + +TODO + diff --git a/samples/server/petstore/erlang-server/.swagger-codegen-ignore b/samples/server/petstore/erlang-server/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/erlang-server/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/erlang-server/LICENSE b/samples/server/petstore/erlang-server/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/server/petstore/erlang-server/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/server/petstore/erlang-server/README.md b/samples/server/petstore/erlang-server/README.md new file mode 100644 index 00000000000..af53effabc7 --- /dev/null +++ b/samples/server/petstore/erlang-server/README.md @@ -0,0 +1,16 @@ +# Swagger rest server library for Erlang + +## Overview + +An Erlang server stub generated by [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) given an OpenAPI/Swagger spec. + +Dependency: [Cowboy](https://github.com/ninenines/cowboy) + +## Prerequisites + +TODO + +## Getting started + +TODO + diff --git a/samples/server/petstore/erlang-server/priv/swagger.json b/samples/server/petstore/erlang-server/priv/swagger.json new file mode 100644 index 00000000000..de3bdd27a50 --- /dev/null +++ b/samples/server/petstore/erlang-server/priv/swagger.json @@ -0,0 +1 @@ +{"swagger":"2.0","info":{"description":"This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.","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","tags":[{"name":"pet","description":"Everything about your Pets","externalDocs":{"description":"Find out more","url":"http://swagger.io"}},{"name":"store","description":"Access to Petstore orders"},{"name":"user","description":"Operations about user","externalDocs":{"description":"Find out more about our store","url":"http://swagger.io"}}],"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/xml","application/json"],"parameters":[{"in":"body","name":"body","description":"Pet object that needs to be added to the store","required":true,"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/xml","application/json"],"parameters":[{"in":"body","name":"body","description":"Pet object that needs to be added to the store","required":true,"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 separated strings","operationId":"findPetsByStatus","produces":["application/xml","application/json"],"parameters":[{"name":"status","in":"query","description":"Status values that need to be considered for filter","required":true,"type":"array","items":{"type":"string","default":"available","enum":["available","pending","sold"]},"collectionFormat":"csv"}],"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":"Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.","operationId":"findPetsByTags","produces":["application/xml","application/json"],"parameters":[{"name":"tags","in":"query","description":"Tags to filter by","required":true,"type":"array","items":{"type":"string"},"collectionFormat":"csv"}],"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 single pet","operationId":"getPetById","produces":["application/xml","application/json"],"parameters":[{"name":"petId","in":"path","description":"ID of pet to return","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":[]}]},"post":{"tags":["pet"],"summary":"Updates a pet in the store with form data","description":"","operationId":"updatePetWithForm","consumes":["application/x-www-form-urlencoded"],"produces":["application/xml","application/json"],"parameters":[{"name":"petId","in":"path","description":"ID of pet that needs to be updated","required":true,"type":"integer","format":"int64"},{"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/xml","application/json"],"parameters":[{"name":"api_key","in":"header","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"],"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":{"200":{"description":"successful operation","schema":{"$ref":"#/definitions/ApiResponse"}}},"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"],"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/xml","application/json"],"parameters":[{"in":"body","name":"body","description":"order placed for purchasing the pet","required":true,"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/xml","application/json"],"parameters":[{"name":"orderId","in":"path","description":"ID of pet that needs to be fetched","required":true,"type":"integer","maximum":5.0,"minimum":1.0,"format":"int64"}],"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/xml","application/json"],"parameters":[{"name":"orderId","in":"path","description":"ID of the order that needs to be deleted","required":true,"type":"string","minimum":1.0}],"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/xml","application/json"],"parameters":[{"in":"body","name":"body","description":"Created user object","required":true,"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/xml","application/json"],"parameters":[{"in":"body","name":"body","description":"List of user object","required":true,"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/xml","application/json"],"parameters":[{"in":"body","name":"body","description":"List of user object","required":true,"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/xml","application/json"],"parameters":[{"name":"username","in":"query","description":"The user name for login","required":true,"type":"string"},{"name":"password","in":"query","description":"The password for login in clear text","required":true,"type":"string"}],"responses":{"200":{"description":"successful operation","schema":{"type":"string"},"headers":{"X-Rate-Limit":{"type":"integer","format":"int32","description":"calls per hour allowed by the user"},"X-Expires-After":{"type":"string","format":"date-time","description":"date in UTC when toekn expires"}}},"400":{"description":"Invalid username/password supplied"}}}},"/user/logout":{"get":{"tags":["user"],"summary":"Logs out current logged in user session","description":"","operationId":"logoutUser","produces":["application/xml","application/json"],"parameters":[],"responses":{"default":{"description":"successful operation"}}}},"/user/{username}":{"get":{"tags":["user"],"summary":"Get user by user name","description":"","operationId":"getUserByName","produces":["application/xml","application/json"],"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"}},"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/xml","application/json"],"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":true,"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/xml","application/json"],"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":{"Order":{"type":"object","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","default":false}},"xml":{"name":"Order"}},"Category":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"}},"xml":{"name":"Category"}},"User":{"type":"object","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"}},"Tag":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"}},"xml":{"name":"Tag"}},"Pet":{"type":"object","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"}},"ApiResponse":{"type":"object","properties":{"code":{"type":"integer","format":"int32"},"type":{"type":"string"},"message":{"type":"string"}}}},"externalDocs":{"description":"Find out more about Swagger","url":"http://swagger.io"}} diff --git a/samples/server/petstore/erlang-server/rebar.config b/samples/server/petstore/erlang-server/rebar.config new file mode 100644 index 00000000000..1c7f7d922e9 --- /dev/null +++ b/samples/server/petstore/erlang-server/rebar.config @@ -0,0 +1,4 @@ +{deps, [ + {jsx, {git, "https://github.com/talentdeficit/jsx.git", {branch, "v2.8.0"}}}, + {jesse, {git, "https://github.com/for-GET/jesse.git", {tag, "1.4.0"}}} +]}. diff --git a/samples/server/petstore/erlang-server/src/swagger.app.src b/samples/server/petstore/erlang-server/src/swagger.app.src new file mode 100644 index 00000000000..9016bde7219 --- /dev/null +++ b/samples/server/petstore/erlang-server/src/swagger.app.src @@ -0,0 +1,19 @@ +{application, swagger, [ + {description, "This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters."}, + {vsn, "1.0.0"}, + {registered, []}, + {applications, [ + kernel, + stdlib, + ssl, + inets, + jsx, + jesse, + cowboy + ]}, + {env, [ + ]}, + {modules, []}, + {licenses, ["Apache 2.0"]}, + {links, []} +]}. diff --git a/samples/server/petstore/erlang-server/src/swagger_api.erl b/samples/server/petstore/erlang-server/src/swagger_api.erl new file mode 100644 index 00000000000..b3020fbbf69 --- /dev/null +++ b/samples/server/petstore/erlang-server/src/swagger_api.erl @@ -0,0 +1,733 @@ +-module(swagger_api). + +-export([request_params/1]). +-export([request_param_info/2]). +-export([populate_request/3]). +-export([validate_response/4]). + +-type operation_id() :: atom(). +-type request_param() :: atom(). + +-export_type([operation_id/0]). + +-spec request_params(OperationID :: operation_id()) -> [Param :: request_param()]. + + +request_params('AddPet') -> + [ + 'Pet' + ]; + +request_params('DeletePet') -> + [ + 'petId', + 'api_key' + ]; + +request_params('FindPetsByStatus') -> + [ + 'status' + ]; + +request_params('FindPetsByTags') -> + [ + 'tags' + ]; + +request_params('GetPetById') -> + [ + 'petId' + ]; + +request_params('UpdatePet') -> + [ + 'Pet' + ]; + +request_params('UpdatePetWithForm') -> + [ + 'petId', + 'name', + 'status' + ]; + +request_params('UploadFile') -> + [ + 'petId', + 'additionalMetadata', + 'file' + ]; + + +request_params('DeleteOrder') -> + [ + 'orderId' + ]; + +request_params('GetInventory') -> + [ + ]; + +request_params('GetOrderById') -> + [ + 'orderId' + ]; + +request_params('PlaceOrder') -> + [ + 'Order' + ]; + + +request_params('CreateUser') -> + [ + 'User' + ]; + +request_params('CreateUsersWithArrayInput') -> + [ + 'list' + ]; + +request_params('CreateUsersWithListInput') -> + [ + 'list' + ]; + +request_params('DeleteUser') -> + [ + 'username' + ]; + +request_params('GetUserByName') -> + [ + 'username' + ]; + +request_params('LoginUser') -> + [ + 'username', + 'password' + ]; + +request_params('LogoutUser') -> + [ + ]; + +request_params('UpdateUser') -> + [ + 'username', + 'User' + ]; + +request_params(_) -> + error(unknown_operation). + +-type rule() :: + {type, 'binary'} | + {type, 'integer'} | + {type, 'float'} | + {type, 'binary'} | + {type, 'boolean'} | + {type, 'date'} | + {type, 'datetime'} | + {enum, [atom()]} | + {max, Max :: number()} | + {exclusive_max, Max :: number()} | + {min, Min :: number()} | + {exclusive_min, Min :: number()} | + {max_length, MaxLength :: integer()} | + {min_length, MaxLength :: integer()} | + {pattern, Pattern :: string()} | + schema | + required | + not_required. + +-spec request_param_info(OperationID :: operation_id(), Name :: request_param()) -> #{ + source => qs_val | binding | header | body, + rules => [rule()] +}. + + + +request_param_info('AddPet', 'Pet') -> + #{ + source => body, + rules => [ + schema, + required + ] + }; + +request_param_info('DeletePet', 'petId') -> + #{ + source => binding , + rules => [ + {type, 'integer'}, + required + ] + }; + +request_param_info('DeletePet', 'api_key') -> + #{ + source => header, + rules => [ + {type, 'binary'}, + not_required + ] + }; + +request_param_info('FindPetsByStatus', 'status') -> + #{ + source => qs_val , + rules => [ + {enum, ['available', 'pending', 'sold'] }, + required + ] + }; + +request_param_info('FindPetsByTags', 'tags') -> + #{ + source => qs_val , + rules => [ + required + ] + }; + +request_param_info('GetPetById', 'petId') -> + #{ + source => binding , + rules => [ + {type, 'integer'}, + required + ] + }; + +request_param_info('UpdatePet', 'Pet') -> + #{ + source => body, + rules => [ + schema, + required + ] + }; + +request_param_info('UpdatePetWithForm', 'petId') -> + #{ + source => binding , + rules => [ + {type, 'integer'}, + required + ] + }; + +request_param_info('UpdatePetWithForm', 'name') -> + #{ + source => , + rules => [ + {type, 'binary'}, + not_required + ] + }; + +request_param_info('UpdatePetWithForm', 'status') -> + #{ + source => , + rules => [ + {type, 'binary'}, + not_required + ] + }; + +request_param_info('UploadFile', 'petId') -> + #{ + source => binding , + rules => [ + {type, 'integer'}, + required + ] + }; + +request_param_info('UploadFile', 'additionalMetadata') -> + #{ + source => , + rules => [ + {type, 'binary'}, + not_required + ] + }; + +request_param_info('UploadFile', 'file') -> + #{ + source => , + rules => [ + not_required + ] + }; + + +request_param_info('DeleteOrder', 'orderId') -> + #{ + source => binding , + rules => [ + {type, 'binary'}, + {min, 1.0 }, + required + ] + }; + +request_param_info('GetOrderById', 'orderId') -> + #{ + source => binding , + rules => [ + {type, 'integer'}, + {max, 5.0 }, + {min, 1.0 }, + required + ] + }; + +request_param_info('PlaceOrder', 'Order') -> + #{ + source => body, + rules => [ + schema, + required + ] + }; + + +request_param_info('CreateUser', 'User') -> + #{ + source => body, + rules => [ + schema, + required + ] + }; + +request_param_info('CreateUsersWithArrayInput', 'list') -> + #{ + source => body, + rules => [ + schema, + required + ] + }; + +request_param_info('CreateUsersWithListInput', 'list') -> + #{ + source => body, + rules => [ + schema, + required + ] + }; + +request_param_info('DeleteUser', 'username') -> + #{ + source => binding , + rules => [ + {type, 'binary'}, + required + ] + }; + +request_param_info('GetUserByName', 'username') -> + #{ + source => binding , + rules => [ + {type, 'binary'}, + required + ] + }; + +request_param_info('LoginUser', 'username') -> + #{ + source => qs_val , + rules => [ + {type, 'binary'}, + required + ] + }; + +request_param_info('LoginUser', 'password') -> + #{ + source => qs_val , + rules => [ + {type, 'binary'}, + required + ] + }; + +request_param_info('UpdateUser', 'username') -> + #{ + source => binding , + rules => [ + {type, 'binary'}, + required + ] + }; + +request_param_info('UpdateUser', 'User') -> + #{ + source => body, + rules => [ + schema, + required + ] + }; + +request_param_info(OperationID, Name) -> + error({unknown_param, OperationID, Name}). + +-spec populate_request( + OperationID :: operation_id(), + Req :: cowboy_req:req(), + ValidatorState :: jesse_state:state() +) -> + {ok, Model :: #{}, Req :: cowboy_req:req()} | + {error, Reason :: any(), Req :: cowboy_req:req()}. + +populate_request(OperationID, Req, ValidatorState) -> + Params = request_params(OperationID), + populate_request_params(OperationID, Params, Req, ValidatorState, #{}). + +populate_request_params(_, [], Req, _, Model) -> + {ok, Model, Req}; + +populate_request_params(OperationID, [FieldParams | T], Req0, ValidatorState, Model) -> + case populate_request_param(OperationID, FieldParams, Req0, ValidatorState) of + {ok, K, V, Req} -> + populate_request_params(OperationID, T, Req, ValidatorState, maps:put(K, V, Model)); + Error -> + Error + end. + +populate_request_param(OperationID, Name, Req0, ValidatorState) -> + #{rules := Rules, source := Source} = request_param_info(OperationID, Name), + {Value, Req} = get_value(Source, Name, Req0), + case prepare_param(Rules, Name, Value, ValidatorState) of + {ok, Result} -> {ok, Name, Result, Req}; + {error, Reason} -> + {error, Reason, Req} + end. + +-spec validate_response( + OperationID :: operation_id(), + Code :: 200..599, + Body :: jesse:json_term(), + ValidatorState :: jesse_state:state() +) -> ok | no_return(). + + +validate_response('AddPet', 405, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + +validate_response('DeletePet', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + +validate_response('FindPetsByStatus', 200, Body, ValidatorState) -> + validate_response_body('list', 'Pet', Body, ValidatorState); +validate_response('FindPetsByStatus', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + +validate_response('FindPetsByTags', 200, Body, ValidatorState) -> + validate_response_body('list', 'Pet', Body, ValidatorState); +validate_response('FindPetsByTags', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + +validate_response('GetPetById', 200, Body, ValidatorState) -> + validate_response_body('Pet', 'Pet', Body, ValidatorState); +validate_response('GetPetById', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('GetPetById', 404, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + +validate_response('UpdatePet', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('UpdatePet', 404, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('UpdatePet', 405, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + +validate_response('UpdatePetWithForm', 405, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + +validate_response('UploadFile', 200, Body, ValidatorState) -> + validate_response_body('ApiResponse', 'ApiResponse', Body, ValidatorState); + + +validate_response('DeleteOrder', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('DeleteOrder', 404, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + +validate_response('GetInventory', 200, Body, ValidatorState) -> + validate_response_body('map', 'integer', Body, ValidatorState); + +validate_response('GetOrderById', 200, Body, ValidatorState) -> + validate_response_body('Order', 'Order', Body, ValidatorState); +validate_response('GetOrderById', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('GetOrderById', 404, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + +validate_response('PlaceOrder', 200, Body, ValidatorState) -> + validate_response_body('Order', 'Order', Body, ValidatorState); +validate_response('PlaceOrder', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + + +validate_response('CreateUser', 0, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + +validate_response('CreateUsersWithArrayInput', 0, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + +validate_response('CreateUsersWithListInput', 0, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + +validate_response('DeleteUser', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('DeleteUser', 404, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + +validate_response('GetUserByName', 200, Body, ValidatorState) -> + validate_response_body('User', 'User', Body, ValidatorState); +validate_response('GetUserByName', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('GetUserByName', 404, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + +validate_response('LoginUser', 200, Body, ValidatorState) -> + validate_response_body('binary', 'string', Body, ValidatorState); +validate_response('LoginUser', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + +validate_response('LogoutUser', 0, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + +validate_response('UpdateUser', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('UpdateUser', 404, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); + + +validate_response(_OperationID, _Code, _Body, _ValidatorState) -> + ok. + +validate_response_body('list', ReturnBaseType, Body, ValidatorState) -> + [ + validate(schema, ReturnBaseType, Item, ValidatorState) + || Item <- Body]; + +validate_response_body(_, ReturnBaseType, Body, ValidatorState) -> + validate(schema, ReturnBaseType, Body, ValidatorState). + +%%% +validate(Rule = required, Name, Value, _ValidatorState) -> + case Value of + undefined -> validation_error(Rule, Name); + _ -> ok + end; + +validate(not_required, _Name, _Value, _ValidatorState) -> + ok; + +validate(_, _Name, undefined, _ValidatorState) -> + ok; + +validate(Rule = {type, 'integer'}, Name, Value, _ValidatorState) -> + try + {ok, swagger_utils:to_int(Value)} + catch + error:badarg -> + validation_error(Rule, Name) + end; + +validate(Rule = {type, 'float'}, Name, Value, _ValidatorState) -> + try + {ok, swagger_utils:to_float(Value)} + catch + error:badarg -> + validation_error(Rule, Name) + end; + +validate(Rule = {type, 'binary'}, Name, Value, _ValidatorState) -> + case is_binary(Value) of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(_Rule = {type, 'boolean'}, _Name, Value, _ValidatorState) when is_boolean(Value) -> + {ok, Value}; + +validate(Rule = {type, 'boolean'}, Name, Value, _ValidatorState) -> + V = binary_to_lower(Value), + try + case binary_to_existing_atom(V, utf8) of + B when is_boolean(B) -> {ok, B}; + _ -> validation_error(Rule, Name) + end + catch + error:badarg -> + validation_error(Rule, Name) + end; + +validate(Rule = {type, 'date'}, Name, Value, _ValidatorState) -> + case is_binary(Value) of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {type, 'datetime'}, Name, Value, _ValidatorState) -> + case is_binary(Value) of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {enum, Values}, Name, Value, _ValidatorState) -> + try + FormattedValue = erlang:binary_to_existing_atom(Value, utf8), + case lists:member(FormattedValue, Values) of + true -> {ok, FormattedValue}; + false -> validation_error(Rule, Name) + end + catch + error:badarg -> + validation_error(Rule, Name) + end; + +validate(Rule = {max, Max}, Name, Value, _ValidatorState) -> + case Value >= Max of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {exclusive_max, ExclusiveMax}, Name, Value, _ValidatorState) -> + case Value > ExclusiveMax of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {min, Min}, Name, Value, _ValidatorState) -> + case Value =< Min of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {exclusive_min, ExclusiveMin}, Name, Value, _ValidatorState) -> + case Value =< ExclusiveMin of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {max_length, MaxLength}, Name, Value, _ValidatorState) -> + case size(Value) =< MaxLength of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {min_length, MinLength}, Name, Value, _ValidatorState) -> + case size(Value) >= MinLength of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {pattern, Pattern}, Name, Value, _ValidatorState) -> + {ok, MP} = re:compile(Pattern), + case re:run(Value, MP) of + {match, _} -> ok; + _ -> validation_error(Rule, Name) + end; + +validate(Rule = schema, Name, Value, ValidatorState) -> + Definition = list_to_binary("#/definitions/" ++ swagger_utils:to_list(Name)), + try + _ = validate_with_schema(Value, Definition, ValidatorState), + ok + catch + throw:[{schema_invalid, _, Error} | _] -> + Info = #{ + type => schema_invalid, + error => Error + }, + validation_error(Rule, Name, Info); + throw:[{data_invalid, Schema, Error, _, Path} | _] -> + Info = #{ + type => data_invalid, + error => Error, + schema => Schema, + path => Path + }, + validation_error(Rule, Name, Info) + end; + +validate(Rule, Name, _Value, _ValidatorState) -> + error_logger:info_msg("Can't validate ~p with ~p", [Name, Rule]), + error({unknown_validation_rule, Rule}). + +-spec validation_error(Rule :: any(), Name :: any()) -> no_return(). + +validation_error(ViolatedRule, Name) -> + validation_error(ViolatedRule, Name, #{}). + +-spec validation_error(Rule :: any(), Name :: any(), Info :: #{}) -> no_return(). + +validation_error(ViolatedRule, Name, Info) -> + throw({wrong_param, Name, ViolatedRule, Info}). + +get_value(body, _Name, Req0) -> + {ok, Body, Req} = cowboy_req:body(Req0), + Value = prepare_body(Body), + {Value, Req}; + +get_value(qs_val, Name, Req0) -> + {QS, Req} = cowboy_req:qs_vals(Req0), + Value = swagger_utils:get_opt(swagger_utils:to_qs(Name), QS), + {Value, Req}; + +get_value(header, Name, Req0) -> + {Headers, Req} = cowboy_req:headers(Req0), + Value = swagger_utils:get_opt(swagger_utils:to_header(Name), Headers), + {Value, Req}; + +get_value(binding, Name, Req0) -> + {Bindings, Req} = cowboy_req:bindings(Req0), + Value = swagger_utils:get_opt(swagger_utils:to_binding(Name), Bindings), + {Value, Req}. + +prepare_body(Body) -> + case Body of + <<"">> -> <<"">>; + _ -> jsx:decode(Body, [return_maps]) + end. + +validate_with_schema(Body, Definition, ValidatorState) -> + jesse_schema_validator:validate_with_state( + [{<<"$ref">>, Definition}], + Body, + ValidatorState + ). + +prepare_param(Rules, Name, Value, ValidatorState) -> + try + Result = lists:foldl( + fun(Rule, Acc) -> + case validate(Rule, Name, Acc, ValidatorState) of + ok -> Acc; + {ok, Prepared} -> Prepared + end + end, + Value, + Rules + ), + {ok, Result} + catch + throw:Reason -> + {error, Reason} + end. + +binary_to_lower(V) when is_binary(V) -> + list_to_binary(string:to_lower(swagger_utils:to_list(V))). diff --git a/samples/server/petstore/erlang-server/src/swagger_auth.erl b/samples/server/petstore/erlang-server/src/swagger_auth.erl new file mode 100644 index 00000000000..275ad19f38f --- /dev/null +++ b/samples/server/petstore/erlang-server/src/swagger_auth.erl @@ -0,0 +1,50 @@ +-module(swagger_auth). + +-export([authorize_api_key/5]). + +-spec authorize_api_key( + LogicHandler :: atom(), + OperationID :: swagger_api:operation_id(), + From :: header | qs_val, + KeyParam :: iodata() | atom(), + Req ::cowboy_req:req() +)-> {true, Context :: #{binary() => any()}, Req ::cowboy_req:req()} | + {false, AuthHeader :: binary(), Req ::cowboy_req:req()}. + +authorize_api_key(LogicHandler, OperationID, From, KeyParam, Req0) -> + {ApiKey, Req} = get_api_key(From, KeyParam, Req0), + case ApiKey of + undefined -> + AuthHeader = <<"">>, + {false, AuthHeader, Req}; + _ -> + Result = swagger_logic_handler:authorize_api_key( + LogicHandler, + OperationID, + ApiKey + ), + case Result of + {true, Context} -> + {true, Context, Req}; + false -> + AuthHeader = <<"">>, + {false, AuthHeader, Req} + end + end. + +get_api_key(header, KeyParam, Req0) -> + {Headers, Req} = cowboy_req:headers(Req0), + { + swagger_utils:get_opt( + swagger_utils:to_header(KeyParam), + Headers + ), + Req + }; + +get_api_key(qs_val, KeyParam, Req0) -> + {QS, Req} = cowboy_req:qs_vals(Req0), + { swagger_utils:get_opt(KeyParam, QS), Req}. + + + diff --git a/samples/server/petstore/erlang-server/src/swagger_default_logic_handler.erl b/samples/server/petstore/erlang-server/src/swagger_default_logic_handler.erl new file mode 100644 index 00000000000..b68b8c00cdb --- /dev/null +++ b/samples/server/petstore/erlang-server/src/swagger_default_logic_handler.erl @@ -0,0 +1,24 @@ +-module(swagger_default_logic_handler). + +-behaviour(swagger_logic_handler). + +-export([handle_request/3]). +-export([authorize_api_key/2]). + +-spec authorize_api_key(OperationID :: swagger_api:operation_id(), ApiKey :: binary()) -> {true, #{}}. + +authorize_api_key(_, _) -> {true, #{}}. + +-spec handle_request( + OperationID :: swagger_api:operation_id(), + Req :: cowboy_req:req(), + Context :: #{} +) -> + {Status :: cowboy:http_status(), Headers :: cowboy:http_headers(), Body :: #{}}. + +handle_request(OperationID, Req, Context) -> + error_logger:error_msg( + "Got not implemented request to process: ~p~n", + [{OperationID, Req, Context}] + ), + {501, [], #{}}. diff --git a/samples/server/petstore/erlang-server/src/swagger_logic_handler.erl b/samples/server/petstore/erlang-server/src/swagger_logic_handler.erl new file mode 100644 index 00000000000..4ff40c85ec6 --- /dev/null +++ b/samples/server/petstore/erlang-server/src/swagger_logic_handler.erl @@ -0,0 +1,38 @@ +-module(swagger_logic_handler). + +-export([handle_request/4]). +-export([authorize_api_key/3]). +-type context() :: #{binary() => any()}. +-type handler_response() ::{ + Status :: cowboy:http_status(), + Headers :: cowboy:http_headers(), + Body :: #{} +}. + +-export_type([handler_response/0]). + +-callback authorize_api_key( + OperationID :: swagger_api:operation_id(), + ApiKey :: binary() +) -> + Result :: boolean() | {boolean(), context()}. + + +-callback handle_request(OperationID :: swagger_api:operation_id(), Request :: any(), Context :: context()) -> + handler_response(). + +-spec handle_request( + Handler :: atom(), + OperationID :: swagger_api:operation_id(), + Request :: any(), + Context :: context() +) -> + handler_response(). + +handle_request(Handler, OperationID, Req, Context) -> + Handler:handle_request(OperationID, Req, Context). + +-spec authorize_api_key(Handler :: atom(), OperationID :: swagger_api:operation_id(), ApiKey :: binary()) -> + Result :: false | {true, context()}. +authorize_api_key(Handler, OperationID, ApiKey) -> + Handler:authorize_api_key(OperationID, ApiKey). diff --git a/samples/server/petstore/erlang-server/src/swagger_pet_handler.erl b/samples/server/petstore/erlang-server/src/swagger_pet_handler.erl new file mode 100644 index 00000000000..4351da7da6c --- /dev/null +++ b/samples/server/petstore/erlang-server/src/swagger_pet_handler.erl @@ -0,0 +1,408 @@ +%% basic handler +-module(swagger_pet_handler). + +%% Cowboy REST callbacks +-export([allowed_methods/2]). +-export([init/3]). +-export([rest_init/2]). +-export([allow_missing_post/2]). +-export([content_types_accepted/2]). +-export([content_types_provided/2]). +-export([delete_resource/2]). +-export([is_authorized/2]). +-export([known_content_type/2]). +-export([malformed_request/2]). +-export([valid_content_headers/2]). +-export([valid_entity_length/2]). + +%% Handlers +-export([handle_request_json/2]). + +-record(state, { + operation_id :: swagger_api:operation_id(), + logic_handler :: atom(), + validator_state :: jesse_state:state(), + context=#{} :: #{} +}). + +-type state() :: state(). + +-spec init(TransportName :: atom(), Req :: cowboy_req:req(), Opts :: swagger_router:init_opts()) -> + {upgrade, protocol, cowboy_rest, Req :: cowboy_req:req(), Opts :: swagger_router:init_opts()}. + +init(_Transport, Req, Opts) -> + {upgrade, protocol, cowboy_rest, Req, Opts}. + +-spec rest_init(Req :: cowboy_req:req(), Opts :: swagger_router:init_opts()) -> + {ok, Req :: cowboy_req:req(), State :: state()}. + +rest_init(Req0, {Operations, LogicHandler, ValidatorState}) -> + {Method, Req} = cowboy_req:method(Req0), + OperationID = maps:get(Method, Operations, undefined), + + error_logger:info_msg("Attempt to process operation: ~p", [OperationID]), + + State = #state{ + operation_id = OperationID, + logic_handler = LogicHandler, + validator_state = ValidatorState + }, + {ok, Req, State}. + +-spec allowed_methods(Req :: cowboy_req:req(), State :: state()) -> + {Value :: [binary()], Req :: cowboy_req:req(), State :: state()}. + + +allowed_methods( + Req, + State = #state{ + operation_id = 'AddPet' + } +) -> + {[<<"POST">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'DeletePet' + } +) -> + {[<<"DELETE">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'FindPetsByStatus' + } +) -> + {[<<"GET">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'FindPetsByTags' + } +) -> + {[<<"GET">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'GetPetById' + } +) -> + {[<<"GET">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'UpdatePet' + } +) -> + {[<<"PUT">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'UpdatePetWithForm' + } +) -> + {[<<"POST">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'UploadFile' + } +) -> + {[<<"POST">>], Req, State}; + +allowed_methods(Req, State) -> + {[], Req, State}. + +-spec is_authorized(Req :: cowboy_req:req(), State :: state()) -> + { + Value :: true | {false, AuthHeader :: iodata()}, + Req :: cowboy_req:req(), + State :: state() + }. + +is_authorized( + Req0, + State = #state{ + operation_id = 'AddPet' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized( + Req0, + State = #state{ + operation_id = 'DeletePet' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized( + Req0, + State = #state{ + operation_id = 'FindPetsByStatus' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized( + Req0, + State = #state{ + operation_id = 'FindPetsByTags' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized( + Req0, + State = #state{ + operation_id = 'GetPetById' = OperationID, + logic_handler = LogicHandler + } +) -> + From = header, + Result = swagger_auth:authorize_api_key( + LogicHandler, + OperationID, + From, + "api_key", + Req0 + ), + case Result of + {true, Context, Req} -> {true, Req, State#state{context = Context}}; + {false, AuthHeader, Req} -> {{false, AuthHeader}, Req, State} + end; + +is_authorized( + Req0, + State = #state{ + operation_id = 'UpdatePet' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized( + Req0, + State = #state{ + operation_id = 'UpdatePetWithForm' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized( + Req0, + State = #state{ + operation_id = 'UploadFile' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized(Req, State) -> + {{false, <<"">>}, Req, State}. + +-spec content_types_accepted(Req :: cowboy_req:req(), State :: state()) -> + { + Value :: [{binary(), AcceptResource :: atom()}], + Req :: cowboy_req:req(), + State :: state() + }. + +content_types_accepted(Req, State) -> + {[ + {<<"application/json">>, handle_request_json} + ], Req, State}. + +-spec valid_content_headers(Req :: cowboy_req:req(), State :: state()) -> + {Value :: boolean(), Req :: cowboy_req:req(), State :: state()}. + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'AddPet' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'DeletePet' + } +) -> + Headers = ["api_key"], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'FindPetsByStatus' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'FindPetsByTags' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'GetPetById' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'UpdatePet' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'UpdatePetWithForm' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'UploadFile' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers(Req, State) -> + {false, Req, State}. + +-spec content_types_provided(Req :: cowboy_req:req(), State :: state()) -> + { + Value :: [{binary(), ProvideResource :: atom()}], + Req :: cowboy_req:req(), + State :: state() + }. + +content_types_provided(Req, State) -> + {[ + {<<"application/json">>, handle_request_json} + ], Req, State}. + +-spec malformed_request(Req :: cowboy_req:req(), State :: state()) -> + {Value :: false, Req :: cowboy_req:req(), State :: state()}. + +malformed_request(Req, State) -> + {false, Req, State}. + +-spec allow_missing_post(Req :: cowboy_req:req(), State :: state()) -> + {Value :: false, Req :: cowboy_req:req(), State :: state()}. + +allow_missing_post(Req, State) -> + {false, Req, State}. + +-spec delete_resource(Req :: cowboy_req:req(), State :: state()) -> + processed_response(). + +delete_resource(Req, State) -> + handle_request_json(Req, State). + +-spec known_content_type(Req :: cowboy_req:req(), State :: state()) -> + {Value :: true, Req :: cowboy_req:req(), State :: state()}. + +known_content_type(Req, State) -> + {true, Req, State}. + +-spec valid_entity_length(Req :: cowboy_req:req(), State :: state()) -> + {Value :: true, Req :: cowboy_req:req(), State :: state()}. + +valid_entity_length(Req, State) -> + %% @TODO check the length + {true, Req, State}. + +%%%% + +-type result_ok() :: { + ok, + {Status :: cowboy:http_status(), Headers :: cowboy:http_headers(), Body :: iodata()} +}. + +-type result_error() :: {error, Reason :: any()}. + +-type processed_response() :: {halt, cowboy_req:req(), state()}. + +-spec process_response(result_ok() | result_error(), cowboy_req:req(), state()) -> + processed_response(). + +process_response(Response, Req0, State = #state{operation_id = OperationID}) -> + case Response of + {ok, {Code, Headers, Body}} -> + {ok, Req} = cowboy_req:reply(Code, Headers, Body, Req0), + {halt, Req, State}; + {error, Message} -> + error_logger:error_msg("Unable to process request for ~p: ~p", [OperationID, Message]), + + {ok, Req} = cowboy_req:reply(400, Req0), + {halt, Req, State} + end. + +-spec handle_request_json(cowboy_req:req(), state()) -> {halt, cowboy_req:req(), state()}. + +handle_request_json( + Req0, + State = #state{ + operation_id = OperationID, + logic_handler = LogicHandler, + validator_state = ValidatorState, + context = Context + } +) -> + case swagger_api:populate_request(OperationID, Req0, ValidatorState) of + {ok, Populated, Req1} -> + {Code, Headers, Body} = swagger_logic_handler:handle_request( + LogicHandler, + OperationID, + Populated, + Context + ), + _ = swagger_api:validate_response( + OperationID, + Code, + Body, + ValidatorState + ), + PreparedBody = jsx:encode(Body), + Response = {ok, {Code, Headers, PreparedBody}}, + process_response(Response, Req1, State); + {error, Reason, Req1} -> + process_response({error, Reason}, Req1, State) + end. + +validate_headers(_, Req) -> {true, Req}. diff --git a/samples/server/petstore/erlang-server/src/swagger_router.erl b/samples/server/petstore/erlang-server/src/swagger_router.erl new file mode 100644 index 00000000000..7a1b004a5f2 --- /dev/null +++ b/samples/server/petstore/erlang-server/src/swagger_router.erl @@ -0,0 +1,169 @@ +-module(swagger_router). + +-export([get_paths/1]). + +-type operations() :: #{ + Method :: binary() => swagger_api:operation_id() +}. + +-type init_opts() :: { + Operations :: operations(), + LogicHandler :: atom(), + ValidatorState :: jesse_state:state() +}. + +-export_type([init_opts/0]). + +-spec get_paths(LogicHandler :: atom()) -> [{'_',[{ + Path :: string(), + Handler :: atom(), + InitOpts :: init_opts() +}]}]. + +get_paths(LogicHandler) -> + ValidatorState = prepare_validator(), + PreparedPaths = maps:fold( + fun(Path, #{operations := Operations, handler := Handler}, Acc) -> + [{Path, Handler, Operations} | Acc] + end, + [], + group_paths() + ), + [ + {'_', + [{P, H, {O, LogicHandler, ValidatorState}} || {P, H, O} <- PreparedPaths] + } + ]. + +group_paths() -> + maps:fold( + fun(OperationID, #{path := Path, method := Method, handler := Handler}, Acc) -> + case maps:find(Path, Acc) of + {ok, PathInfo0 = #{operations := Operations0}} -> + Operations = Operations0#{Method => OperationID}, + PathInfo = PathInfo0#{operations => Operations}, + Acc#{Path => PathInfo}; + error -> + Operations = #{Method => OperationID}, + PathInfo = #{handler => Handler, operations => Operations}, + Acc#{Path => PathInfo} + end + end, + #{}, + get_operations() + ). + +get_operations() -> + #{ + 'AddPet' => #{ + path => "/v2/pet", + method => <<"POST">>, + handler => 'swagger_pet_handler' + }, + 'DeletePet' => #{ + path => "/v2/pet/:petId", + method => <<"DELETE">>, + handler => 'swagger_pet_handler' + }, + 'FindPetsByStatus' => #{ + path => "/v2/pet/findByStatus", + method => <<"GET">>, + handler => 'swagger_pet_handler' + }, + 'FindPetsByTags' => #{ + path => "/v2/pet/findByTags", + method => <<"GET">>, + handler => 'swagger_pet_handler' + }, + 'GetPetById' => #{ + path => "/v2/pet/:petId", + method => <<"GET">>, + handler => 'swagger_pet_handler' + }, + 'UpdatePet' => #{ + path => "/v2/pet", + method => <<"PUT">>, + handler => 'swagger_pet_handler' + }, + 'UpdatePetWithForm' => #{ + path => "/v2/pet/:petId", + method => <<"POST">>, + handler => 'swagger_pet_handler' + }, + 'UploadFile' => #{ + path => "/v2/pet/:petId/uploadImage", + method => <<"POST">>, + handler => 'swagger_pet_handler' + }, + 'DeleteOrder' => #{ + path => "/v2/store/order/:orderId", + method => <<"DELETE">>, + handler => 'swagger_store_handler' + }, + 'GetInventory' => #{ + path => "/v2/store/inventory", + method => <<"GET">>, + handler => 'swagger_store_handler' + }, + 'GetOrderById' => #{ + path => "/v2/store/order/:orderId", + method => <<"GET">>, + handler => 'swagger_store_handler' + }, + 'PlaceOrder' => #{ + path => "/v2/store/order", + method => <<"POST">>, + handler => 'swagger_store_handler' + }, + 'CreateUser' => #{ + path => "/v2/user", + method => <<"POST">>, + handler => 'swagger_user_handler' + }, + 'CreateUsersWithArrayInput' => #{ + path => "/v2/user/createWithArray", + method => <<"POST">>, + handler => 'swagger_user_handler' + }, + 'CreateUsersWithListInput' => #{ + path => "/v2/user/createWithList", + method => <<"POST">>, + handler => 'swagger_user_handler' + }, + 'DeleteUser' => #{ + path => "/v2/user/:username", + method => <<"DELETE">>, + handler => 'swagger_user_handler' + }, + 'GetUserByName' => #{ + path => "/v2/user/:username", + method => <<"GET">>, + handler => 'swagger_user_handler' + }, + 'LoginUser' => #{ + path => "/v2/user/login", + method => <<"GET">>, + handler => 'swagger_user_handler' + }, + 'LogoutUser' => #{ + path => "/v2/user/logout", + method => <<"GET">>, + handler => 'swagger_user_handler' + }, + 'UpdateUser' => #{ + path => "/v2/user/:username", + method => <<"PUT">>, + handler => 'swagger_user_handler' + } + }. + +prepare_validator() -> + R = jsx:decode(element(2, file:read_file(get_swagger_path()))), + jesse_state:new(R, [{default_schema_ver, <<"http://json-schema.org/draft-04/schema#">>}]). + + +get_swagger_path() -> + {ok, AppName} = application:get_application(?MODULE), + filename:join(swagger_utils:priv_dir(AppName), "swagger.json"). + + diff --git a/samples/server/petstore/erlang-server/src/swagger_server.erl b/samples/server/petstore/erlang-server/src/swagger_server.erl new file mode 100644 index 00000000000..4f56a326034 --- /dev/null +++ b/samples/server/petstore/erlang-server/src/swagger_server.erl @@ -0,0 +1,64 @@ +-module(swagger_server). + + +-define(DEFAULT_ACCEPTORS_POOLSIZE, 100). +-define(DEFAULT_LOGIC_HANDLER, swagger_default_logic_handler). + +-export([child_spec/2]). + +-spec child_spec( ID :: any(), #{ + ip => inet:ip_address(), + port => inet:port_number(), + net_opts => [] +}) -> supervisor:child_spec(). + +child_spec(ID, #{ + ip := IP , + port := Port, + net_opts := NetOpts +} = Params) -> + AcceptorsPool = ?DEFAULT_ACCEPTORS_POOLSIZE, + {Transport, TransportOpts} = get_socket_transport(IP, Port, NetOpts), + LogicHandler = maps:get(logic_handler, Params, ?DEFAULT_LOGIC_HANDLER), + ExtraOpts = maps:get(cowboy_extra_opts, Params, []), + CowboyOpts = get_cowboy_config(LogicHandler, ExtraOpts), + ranch:child_spec({?MODULE, ID}, AcceptorsPool, + Transport, TransportOpts, cowboy_protocol, CowboyOpts). + +get_socket_transport(IP, Port, Options) -> + Opts = [ + {ip, IP}, + {port, Port} + ], + case swagger_utils:get_opt(ssl, Options) of + SslOpts = [_|_] -> + {ranch_ssl, Opts ++ SslOpts}; + undefined -> + {ranch_tcp, Opts} + end. + +get_cowboy_config(LogicHandler, ExtraOpts) -> + get_cowboy_config(LogicHandler, ExtraOpts, get_default_opts(LogicHandler)). + +get_cowboy_config(_LogicHandler, [], Opts) -> + Opts; + +get_cowboy_config(LogicHandler, [{env, Env} | Rest], Opts) -> + NewEnv = case proplists:get_value(dispatch, Env) of + undefined -> [get_default_dispatch(LogicHandler) | Env]; + _ -> Env + end, + get_cowboy_config(LogicHandler, Rest, store_key(env, NewEnv, Opts)); + +get_cowboy_config(LogicHandler, [{Key, Value}| Rest], Opts) -> + get_cowboy_config(LogicHandler, Rest, store_key(Key, Value, Opts)). + +get_default_dispatch(LogicHandler) -> + Paths = swagger_router:get_paths(LogicHandler), + {dispatch, cowboy_router:compile(Paths)}. + +get_default_opts(LogicHandler) -> + [{env, [get_default_dispatch(LogicHandler)]}]. + +store_key(Key, Value, Opts) -> + lists:keystore(Key, 1, Opts, {Key, Value}). diff --git a/samples/server/petstore/erlang-server/src/swagger_store_handler.erl b/samples/server/petstore/erlang-server/src/swagger_store_handler.erl new file mode 100644 index 00000000000..d70470d6384 --- /dev/null +++ b/samples/server/petstore/erlang-server/src/swagger_store_handler.erl @@ -0,0 +1,304 @@ +%% basic handler +-module(swagger_store_handler). + +%% Cowboy REST callbacks +-export([allowed_methods/2]). +-export([init/3]). +-export([rest_init/2]). +-export([allow_missing_post/2]). +-export([content_types_accepted/2]). +-export([content_types_provided/2]). +-export([delete_resource/2]). +-export([is_authorized/2]). +-export([known_content_type/2]). +-export([malformed_request/2]). +-export([valid_content_headers/2]). +-export([valid_entity_length/2]). + +%% Handlers +-export([handle_request_json/2]). + +-record(state, { + operation_id :: swagger_api:operation_id(), + logic_handler :: atom(), + validator_state :: jesse_state:state(), + context=#{} :: #{} +}). + +-type state() :: state(). + +-spec init(TransportName :: atom(), Req :: cowboy_req:req(), Opts :: swagger_router:init_opts()) -> + {upgrade, protocol, cowboy_rest, Req :: cowboy_req:req(), Opts :: swagger_router:init_opts()}. + +init(_Transport, Req, Opts) -> + {upgrade, protocol, cowboy_rest, Req, Opts}. + +-spec rest_init(Req :: cowboy_req:req(), Opts :: swagger_router:init_opts()) -> + {ok, Req :: cowboy_req:req(), State :: state()}. + +rest_init(Req0, {Operations, LogicHandler, ValidatorState}) -> + {Method, Req} = cowboy_req:method(Req0), + OperationID = maps:get(Method, Operations, undefined), + + error_logger:info_msg("Attempt to process operation: ~p", [OperationID]), + + State = #state{ + operation_id = OperationID, + logic_handler = LogicHandler, + validator_state = ValidatorState + }, + {ok, Req, State}. + +-spec allowed_methods(Req :: cowboy_req:req(), State :: state()) -> + {Value :: [binary()], Req :: cowboy_req:req(), State :: state()}. + + +allowed_methods( + Req, + State = #state{ + operation_id = 'DeleteOrder' + } +) -> + {[<<"DELETE">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'GetInventory' + } +) -> + {[<<"GET">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'GetOrderById' + } +) -> + {[<<"GET">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'PlaceOrder' + } +) -> + {[<<"POST">>], Req, State}; + +allowed_methods(Req, State) -> + {[], Req, State}. + +-spec is_authorized(Req :: cowboy_req:req(), State :: state()) -> + { + Value :: true | {false, AuthHeader :: iodata()}, + Req :: cowboy_req:req(), + State :: state() + }. + +is_authorized( + Req0, + State = #state{ + operation_id = 'DeleteOrder' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized( + Req0, + State = #state{ + operation_id = 'GetInventory' = OperationID, + logic_handler = LogicHandler + } +) -> + From = header, + Result = swagger_auth:authorize_api_key( + LogicHandler, + OperationID, + From, + "api_key", + Req0 + ), + case Result of + {true, Context, Req} -> {true, Req, State#state{context = Context}}; + {false, AuthHeader, Req} -> {{false, AuthHeader}, Req, State} + end; + +is_authorized( + Req0, + State = #state{ + operation_id = 'GetOrderById' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized( + Req0, + State = #state{ + operation_id = 'PlaceOrder' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized(Req, State) -> + {{false, <<"">>}, Req, State}. + +-spec content_types_accepted(Req :: cowboy_req:req(), State :: state()) -> + { + Value :: [{binary(), AcceptResource :: atom()}], + Req :: cowboy_req:req(), + State :: state() + }. + +content_types_accepted(Req, State) -> + {[ + {<<"application/json">>, handle_request_json} + ], Req, State}. + +-spec valid_content_headers(Req :: cowboy_req:req(), State :: state()) -> + {Value :: boolean(), Req :: cowboy_req:req(), State :: state()}. + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'DeleteOrder' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'GetInventory' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'GetOrderById' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'PlaceOrder' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers(Req, State) -> + {false, Req, State}. + +-spec content_types_provided(Req :: cowboy_req:req(), State :: state()) -> + { + Value :: [{binary(), ProvideResource :: atom()}], + Req :: cowboy_req:req(), + State :: state() + }. + +content_types_provided(Req, State) -> + {[ + {<<"application/json">>, handle_request_json} + ], Req, State}. + +-spec malformed_request(Req :: cowboy_req:req(), State :: state()) -> + {Value :: false, Req :: cowboy_req:req(), State :: state()}. + +malformed_request(Req, State) -> + {false, Req, State}. + +-spec allow_missing_post(Req :: cowboy_req:req(), State :: state()) -> + {Value :: false, Req :: cowboy_req:req(), State :: state()}. + +allow_missing_post(Req, State) -> + {false, Req, State}. + +-spec delete_resource(Req :: cowboy_req:req(), State :: state()) -> + processed_response(). + +delete_resource(Req, State) -> + handle_request_json(Req, State). + +-spec known_content_type(Req :: cowboy_req:req(), State :: state()) -> + {Value :: true, Req :: cowboy_req:req(), State :: state()}. + +known_content_type(Req, State) -> + {true, Req, State}. + +-spec valid_entity_length(Req :: cowboy_req:req(), State :: state()) -> + {Value :: true, Req :: cowboy_req:req(), State :: state()}. + +valid_entity_length(Req, State) -> + %% @TODO check the length + {true, Req, State}. + +%%%% + +-type result_ok() :: { + ok, + {Status :: cowboy:http_status(), Headers :: cowboy:http_headers(), Body :: iodata()} +}. + +-type result_error() :: {error, Reason :: any()}. + +-type processed_response() :: {halt, cowboy_req:req(), state()}. + +-spec process_response(result_ok() | result_error(), cowboy_req:req(), state()) -> + processed_response(). + +process_response(Response, Req0, State = #state{operation_id = OperationID}) -> + case Response of + {ok, {Code, Headers, Body}} -> + {ok, Req} = cowboy_req:reply(Code, Headers, Body, Req0), + {halt, Req, State}; + {error, Message} -> + error_logger:error_msg("Unable to process request for ~p: ~p", [OperationID, Message]), + + {ok, Req} = cowboy_req:reply(400, Req0), + {halt, Req, State} + end. + +-spec handle_request_json(cowboy_req:req(), state()) -> {halt, cowboy_req:req(), state()}. + +handle_request_json( + Req0, + State = #state{ + operation_id = OperationID, + logic_handler = LogicHandler, + validator_state = ValidatorState, + context = Context + } +) -> + case swagger_api:populate_request(OperationID, Req0, ValidatorState) of + {ok, Populated, Req1} -> + {Code, Headers, Body} = swagger_logic_handler:handle_request( + LogicHandler, + OperationID, + Populated, + Context + ), + _ = swagger_api:validate_response( + OperationID, + Code, + Body, + ValidatorState + ), + PreparedBody = jsx:encode(Body), + Response = {ok, {Code, Headers, PreparedBody}}, + process_response(Response, Req1, State); + {error, Reason, Req1} -> + process_response({error, Reason}, Req1, State) + end. + +validate_headers(_, Req) -> {true, Req}. diff --git a/samples/server/petstore/erlang-server/src/swagger_user_handler.erl b/samples/server/petstore/erlang-server/src/swagger_user_handler.erl new file mode 100644 index 00000000000..11c8d659416 --- /dev/null +++ b/samples/server/petstore/erlang-server/src/swagger_user_handler.erl @@ -0,0 +1,396 @@ +%% basic handler +-module(swagger_user_handler). + +%% Cowboy REST callbacks +-export([allowed_methods/2]). +-export([init/3]). +-export([rest_init/2]). +-export([allow_missing_post/2]). +-export([content_types_accepted/2]). +-export([content_types_provided/2]). +-export([delete_resource/2]). +-export([is_authorized/2]). +-export([known_content_type/2]). +-export([malformed_request/2]). +-export([valid_content_headers/2]). +-export([valid_entity_length/2]). + +%% Handlers +-export([handle_request_json/2]). + +-record(state, { + operation_id :: swagger_api:operation_id(), + logic_handler :: atom(), + validator_state :: jesse_state:state(), + context=#{} :: #{} +}). + +-type state() :: state(). + +-spec init(TransportName :: atom(), Req :: cowboy_req:req(), Opts :: swagger_router:init_opts()) -> + {upgrade, protocol, cowboy_rest, Req :: cowboy_req:req(), Opts :: swagger_router:init_opts()}. + +init(_Transport, Req, Opts) -> + {upgrade, protocol, cowboy_rest, Req, Opts}. + +-spec rest_init(Req :: cowboy_req:req(), Opts :: swagger_router:init_opts()) -> + {ok, Req :: cowboy_req:req(), State :: state()}. + +rest_init(Req0, {Operations, LogicHandler, ValidatorState}) -> + {Method, Req} = cowboy_req:method(Req0), + OperationID = maps:get(Method, Operations, undefined), + + error_logger:info_msg("Attempt to process operation: ~p", [OperationID]), + + State = #state{ + operation_id = OperationID, + logic_handler = LogicHandler, + validator_state = ValidatorState + }, + {ok, Req, State}. + +-spec allowed_methods(Req :: cowboy_req:req(), State :: state()) -> + {Value :: [binary()], Req :: cowboy_req:req(), State :: state()}. + + +allowed_methods( + Req, + State = #state{ + operation_id = 'CreateUser' + } +) -> + {[<<"POST">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'CreateUsersWithArrayInput' + } +) -> + {[<<"POST">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'CreateUsersWithListInput' + } +) -> + {[<<"POST">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'DeleteUser' + } +) -> + {[<<"DELETE">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'GetUserByName' + } +) -> + {[<<"GET">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'LoginUser' + } +) -> + {[<<"GET">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'LogoutUser' + } +) -> + {[<<"GET">>], Req, State}; + +allowed_methods( + Req, + State = #state{ + operation_id = 'UpdateUser' + } +) -> + {[<<"PUT">>], Req, State}; + +allowed_methods(Req, State) -> + {[], Req, State}. + +-spec is_authorized(Req :: cowboy_req:req(), State :: state()) -> + { + Value :: true | {false, AuthHeader :: iodata()}, + Req :: cowboy_req:req(), + State :: state() + }. + +is_authorized( + Req0, + State = #state{ + operation_id = 'CreateUser' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized( + Req0, + State = #state{ + operation_id = 'CreateUsersWithArrayInput' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized( + Req0, + State = #state{ + operation_id = 'CreateUsersWithListInput' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized( + Req0, + State = #state{ + operation_id = 'DeleteUser' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized( + Req0, + State = #state{ + operation_id = 'GetUserByName' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized( + Req0, + State = #state{ + operation_id = 'LoginUser' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized( + Req0, + State = #state{ + operation_id = 'LogoutUser' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized( + Req0, + State = #state{ + operation_id = 'UpdateUser' = OperationID, + logic_handler = LogicHandler + } +) -> + +is_authorized(Req, State) -> + {{false, <<"">>}, Req, State}. + +-spec content_types_accepted(Req :: cowboy_req:req(), State :: state()) -> + { + Value :: [{binary(), AcceptResource :: atom()}], + Req :: cowboy_req:req(), + State :: state() + }. + +content_types_accepted(Req, State) -> + {[ + {<<"application/json">>, handle_request_json} + ], Req, State}. + +-spec valid_content_headers(Req :: cowboy_req:req(), State :: state()) -> + {Value :: boolean(), Req :: cowboy_req:req(), State :: state()}. + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'CreateUser' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'CreateUsersWithArrayInput' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'CreateUsersWithListInput' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'DeleteUser' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'GetUserByName' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'LoginUser' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'LogoutUser' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers( + Req0, + State = #state{ + operation_id = 'UpdateUser' + } +) -> + Headers = [], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; + +valid_content_headers(Req, State) -> + {false, Req, State}. + +-spec content_types_provided(Req :: cowboy_req:req(), State :: state()) -> + { + Value :: [{binary(), ProvideResource :: atom()}], + Req :: cowboy_req:req(), + State :: state() + }. + +content_types_provided(Req, State) -> + {[ + {<<"application/json">>, handle_request_json} + ], Req, State}. + +-spec malformed_request(Req :: cowboy_req:req(), State :: state()) -> + {Value :: false, Req :: cowboy_req:req(), State :: state()}. + +malformed_request(Req, State) -> + {false, Req, State}. + +-spec allow_missing_post(Req :: cowboy_req:req(), State :: state()) -> + {Value :: false, Req :: cowboy_req:req(), State :: state()}. + +allow_missing_post(Req, State) -> + {false, Req, State}. + +-spec delete_resource(Req :: cowboy_req:req(), State :: state()) -> + processed_response(). + +delete_resource(Req, State) -> + handle_request_json(Req, State). + +-spec known_content_type(Req :: cowboy_req:req(), State :: state()) -> + {Value :: true, Req :: cowboy_req:req(), State :: state()}. + +known_content_type(Req, State) -> + {true, Req, State}. + +-spec valid_entity_length(Req :: cowboy_req:req(), State :: state()) -> + {Value :: true, Req :: cowboy_req:req(), State :: state()}. + +valid_entity_length(Req, State) -> + %% @TODO check the length + {true, Req, State}. + +%%%% + +-type result_ok() :: { + ok, + {Status :: cowboy:http_status(), Headers :: cowboy:http_headers(), Body :: iodata()} +}. + +-type result_error() :: {error, Reason :: any()}. + +-type processed_response() :: {halt, cowboy_req:req(), state()}. + +-spec process_response(result_ok() | result_error(), cowboy_req:req(), state()) -> + processed_response(). + +process_response(Response, Req0, State = #state{operation_id = OperationID}) -> + case Response of + {ok, {Code, Headers, Body}} -> + {ok, Req} = cowboy_req:reply(Code, Headers, Body, Req0), + {halt, Req, State}; + {error, Message} -> + error_logger:error_msg("Unable to process request for ~p: ~p", [OperationID, Message]), + + {ok, Req} = cowboy_req:reply(400, Req0), + {halt, Req, State} + end. + +-spec handle_request_json(cowboy_req:req(), state()) -> {halt, cowboy_req:req(), state()}. + +handle_request_json( + Req0, + State = #state{ + operation_id = OperationID, + logic_handler = LogicHandler, + validator_state = ValidatorState, + context = Context + } +) -> + case swagger_api:populate_request(OperationID, Req0, ValidatorState) of + {ok, Populated, Req1} -> + {Code, Headers, Body} = swagger_logic_handler:handle_request( + LogicHandler, + OperationID, + Populated, + Context + ), + _ = swagger_api:validate_response( + OperationID, + Code, + Body, + ValidatorState + ), + PreparedBody = jsx:encode(Body), + Response = {ok, {Code, Headers, PreparedBody}}, + process_response(Response, Req1, State); + {error, Reason, Req1} -> + process_response({error, Reason}, Req1, State) + end. + +validate_headers(_, Req) -> {true, Req}. diff --git a/samples/server/petstore/erlang-server/src/swagger_utils.erl b/samples/server/petstore/erlang-server/src/swagger_utils.erl new file mode 100644 index 00000000000..f7897fddd84 --- /dev/null +++ b/samples/server/petstore/erlang-server/src/swagger_utils.erl @@ -0,0 +1,173 @@ +-module(swagger_utils). + +-export([to_binary/1]). +-export([to_list/1]). +-export([to_float/1]). +-export([to_int/1]). +-export([to_lower/1]). +-export([to_upper/1]). +-export([set_resp_headers/2]). +-export([to_header/1]). +-export([to_qs/1]). +-export([to_binding/1]). +-export([get_opt/2]). +-export([get_opt/3]). +-export([priv_dir/0]). +-export([priv_dir/1]). +-export([priv_path/1]). + + +-spec to_binary(iodata() | atom() | number()) -> binary(). + +to_binary(V) when is_binary(V) -> V; +to_binary(V) when is_list(V) -> iolist_to_binary(V); +to_binary(V) when is_atom(V) -> atom_to_binary(V, utf8); +to_binary(V) when is_integer(V) -> integer_to_binary(V); +to_binary(V) when is_float(V) -> float_to_binary(V). + +-spec to_list(iodata() | atom() | number()) -> string(). + +to_list(V) when is_list(V) -> V; +to_list(V) -> binary_to_list(to_binary(V)). + +-spec to_float(iodata()) -> number(). + +to_float(V) -> + Data = iolist_to_binary([V]), + case binary:split(Data, <<$.>>) of + [Data] -> + binary_to_integer(Data); + [<<>>, _] -> + binary_to_float(<<$0, Data/binary>>); + _ -> + binary_to_float(Data) + end. + +%% + +-spec to_int(integer() | binary() | list()) -> integer(). + +to_int(Data) when is_integer(Data) -> + Data; +to_int(Data) when is_binary(Data) -> + binary_to_integer(Data); +to_int(Data) when is_list(Data) -> + list_to_integer(Data). + +-spec set_resp_headers([{binary(), iodata()}], cowboy_req:req()) -> cowboy_req:req(). + +set_resp_headers([], Req) -> + Req; +set_resp_headers([{K, V} | T], Req0) -> + Req = cowboy_req:set_resp_header(K, V, Req0), + set_resp_headers(T, Req). + +-spec to_header(iodata() | atom() | number()) -> binary(). + +to_header(Name) -> + Prepared = to_binary(Name), + to_lower(Prepared). + +-spec to_qs(iodata() | atom() | number()) -> binary(). + +to_qs(Name) -> + to_binary(Name). + +-spec to_binding(iodata() | atom() | number()) -> atom(). + +to_binding(Name) -> + Prepared = to_binary(Name), + binary_to_atom(Prepared, utf8). + +-spec get_opt(any(), []) -> any(). + +get_opt(Key, Opts) -> + get_opt(Key, Opts, undefined). + +-spec get_opt(any(), [], any()) -> any(). + +get_opt(Key, Opts, Default) -> + case lists:keyfind(Key, 1, Opts) of + {_, Value} -> Value; + false -> Default + end. + +-spec priv_dir() -> file:filename(). + +priv_dir() -> + {ok, AppName} = application:get_application(), + priv_dir(AppName). + +-spec priv_dir(Application :: atom()) -> file:filename(). + +priv_dir(AppName) -> + case code:priv_dir(AppName) of + Value when is_list(Value) -> + Value ++ "/"; + _Error -> + select_priv_dir([filename:join(["apps", atom_to_list(AppName), "priv"]), "priv"]) + end. + +-spec priv_path(Relative :: file:filename()) -> file:filename(). + +priv_path(Relative) -> + filename:join(priv_dir(), Relative). + +-include_lib("kernel/include/file.hrl"). + +select_priv_dir(Paths) -> + case lists:dropwhile(fun test_priv_dir/1, Paths) of + [Path | _] -> Path; + _ -> exit(no_priv_dir) + end. + +test_priv_dir(Path) -> + case file:read_file_info(Path) of + {ok, #file_info{type = directory}} -> + false; + _ -> + true + end. + + +%% + +-spec to_lower(binary()) -> binary(). + +to_lower(S) -> + to_case(lower, S, <<>>). + +-spec to_upper(binary()) -> binary(). + +to_upper(S) -> + to_case(upper, S, <<>>). + +to_case(_Case, <<>>, Acc) -> + Acc; + +to_case(_Case, <>, _Acc) when C > 127 -> + error(badarg); + +to_case(Case = lower, <>, Acc) -> + to_case(Case, Rest, <>); + +to_case(Case = upper, <>, Acc) -> + to_case(Case, Rest, <>). + +to_lower_char(C) when is_integer(C), $A =< C, C =< $Z -> + C + 32; +to_lower_char(C) when is_integer(C), 16#C0 =< C, C =< 16#D6 -> + C + 32; +to_lower_char(C) when is_integer(C), 16#D8 =< C, C =< 16#DE -> + C + 32; +to_lower_char(C) -> + C. + +to_upper_char(C) when is_integer(C), $a =< C, C =< $z -> + C - 32; +to_upper_char(C) when is_integer(C), 16#E0 =< C, C =< 16#F6 -> + C - 32; +to_upper_char(C) when is_integer(C), 16#F8 =< C, C =< 16#FE -> + C - 32; +to_upper_char(C) -> + C. From 81e9bd0d738969a23b0d2945a27ce6ca76151246 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sat, 10 Sep 2016 00:23:00 +0800 Subject: [PATCH 344/470] add tips for filing better PR --- CONTRIBUTING.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2551c58bc6d..e22da10e35b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -72,3 +72,4 @@ To start the CI tests, you can run `mvn verify -Psamples` (assuming you've all t - Add test case(s) to cover the change - Document the fix in the code to make the code more readable - Make sure test cases passed after the change (one way is to leverage https://travis-ci.org/ to run the CI tests) +- File a PR with meaningful title, description and commit messages. A good example is https://github.com/swagger-api/swagger-codegen/pull/3306 From b6e2c5a301284c22e4a73b46322a2241c130f0ce Mon Sep 17 00:00:00 2001 From: wing328 Date: Sat, 10 Sep 2016 00:23:49 +0800 Subject: [PATCH 345/470] Update CONTRIBUTING.md --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e22da10e35b..f1ef0aa469b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -72,4 +72,4 @@ To start the CI tests, you can run `mvn verify -Psamples` (assuming you've all t - Add test case(s) to cover the change - Document the fix in the code to make the code more readable - Make sure test cases passed after the change (one way is to leverage https://travis-ci.org/ to run the CI tests) -- File a PR with meaningful title, description and commit messages. A good example is https://github.com/swagger-api/swagger-codegen/pull/3306 +- File a PR with meaningful title, description and commit messages. A good example is [PR-3306](https://github.com/swagger-api/swagger-codegen/pull/3306) From 06144f0ef795cf97f916a3d9530ae2c0ecddf490 Mon Sep 17 00:00:00 2001 From: jfiala Date: Sat, 10 Sep 2016 20:23:47 +0200 Subject: [PATCH 346/470] add cli switch for beanvalidation #2549 --- .../languages/JavaCXFServerCodegen.java | 29 ++++++++++++- .../codegen/languages/JavaClientCodegen.java | 17 +++++++- .../src/main/resources/Java/model.mustache | 2 + .../src/main/resources/Java/pojo.mustache | 2 + .../src/main/resources/Java/pom.mustache | 4 +- .../main/resources/JavaJaxRS/cxf/api.mustache | 5 ++- .../JavaJaxRS/cxf/apiServiceImpl.mustache | 12 +----- .../resources/JavaJaxRS/cxf/pojo.mustache | 42 ++++++++++--------- .../main/resources/JavaJaxRS/cxf/pom.mustache | 2 + 9 files changed, 78 insertions(+), 37 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java index 5ccb88459e3..6669963abe4 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java @@ -4,7 +4,12 @@ import java.io.File; import java.util.List; import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenModel; import io.swagger.codegen.CodegenOperation; import io.swagger.codegen.CodegenProperty; @@ -21,7 +26,14 @@ * */ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen -{ +{ + private static final Logger LOGGER = LoggerFactory.getLogger(JavaCXFServerCodegen.class); + + public static final String USE_BEANVALIDATION = "useBeanValidation"; + + protected boolean useBeanValidation = false; + + public JavaCXFServerCodegen() { super(); @@ -49,6 +61,8 @@ public JavaCXFServerCodegen() embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "cxf"; + cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations")); + } @@ -57,6 +71,15 @@ public void processOpts() { super.processOpts(); + if (additionalProperties.containsKey(USE_BEANVALIDATION)) { + boolean useBeanValidationProp = Boolean.valueOf(additionalProperties.get(USE_BEANVALIDATION).toString()); + this.setUseBeanValidation(useBeanValidationProp); + + // write back as boolean + additionalProperties.put(USE_BEANVALIDATION, useBeanValidationProp); + } + + supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); @@ -98,4 +121,8 @@ public String getHelp() { return "Generates a Java JAXRS Server application based on Apache CXF framework."; } + + public void setUseBeanValidation(boolean useBeanValidation) { + this.useBeanValidation = useBeanValidation; + } } 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 27e95190648..099f37c7cfb 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 @@ -14,12 +14,14 @@ public class JavaClientCodegen extends AbstractJavaCodegen { private static final Logger LOGGER = LoggerFactory.getLogger(JavaClientCodegen.class); public static final String USE_RX_JAVA = "useRxJava"; + public static final String USE_BEANVALIDATION = "useBeanValidation"; public static final String RETROFIT_1 = "retrofit"; public static final String RETROFIT_2 = "retrofit2"; protected String gradleWrapperPackage = "gradle.wrapper"; protected boolean useRxJava = false; + protected boolean useBeanValidation = false; public JavaClientCodegen() { super(); @@ -31,6 +33,7 @@ public JavaClientCodegen() { modelPackage = "io.swagger.client.model"; cliOptions.add(CliOption.newBoolean(USE_RX_JAVA, "Whether to use the RxJava adapter with the retrofit2 library.")); + cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations")); supportedLibraries.put(DEFAULT_LIBRARY, "HTTP client: Jersey client 1.19.1. JSON processing: Jackson 2.7.0"); supportedLibraries.put("feign", "HTTP client: Netflix Feign 8.16.0. JSON processing: Jackson 2.7.0"); @@ -68,6 +71,14 @@ public void processOpts() { if (additionalProperties.containsKey(USE_RX_JAVA)) { this.setUseRxJava(Boolean.valueOf(additionalProperties.get(USE_RX_JAVA).toString())); } + + if (additionalProperties.containsKey(USE_BEANVALIDATION)) { + boolean useBeanValidationProp = Boolean.valueOf(additionalProperties.get(USE_BEANVALIDATION).toString()); + this.setUseBeanValidation(useBeanValidationProp); + + // write back as boolean + additionalProperties.put(USE_BEANVALIDATION, useBeanValidationProp); + } final String invokerFolder = (sourceFolder + '/' + invokerPackage).replace(".", "/"); final String authFolder = (sourceFolder + '/' + invokerPackage + ".auth").replace(".", "/"); @@ -164,7 +175,7 @@ public Map postProcessOperations(Map objs) { operation.returnType = "Void"; } if (usesRetrofit2Library() && StringUtils.isNotEmpty(operation.path) && operation.path.startsWith("/")) - operation.path = operation.path.substring(1); + operation.path = operation.path.substring(1); } } } @@ -212,4 +223,8 @@ public void setUseRxJava(boolean useRxJava) { this.useRxJava = useRxJava; } + public void setUseBeanValidation(boolean useBeanValidation) { + this.useBeanValidation = useBeanValidation; + } + } diff --git a/modules/swagger-codegen/src/main/resources/Java/model.mustache b/modules/swagger-codegen/src/main/resources/Java/model.mustache index 1d72c3a4efe..073ce8978f7 100644 --- a/modules/swagger-codegen/src/main/resources/Java/model.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/model.mustache @@ -6,7 +6,9 @@ import java.util.Objects; {{#imports}} import {{import}}; {{/imports}} +{{#useBeanValidation}} import javax.validation.constraints.*; +{{/useBeanValidation}} {{#serializableModel}}import java.io.Serializable;{{/serializableModel}} {{#models}} diff --git a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache index 385fddfc036..ea1f2ad9456 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache @@ -49,6 +49,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali {{/maximum}} * @return {{name}} **/ +{{#useBeanValidation}} {{#required}} @NotNull {{/required}} @@ -76,6 +77,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali {{#maximum}} //@Max({{maximum}}) {{/maximum}} +{{/useBeanValidation}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") {{#vendorExtensions.extraAnnotation}} {{vendorExtensions.extraAnnotation}} diff --git a/modules/swagger-codegen/src/main/resources/Java/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/pom.mustache index 66e6aeb2517..fa6e82de77c 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pom.mustache @@ -175,7 +175,7 @@ migbase64 2.2 - +{{#useBeanValidation}} javax.validation @@ -183,7 +183,7 @@ 1.1.0.Final provided - +{{/useBeanValidation}} junit diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache index c949f117f8d..2ecbb80360d 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache @@ -20,14 +20,15 @@ import io.swagger.annotations.ApiOperation; public interface {{classname}} { {{#operations}} {{#operation}} + @{{httpMethod}} {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} {{#hasConsumes}}@Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} {{#hasProduces}}@Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} {{#summary}} -@ApiOperation(value = "{{summary}}") + @ApiOperation(value = "{{summary}}") {{/summary}} - public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}); + public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); {{/operation}} } {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache index dde547f91c6..3a9fe5480ca 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache @@ -17,22 +17,12 @@ import org.apache.cxf.jaxrs.ext.multipart.*; import io.swagger.annotations.Api; -@Path("/") {{#description}} -@Api(value = "/", description = "{{description}}") {{/description}} public class {{classname}}ServiceImpl implements {{classname}} { {{#operations}} {{#operation}} - @{{httpMethod}} - {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} - {{#hasConsumes}}@Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} - {{#hasProduces}}@Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} - {{! add description for CXF WADL (must be added to implementation class }} -{{#summary}} - @Description(value = "{{summary}}", target = DocTarget.METHOD) -{{/summary}} - public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}) { + public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { // TODO: Implement... {{#returnType}}return null;{{/returnType}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache index af565cdbf35..d8be3155f56 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache @@ -23,6 +23,26 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{>enumClass}}{{/items}}{{/items.isEnum}} @XmlElement(name="{{baseName}}") + @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") + private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}} + + {{#vars}} + /** + {{#description}} + * {{{description}}} + {{/description}} + {{^description}} + * Get {{name}} + {{/description}} + {{#minimum}} + * minimum: {{minimum}} + {{/minimum}} + {{#maximum}} + * maximum: {{maximum}} + {{/maximum}} + * @return {{name}} + **/ +{{#useBeanValidation}} {{#required}} @NotNull {{/required}} @@ -49,26 +69,8 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{/minimum}} {{#maximum}} //@Max({{maximum}}) -{{/maximum}} - @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") - private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}} - - {{#vars}} - /** - {{#description}} - * {{{description}}} - {{/description}} - {{^description}} - * Get {{name}} - {{/description}} - {{#minimum}} - * minimum: {{minimum}} - {{/minimum}} - {{#maximum}} - * maximum: {{maximum}} - {{/maximum}} - * @return {{name}} - **/ +{{/maximum}} +{{/useBeanValidation}} {{#vendorExtensions.extraAnnotation}} {{vendorExtensions.extraAnnotation}} {{/vendorExtensions.extraAnnotation}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache index 40a6135e636..f600dfee8e4 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache @@ -116,6 +116,7 @@ ${junit-version} test +{{#useBeanValidation}} javax.validation @@ -123,6 +124,7 @@ ${beanvalidation-version} provided +{{/useBeanValidation}} org.apache.cxf From f9d1f2472609e0f16bb8e0d6d45d31fb88031b95 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 11 Sep 2016 14:52:46 +0800 Subject: [PATCH 347/470] Fix appveyor maven environment variable (#3769) * fix maven env variable in appveyor * fix maven home --- appveyor.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/appveyor.yml b/appveyor.yml index 5710fa5bc3a..44827f51a44 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -17,6 +17,7 @@ install: - cmd: SET PATH=C:\maven\apache-maven-3.2.5\bin;%JAVA_HOME%\bin;%PATH% - cmd: SET MAVEN_OPTS=-XX:MaxPermSize=2g -Xmx4g - cmd: SET JAVA_OPTS=-XX:MaxPermSize=2g -Xmx4g + - cmd: SET M2_HOME=C:\maven\apache-maven-3.2.5 - git clone https://github.com/wing328/swagger-samples - ps: Start-Process -FilePath 'C:\maven\apache-maven-3.2.5\bin\mvn' -ArgumentList 'jetty:run' -WorkingDirectory "$env:appveyor_build_folder\swagger-samples\java\java-jersey-jaxrs" build_script: From bd3a15e273947fa29de83ad2ab2e9dfab3ae0a66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pa=C5=ADlo=20Ebermann?= Date: Sun, 11 Sep 2016 12:00:38 +0200 Subject: [PATCH 348/470] Feature/#3738 extract abstract scala codegen (#3755) * Issue #3738: extract AbstractScalaCodegen. This seems to not change anything in the output, at least for the Petstore samples. * Issue #3738: move languageSpecificPrimitives initialization to the super class * Issue #3738 move CliOptions to AbstractScalaCodegen. * Issue #3738 update samples. Only one change, remove of unnecessary imports. --- .../languages/AbstractScalaCodegen.java | 166 +++++++++++++ .../languages/AkkaScalaClientCodegen.java | 83 +------ .../languages/AsyncScalaClientCodegen.java | 124 +--------- .../codegen/languages/ScalaClientCodegen.java | 230 +++--------------- .../languages/ScalatraServerCodegen.java | 75 +----- .../scala/com/wordnik/client/model/Pet.scala | 2 - 6 files changed, 210 insertions(+), 470 deletions(-) create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractScalaCodegen.java diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractScalaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractScalaCodegen.java new file mode 100644 index 00000000000..29942fb31f4 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractScalaCodegen.java @@ -0,0 +1,166 @@ +package io.swagger.codegen.languages; + +import java.io.File; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import io.swagger.codegen.CliOption; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.BooleanProperty; +import io.swagger.models.properties.DateProperty; +import io.swagger.models.properties.DateTimeProperty; +import io.swagger.models.properties.DoubleProperty; +import io.swagger.models.properties.FloatProperty; +import io.swagger.models.properties.IntegerProperty; +import io.swagger.models.properties.LongProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; +import io.swagger.models.properties.StringProperty; + +public abstract class AbstractScalaCodegen extends DefaultCodegen { + + protected String modelPropertyNaming = "camelCase"; + protected String invokerPackage = "io.swagger.client"; + protected String sourceFolder = "src/main/scala"; + + public AbstractScalaCodegen() { + super(); + + languageSpecificPrimitives.addAll(Arrays.asList( + "String", + "boolean", + "Boolean", + "Double", + "Int", + "Long", + "Float", + "Object", + "Any", + "List", + "Seq", + "Map")); + + cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); + } + + @Override + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); + } + + @Override + public String 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); + } + + @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); + } + + @Override + public String toInstantiationType(Property p) { + if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return instantiationTypes.get("map") + "[String, " + inner + "]"; + } else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return instantiationTypes.get("array") + "[" + inner + "]"; + } else { + return null; + } + } + + @Override + public String toDefaultValue(Property p) { + if (p instanceof StringProperty) { + return "null"; + } else if (p instanceof BooleanProperty) { + return "null"; + } else if (p instanceof DateProperty) { + return "null"; + } else if (p instanceof DateTimeProperty) { + return "null"; + } else if (p instanceof DoubleProperty) { + return "null"; + } else if (p instanceof FloatProperty) { + return "null"; + } else if (p instanceof IntegerProperty) { + return "null"; + } else if (p instanceof LongProperty) { + return "null"; + } else if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return "new HashMap[String, " + inner + "]() "; + } else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return "new ListBuffer[" + inner + "]() "; + } else { + return "null"; + } + } + + @Override + public Map postProcessModels(Map objs) { + // remove model imports to avoid warnings for importing class in the same package in Scala + List> imports = (List>) objs.get("imports"); + final String prefix = modelPackage() + "."; + Iterator> iterator = imports.iterator(); + while (iterator.hasNext()) { + String _import = iterator.next().get("import"); + if (_import.startsWith(prefix)) iterator.remove(); + } + return objs; + } + + @Override + public String toModelFilename(String name) { + // should be the same as the model name + return toModelName(name); + } + + @Override + public String escapeUnsafeCharacters(String input) { + return input.replace("*/", "*_/").replace("/*", "/_*"); + } + +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java index 4b7c321e802..8be1c1f6d50 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java @@ -12,7 +12,6 @@ import io.swagger.codegen.CodegenResponse; import io.swagger.codegen.CodegenSecurity; import io.swagger.codegen.CodegenType; -import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; import io.swagger.models.auth.SecuritySchemeDefinition; import io.swagger.models.properties.ArrayProperty; @@ -42,13 +41,11 @@ import java.util.List; import java.util.Map; -public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenConfig { +public class AkkaScalaClientCodegen extends AbstractScalaCodegen implements CodegenConfig { protected String mainPackage = "io.swagger.client"; - protected String invokerPackage = mainPackage + ".core"; protected String groupId = "io.swagger"; protected String artifactId = "swagger-client"; protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "src/main/scala"; protected String resourcesFolder = "src/main/resources"; protected String configKey = "apiRequest"; protected int defaultTimeoutInMs = 5000; @@ -75,6 +72,7 @@ public AkkaScalaClientCodegen() { embeddedTemplateDir = templateDir = "akka-scala"; apiPackage = mainPackage + ".api"; modelPackage = mainPackage + ".model"; + invokerPackage = mainPackage + ".core"; setReservedWordsLowerCase( Arrays.asList( @@ -135,25 +133,8 @@ public AkkaScalaClientCodegen() { typeMapping.put("file", "File"); typeMapping.put("number", "Double"); - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Int", - "Long", - "Float", - "Object", - "List", - "Seq", - "Map") - ); instantiationTypes.put("array", "ListBuffer"); instantiationTypes.put("map", "Map"); - - cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); - cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); } @Override @@ -176,16 +157,6 @@ public String escapeReservedWord(String name) { return "`" + name + "`"; } - @Override - public String apiFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); - } - - @Override - public String modelFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); - } - @Override public Map postProcessOperations(Map objs) { if (registerNonStandardStatusCodes) { @@ -218,21 +189,6 @@ public Map postProcessOperations(Map objs) { return super.postProcessOperations(objs); } - @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); - } - @Override public List fromSecurity(Map schemes) { final List codegenSecurities = super.fromSecurity(schemes); @@ -297,36 +253,6 @@ public String toEnumName(CodegenProperty property) { return formatIdentifier(property.baseName, true); } - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if (languageSpecificPrimitives.contains(type)) { - return toModelName(type); - } - } else { - type = swaggerType; - } - return toModelName(type); - } - - @Override - public String toInstantiationType(Property p) { - if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); - return instantiationTypes.get("map") + "[String, " + inner + "]"; - } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - return instantiationTypes.get("array") + "[" + inner + "]"; - } else { - return null; - } - } - @Override public String toDefaultValue(Property p) { if (!p.getRequired()) { @@ -419,9 +345,4 @@ public String escapeQuotationMark(String input) { // remove " to avoid code injection return input.replace("\"", ""); } - - @Override - public String escapeUnsafeCharacters(String input) { - return input.replace("*/", "*_/").replace("/*", "/_*"); - } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java index 17fd4ab57b6..ea8ae308081 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java @@ -4,31 +4,16 @@ import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenType; -import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.BooleanProperty; -import io.swagger.models.properties.DateProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.DoubleProperty; -import io.swagger.models.properties.FloatProperty; -import io.swagger.models.properties.IntegerProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.StringProperty; import java.io.File; import java.util.Arrays; import java.util.HashMap; -import java.util.HashSet; -public class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String invokerPackage = "io.swagger.client"; +public class AsyncScalaClientCodegen extends AbstractScalaCodegen implements CodegenConfig { protected String groupId = "io.swagger"; protected String artifactId = "swagger-async-scala-client"; protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "src/main/scala"; protected String clientName = "SwaggerClient"; protected String authScheme = ""; protected boolean authPreemptive; @@ -94,24 +79,8 @@ public AsyncScalaClientCodegen() { typeMapping.put("object", "Any"); typeMapping.put("file", "File"); - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Int", - "Long", - "Float", - "Object", - "List", - "Map") - ); instantiationTypes.put("array", "ListBuffer"); instantiationTypes.put("map", "HashMap"); - - cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); - cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); } @Override @@ -128,95 +97,4 @@ public String getName() { public String getHelp() { return "Generates an Asynchronous Scala client library."; } - - @Override - public String escapeReservedWord(String name) { - return "_" + name; - } - - @Override - public String apiFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); - } - - @Override - public String modelFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); - } - - @Override - public String 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); - } - - @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); - } - - @Override - public String toInstantiationType(Property p) { - if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); - return instantiationTypes.get("map") + "[String, " + inner + "]"; - } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - return instantiationTypes.get("array") + "[" + inner + "]"; - } else { - return null; - } - } - - @Override - public String toDefaultValue(Property p) { - if (p instanceof StringProperty) { - return "null"; - } else if (p instanceof BooleanProperty) { - return "null"; - } else if (p instanceof DateProperty) { - return "null"; - } else if (p instanceof DateTimeProperty) { - return "null"; - } else if (p instanceof DoubleProperty) { - return "null"; - } else if (p instanceof FloatProperty) { - return "null"; - } else if (p instanceof IntegerProperty) { - return "null"; - } else if (p instanceof LongProperty) { - return "null"; - } else if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); - return "new HashMap[String, " + inner + "]() "; - } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - return "new ListBuffer[" + inner + "]() "; - } else { - return "null"; - } - } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java index a4f263f858a..ea4539133af 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java @@ -4,41 +4,22 @@ import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenType; -import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.BooleanProperty; -import io.swagger.models.properties.DateProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.DoubleProperty; -import io.swagger.models.properties.FloatProperty; -import io.swagger.models.properties.IntegerProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.StringProperty; import java.io.File; import java.util.Arrays; import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; import org.apache.commons.lang3.StringUtils; -public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String modelPropertyNaming= "camelCase"; - protected String invokerPackage = "io.swagger.client"; - protected String groupId = "io.swagger"; - protected String artifactId = "swagger-scala-client"; - protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "src/main/scala"; +public class ScalaClientCodegen extends AbstractScalaCodegen implements CodegenConfig { protected String authScheme = ""; protected String gradleWrapperPackage = "gradle.wrapper"; protected boolean authPreemptive; protected boolean asyncHttpClient = !authScheme.isEmpty(); + protected String groupId = "io.swagger"; + protected String artifactId = "swagger-scala-client"; + protected String artifactVersion = "1.0.0"; public ScalaClientCodegen() { super(); @@ -118,37 +99,21 @@ public ScalaClientCodegen() { typeMapping.put("binary", "String"); typeMapping.put("ByteArray", "String"); - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Int", - "Long", - "Float", - "Object", - "Any", - "List", - "Map") - ); instantiationTypes.put("array", "ListBuffer"); instantiationTypes.put("map", "HashMap"); - cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); - cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); cliOptions.add(new CliOption(CodegenConstants.MODEL_PROPERTY_NAMING, CodegenConstants.MODEL_PROPERTY_NAMING_DESC).defaultValue("camelCase")); } @Override public void processOpts() { super.processOpts(); - + if (additionalProperties.containsKey(CodegenConstants.MODEL_PROPERTY_NAMING)) { setModelPropertyNaming((String) additionalProperties.get(CodegenConstants.MODEL_PROPERTY_NAMING)); } } - + public void setModelPropertyNaming(String naming) { if ("original".equals(naming) || "camelCase".equals(naming) || "PascalCase".equals(naming) || "snake_case".equals(naming)) { @@ -163,6 +128,35 @@ public void setModelPropertyNaming(String naming) { public String getModelPropertyNaming() { return this.modelPropertyNaming; } + @Override + public String toVarName(String name) { + // sanitize name + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + + if("_".equals(name)) { + name = "_u"; + } + + // if it's all uppper case, do nothing + if (name.matches("^[A-Z_]*$")) { + return name; + } + + name = getNameUsingModelPropertyNaming(name); + + // for reserved word or word starting with number, append _ + if (isReservedWord(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } + + return name; + } + + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } public String getNameUsingModelPropertyNaming(String name) { switch (CodegenConstants.MODEL_PROPERTY_NAMING_TYPE.valueOf(getModelPropertyNaming())) { @@ -192,98 +186,6 @@ public String getHelp() { return "Generates a Scala client library."; } - @Override - public String escapeReservedWord(String name) { - return "_" + name; - } - - @Override - public String apiFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); - } - - @Override - public String modelFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); - } - - @Override - public String 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); - } - - @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); - } - - @Override - public String toInstantiationType(Property p) { - if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); - return instantiationTypes.get("map") + "[String, " + inner + "]"; - } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - return instantiationTypes.get("array") + "[" + inner + "]"; - } else { - return null; - } - } - - @Override - public String toDefaultValue(Property p) { - if (p instanceof StringProperty) { - return "null"; - } else if (p instanceof BooleanProperty) { - return "null"; - } else if (p instanceof DateProperty) { - return "null"; - } else if (p instanceof DateTimeProperty) { - return "null"; - } else if (p instanceof DoubleProperty) { - return "null"; - } else if (p instanceof FloatProperty) { - return "null"; - } else if (p instanceof IntegerProperty) { - return "null"; - } else if (p instanceof LongProperty) { - return "null"; - } else if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); - return "new HashMap[String, " + inner + "]() "; - } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - return "new ListBuffer[" + inner + "]() "; - } else { - return "null"; - } - } - - @Override public String toOperationId(String operationId) { // throw exception if method name is empty @@ -299,89 +201,35 @@ public String toOperationId(String operationId) { return camelize(operationId, true); } - @Override - public Map postProcessModels(Map objs) { - // remove model imports to avoid warnings for importing class in the same package in Scala - List> imports = (List>) objs.get("imports"); - final String prefix = modelPackage() + "."; - Iterator> iterator = imports.iterator(); - while (iterator.hasNext()) { - String _import = iterator.next().get("import"); - if (_import.startsWith(prefix)) iterator.remove(); - } - return objs; - } - - @Override - public String toVarName(String name) { - // sanitize name - name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - - if("_".equals(name)) { - name = "_u"; - } - - // if it's all uppper case, do nothing - if (name.matches("^[A-Z_]*$")) { - return name; - } - - name = getNameUsingModelPropertyNaming(name); - - // for reserved word or word starting with number, append _ - if (isReservedWord(name) || name.matches("^\\d.*")) { - name = escapeReservedWord(name); - } - - return name; - } - - @Override - public String toParamName(String name) { - // should be the same as variable name - return toVarName(name); - } - @Override public String toModelName(final String name) { final String sanitizedName = sanitizeName(modelNamePrefix + name + modelNameSuffix); - + // camelize the model name // phone_number => PhoneNumber final String camelizedName = camelize(sanitizedName); - + // model name cannot use reserved keyword, e.g. return if (isReservedWord(camelizedName)) { final String modelName = "Model" + camelizedName; LOGGER.warn(camelizedName + " (reserved word) cannot be used as model name. Renamed to " + modelName); return modelName; } - + // model name starts with number if (name.matches("^\\d.*")) { final String modelName = "Model" + camelizedName; // e.g. 200Response => Model200Response (after camelize) LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); return modelName; } - + return camelizedName; } - @Override - public String toModelFilename(String name) { - // should be the same as the model name - return toModelName(name); - } - @Override public String escapeQuotationMark(String input) { // remove " to avoid code injection return input.replace("\"", ""); } - @Override - public String escapeUnsafeCharacters(String input) { - return input.replace("*/", "*_/").replace("/*", "/_*"); - } - } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java index 3672ddd9857..cab432e5d17 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java @@ -4,27 +4,20 @@ import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenOperation; -import io.swagger.codegen.CodegenParameter; 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 java.io.File; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; -public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConfig { - protected String invokerPackage = "io.swagger.client"; +public class ScalatraServerCodegen extends AbstractScalaCodegen implements CodegenConfig { + protected String groupId = "io.swagger"; protected String artifactId = "swagger-client"; protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "src/main/scala"; public ScalatraServerCodegen() { super(); @@ -94,17 +87,6 @@ public ScalatraServerCodegen() { supportingFiles.add(new SupportingFile("project/plugins.sbt", "project", "plugins.sbt")); supportingFiles.add(new SupportingFile("sbt", "", "sbt")); - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Integer", - "Long", - "Float", - "Object") - ); instantiationTypes.put("array", "ArrayList"); instantiationTypes.put("map", "HashMap"); @@ -122,9 +104,6 @@ public ScalatraServerCodegen() { importMapping.put("LocalDateTime", "org.joda.time.LocalDateTime"); importMapping.put("LocalDate", "org.joda.time.LocalDate"); importMapping.put("LocalTime", "org.joda.time.LocalTime"); - - cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); - cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); } @Override @@ -142,21 +121,6 @@ public String getHelp() { return "Generates a Scala server application with Scalatra."; } - @Override - public String escapeReservedWord(String name) { - return "_" + name; - } - - @Override - public String apiFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); - } - - @Override - public String modelFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); - } - @Override public Map postProcessOperations(Map objs) { Map operations = (Map) objs.get("operations"); @@ -189,45 +153,10 @@ public Map postProcessOperations(Map objs) { } - @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); - } - - @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); - } - @Override public String escapeQuotationMark(String input) { // remove " to avoid code injection return input.replace("\"", ""); } - @Override - public String escapeUnsafeCharacters(String input) { - return input.replace("*/", "*_/").replace("/*", "/_*"); - } - } diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Pet.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Pet.scala index 01aa08e73ce..394ee79b7d9 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Pet.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Pet.scala @@ -24,8 +24,6 @@ package com.wordnik.client.model -import com.wordnik.client.model.Category -import com.wordnik.client.model.Tag case class Pet ( From 2dfc291a2d41825c149529fd4a9f6082e0135649 Mon Sep 17 00:00:00 2001 From: Johannes Fiala Date: Sun, 11 Sep 2016 12:09:00 +0200 Subject: [PATCH 349/470] move beanvalidation into separate subtemplate and reuse for cxf --- .../src/main/resources/Java/pojo.mustache | 31 +------------------ .../resources/JavaJaxRS/cxf/pojo.mustache | 31 +------------------ 2 files changed, 2 insertions(+), 60 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache index ea1f2ad9456..7dfee466755 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache @@ -49,36 +49,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali {{/maximum}} * @return {{name}} **/ -{{#useBeanValidation}} -{{#required}} - @NotNull -{{/required}} -{{#pattern}} - @Pattern(regexp="{{pattern}}") -{{/pattern}} -{{#minLength}} -{{#maxLength}} - @Size(min={{minLength}},max={{maxLength}}) -{{/maxLength}} -{{/minLength}} -{{#minLength}} -{{^maxLength}} - @Size(min={{minLength}}) -{{/maxLength}} -{{/minLength}} -{{^minLength}} -{{#maxLength}} - @Size(max={{maxLength}}) - {{/maxLength}} - {{/minLength}} -{{#minimum}} - //@Min({{minimum}}) -{{/minimum}} -{{#maximum}} - //@Max({{maximum}}) -{{/maximum}} -{{/useBeanValidation}} - @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") +{{#useBeanValidation}}{{>beanValidation}}{{/useBeanValidation}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") {{#vendorExtensions.extraAnnotation}} {{vendorExtensions.extraAnnotation}} {{/vendorExtensions.extraAnnotation}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache index d8be3155f56..dbf7ab6b87f 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache @@ -42,39 +42,10 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{/maximum}} * @return {{name}} **/ -{{#useBeanValidation}} -{{#required}} - @NotNull -{{/required}} -{{#pattern}} - @Pattern(regexp="{{pattern}}") -{{/pattern}} -{{#minLength}} -{{#maxLength}} - @Size(min={{minLength}},max={{maxLength}}) -{{/maxLength}} -{{/minLength}} -{{#minLength}} -{{^maxLength}} - @Size(min={{minLength}}) -{{/maxLength}} -{{/minLength}} -{{^minLength}} -{{#maxLength}} - @Size(max={{maxLength}}) - {{/maxLength}} - {{/minLength}} -{{#minimum}} - //@Min({{minimum}}) -{{/minimum}} -{{#maximum}} - //@Max({{maximum}}) -{{/maximum}} -{{/useBeanValidation}} {{#vendorExtensions.extraAnnotation}} {{vendorExtensions.extraAnnotation}} {{/vendorExtensions.extraAnnotation}} - public {{{datatypeWithEnum}}} {{getter}}() { +{{#useBeanValidation}}{{>..\..\java\beanValidation}}{{/useBeanValidation}} public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; } public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { From 4b7c32263b829b3148508115a293dc86b846ad6d Mon Sep 17 00:00:00 2001 From: Johannes Fiala Date: Sun, 11 Sep 2016 12:17:24 +0200 Subject: [PATCH 350/470] add beanValidation java template --- .../resources/Java/beanValidation.mustache | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 modules/swagger-codegen/src/main/resources/Java/beanValidation.mustache diff --git a/modules/swagger-codegen/src/main/resources/Java/beanValidation.mustache b/modules/swagger-codegen/src/main/resources/Java/beanValidation.mustache new file mode 100644 index 00000000000..f9a3265fbb2 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/beanValidation.mustache @@ -0,0 +1,27 @@ +{{#required}} + @NotNull +{{/required}} +{{#pattern}} + @Pattern(regexp="{{pattern}}") +{{/pattern}} +{{#minLength}} +{{#maxLength}} + @Size(min={{minLength}},max={{maxLength}}) +{{/maxLength}} +{{/minLength}} +{{#minLength}} +{{^maxLength}} + @Size(min={{minLength}}) +{{/maxLength}} +{{/minLength}} +{{^minLength}} +{{#maxLength}} + @Size(max={{maxLength}}) + {{/maxLength}} + {{/minLength}} +{{#minimum}} + //@Min({{minimum}}) +{{/minimum}} +{{#maximum}} + //@Max({{maximum}}) +{{/maximum}} \ No newline at end of file From ac69f45ddc18dacd1b3972495c3613cdc47559e6 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 11 Sep 2016 18:44:36 +0800 Subject: [PATCH 351/470] better format of model properties --- .../main/resources/akka-scala/model.mustache | 25 +++++++++++++------ .../src/main/resources/scala/model.mustache | 13 ++++++---- .../main/resources/scalatra/model.mustache | 7 ++++-- .../scala/io/swagger/client/api/PetApi.scala | 2 +- .../io/swagger/client/model/ApiResponse.scala | 5 ++-- .../io/swagger/client/model/Category.scala | 5 ++-- .../scala/io/swagger/client/model/Order.scala | 7 ++---- .../scala/io/swagger/client/model/Pet.scala | 7 ++---- .../scala/io/swagger/client/model/Tag.scala | 5 ++-- .../scala/io/swagger/client/model/User.scala | 5 ++-- .../scala/io/swagger/client/api/PetApi.scala | 2 +- .../io/swagger/client/model/ApiResponse.scala | 7 +++--- .../io/swagger/client/model/Category.scala | 5 ++-- .../scala/io/swagger/client/model/Order.scala | 13 +++++----- .../scala/io/swagger/client/model/Pet.scala | 15 ++++++----- .../scala/io/swagger/client/model/Tag.scala | 5 ++-- .../scala/io/swagger/client/model/User.scala | 19 +++++++------- .../scala/com/wordnik/client/api/PetApi.scala | 2 +- .../wordnik/client/model/ApiResponse.scala | 5 ++-- .../com/wordnik/client/model/Category.scala | 3 +-- .../com/wordnik/client/model/Order.scala | 12 ++++----- .../scala/com/wordnik/client/model/Pet.scala | 12 ++++----- .../scala/com/wordnik/client/model/Tag.scala | 3 +-- .../scala/com/wordnik/client/model/User.scala | 16 ++++++------ 24 files changed, 98 insertions(+), 102 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/model.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/model.mustache index 0c08f91af78..7743c15718d 100644 --- a/modules/swagger-codegen/src/main/resources/akka-scala/model.mustache +++ b/modules/swagger-codegen/src/main/resources/akka-scala/model.mustache @@ -11,24 +11,33 @@ import org.joda.time.DateTime {{#models}} {{#model}} - case class {{classname}} ( - {{#vars}}{{#description}}/* {{{description}}} */ - {{/description}}{{{name}}}: {{^required}}Option[{{/required}}{{^isEnum}}{{datatype}}{{/isEnum}}{{#isEnum}}{{classname}}Enums.{{datatypeWithEnum}}{{/isEnum}}{{^required}}]{{/required}}{{#hasMore}},{{/hasMore}}{{^hasMore}}){{/hasMore}} - {{/vars}} extends ApiModel + {{#vars}} + {{#description}} + /* {{{description}}} */ + {{/description}} + {{{name}}}: {{^required}}Option[{{/required}}{{^isEnum}}{{datatype}}{{/isEnum}}{{#isEnum}}{{classname}}Enums.{{datatypeWithEnum}}{{/isEnum}}{{^required}}]{{/required}}{{#hasMore}},{{/hasMore}} + {{/vars}} +) extends ApiModel {{#hasEnums}} object {{classname}}Enums { - {{#vars}}{{#isEnum}}type {{datatypeWithEnum}} = {{datatypeWithEnum}}.Value - {{/isEnum}}{{/vars}} - {{#vars}}{{#isEnum}}object {{datatypeWithEnum}} extends Enumeration { + {{#vars}} + {{#isEnum}} + type {{datatypeWithEnum}} = {{datatypeWithEnum}}.Value + {{/isEnum}} + {{/vars}} + {{#vars}} + {{#isEnum}} + object {{datatypeWithEnum}} extends Enumeration { {{#_enum}} val {{#fnEnumEntry}}{{.}}{{/fnEnumEntry}} = Value("{{.}}") {{/_enum}} } - {{/isEnum}}{{/vars}} + {{/isEnum}} + {{/vars}} } {{/hasEnums}} {{/model}} diff --git a/modules/swagger-codegen/src/main/resources/scala/model.mustache b/modules/swagger-codegen/src/main/resources/scala/model.mustache index 40a9da8dc90..b6920ae9fd4 100644 --- a/modules/swagger-codegen/src/main/resources/scala/model.mustache +++ b/modules/swagger-codegen/src/main/resources/scala/model.mustache @@ -1,16 +1,19 @@ {{>licenseInfo}} package {{package}} -{{#imports}}import {{import}} +{{#imports}} +import {{import}} {{/imports}} {{#models}} - {{#model}} - case class {{classname}} ( - {{#vars}}{{#description}}/* {{{description}}} */ - {{/description}}{{name}}: {{{datatype}}}{{#hasMore}},{{/hasMore}}{{^hasMore}}){{/hasMore}} + {{#vars}} + {{#description}} + /* {{{description}}} */ + {{/description}} + {{name}}: {{{datatype}}}{{#hasMore}},{{/hasMore}} {{/vars}} +) {{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/scalatra/model.mustache b/modules/swagger-codegen/src/main/resources/scalatra/model.mustache index c1a2f2585de..cf14e9a7362 100644 --- a/modules/swagger-codegen/src/main/resources/scalatra/model.mustache +++ b/modules/swagger-codegen/src/main/resources/scalatra/model.mustache @@ -6,10 +6,13 @@ package {{package}} {{/imports}} {{#models}} - {{#model}} case class {{classname}} ( - {{#vars}}{{name}}: {{^required}}Option[{{/required}}{{datatype}}{{^required}}]{{/required}}{{#hasMore}},{{/hasMore}}{{#description}} // {{description}}{{/description}} + {{#vars}} + {{#description}} + /* {{{description}}} */ + {{/description}} + {{name}}: {{^required}}Option[{{/required}}{{datatype}}{{^required}}]{{/required}}{{#hasMore}},{{/hasMore}} {{/vars}} ) {{/model}} diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/PetApi.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/PetApi.scala index d6c0d9c08b4..b59e7f912b4 100644 --- a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/PetApi.scala +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/PetApi.scala @@ -6,8 +6,8 @@ package io.swagger.client.api import io.swagger.client.model.Pet -import java.io.File import io.swagger.client.model.ApiResponse +import java.io.File import io.swagger.client.core._ import io.swagger.client.core.CollectionFormats._ import io.swagger.client.core.ApiKeyLocations._ diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/ApiResponse.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/ApiResponse.scala index 31a9325c6f8..0b996a89cc5 100644 --- a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/ApiResponse.scala +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/ApiResponse.scala @@ -9,11 +9,10 @@ package io.swagger.client.model import io.swagger.client.core.ApiModel import org.joda.time.DateTime - case class ApiResponse ( code: Option[Int], `type`: Option[String], - message: Option[String]) - extends ApiModel + message: Option[String] +) extends ApiModel diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Category.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Category.scala index 6d14fc12276..48af020f18d 100644 --- a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Category.scala +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Category.scala @@ -9,10 +9,9 @@ package io.swagger.client.model import io.swagger.client.core.ApiModel import org.joda.time.DateTime - case class Category ( id: Option[Long], - name: Option[String]) - extends ApiModel + name: Option[String] +) extends ApiModel diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Order.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Order.scala index 7ed7ae6109c..3c2d7a255e2 100644 --- a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Order.scala +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Order.scala @@ -9,7 +9,6 @@ package io.swagger.client.model import io.swagger.client.core.ApiModel import org.joda.time.DateTime - case class Order ( id: Option[Long], petId: Option[Long], @@ -17,19 +16,17 @@ case class Order ( shipDate: Option[DateTime], /* Order Status */ status: Option[OrderEnums.Status], - complete: Option[Boolean]) - extends ApiModel + complete: Option[Boolean] +) extends ApiModel object OrderEnums { type Status = Status.Value - object Status extends Enumeration { val Placed = Value("placed") val Approved = Value("approved") val Delivered = Value("delivered") } - } diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Pet.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Pet.scala index 0b8cf84d49a..2adadb61eaa 100644 --- a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Pet.scala +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Pet.scala @@ -9,7 +9,6 @@ package io.swagger.client.model import io.swagger.client.core.ApiModel import org.joda.time.DateTime - case class Pet ( id: Option[Long], category: Option[Category], @@ -17,19 +16,17 @@ case class Pet ( photoUrls: Seq[String], tags: Option[Seq[Tag]], /* pet status in the store */ - status: Option[PetEnums.Status]) - extends ApiModel + status: Option[PetEnums.Status] +) extends ApiModel object PetEnums { type Status = Status.Value - object Status extends Enumeration { val Available = Value("available") val Pending = Value("pending") val Sold = Value("sold") } - } diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Tag.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Tag.scala index 5a4b2f412c7..6658e733b4e 100644 --- a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Tag.scala +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Tag.scala @@ -9,10 +9,9 @@ package io.swagger.client.model import io.swagger.client.core.ApiModel import org.joda.time.DateTime - case class Tag ( id: Option[Long], - name: Option[String]) - extends ApiModel + name: Option[String] +) extends ApiModel diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/User.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/User.scala index 2dc7325c465..6db0c80fc33 100644 --- a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/User.scala +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/User.scala @@ -9,7 +9,6 @@ package io.swagger.client.model import io.swagger.client.core.ApiModel import org.joda.time.DateTime - case class User ( id: Option[Long], username: Option[String], @@ -19,7 +18,7 @@ case class User ( password: Option[String], phone: Option[String], /* User Status */ - userStatus: Option[Int]) - extends ApiModel + userStatus: Option[Int] +) extends ApiModel diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala index 52974fb7e86..9feaf3603c4 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala @@ -25,8 +25,8 @@ package io.swagger.client.api import io.swagger.client.model.Pet -import java.io.File import io.swagger.client.model.ApiResponse +import java.io.File import io.swagger.client.ApiInvoker import io.swagger.client.ApiException diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/ApiResponse.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/ApiResponse.scala index 49721a758a0..99e93a5d348 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/ApiResponse.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/ApiResponse.scala @@ -25,9 +25,8 @@ package io.swagger.client.model - - case class ApiResponse ( code: Integer, -_type: String, -message: String) + _type: String, + message: String +) diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Category.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Category.scala index c8843e065e7..3499402cef3 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Category.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Category.scala @@ -25,8 +25,7 @@ package io.swagger.client.model - - case class Category ( id: Long, -name: String) + name: String +) diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Order.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Order.scala index 12fe2850ec4..cffd2211409 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Order.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Order.scala @@ -26,13 +26,12 @@ package io.swagger.client.model import org.joda.time.DateTime - - case class Order ( id: Long, -petId: Long, -quantity: Integer, -shipDate: DateTime, -/* Order Status */ + petId: Long, + quantity: Integer, + shipDate: DateTime, + /* Order Status */ status: String, -complete: Boolean) + complete: Boolean +) diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Pet.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Pet.scala index 43420b1a9e0..fc8f5e09764 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Pet.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Pet.scala @@ -25,13 +25,12 @@ package io.swagger.client.model - - case class Pet ( id: Long, -category: Category, -name: String, -photoUrls: List[String], -tags: List[Tag], -/* pet status in the store */ - status: String) + category: Category, + name: String, + photoUrls: List[String], + tags: List[Tag], + /* pet status in the store */ + status: String +) diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Tag.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Tag.scala index 6cc351ba45b..bb2bfae71e3 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Tag.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Tag.scala @@ -25,8 +25,7 @@ package io.swagger.client.model - - case class Tag ( id: Long, -name: String) + name: String +) diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/User.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/User.scala index 4e80b6c6697..cbbbded06f0 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/User.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/User.scala @@ -25,15 +25,14 @@ package io.swagger.client.model - - case class User ( id: Long, -username: String, -firstName: String, -lastName: String, -email: String, -password: String, -phone: String, -/* User Status */ - userStatus: Integer) + username: String, + firstName: String, + lastName: String, + email: String, + password: String, + phone: String, + /* User Status */ + userStatus: Integer +) diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala index 867e4605f2a..9995f630123 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala @@ -25,8 +25,8 @@ package com.wordnik.client.api import com.wordnik.client.model.Pet -import java.io.File import com.wordnik.client.model.ApiResponse +import java.io.File import java.io.File diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/ApiResponse.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/ApiResponse.scala index c09ed4217e7..13658983f75 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/ApiResponse.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/ApiResponse.scala @@ -25,9 +25,8 @@ package com.wordnik.client.model - case class ApiResponse ( code: Option[Int], -_type: Option[String], -message: Option[String] + _type: Option[String], + message: Option[String] ) diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Category.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Category.scala index 4bdadfbbe5c..ab54f62c0ea 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Category.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Category.scala @@ -25,8 +25,7 @@ package com.wordnik.client.model - case class Category ( id: Option[Long], -name: Option[String] + name: Option[String] ) diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Order.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Order.scala index 6f399b0d1c3..b55c2ab26ef 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Order.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Order.scala @@ -26,12 +26,12 @@ package com.wordnik.client.model import java.util.Date - case class Order ( id: Option[Long], -petId: Option[Long], -quantity: Option[Int], -shipDate: Option[Date], -status: Option[String], // Order Status -complete: Option[Boolean] + petId: Option[Long], + quantity: Option[Int], + shipDate: Option[Date], + /* Order Status */ + status: Option[String], + complete: Option[Boolean] ) diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Pet.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Pet.scala index 394ee79b7d9..7d3c9093595 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Pet.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Pet.scala @@ -25,12 +25,12 @@ package com.wordnik.client.model - case class Pet ( id: Option[Long], -category: Option[Category], -name: String, -photoUrls: List[String], -tags: Option[List[Tag]], -status: Option[String] // pet status in the store + category: Option[Category], + name: String, + photoUrls: List[String], + tags: Option[List[Tag]], + /* pet status in the store */ + status: Option[String] ) diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Tag.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Tag.scala index a3d34e8d557..888c2f31346 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Tag.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Tag.scala @@ -25,8 +25,7 @@ package com.wordnik.client.model - case class Tag ( id: Option[Long], -name: Option[String] + name: Option[String] ) diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/User.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/User.scala index ff792d91371..3b4f9dc68e0 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/User.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/User.scala @@ -25,14 +25,14 @@ package com.wordnik.client.model - case class User ( id: Option[Long], -username: Option[String], -firstName: Option[String], -lastName: Option[String], -email: Option[String], -password: Option[String], -phone: Option[String], -userStatus: Option[Int] // User Status + username: Option[String], + firstName: Option[String], + lastName: Option[String], + email: Option[String], + password: Option[String], + phone: Option[String], + /* User Status */ + userStatus: Option[Int] ) From 1d7d37409aac271fb741746c70f01ffa020647d8 Mon Sep 17 00:00:00 2001 From: ataraxus Date: Sun, 11 Sep 2016 17:11:35 +0200 Subject: [PATCH 352/470] Fix for issue #3743 (#3744) * fix map usage in api generation #3694 * fix map usage in api generation #3695 * close impl gap between queryParam and formParam, to be more consistent * use working copy constructor --- .../typescript-angular2/api.mustache | 2 +- .../typescript-angular2/default/api/PetApi.ts | 24 +++++++------------ .../default/api/StoreApi.ts | 12 ++++------ .../default/api/UserApi.ts | 24 +++++++------------ .../typescript-angular2/npm/README.md | 4 ++-- .../typescript-angular2/npm/api/PetApi.ts | 24 +++++++------------ .../typescript-angular2/npm/api/StoreApi.ts | 12 ++++------ .../typescript-angular2/npm/api/UserApi.ts | 24 +++++++------------ .../typescript-angular2/npm/package.json | 2 +- 9 files changed, 44 insertions(+), 84 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache index f033a8a4b6c..7e9078b8735 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache @@ -40,7 +40,7 @@ export class {{classname}} { const path = this.basePath + `{{path}}`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 {{#hasFormParams}} let formParams = new URLSearchParams(); diff --git a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts index 7159642a26a..141627b5ef4 100644 --- a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts @@ -56,7 +56,7 @@ export class PetApi { const path = this.basePath + `/pet`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Content-Type header @@ -74,7 +74,6 @@ export class PetApi { headers.set('Content-Type', 'application/json'); -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, @@ -104,7 +103,7 @@ export class PetApi { const path = this.basePath + `/pet/${petId}`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling deletePet.'); @@ -123,7 +122,6 @@ export class PetApi { -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, @@ -151,7 +149,7 @@ export class PetApi { const path = this.basePath + `/pet/findByStatus`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (status !== undefined) { queryParameters.set('status', status); } @@ -169,7 +167,6 @@ export class PetApi { -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, @@ -197,7 +194,7 @@ export class PetApi { const path = this.basePath + `/pet/findByTags`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (tags !== undefined) { queryParameters.set('tags', tags); } @@ -215,7 +212,6 @@ export class PetApi { -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, @@ -243,7 +239,7 @@ export class PetApi { const path = this.basePath + `/pet/${petId}`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling getPetById.'); @@ -262,7 +258,6 @@ export class PetApi { -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, @@ -290,7 +285,7 @@ export class PetApi { const path = this.basePath + `/pet`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Content-Type header @@ -308,7 +303,6 @@ export class PetApi { headers.set('Content-Type', 'application/json'); -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Put, @@ -339,7 +333,7 @@ export class PetApi { const path = this.basePath + `/pet/${petId}`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 let formParams = new URLSearchParams(); // verify required parameter 'petId' is not null or undefined @@ -362,7 +356,6 @@ export class PetApi { headers.set('Content-Type', 'application/x-www-form-urlencoded'); -// add form parameters if provided if (name !== undefined) { formParams.set('name', name); } @@ -399,7 +392,7 @@ export class PetApi { const path = this.basePath + `/pet/${petId}/uploadImage`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 let formParams = new URLSearchParams(); // verify required parameter 'petId' is not null or undefined @@ -422,7 +415,6 @@ export class PetApi { headers.set('Content-Type', 'application/x-www-form-urlencoded'); -// add form parameters if provided if (additionalMetadata !== undefined) { formParams.set('additionalMetadata', additionalMetadata); } diff --git a/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts b/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts index 0987c9fb724..b993eda8311 100644 --- a/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts @@ -56,7 +56,7 @@ export class StoreApi { const path = this.basePath + `/store/order/${orderId}`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); @@ -75,7 +75,6 @@ export class StoreApi { -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, @@ -102,7 +101,7 @@ export class StoreApi { const path = this.basePath + `/store/inventory`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Content-Type header @@ -117,7 +116,6 @@ export class StoreApi { -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, @@ -145,7 +143,7 @@ export class StoreApi { const path = this.basePath + `/store/order/${orderId}`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); @@ -164,7 +162,6 @@ export class StoreApi { -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, @@ -192,7 +189,7 @@ export class StoreApi { const path = this.basePath + `/store/order`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Content-Type header @@ -208,7 +205,6 @@ export class StoreApi { headers.set('Content-Type', 'application/json'); -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, diff --git a/samples/client/petstore/typescript-angular2/default/api/UserApi.ts b/samples/client/petstore/typescript-angular2/default/api/UserApi.ts index bd7f09522f4..16e17d846ef 100644 --- a/samples/client/petstore/typescript-angular2/default/api/UserApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/UserApi.ts @@ -56,7 +56,7 @@ export class UserApi { const path = this.basePath + `/user`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Content-Type header @@ -72,7 +72,6 @@ export class UserApi { headers.set('Content-Type', 'application/json'); -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, @@ -101,7 +100,7 @@ export class UserApi { const path = this.basePath + `/user/createWithArray`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Content-Type header @@ -117,7 +116,6 @@ export class UserApi { headers.set('Content-Type', 'application/json'); -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, @@ -146,7 +144,7 @@ export class UserApi { const path = this.basePath + `/user/createWithList`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Content-Type header @@ -162,7 +160,6 @@ export class UserApi { headers.set('Content-Type', 'application/json'); -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, @@ -191,7 +188,7 @@ export class UserApi { const path = this.basePath + `/user/${username}`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling deleteUser.'); @@ -210,7 +207,6 @@ export class UserApi { -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, @@ -238,7 +234,7 @@ export class UserApi { const path = this.basePath + `/user/${username}`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling getUserByName.'); @@ -257,7 +253,6 @@ export class UserApi { -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, @@ -286,7 +281,7 @@ export class UserApi { const path = this.basePath + `/user/login`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (username !== undefined) { queryParameters.set('username', username); } @@ -307,7 +302,6 @@ export class UserApi { -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, @@ -334,7 +328,7 @@ export class UserApi { const path = this.basePath + `/user/logout`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Content-Type header @@ -349,7 +343,6 @@ export class UserApi { -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, @@ -378,7 +371,7 @@ export class UserApi { const path = this.basePath + `/user/${username}`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling updateUser.'); @@ -398,7 +391,6 @@ export class UserApi { headers.set('Content-Type', 'application/json'); -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Put, diff --git a/samples/client/petstore/typescript-angular2/npm/README.md b/samples/client/petstore/typescript-angular2/npm/README.md index b688e462e7d..2a9de3be422 100644 --- a/samples/client/petstore/typescript-angular2/npm/README.md +++ b/samples/client/petstore/typescript-angular2/npm/README.md @@ -1,4 +1,4 @@ -## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201609051239 +## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201609071612 ### Building @@ -19,7 +19,7 @@ navigate to the folder of your consuming project and run one of next commando's. _published:_ ``` -npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201609051239 --save +npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201609071612 --save ``` _unPublished (not recommended):_ diff --git a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts index 7159642a26a..141627b5ef4 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts @@ -56,7 +56,7 @@ export class PetApi { const path = this.basePath + `/pet`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Content-Type header @@ -74,7 +74,6 @@ export class PetApi { headers.set('Content-Type', 'application/json'); -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, @@ -104,7 +103,7 @@ export class PetApi { const path = this.basePath + `/pet/${petId}`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling deletePet.'); @@ -123,7 +122,6 @@ export class PetApi { -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, @@ -151,7 +149,7 @@ export class PetApi { const path = this.basePath + `/pet/findByStatus`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (status !== undefined) { queryParameters.set('status', status); } @@ -169,7 +167,6 @@ export class PetApi { -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, @@ -197,7 +194,7 @@ export class PetApi { const path = this.basePath + `/pet/findByTags`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (tags !== undefined) { queryParameters.set('tags', tags); } @@ -215,7 +212,6 @@ export class PetApi { -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, @@ -243,7 +239,7 @@ export class PetApi { const path = this.basePath + `/pet/${petId}`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling getPetById.'); @@ -262,7 +258,6 @@ export class PetApi { -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, @@ -290,7 +285,7 @@ export class PetApi { const path = this.basePath + `/pet`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Content-Type header @@ -308,7 +303,6 @@ export class PetApi { headers.set('Content-Type', 'application/json'); -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Put, @@ -339,7 +333,7 @@ export class PetApi { const path = this.basePath + `/pet/${petId}`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 let formParams = new URLSearchParams(); // verify required parameter 'petId' is not null or undefined @@ -362,7 +356,6 @@ export class PetApi { headers.set('Content-Type', 'application/x-www-form-urlencoded'); -// add form parameters if provided if (name !== undefined) { formParams.set('name', name); } @@ -399,7 +392,7 @@ export class PetApi { const path = this.basePath + `/pet/${petId}/uploadImage`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 let formParams = new URLSearchParams(); // verify required parameter 'petId' is not null or undefined @@ -422,7 +415,6 @@ export class PetApi { headers.set('Content-Type', 'application/x-www-form-urlencoded'); -// add form parameters if provided if (additionalMetadata !== undefined) { formParams.set('additionalMetadata', additionalMetadata); } diff --git a/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts b/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts index 0987c9fb724..b993eda8311 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts @@ -56,7 +56,7 @@ export class StoreApi { const path = this.basePath + `/store/order/${orderId}`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); @@ -75,7 +75,6 @@ export class StoreApi { -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, @@ -102,7 +101,7 @@ export class StoreApi { const path = this.basePath + `/store/inventory`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Content-Type header @@ -117,7 +116,6 @@ export class StoreApi { -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, @@ -145,7 +143,7 @@ export class StoreApi { const path = this.basePath + `/store/order/${orderId}`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); @@ -164,7 +162,6 @@ export class StoreApi { -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, @@ -192,7 +189,7 @@ export class StoreApi { const path = this.basePath + `/store/order`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Content-Type header @@ -208,7 +205,6 @@ export class StoreApi { headers.set('Content-Type', 'application/json'); -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, diff --git a/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts b/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts index bd7f09522f4..16e17d846ef 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts @@ -56,7 +56,7 @@ export class UserApi { const path = this.basePath + `/user`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Content-Type header @@ -72,7 +72,6 @@ export class UserApi { headers.set('Content-Type', 'application/json'); -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, @@ -101,7 +100,7 @@ export class UserApi { const path = this.basePath + `/user/createWithArray`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Content-Type header @@ -117,7 +116,6 @@ export class UserApi { headers.set('Content-Type', 'application/json'); -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, @@ -146,7 +144,7 @@ export class UserApi { const path = this.basePath + `/user/createWithList`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Content-Type header @@ -162,7 +160,6 @@ export class UserApi { headers.set('Content-Type', 'application/json'); -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, @@ -191,7 +188,7 @@ export class UserApi { const path = this.basePath + `/user/${username}`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling deleteUser.'); @@ -210,7 +207,6 @@ export class UserApi { -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, @@ -238,7 +234,7 @@ export class UserApi { const path = this.basePath + `/user/${username}`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling getUserByName.'); @@ -257,7 +253,6 @@ export class UserApi { -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, @@ -286,7 +281,7 @@ export class UserApi { const path = this.basePath + `/user/login`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (username !== undefined) { queryParameters.set('username', username); } @@ -307,7 +302,6 @@ export class UserApi { -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, @@ -334,7 +328,7 @@ export class UserApi { const path = this.basePath + `/user/logout`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Content-Type header @@ -349,7 +343,6 @@ export class UserApi { -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, @@ -378,7 +371,7 @@ export class UserApi { const path = this.basePath + `/user/${username}`; let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.values()); // https://github.com/angular/angular/issues/6845 + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling updateUser.'); @@ -398,7 +391,6 @@ export class UserApi { headers.set('Content-Type', 'application/json'); -// add form parameters if provided let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Put, diff --git a/samples/client/petstore/typescript-angular2/npm/package.json b/samples/client/petstore/typescript-angular2/npm/package.json index 8a6efafddf9..876c006bd29 100644 --- a/samples/client/petstore/typescript-angular2/npm/package.json +++ b/samples/client/petstore/typescript-angular2/npm/package.json @@ -1,6 +1,6 @@ { "name": "@swagger/angular2-typescript-petstore", - "version": "0.0.1-SNAPSHOT.201609051239", + "version": "0.0.1-SNAPSHOT.201609071612", "description": "swagger client for @swagger/angular2-typescript-petstore", "author": "Swagger Codegen Contributors", "keywords": [ From d3eedafe84ee05e7ecbc7e0819711a8faa818a81 Mon Sep 17 00:00:00 2001 From: Paul Ebermann Date: Thu, 8 Sep 2016 17:21:30 +0200 Subject: [PATCH 353/470] Issue #3738: introduce the sourceFolder property for all Scala "languages". --- .../languages/AbstractScalaCodegen.java | 18 ++++++++++++++++++ .../akkascala/AkkaScalaClientOptionsTest.java | 2 ++ .../AsyncScalaClientOptionsTest.java | 2 ++ .../AkkaScalaClientOptionsProvider.java | 2 ++ .../AsyncScalaClientOptionsProvider.java | 2 ++ .../options/ScalaClientOptionsProvider.java | 2 ++ .../options/ScalatraServerOptionsProvider.java | 2 ++ .../codegen/scala/ScalaClientOptionsTest.java | 2 ++ .../scalatra/ScalatraServerOptionsTest.java | 2 ++ 9 files changed, 34 insertions(+) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractScalaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractScalaCodegen.java index 29942fb31f4..e482fa1dd27 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractScalaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractScalaCodegen.java @@ -46,6 +46,24 @@ public AbstractScalaCodegen() { cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC)); + } + + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) { + this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); + } + } + + public void setSourceFolder(String sourceFolder) { + this.sourceFolder = sourceFolder; + } + + public String getSourceFolder() { + return sourceFolder; } @Override diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/akkascala/AkkaScalaClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/akkascala/AkkaScalaClientOptionsTest.java index 7ad1ff07e2b..4acf7d5aaa9 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/akkascala/AkkaScalaClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/akkascala/AkkaScalaClientOptionsTest.java @@ -32,6 +32,8 @@ protected void setExpectations() { times = 1; clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(AkkaScalaClientOptionsProvider.SORT_PARAMS_VALUE)); times = 1; + clientCodegen.setSourceFolder(AkkaScalaClientOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/asyncscala/AsyncScalaClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/asyncscala/AsyncScalaClientOptionsTest.java index 8ea0280434a..12f4f19e379 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/asyncscala/AsyncScalaClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/asyncscala/AsyncScalaClientOptionsTest.java @@ -32,6 +32,8 @@ protected void setExpectations() { times = 1; clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(AsyncScalaClientOptionsProvider.SORT_PARAMS_VALUE)); times = 1; + clientCodegen.setSourceFolder(AsyncScalaClientOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AkkaScalaClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AkkaScalaClientOptionsProvider.java index e26968500d7..c9fd8bca97a 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AkkaScalaClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AkkaScalaClientOptionsProvider.java @@ -7,6 +7,7 @@ import java.util.Map; public class AkkaScalaClientOptionsProvider implements OptionsProvider { + public static final String SOURCE_FOLDER_VALUE = "sourceFolder"; public static final String MODEL_PACKAGE_VALUE = "package"; public static final String API_PACKAGE_VALUE = "apiPackage"; public static final String SORT_PARAMS_VALUE = "false"; @@ -24,6 +25,7 @@ public Map createOptions() { .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AsyncScalaClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AsyncScalaClientOptionsProvider.java index be21a20efe4..aa09c1e4aec 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AsyncScalaClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AsyncScalaClientOptionsProvider.java @@ -7,6 +7,7 @@ import java.util.Map; public class AsyncScalaClientOptionsProvider implements OptionsProvider { + public static final String SOURCE_FOLDER_VALUE = "sourceFolder"; public static final String MODEL_PACKAGE_VALUE = "package"; public static final String API_PACKAGE_VALUE = "apiPackage"; public static final String SORT_PARAMS_VALUE = "false"; @@ -24,6 +25,7 @@ public Map createOptions() { .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalaClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalaClientOptionsProvider.java index fade9a7cc07..f8a22c031ba 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalaClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalaClientOptionsProvider.java @@ -7,6 +7,7 @@ import java.util.Map; public class ScalaClientOptionsProvider implements OptionsProvider { + public static final String SOURCE_FOLDER_VALUE = "sourceFolder"; public static final String MODEL_PACKAGE_VALUE = "package"; public static final String API_PACKAGE_VALUE = "apiPackage"; public static final String SORT_PARAMS_VALUE = "false"; @@ -26,6 +27,7 @@ public Map createOptions() { .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING) + .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalatraServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalatraServerOptionsProvider.java index a0fef2f4858..e36ed80bbd5 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalatraServerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalatraServerOptionsProvider.java @@ -7,6 +7,7 @@ import java.util.Map; public class ScalatraServerOptionsProvider implements OptionsProvider { + public static final String SOURCE_FOLDER_VALUE = "sourceFolder"; public static final String MODEL_PACKAGE_VALUE = "package"; public static final String API_PACKAGE_VALUE = "apiPackage"; public static final String SORT_PARAMS_VALUE = "false"; @@ -24,6 +25,7 @@ public Map createOptions() { .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaClientOptionsTest.java index 4a934025dc3..d03cfee7ee7 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaClientOptionsTest.java @@ -34,6 +34,8 @@ protected void setExpectations() { times = 1; clientCodegen.setModelPropertyNaming(ScalaClientOptionsProvider.MODEL_PROPERTY_NAMING); times = 1; + clientCodegen.setSourceFolder(ScalaClientOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/scalatra/ScalatraServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/scalatra/ScalatraServerOptionsTest.java index 70c3dd30987..53ff0ce48e5 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/scalatra/ScalatraServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/scalatra/ScalatraServerOptionsTest.java @@ -32,6 +32,8 @@ protected void setExpectations() { times = 1; clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(ScalatraServerOptionsProvider.SORT_PARAMS_VALUE)); times = 1; + clientCodegen.setSourceFolder(ScalatraServerOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; }}; } } From 245b63a1339be07736233b24b54d08e5d62ab78b Mon Sep 17 00:00:00 2001 From: jfiala Date: Sun, 11 Sep 2016 20:47:55 +0200 Subject: [PATCH 354/470] corrected path to mustache file --- .../src/main/resources/JavaJaxRS/cxf/pojo.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache index dbf7ab6b87f..3078ef74ece 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache @@ -45,7 +45,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{#vendorExtensions.extraAnnotation}} {{vendorExtensions.extraAnnotation}} {{/vendorExtensions.extraAnnotation}} -{{#useBeanValidation}}{{>..\..\java\beanValidation}}{{/useBeanValidation}} public {{{datatypeWithEnum}}} {{getter}}() { +{{#useBeanValidation}}{{>../../java/beanValidation}}{{/useBeanValidation}} public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; } public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { From 72e051ab47ca22075b536d8e998c5c56870bb42e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pa=C5=ADlo=20Ebermann?= Date: Mon, 12 Sep 2016 05:00:02 +0200 Subject: [PATCH 355/470] Feature/remove unused variables in html codegens (#3739) * Remove unused variables/constants in StaticHtml[2]Generator. It looks like those were remainders from copy+paste. * run html-petstore.sh --- .../languages/StaticHtml2Generator.java | 2 - .../languages/StaticHtmlGenerator.java | 2 - samples/html/.swagger-codegen-ignore | 23 ++ samples/html/LICENSE | 201 +++++++++++++ samples/html/index.html | 277 +++++++++++++++--- 5 files changed, 464 insertions(+), 41 deletions(-) create mode 100644 samples/html/.swagger-codegen-ignore create mode 100644 samples/html/LICENSE diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtml2Generator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtml2Generator.java index 76351a963ca..c4c42bc9920 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtml2Generator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtml2Generator.java @@ -14,12 +14,10 @@ import java.util.Map; public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfig { - private static final String ALL_OPERATIONS = ""; protected String invokerPackage = "io.swagger.client"; protected String groupId = "io.swagger"; protected String artifactId = "swagger-client"; protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "src/main/scala"; public StaticHtml2Generator() { super(); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java index 0db05d5bc0a..8ca31ea678d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java @@ -19,12 +19,10 @@ import java.util.Map; public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig { - private static final String ALL_OPERATIONS = ""; protected String invokerPackage = "io.swagger.client"; protected String groupId = "io.swagger"; protected String artifactId = "swagger-client"; protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "src/main/scala"; public StaticHtmlGenerator() { super(); diff --git a/samples/html/.swagger-codegen-ignore b/samples/html/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/html/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/html/LICENSE b/samples/html/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/html/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/html/index.html b/samples/html/index.html index c16a59a025a..7ab2a9b0e98 100644 --- a/samples/html/index.html +++ b/samples/html/index.html @@ -1,7 +1,5 @@ - - - + + Swagger Petstore + + + + + + +
+
+ +
+
+
+

Swagger Petstore

+
+
+
+ +
+ + +
+

Pet

+ + + + + + + +
+ +
+
+

addPet

+
+
+ +
+
+ +

+

+

+
+ +
/pet
+ +

+

Usage and SDK Samples

+

+ + + +
+
+

+curl -X post "http://petstore.swagger.io/v2/pet"
+
+
+
+
+ +
+

+import io.swagger.client.*;
+import io.swagger.client.auth.*;
+import io.swagger.client.model.*;
+import .PetApi;
+
+import java.io.File;
+import java.util.*;
+
+public class PetApiExample {
+
+    public static void main(String[] args) {
+        ApiClient defaultClient = Configuration.getDefaultApiClient();
+        
+        // Configure OAuth2 access token for authorization: petstore_auth
+        OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth");
+        petstore_auth.setAccessToken("YOUR ACCESS TOKEN");
+
+        PetApi apiInstance = new PetApi();
+        Pet body = ; // Pet | Pet object that needs to be added to the store
+        try {
+            apiInstance.addPet(body);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling PetApi#addPet");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + +
+

+import .PetApi;
+
+public class PetApiExample {
+
+    public static void main(String[] args) {
+        PetApi apiInstance = new PetApi();
+        Pet body = ; // Pet | Pet object that needs to be added to the store
+        try {
+            apiInstance.addPet(body);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling PetApi#addPet");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + + + +
+

+Configuration *apiConfig = [Configuration sharedConfig];
+
+// Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth)
+[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"];
+
+
+Pet *body = ; // Pet object that needs to be added to the store
+
+PetApi *apiInstance = [[PetApi alloc] init];
+
+// Add a new pet to the store
+[apiInstance addPetWith:body
+              completionHandler: ^(NSError* error) {
+                            if (error) {
+                                NSLog(@"Error: %@", error);
+                            }
+                        }];
+
+                                                    
+
+
+

+var  = require('');
+var defaultClient = .ApiClient.instance;
+
+// Configure OAuth2 access token for authorization: petstore_auth
+var petstore_auth = defaultClient.authentications['petstore_auth'];
+petstore_auth.accessToken = "YOUR ACCESS TOKEN"
+
+var api = new .PetApi()
+
+var body = ; // {Pet} Pet object that needs to be added to the store
+
+
+var callback = function(error, data, response) {
+  if (error) {
+    console.error(error);
+  } else {
+    console.log('API called successfully.');
+  }
+};
+api.addPet(body, callback);
+
+                                                    
+
+ + + +
+

+using System;
+using System.Diagnostics;
+using .Api;
+using .Client;
+using ;
+
+namespace Example
+{
+    public class addPetExample
+    {
+        public void main()
+        {
+            
+            // Configure OAuth2 access token for authorization: petstore_auth
+            Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN";
+
+            var apiInstance = new PetApi();
+            var body = new Pet(); // Pet | Pet object that needs to be added to the store
+
+            try
+            {
+                // Add a new pet to the store
+                apiInstance.addPet(body);
+            }
+            catch (Exception e)
+            {
+                Debug.Print("Exception when calling PetApi.addPet: " + e.Message );
+            }
+        }
+    }
+}
+
+                                                    
+
+ + +
+

+setAccessToken('YOUR_ACCESS_TOKEN');
+
+$api_instance = new io.swagger.client\Api\PetApi();
+$body = ; // Pet | Pet object that needs to be added to the store
+
+try {
+    $api_instance->addPet($body);
+} catch (Exception $e) {
+    echo 'Exception when calling PetApi->addPet: ', $e->getMessage(), PHP_EOL;
+}
+
+                                                  
+
+ +
+ + + + + +

Parameters

+ + + + + + +
Body parameters
+ + + + + + + + + + + +
NameDescription
body * + + + +
+
+ + +

Responses

+ +

Status: 405 - Invalid input

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + + + + + + +
+ +
+ +
+ + + + + + + + +
+ +
+
+

deletePet

+
+
+ +
+
+ +

+

+

+
+ +
/pet/{petId}
+ +

+

Usage and SDK Samples

+

+ + + +
+
+

+curl -X delete "http://petstore.swagger.io/v2/pet/{petId}"
+
+
+
+
+ +
+

+import io.swagger.client.*;
+import io.swagger.client.auth.*;
+import io.swagger.client.model.*;
+import .PetApi;
+
+import java.io.File;
+import java.util.*;
+
+public class PetApiExample {
+
+    public static void main(String[] args) {
+        ApiClient defaultClient = Configuration.getDefaultApiClient();
+        
+        // Configure OAuth2 access token for authorization: petstore_auth
+        OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth");
+        petstore_auth.setAccessToken("YOUR ACCESS TOKEN");
+
+        PetApi apiInstance = new PetApi();
+        Long petId = 789; // Long | Pet id to delete
+        String apiKey = apiKey_example; // String | 
+        try {
+            apiInstance.deletePet(petId, apiKey);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling PetApi#deletePet");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + +
+

+import .PetApi;
+
+public class PetApiExample {
+
+    public static void main(String[] args) {
+        PetApi apiInstance = new PetApi();
+        Long petId = 789; // Long | Pet id to delete
+        String apiKey = apiKey_example; // String | 
+        try {
+            apiInstance.deletePet(petId, apiKey);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling PetApi#deletePet");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + + + +
+

+Configuration *apiConfig = [Configuration sharedConfig];
+
+// Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth)
+[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"];
+
+
+Long *petId = 789; // Pet id to delete
+String *apiKey = apiKey_example; //  (optional)
+
+PetApi *apiInstance = [[PetApi alloc] init];
+
+// Deletes a pet
+[apiInstance deletePetWith:petId
+    apiKey:apiKey
+              completionHandler: ^(NSError* error) {
+                            if (error) {
+                                NSLog(@"Error: %@", error);
+                            }
+                        }];
+
+                                                    
+
+
+

+var  = require('');
+var defaultClient = .ApiClient.instance;
+
+// Configure OAuth2 access token for authorization: petstore_auth
+var petstore_auth = defaultClient.authentications['petstore_auth'];
+petstore_auth.accessToken = "YOUR ACCESS TOKEN"
+
+var api = new .PetApi()
+
+var petId = 789; // {Long} Pet id to delete
+
+var opts = { 
+  'apiKey': apiKey_example // {String} 
+};
+
+var callback = function(error, data, response) {
+  if (error) {
+    console.error(error);
+  } else {
+    console.log('API called successfully.');
+  }
+};
+api.deletePet(petId, opts, callback);
+
+                                                    
+
+ + + +
+

+using System;
+using System.Diagnostics;
+using .Api;
+using .Client;
+using ;
+
+namespace Example
+{
+    public class deletePetExample
+    {
+        public void main()
+        {
+            
+            // Configure OAuth2 access token for authorization: petstore_auth
+            Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN";
+
+            var apiInstance = new PetApi();
+            var petId = 789;  // Long | Pet id to delete
+            var apiKey = apiKey_example;  // String |  (optional) 
+
+            try
+            {
+                // Deletes a pet
+                apiInstance.deletePet(petId, apiKey);
+            }
+            catch (Exception e)
+            {
+                Debug.Print("Exception when calling PetApi.deletePet: " + e.Message );
+            }
+        }
+    }
+}
+
+                                                    
+
+ + +
+

+setAccessToken('YOUR_ACCESS_TOKEN');
+
+$api_instance = new io.swagger.client\Api\PetApi();
+$petId = 789; // Long | Pet id to delete
+$apiKey = apiKey_example; // String | 
+
+try {
+    $api_instance->deletePet($petId, $apiKey);
+} catch (Exception $e) {
+    echo 'Exception when calling PetApi->deletePet: ', $e->getMessage(), PHP_EOL;
+}
+
+                                                  
+
+ +
+ + + + + +

Parameters

+ + + +
Path parameters
+ + + + + + + + + + +
NameDescription
petId* + + + +
+
+ +
Header parameters
+ + + + + + + + + + + +
NameDescription
apiKey + + + +
+
+ + + + +

Responses

+ +

Status: 400 - Invalid pet value

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + + + + + + +
+ +
+ +
+ + + + + + + + +
+ +
+
+

findPetsByStatus

+
+
+ +
+
+ +

+

Multiple status values can be provided with comma separated strings

+

+
+ +
/pet/findByStatus
+ +

+

Usage and SDK Samples

+

+ + + +
+
+

+curl -X get "http://petstore.swagger.io/v2/pet/findByStatus?status="
+
+
+
+
+ +
+

+import io.swagger.client.*;
+import io.swagger.client.auth.*;
+import io.swagger.client.model.*;
+import .PetApi;
+
+import java.io.File;
+import java.util.*;
+
+public class PetApiExample {
+
+    public static void main(String[] args) {
+        ApiClient defaultClient = Configuration.getDefaultApiClient();
+        
+        // Configure OAuth2 access token for authorization: petstore_auth
+        OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth");
+        petstore_auth.setAccessToken("YOUR ACCESS TOKEN");
+
+        PetApi apiInstance = new PetApi();
+        array[String] status = ; // array[String] | Status values that need to be considered for filter
+        try {
+            array[Pet] result = apiInstance.findPetsByStatus(status);
+            System.out.println(result);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling PetApi#findPetsByStatus");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + +
+

+import .PetApi;
+
+public class PetApiExample {
+
+    public static void main(String[] args) {
+        PetApi apiInstance = new PetApi();
+        array[String] status = ; // array[String] | Status values that need to be considered for filter
+        try {
+            array[Pet] result = apiInstance.findPetsByStatus(status);
+            System.out.println(result);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling PetApi#findPetsByStatus");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + + + +
+

+Configuration *apiConfig = [Configuration sharedConfig];
+
+// Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth)
+[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"];
+
+
+array[String] *status = ; // Status values that need to be considered for filter
+
+PetApi *apiInstance = [[PetApi alloc] init];
+
+// Finds Pets by status
+[apiInstance findPetsByStatusWith:status
+              completionHandler: ^(array[Pet] output, NSError* error) {
+                            if (output) {
+                                NSLog(@"%@", output);
+                            }
+                            if (error) {
+                                NSLog(@"Error: %@", error);
+                            }
+                        }];
+
+                                                    
+
+
+

+var  = require('');
+var defaultClient = .ApiClient.instance;
+
+// Configure OAuth2 access token for authorization: petstore_auth
+var petstore_auth = defaultClient.authentications['petstore_auth'];
+petstore_auth.accessToken = "YOUR ACCESS TOKEN"
+
+var api = new .PetApi()
+
+var status = ; // {array[String]} Status values that need to be considered for filter
+
+
+var callback = function(error, data, response) {
+  if (error) {
+    console.error(error);
+  } else {
+    console.log('API called successfully. Returned data: ' + data);
+  }
+};
+api.findPetsByStatus(status, callback);
+
+                                                    
+
+ + + +
+

+using System;
+using System.Diagnostics;
+using .Api;
+using .Client;
+using ;
+
+namespace Example
+{
+    public class findPetsByStatusExample
+    {
+        public void main()
+        {
+            
+            // Configure OAuth2 access token for authorization: petstore_auth
+            Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN";
+
+            var apiInstance = new PetApi();
+            var status = new array[String](); // array[String] | Status values that need to be considered for filter
+
+            try
+            {
+                // Finds Pets by status
+                array[Pet] result = apiInstance.findPetsByStatus(status);
+                Debug.WriteLine(result);
+            }
+            catch (Exception e)
+            {
+                Debug.Print("Exception when calling PetApi.findPetsByStatus: " + e.Message );
+            }
+        }
+    }
+}
+
+                                                    
+
+ + +
+

+setAccessToken('YOUR_ACCESS_TOKEN');
+
+$api_instance = new io.swagger.client\Api\PetApi();
+$status = ; // array[String] | Status values that need to be considered for filter
+
+try {
+    $result = $api_instance->findPetsByStatus($status);
+    print_r($result);
+} catch (Exception $e) {
+    echo 'Exception when calling PetApi->findPetsByStatus: ', $e->getMessage(), PHP_EOL;
+}
+
+                                                  
+
+ +
+ + + + + +

Parameters

+ + + + + + + +
Query parameters
+ + + + + + + + + + +
NameDescription
status* + + + +
+
+ +

Responses

+ +

Status: 200 - successful operation

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + +

Status: 400 - Invalid status value

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + + + + + + +
+ +
+ +
+ + + + + + + + +
+ +
+
+

findPetsByTags

+
+
+ +
+
+ +

+

Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.

+

+
+ +
/pet/findByTags
+ +

+

Usage and SDK Samples

+

+ + + +
+
+

+curl -X get "http://petstore.swagger.io/v2/pet/findByTags?tags="
+
+
+
+
+ +
+

+import io.swagger.client.*;
+import io.swagger.client.auth.*;
+import io.swagger.client.model.*;
+import .PetApi;
+
+import java.io.File;
+import java.util.*;
+
+public class PetApiExample {
+
+    public static void main(String[] args) {
+        ApiClient defaultClient = Configuration.getDefaultApiClient();
+        
+        // Configure OAuth2 access token for authorization: petstore_auth
+        OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth");
+        petstore_auth.setAccessToken("YOUR ACCESS TOKEN");
+
+        PetApi apiInstance = new PetApi();
+        array[String] tags = ; // array[String] | Tags to filter by
+        try {
+            array[Pet] result = apiInstance.findPetsByTags(tags);
+            System.out.println(result);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling PetApi#findPetsByTags");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + +
+

+import .PetApi;
+
+public class PetApiExample {
+
+    public static void main(String[] args) {
+        PetApi apiInstance = new PetApi();
+        array[String] tags = ; // array[String] | Tags to filter by
+        try {
+            array[Pet] result = apiInstance.findPetsByTags(tags);
+            System.out.println(result);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling PetApi#findPetsByTags");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + + + +
+

+Configuration *apiConfig = [Configuration sharedConfig];
+
+// Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth)
+[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"];
+
+
+array[String] *tags = ; // Tags to filter by
+
+PetApi *apiInstance = [[PetApi alloc] init];
+
+// Finds Pets by tags
+[apiInstance findPetsByTagsWith:tags
+              completionHandler: ^(array[Pet] output, NSError* error) {
+                            if (output) {
+                                NSLog(@"%@", output);
+                            }
+                            if (error) {
+                                NSLog(@"Error: %@", error);
+                            }
+                        }];
+
+                                                    
+
+
+

+var  = require('');
+var defaultClient = .ApiClient.instance;
+
+// Configure OAuth2 access token for authorization: petstore_auth
+var petstore_auth = defaultClient.authentications['petstore_auth'];
+petstore_auth.accessToken = "YOUR ACCESS TOKEN"
+
+var api = new .PetApi()
+
+var tags = ; // {array[String]} Tags to filter by
+
+
+var callback = function(error, data, response) {
+  if (error) {
+    console.error(error);
+  } else {
+    console.log('API called successfully. Returned data: ' + data);
+  }
+};
+api.findPetsByTags(tags, callback);
+
+                                                    
+
+ + + +
+

+using System;
+using System.Diagnostics;
+using .Api;
+using .Client;
+using ;
+
+namespace Example
+{
+    public class findPetsByTagsExample
+    {
+        public void main()
+        {
+            
+            // Configure OAuth2 access token for authorization: petstore_auth
+            Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN";
+
+            var apiInstance = new PetApi();
+            var tags = new array[String](); // array[String] | Tags to filter by
+
+            try
+            {
+                // Finds Pets by tags
+                array[Pet] result = apiInstance.findPetsByTags(tags);
+                Debug.WriteLine(result);
+            }
+            catch (Exception e)
+            {
+                Debug.Print("Exception when calling PetApi.findPetsByTags: " + e.Message );
+            }
+        }
+    }
+}
+
+                                                    
+
+ + +
+

+setAccessToken('YOUR_ACCESS_TOKEN');
+
+$api_instance = new io.swagger.client\Api\PetApi();
+$tags = ; // array[String] | Tags to filter by
+
+try {
+    $result = $api_instance->findPetsByTags($tags);
+    print_r($result);
+} catch (Exception $e) {
+    echo 'Exception when calling PetApi->findPetsByTags: ', $e->getMessage(), PHP_EOL;
+}
+
+                                                  
+
+ +
+ + + + + +

Parameters

+ + + + + + + +
Query parameters
+ + + + + + + + + + +
NameDescription
tags* + + + +
+
+ +

Responses

+ +

Status: 200 - successful operation

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + +

Status: 400 - Invalid tag value

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + + + + + + +
+ +
+ +
+ + + + + + + + +
+ +
+
+

getPetById

+
+
+ +
+
+ +

+

Returns a single pet

+

+
+ +
/pet/{petId}
+ +

+

Usage and SDK Samples

+

+ + + +
+
+

+curl -X get "http://petstore.swagger.io/v2/pet/{petId}"
+
+
+
+
+ +
+

+import io.swagger.client.*;
+import io.swagger.client.auth.*;
+import io.swagger.client.model.*;
+import .PetApi;
+
+import java.io.File;
+import java.util.*;
+
+public class PetApiExample {
+
+    public static void main(String[] args) {
+        ApiClient defaultClient = Configuration.getDefaultApiClient();
+        
+        // Configure API key authorization: api_key
+        ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key");
+        api_key.setApiKey("YOUR API KEY");
+        // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
+        //api_key.setApiKeyPrefix("Token");
+
+        PetApi apiInstance = new PetApi();
+        Long petId = 789; // Long | ID of pet to return
+        try {
+            Pet result = apiInstance.getPetById(petId);
+            System.out.println(result);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling PetApi#getPetById");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + +
+

+import .PetApi;
+
+public class PetApiExample {
+
+    public static void main(String[] args) {
+        PetApi apiInstance = new PetApi();
+        Long petId = 789; // Long | ID of pet to return
+        try {
+            Pet result = apiInstance.getPetById(petId);
+            System.out.println(result);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling PetApi#getPetById");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + + + +
+

+Configuration *apiConfig = [Configuration sharedConfig];
+
+// Configure API key authorization: (authentication scheme: api_key)
+[apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"api_key"];
+// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
+//[apiConfig setApiKeyPrefix:@"Bearer" forApiKeyIdentifier:@"api_key"];
+
+
+Long *petId = 789; // ID of pet to return
+
+PetApi *apiInstance = [[PetApi alloc] init];
+
+// Find pet by ID
+[apiInstance getPetByIdWith:petId
+              completionHandler: ^(Pet output, NSError* error) {
+                            if (output) {
+                                NSLog(@"%@", output);
+                            }
+                            if (error) {
+                                NSLog(@"Error: %@", error);
+                            }
+                        }];
+
+                                                    
+
+
+

+var  = require('');
+var defaultClient = .ApiClient.instance;
+
+// Configure API key authorization: api_key
+var api_key = defaultClient.authentications['api_key'];
+api_key.apiKey = "YOUR API KEY"
+// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
+//api_key.apiKeyPrefix['api_key'] = "Token"
+
+var api = new .PetApi()
+
+var petId = 789; // {Long} ID of pet to return
+
+
+var callback = function(error, data, response) {
+  if (error) {
+    console.error(error);
+  } else {
+    console.log('API called successfully. Returned data: ' + data);
+  }
+};
+api.getPetById(petId, callback);
+
+                                                    
+
+ + + +
+

+using System;
+using System.Diagnostics;
+using .Api;
+using .Client;
+using ;
+
+namespace Example
+{
+    public class getPetByIdExample
+    {
+        public void main()
+        {
+            
+            // Configure API key authorization: api_key
+            Configuration.Default.ApiKey.Add("api_key", "YOUR_API_KEY");
+            // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
+            // Configuration.Default.ApiKeyPrefix.Add("api_key", "Bearer");
+
+            var apiInstance = new PetApi();
+            var petId = 789;  // Long | ID of pet to return
+
+            try
+            {
+                // Find pet by ID
+                Pet result = apiInstance.getPetById(petId);
+                Debug.WriteLine(result);
+            }
+            catch (Exception e)
+            {
+                Debug.Print("Exception when calling PetApi.getPetById: " + e.Message );
+            }
+        }
+    }
+}
+
+                                                    
+
+ + +
+

+setApiKey('api_key', 'YOUR_API_KEY');
+// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
+// io.swagger.client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer');
+
+$api_instance = new io.swagger.client\Api\PetApi();
+$petId = 789; // Long | ID of pet to return
+
+try {
+    $result = $api_instance->getPetById($petId);
+    print_r($result);
+} catch (Exception $e) {
+    echo 'Exception when calling PetApi->getPetById: ', $e->getMessage(), PHP_EOL;
+}
+
+                                                  
+
+ +
+ + + + + +

Parameters

+ + + +
Path parameters
+ + + + + + + + + + +
NameDescription
petId* + + + +
+
+ + + + + +

Responses

+ +

Status: 200 - successful operation

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + +

Status: 400 - Invalid ID supplied

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + +

Status: 404 - Pet not found

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + + + + + + +
+ +
+ +
+ + + + + + + + +
+ +
+
+

updatePet

+
+
+ +
+
+ +

+

+

+
+ +
/pet
+ +

+

Usage and SDK Samples

+

+ + + +
+
+

+curl -X put "http://petstore.swagger.io/v2/pet"
+
+
+
+
+ +
+

+import io.swagger.client.*;
+import io.swagger.client.auth.*;
+import io.swagger.client.model.*;
+import .PetApi;
+
+import java.io.File;
+import java.util.*;
+
+public class PetApiExample {
+
+    public static void main(String[] args) {
+        ApiClient defaultClient = Configuration.getDefaultApiClient();
+        
+        // Configure OAuth2 access token for authorization: petstore_auth
+        OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth");
+        petstore_auth.setAccessToken("YOUR ACCESS TOKEN");
+
+        PetApi apiInstance = new PetApi();
+        Pet body = ; // Pet | Pet object that needs to be added to the store
+        try {
+            apiInstance.updatePet(body);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling PetApi#updatePet");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + +
+

+import .PetApi;
+
+public class PetApiExample {
+
+    public static void main(String[] args) {
+        PetApi apiInstance = new PetApi();
+        Pet body = ; // Pet | Pet object that needs to be added to the store
+        try {
+            apiInstance.updatePet(body);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling PetApi#updatePet");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + + + +
+

+Configuration *apiConfig = [Configuration sharedConfig];
+
+// Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth)
+[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"];
+
+
+Pet *body = ; // Pet object that needs to be added to the store
+
+PetApi *apiInstance = [[PetApi alloc] init];
+
+// Update an existing pet
+[apiInstance updatePetWith:body
+              completionHandler: ^(NSError* error) {
+                            if (error) {
+                                NSLog(@"Error: %@", error);
+                            }
+                        }];
+
+                                                    
+
+
+

+var  = require('');
+var defaultClient = .ApiClient.instance;
+
+// Configure OAuth2 access token for authorization: petstore_auth
+var petstore_auth = defaultClient.authentications['petstore_auth'];
+petstore_auth.accessToken = "YOUR ACCESS TOKEN"
+
+var api = new .PetApi()
+
+var body = ; // {Pet} Pet object that needs to be added to the store
+
+
+var callback = function(error, data, response) {
+  if (error) {
+    console.error(error);
+  } else {
+    console.log('API called successfully.');
+  }
+};
+api.updatePet(body, callback);
+
+                                                    
+
+ + + +
+

+using System;
+using System.Diagnostics;
+using .Api;
+using .Client;
+using ;
+
+namespace Example
+{
+    public class updatePetExample
+    {
+        public void main()
+        {
+            
+            // Configure OAuth2 access token for authorization: petstore_auth
+            Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN";
+
+            var apiInstance = new PetApi();
+            var body = new Pet(); // Pet | Pet object that needs to be added to the store
+
+            try
+            {
+                // Update an existing pet
+                apiInstance.updatePet(body);
+            }
+            catch (Exception e)
+            {
+                Debug.Print("Exception when calling PetApi.updatePet: " + e.Message );
+            }
+        }
+    }
+}
+
+                                                    
+
+ + +
+

+setAccessToken('YOUR_ACCESS_TOKEN');
+
+$api_instance = new io.swagger.client\Api\PetApi();
+$body = ; // Pet | Pet object that needs to be added to the store
+
+try {
+    $api_instance->updatePet($body);
+} catch (Exception $e) {
+    echo 'Exception when calling PetApi->updatePet: ', $e->getMessage(), PHP_EOL;
+}
+
+                                                  
+
+ +
+ + + + + +

Parameters

+ + + + + + +
Body parameters
+ + + + + + + + + + + +
NameDescription
body * + + + +
+
+ + +

Responses

+ +

Status: 400 - Invalid ID supplied

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + +

Status: 404 - Pet not found

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + +

Status: 405 - Validation exception

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + + + + + + +
+ +
+ +
+ + + + + + + + +
+ +
+
+

updatePetWithForm

+
+
+ +
+
+ +

+

+

+
+ +
/pet/{petId}
+ +

+

Usage and SDK Samples

+

+ + + +
+
+

+curl -X post "http://petstore.swagger.io/v2/pet/{petId}"
+
+
+
+
+ +
+

+import io.swagger.client.*;
+import io.swagger.client.auth.*;
+import io.swagger.client.model.*;
+import .PetApi;
+
+import java.io.File;
+import java.util.*;
+
+public class PetApiExample {
+
+    public static void main(String[] args) {
+        ApiClient defaultClient = Configuration.getDefaultApiClient();
+        
+        // Configure OAuth2 access token for authorization: petstore_auth
+        OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth");
+        petstore_auth.setAccessToken("YOUR ACCESS TOKEN");
+
+        PetApi apiInstance = new PetApi();
+        Long petId = 789; // Long | ID of pet that needs to be updated
+        String name = name_example; // String | Updated name of the pet
+        String status = status_example; // String | Updated status of the pet
+        try {
+            apiInstance.updatePetWithForm(petId, name, status);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling PetApi#updatePetWithForm");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + +
+

+import .PetApi;
+
+public class PetApiExample {
+
+    public static void main(String[] args) {
+        PetApi apiInstance = new PetApi();
+        Long petId = 789; // Long | ID of pet that needs to be updated
+        String name = name_example; // String | Updated name of the pet
+        String status = status_example; // String | Updated status of the pet
+        try {
+            apiInstance.updatePetWithForm(petId, name, status);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling PetApi#updatePetWithForm");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + + + +
+

+Configuration *apiConfig = [Configuration sharedConfig];
+
+// Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth)
+[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"];
+
+
+Long *petId = 789; // ID of pet that needs to be updated
+String *name = name_example; // Updated name of the pet (optional)
+String *status = status_example; // Updated status of the pet (optional)
+
+PetApi *apiInstance = [[PetApi alloc] init];
+
+// Updates a pet in the store with form data
+[apiInstance updatePetWithFormWith:petId
+    name:name
+    status:status
+              completionHandler: ^(NSError* error) {
+                            if (error) {
+                                NSLog(@"Error: %@", error);
+                            }
+                        }];
+
+                                                    
+
+
+

+var  = require('');
+var defaultClient = .ApiClient.instance;
+
+// Configure OAuth2 access token for authorization: petstore_auth
+var petstore_auth = defaultClient.authentications['petstore_auth'];
+petstore_auth.accessToken = "YOUR ACCESS TOKEN"
+
+var api = new .PetApi()
+
+var petId = 789; // {Long} ID of pet that needs to be updated
+
+var opts = { 
+  'name': name_example, // {String} Updated name of the pet
+  'status': status_example // {String} Updated status of the pet
+};
+
+var callback = function(error, data, response) {
+  if (error) {
+    console.error(error);
+  } else {
+    console.log('API called successfully.');
+  }
+};
+api.updatePetWithForm(petId, opts, callback);
+
+                                                    
+
+ + + +
+

+using System;
+using System.Diagnostics;
+using .Api;
+using .Client;
+using ;
+
+namespace Example
+{
+    public class updatePetWithFormExample
+    {
+        public void main()
+        {
+            
+            // Configure OAuth2 access token for authorization: petstore_auth
+            Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN";
+
+            var apiInstance = new PetApi();
+            var petId = 789;  // Long | ID of pet that needs to be updated
+            var name = name_example;  // String | Updated name of the pet (optional) 
+            var status = status_example;  // String | Updated status of the pet (optional) 
+
+            try
+            {
+                // Updates a pet in the store with form data
+                apiInstance.updatePetWithForm(petId, name, status);
+            }
+            catch (Exception e)
+            {
+                Debug.Print("Exception when calling PetApi.updatePetWithForm: " + e.Message );
+            }
+        }
+    }
+}
+
+                                                    
+
+ + +
+

+setAccessToken('YOUR_ACCESS_TOKEN');
+
+$api_instance = new io.swagger.client\Api\PetApi();
+$petId = 789; // Long | ID of pet that needs to be updated
+$name = name_example; // String | Updated name of the pet
+$status = status_example; // String | Updated status of the pet
+
+try {
+    $api_instance->updatePetWithForm($petId, $name, $status);
+} catch (Exception $e) {
+    echo 'Exception when calling PetApi->updatePetWithForm: ', $e->getMessage(), PHP_EOL;
+}
+
+                                                  
+
+ +
+ + + + + +

Parameters

+ + + +
Path parameters
+ + + + + + + + + + +
NameDescription
petId* + + + +
+
+ + + + + +

Responses

+ +

Status: 405 - Invalid input

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + + + + + + +
+ +
+ +
+ + + + + + + + +
+ +
+
+

uploadFile

+
+
+ +
+
+ +

+

+

+
+ +
/pet/{petId}/uploadImage
+ +

+

Usage and SDK Samples

+

+ + + +
+
+

+curl -X post "http://petstore.swagger.io/v2/pet/{petId}/uploadImage"
+
+
+
+
+ +
+

+import io.swagger.client.*;
+import io.swagger.client.auth.*;
+import io.swagger.client.model.*;
+import .PetApi;
+
+import java.io.File;
+import java.util.*;
+
+public class PetApiExample {
+
+    public static void main(String[] args) {
+        ApiClient defaultClient = Configuration.getDefaultApiClient();
+        
+        // Configure OAuth2 access token for authorization: petstore_auth
+        OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth");
+        petstore_auth.setAccessToken("YOUR ACCESS TOKEN");
+
+        PetApi apiInstance = new PetApi();
+        Long petId = 789; // Long | ID of pet to update
+        String additionalMetadata = additionalMetadata_example; // String | Additional data to pass to server
+        file file = /path/to/file.txt; // file | file to upload
+        try {
+            ApiResponse result = apiInstance.uploadFile(petId, additionalMetadata, file);
+            System.out.println(result);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling PetApi#uploadFile");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + +
+

+import .PetApi;
+
+public class PetApiExample {
+
+    public static void main(String[] args) {
+        PetApi apiInstance = new PetApi();
+        Long petId = 789; // Long | ID of pet to update
+        String additionalMetadata = additionalMetadata_example; // String | Additional data to pass to server
+        file file = /path/to/file.txt; // file | file to upload
+        try {
+            ApiResponse result = apiInstance.uploadFile(petId, additionalMetadata, file);
+            System.out.println(result);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling PetApi#uploadFile");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + + + +
+

+Configuration *apiConfig = [Configuration sharedConfig];
+
+// Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth)
+[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"];
+
+
+Long *petId = 789; // ID of pet to update
+String *additionalMetadata = additionalMetadata_example; // Additional data to pass to server (optional)
+file *file = /path/to/file.txt; // file to upload (optional)
+
+PetApi *apiInstance = [[PetApi alloc] init];
+
+// uploads an image
+[apiInstance uploadFileWith:petId
+    additionalMetadata:additionalMetadata
+    file:file
+              completionHandler: ^(ApiResponse output, NSError* error) {
+                            if (output) {
+                                NSLog(@"%@", output);
+                            }
+                            if (error) {
+                                NSLog(@"Error: %@", error);
+                            }
+                        }];
+
+                                                    
+
+
+

+var  = require('');
+var defaultClient = .ApiClient.instance;
+
+// Configure OAuth2 access token for authorization: petstore_auth
+var petstore_auth = defaultClient.authentications['petstore_auth'];
+petstore_auth.accessToken = "YOUR ACCESS TOKEN"
+
+var api = new .PetApi()
+
+var petId = 789; // {Long} ID of pet to update
+
+var opts = { 
+  'additionalMetadata': additionalMetadata_example, // {String} Additional data to pass to server
+  'file': /path/to/file.txt // {file} file to upload
+};
+
+var callback = function(error, data, response) {
+  if (error) {
+    console.error(error);
+  } else {
+    console.log('API called successfully. Returned data: ' + data);
+  }
+};
+api.uploadFile(petId, opts, callback);
+
+                                                    
+
+ + + +
+

+using System;
+using System.Diagnostics;
+using .Api;
+using .Client;
+using ;
+
+namespace Example
+{
+    public class uploadFileExample
+    {
+        public void main()
+        {
+            
+            // Configure OAuth2 access token for authorization: petstore_auth
+            Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN";
+
+            var apiInstance = new PetApi();
+            var petId = 789;  // Long | ID of pet to update
+            var additionalMetadata = additionalMetadata_example;  // String | Additional data to pass to server (optional) 
+            var file = new file(); // file | file to upload (optional) 
+
+            try
+            {
+                // uploads an image
+                ApiResponse result = apiInstance.uploadFile(petId, additionalMetadata, file);
+                Debug.WriteLine(result);
+            }
+            catch (Exception e)
+            {
+                Debug.Print("Exception when calling PetApi.uploadFile: " + e.Message );
+            }
+        }
+    }
+}
+
+                                                    
+
+ + +
+

+setAccessToken('YOUR_ACCESS_TOKEN');
+
+$api_instance = new io.swagger.client\Api\PetApi();
+$petId = 789; // Long | ID of pet to update
+$additionalMetadata = additionalMetadata_example; // String | Additional data to pass to server
+$file = /path/to/file.txt; // file | file to upload
+
+try {
+    $result = $api_instance->uploadFile($petId, $additionalMetadata, $file);
+    print_r($result);
+} catch (Exception $e) {
+    echo 'Exception when calling PetApi->uploadFile: ', $e->getMessage(), PHP_EOL;
+}
+
+                                                  
+
+ +
+ + + + + +

Parameters

+ + + +
Path parameters
+ + + + + + + + + + +
NameDescription
petId* + + + +
+
+ + + + + +

Responses

+ +

Status: 200 - successful operation

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + + + + + + +
+ +
+ +
+ +
+ +
+

Store

+ + + + + + + +
+ +
+
+

deleteOrder

+
+
+ +
+
+ +

+

For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors

+

+
+ +
/store/order/{orderId}
+ +

+

Usage and SDK Samples

+

+ + + +
+
+

+curl -X delete "http://petstore.swagger.io/v2/store/order/{orderId}"
+
+
+
+
+ +
+

+import io.swagger.client.*;
+import io.swagger.client.auth.*;
+import io.swagger.client.model.*;
+import .StoreApi;
+
+import java.io.File;
+import java.util.*;
+
+public class StoreApiExample {
+
+    public static void main(String[] args) {
+        
+        StoreApi apiInstance = new StoreApi();
+        String orderId = orderId_example; // String | ID of the order that needs to be deleted
+        try {
+            apiInstance.deleteOrder(orderId);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling StoreApi#deleteOrder");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + +
+

+import .StoreApi;
+
+public class StoreApiExample {
+
+    public static void main(String[] args) {
+        StoreApi apiInstance = new StoreApi();
+        String orderId = orderId_example; // String | ID of the order that needs to be deleted
+        try {
+            apiInstance.deleteOrder(orderId);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling StoreApi#deleteOrder");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + + + +
+

+
+String *orderId = orderId_example; // ID of the order that needs to be deleted
+
+StoreApi *apiInstance = [[StoreApi alloc] init];
+
+// Delete purchase order by ID
+[apiInstance deleteOrderWith:orderId
+              completionHandler: ^(NSError* error) {
+                            if (error) {
+                                NSLog(@"Error: %@", error);
+                            }
+                        }];
+
+                                                    
+
+
+

+var  = require('');
+
+var api = new .StoreApi()
+
+var orderId = orderId_example; // {String} ID of the order that needs to be deleted
+
+
+var callback = function(error, data, response) {
+  if (error) {
+    console.error(error);
+  } else {
+    console.log('API called successfully.');
+  }
+};
+api.deleteOrder(orderId, callback);
+
+                                                    
+
+ + + +
+

+using System;
+using System.Diagnostics;
+using .Api;
+using .Client;
+using ;
+
+namespace Example
+{
+    public class deleteOrderExample
+    {
+        public void main()
+        {
+            
+            var apiInstance = new StoreApi();
+            var orderId = orderId_example;  // String | ID of the order that needs to be deleted
+
+            try
+            {
+                // Delete purchase order by ID
+                apiInstance.deleteOrder(orderId);
+            }
+            catch (Exception e)
+            {
+                Debug.Print("Exception when calling StoreApi.deleteOrder: " + e.Message );
+            }
+        }
+    }
+}
+
+                                                    
+
+ + +
+

+deleteOrder($orderId);
+} catch (Exception $e) {
+    echo 'Exception when calling StoreApi->deleteOrder: ', $e->getMessage(), PHP_EOL;
+}
+
+                                                  
+
+ +
+ + + + + +

Parameters

+ + + +
Path parameters
+ + + + + + + + + + +
NameDescription
orderId* + + + +
+
+ + + + + +

Responses

+ +

Status: 400 - Invalid ID supplied

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + +

Status: 404 - Order not found

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + + + + + + +
+ +
+ +
+ + + + + + + + +
+ +
+
+

getInventory

+
+
+ +
+
+ +

+

Returns a map of status codes to quantities

+

+
+ +
/store/inventory
+ +

+

Usage and SDK Samples

+

+ + + +
+
+

+curl -X get "http://petstore.swagger.io/v2/store/inventory"
+
+
+
+
+ +
+

+import io.swagger.client.*;
+import io.swagger.client.auth.*;
+import io.swagger.client.model.*;
+import .StoreApi;
+
+import java.io.File;
+import java.util.*;
+
+public class StoreApiExample {
+
+    public static void main(String[] args) {
+        ApiClient defaultClient = Configuration.getDefaultApiClient();
+        
+        // Configure API key authorization: api_key
+        ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key");
+        api_key.setApiKey("YOUR API KEY");
+        // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
+        //api_key.setApiKeyPrefix("Token");
+
+        StoreApi apiInstance = new StoreApi();
+        try {
+            map['String', 'Integer'] result = apiInstance.getInventory();
+            System.out.println(result);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling StoreApi#getInventory");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + +
+

+import .StoreApi;
+
+public class StoreApiExample {
+
+    public static void main(String[] args) {
+        StoreApi apiInstance = new StoreApi();
+        try {
+            map['String', 'Integer'] result = apiInstance.getInventory();
+            System.out.println(result);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling StoreApi#getInventory");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + + + +
+

+Configuration *apiConfig = [Configuration sharedConfig];
+
+// Configure API key authorization: (authentication scheme: api_key)
+[apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"api_key"];
+// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
+//[apiConfig setApiKeyPrefix:@"Bearer" forApiKeyIdentifier:@"api_key"];
+
+
+
+StoreApi *apiInstance = [[StoreApi alloc] init];
+
+// Returns pet inventories by status
+[apiInstance getInventoryWithCompletionHandler: 
+              ^(map['String', 'Integer'] output, NSError* error) {
+                            if (output) {
+                                NSLog(@"%@", output);
+                            }
+                            if (error) {
+                                NSLog(@"Error: %@", error);
+                            }
+                        }];
+
+                                                    
+
+
+

+var  = require('');
+var defaultClient = .ApiClient.instance;
+
+// Configure API key authorization: api_key
+var api_key = defaultClient.authentications['api_key'];
+api_key.apiKey = "YOUR API KEY"
+// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
+//api_key.apiKeyPrefix['api_key'] = "Token"
+
+var api = new .StoreApi()
+
+var callback = function(error, data, response) {
+  if (error) {
+    console.error(error);
+  } else {
+    console.log('API called successfully. Returned data: ' + data);
+  }
+};
+api.getInventory(callback);
+
+                                                    
+
+ + + +
+

+using System;
+using System.Diagnostics;
+using .Api;
+using .Client;
+using ;
+
+namespace Example
+{
+    public class getInventoryExample
+    {
+        public void main()
+        {
+            
+            // Configure API key authorization: api_key
+            Configuration.Default.ApiKey.Add("api_key", "YOUR_API_KEY");
+            // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
+            // Configuration.Default.ApiKeyPrefix.Add("api_key", "Bearer");
+
+            var apiInstance = new StoreApi();
+
+            try
+            {
+                // Returns pet inventories by status
+                map['String', 'Integer'] result = apiInstance.getInventory();
+                Debug.WriteLine(result);
+            }
+            catch (Exception e)
+            {
+                Debug.Print("Exception when calling StoreApi.getInventory: " + e.Message );
+            }
+        }
+    }
+}
+
+                                                    
+
+ + +
+

+setApiKey('api_key', 'YOUR_API_KEY');
+// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
+// io.swagger.client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer');
+
+$api_instance = new io.swagger.client\Api\StoreApi();
+
+try {
+    $result = $api_instance->getInventory();
+    print_r($result);
+} catch (Exception $e) {
+    echo 'Exception when calling StoreApi->getInventory: ', $e->getMessage(), PHP_EOL;
+}
+
+                                                  
+
+ +
+ + + + + +

Parameters

+ + + + + + + + +

Responses

+ +

Status: 200 - successful operation

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + + + + + + +
+ +
+ +
+ + + + + + + + +
+ +
+
+

getOrderById

+
+
+ +
+
+ +

+

For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions

+

+
+ +
/store/order/{orderId}
+ +

+

Usage and SDK Samples

+

+ + + +
+
+

+curl -X get "http://petstore.swagger.io/v2/store/order/{orderId}"
+
+
+
+
+ +
+

+import io.swagger.client.*;
+import io.swagger.client.auth.*;
+import io.swagger.client.model.*;
+import .StoreApi;
+
+import java.io.File;
+import java.util.*;
+
+public class StoreApiExample {
+
+    public static void main(String[] args) {
+        
+        StoreApi apiInstance = new StoreApi();
+        Long orderId = 789; // Long | ID of pet that needs to be fetched
+        try {
+            Order result = apiInstance.getOrderById(orderId);
+            System.out.println(result);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling StoreApi#getOrderById");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + +
+

+import .StoreApi;
+
+public class StoreApiExample {
+
+    public static void main(String[] args) {
+        StoreApi apiInstance = new StoreApi();
+        Long orderId = 789; // Long | ID of pet that needs to be fetched
+        try {
+            Order result = apiInstance.getOrderById(orderId);
+            System.out.println(result);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling StoreApi#getOrderById");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + + + +
+

+
+Long *orderId = 789; // ID of pet that needs to be fetched
+
+StoreApi *apiInstance = [[StoreApi alloc] init];
+
+// Find purchase order by ID
+[apiInstance getOrderByIdWith:orderId
+              completionHandler: ^(Order output, NSError* error) {
+                            if (output) {
+                                NSLog(@"%@", output);
+                            }
+                            if (error) {
+                                NSLog(@"Error: %@", error);
+                            }
+                        }];
+
+                                                    
+
+
+

+var  = require('');
+
+var api = new .StoreApi()
+
+var orderId = 789; // {Long} ID of pet that needs to be fetched
+
+
+var callback = function(error, data, response) {
+  if (error) {
+    console.error(error);
+  } else {
+    console.log('API called successfully. Returned data: ' + data);
+  }
+};
+api.getOrderById(orderId, callback);
+
+                                                    
+
+ + + +
+

+using System;
+using System.Diagnostics;
+using .Api;
+using .Client;
+using ;
+
+namespace Example
+{
+    public class getOrderByIdExample
+    {
+        public void main()
+        {
+            
+            var apiInstance = new StoreApi();
+            var orderId = 789;  // Long | ID of pet that needs to be fetched
+
+            try
+            {
+                // Find purchase order by ID
+                Order result = apiInstance.getOrderById(orderId);
+                Debug.WriteLine(result);
+            }
+            catch (Exception e)
+            {
+                Debug.Print("Exception when calling StoreApi.getOrderById: " + e.Message );
+            }
+        }
+    }
+}
+
+                                                    
+
+ + +
+

+getOrderById($orderId);
+    print_r($result);
+} catch (Exception $e) {
+    echo 'Exception when calling StoreApi->getOrderById: ', $e->getMessage(), PHP_EOL;
+}
+
+                                                  
+
+ +
+ + + + + +

Parameters

+ + + +
Path parameters
+ + + + + + + + + + +
NameDescription
orderId* + + + +
+
+ + + + + +

Responses

+ +

Status: 200 - successful operation

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + +

Status: 400 - Invalid ID supplied

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + +

Status: 404 - Order not found

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + + + + + + +
+ +
+ +
+ + + + + + + + +
+ +
+
+

placeOrder

+
+
+ +
+
+ +

+

+

+
+ +
/store/order
+ +

+

Usage and SDK Samples

+

+ + + +
+
+

+curl -X post "http://petstore.swagger.io/v2/store/order"
+
+
+
+
+ +
+

+import io.swagger.client.*;
+import io.swagger.client.auth.*;
+import io.swagger.client.model.*;
+import .StoreApi;
+
+import java.io.File;
+import java.util.*;
+
+public class StoreApiExample {
+
+    public static void main(String[] args) {
+        
+        StoreApi apiInstance = new StoreApi();
+        Order body = ; // Order | order placed for purchasing the pet
+        try {
+            Order result = apiInstance.placeOrder(body);
+            System.out.println(result);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling StoreApi#placeOrder");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + +
+

+import .StoreApi;
+
+public class StoreApiExample {
+
+    public static void main(String[] args) {
+        StoreApi apiInstance = new StoreApi();
+        Order body = ; // Order | order placed for purchasing the pet
+        try {
+            Order result = apiInstance.placeOrder(body);
+            System.out.println(result);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling StoreApi#placeOrder");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + + + +
+

+
+Order *body = ; // order placed for purchasing the pet
+
+StoreApi *apiInstance = [[StoreApi alloc] init];
+
+// Place an order for a pet
+[apiInstance placeOrderWith:body
+              completionHandler: ^(Order output, NSError* error) {
+                            if (output) {
+                                NSLog(@"%@", output);
+                            }
+                            if (error) {
+                                NSLog(@"Error: %@", error);
+                            }
+                        }];
+
+                                                    
+
+
+

+var  = require('');
+
+var api = new .StoreApi()
+
+var body = ; // {Order} order placed for purchasing the pet
+
+
+var callback = function(error, data, response) {
+  if (error) {
+    console.error(error);
+  } else {
+    console.log('API called successfully. Returned data: ' + data);
+  }
+};
+api.placeOrder(body, callback);
+
+                                                    
+
+ + + +
+

+using System;
+using System.Diagnostics;
+using .Api;
+using .Client;
+using ;
+
+namespace Example
+{
+    public class placeOrderExample
+    {
+        public void main()
+        {
+            
+            var apiInstance = new StoreApi();
+            var body = new Order(); // Order | order placed for purchasing the pet
+
+            try
+            {
+                // Place an order for a pet
+                Order result = apiInstance.placeOrder(body);
+                Debug.WriteLine(result);
+            }
+            catch (Exception e)
+            {
+                Debug.Print("Exception when calling StoreApi.placeOrder: " + e.Message );
+            }
+        }
+    }
+}
+
+                                                    
+
+ + +
+

+placeOrder($body);
+    print_r($result);
+} catch (Exception $e) {
+    echo 'Exception when calling StoreApi->placeOrder: ', $e->getMessage(), PHP_EOL;
+}
+
+                                                  
+
+ +
+ + + + + +

Parameters

+ + + + + + +
Body parameters
+ + + + + + + + + + + +
NameDescription
body * + + + +
+
+ + +

Responses

+ +

Status: 200 - successful operation

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + +

Status: 400 - Invalid Order

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + + + + + + +
+ +
+ +
+ +
+ +
+

User

+ + + + + + + +
+ +
+
+

createUser

+
+
+ +
+
+ +

+

This can only be done by the logged in user.

+

+
+ +
/user
+ +

+

Usage and SDK Samples

+

+ + + +
+
+

+curl -X post "http://petstore.swagger.io/v2/user"
+
+
+
+
+ +
+

+import io.swagger.client.*;
+import io.swagger.client.auth.*;
+import io.swagger.client.model.*;
+import .UserApi;
+
+import java.io.File;
+import java.util.*;
+
+public class UserApiExample {
+
+    public static void main(String[] args) {
+        
+        UserApi apiInstance = new UserApi();
+        User body = ; // User | Created user object
+        try {
+            apiInstance.createUser(body);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling UserApi#createUser");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + +
+

+import .UserApi;
+
+public class UserApiExample {
+
+    public static void main(String[] args) {
+        UserApi apiInstance = new UserApi();
+        User body = ; // User | Created user object
+        try {
+            apiInstance.createUser(body);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling UserApi#createUser");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + + + +
+

+
+User *body = ; // Created user object
+
+UserApi *apiInstance = [[UserApi alloc] init];
+
+// Create user
+[apiInstance createUserWith:body
+              completionHandler: ^(NSError* error) {
+                            if (error) {
+                                NSLog(@"Error: %@", error);
+                            }
+                        }];
+
+                                                    
+
+
+

+var  = require('');
+
+var api = new .UserApi()
+
+var body = ; // {User} Created user object
+
+
+var callback = function(error, data, response) {
+  if (error) {
+    console.error(error);
+  } else {
+    console.log('API called successfully.');
+  }
+};
+api.createUser(body, callback);
+
+                                                    
+
+ + + +
+

+using System;
+using System.Diagnostics;
+using .Api;
+using .Client;
+using ;
+
+namespace Example
+{
+    public class createUserExample
+    {
+        public void main()
+        {
+            
+            var apiInstance = new UserApi();
+            var body = new User(); // User | Created user object
+
+            try
+            {
+                // Create user
+                apiInstance.createUser(body);
+            }
+            catch (Exception e)
+            {
+                Debug.Print("Exception when calling UserApi.createUser: " + e.Message );
+            }
+        }
+    }
+}
+
+                                                    
+
+ + +
+

+createUser($body);
+} catch (Exception $e) {
+    echo 'Exception when calling UserApi->createUser: ', $e->getMessage(), PHP_EOL;
+}
+
+                                                  
+
+ +
+ + + + + +

Parameters

+ + + + + + +
Body parameters
+ + + + + + + + + + + +
NameDescription
body * + + + +
+
+ + +

Responses

+ +

Status: 0 - successful operation

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + + + + + + +
+ +
+ +
+ + + + + + + + +
+ +
+
+

createUsersWithArrayInput

+
+
+ +
+
+ +

+

+

+
+ +
/user/createWithArray
+ +

+

Usage and SDK Samples

+

+ + + +
+
+

+curl -X post "http://petstore.swagger.io/v2/user/createWithArray"
+
+
+
+
+ +
+

+import io.swagger.client.*;
+import io.swagger.client.auth.*;
+import io.swagger.client.model.*;
+import .UserApi;
+
+import java.io.File;
+import java.util.*;
+
+public class UserApiExample {
+
+    public static void main(String[] args) {
+        
+        UserApi apiInstance = new UserApi();
+        array[User] body = ; // array[User] | List of user object
+        try {
+            apiInstance.createUsersWithArrayInput(body);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling UserApi#createUsersWithArrayInput");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + +
+

+import .UserApi;
+
+public class UserApiExample {
+
+    public static void main(String[] args) {
+        UserApi apiInstance = new UserApi();
+        array[User] body = ; // array[User] | List of user object
+        try {
+            apiInstance.createUsersWithArrayInput(body);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling UserApi#createUsersWithArrayInput");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + + + +
+

+
+array[User] *body = ; // List of user object
+
+UserApi *apiInstance = [[UserApi alloc] init];
+
+// Creates list of users with given input array
+[apiInstance createUsersWithArrayInputWith:body
+              completionHandler: ^(NSError* error) {
+                            if (error) {
+                                NSLog(@"Error: %@", error);
+                            }
+                        }];
+
+                                                    
+
+
+

+var  = require('');
+
+var api = new .UserApi()
+
+var body = ; // {array[User]} List of user object
+
+
+var callback = function(error, data, response) {
+  if (error) {
+    console.error(error);
+  } else {
+    console.log('API called successfully.');
+  }
+};
+api.createUsersWithArrayInput(body, callback);
+
+                                                    
+
+ + + +
+

+using System;
+using System.Diagnostics;
+using .Api;
+using .Client;
+using ;
+
+namespace Example
+{
+    public class createUsersWithArrayInputExample
+    {
+        public void main()
+        {
+            
+            var apiInstance = new UserApi();
+            var body = new array[User](); // array[User] | List of user object
+
+            try
+            {
+                // Creates list of users with given input array
+                apiInstance.createUsersWithArrayInput(body);
+            }
+            catch (Exception e)
+            {
+                Debug.Print("Exception when calling UserApi.createUsersWithArrayInput: " + e.Message );
+            }
+        }
+    }
+}
+
+                                                    
+
+ + +
+

+createUsersWithArrayInput($body);
+} catch (Exception $e) {
+    echo 'Exception when calling UserApi->createUsersWithArrayInput: ', $e->getMessage(), PHP_EOL;
+}
+
+                                                  
+
+ +
+ + + + + +

Parameters

+ + + + + + +
Body parameters
+ + + + + + + + + + + +
NameDescription
body * + + + +
+
+ + +

Responses

+ +

Status: 0 - successful operation

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + + + + + + +
+ +
+ +
+ + + + + + + + +
+ +
+
+

createUsersWithListInput

+
+
+ +
+
+ +

+

+

+
+ +
/user/createWithList
+ +

+

Usage and SDK Samples

+

+ + + +
+
+

+curl -X post "http://petstore.swagger.io/v2/user/createWithList"
+
+
+
+
+ +
+

+import io.swagger.client.*;
+import io.swagger.client.auth.*;
+import io.swagger.client.model.*;
+import .UserApi;
+
+import java.io.File;
+import java.util.*;
+
+public class UserApiExample {
+
+    public static void main(String[] args) {
+        
+        UserApi apiInstance = new UserApi();
+        array[User] body = ; // array[User] | List of user object
+        try {
+            apiInstance.createUsersWithListInput(body);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling UserApi#createUsersWithListInput");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + +
+

+import .UserApi;
+
+public class UserApiExample {
+
+    public static void main(String[] args) {
+        UserApi apiInstance = new UserApi();
+        array[User] body = ; // array[User] | List of user object
+        try {
+            apiInstance.createUsersWithListInput(body);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling UserApi#createUsersWithListInput");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + + + +
+

+
+array[User] *body = ; // List of user object
+
+UserApi *apiInstance = [[UserApi alloc] init];
+
+// Creates list of users with given input array
+[apiInstance createUsersWithListInputWith:body
+              completionHandler: ^(NSError* error) {
+                            if (error) {
+                                NSLog(@"Error: %@", error);
+                            }
+                        }];
+
+                                                    
+
+
+

+var  = require('');
+
+var api = new .UserApi()
+
+var body = ; // {array[User]} List of user object
+
+
+var callback = function(error, data, response) {
+  if (error) {
+    console.error(error);
+  } else {
+    console.log('API called successfully.');
+  }
+};
+api.createUsersWithListInput(body, callback);
+
+                                                    
+
+ + + +
+

+using System;
+using System.Diagnostics;
+using .Api;
+using .Client;
+using ;
+
+namespace Example
+{
+    public class createUsersWithListInputExample
+    {
+        public void main()
+        {
+            
+            var apiInstance = new UserApi();
+            var body = new array[User](); // array[User] | List of user object
+
+            try
+            {
+                // Creates list of users with given input array
+                apiInstance.createUsersWithListInput(body);
+            }
+            catch (Exception e)
+            {
+                Debug.Print("Exception when calling UserApi.createUsersWithListInput: " + e.Message );
+            }
+        }
+    }
+}
+
+                                                    
+
+ + +
+

+createUsersWithListInput($body);
+} catch (Exception $e) {
+    echo 'Exception when calling UserApi->createUsersWithListInput: ', $e->getMessage(), PHP_EOL;
+}
+
+                                                  
+
+ +
+ + + + + +

Parameters

+ + + + + + +
Body parameters
+ + + + + + + + + + + +
NameDescription
body * + + + +
+
+ + +

Responses

+ +

Status: 0 - successful operation

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + + + + + + +
+ +
+ +
+ + + + + + + + +
+ +
+
+

deleteUser

+
+
+ +
+
+ +

+

This can only be done by the logged in user.

+

+
+ +
/user/{username}
+ +

+

Usage and SDK Samples

+

+ + + +
+
+

+curl -X delete "http://petstore.swagger.io/v2/user/{username}"
+
+
+
+
+ +
+

+import io.swagger.client.*;
+import io.swagger.client.auth.*;
+import io.swagger.client.model.*;
+import .UserApi;
+
+import java.io.File;
+import java.util.*;
+
+public class UserApiExample {
+
+    public static void main(String[] args) {
+        
+        UserApi apiInstance = new UserApi();
+        String username = username_example; // String | The name that needs to be deleted
+        try {
+            apiInstance.deleteUser(username);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling UserApi#deleteUser");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + +
+

+import .UserApi;
+
+public class UserApiExample {
+
+    public static void main(String[] args) {
+        UserApi apiInstance = new UserApi();
+        String username = username_example; // String | The name that needs to be deleted
+        try {
+            apiInstance.deleteUser(username);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling UserApi#deleteUser");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + + + +
+

+
+String *username = username_example; // The name that needs to be deleted
+
+UserApi *apiInstance = [[UserApi alloc] init];
+
+// Delete user
+[apiInstance deleteUserWith:username
+              completionHandler: ^(NSError* error) {
+                            if (error) {
+                                NSLog(@"Error: %@", error);
+                            }
+                        }];
+
+                                                    
+
+
+

+var  = require('');
+
+var api = new .UserApi()
+
+var username = username_example; // {String} The name that needs to be deleted
+
+
+var callback = function(error, data, response) {
+  if (error) {
+    console.error(error);
+  } else {
+    console.log('API called successfully.');
+  }
+};
+api.deleteUser(username, callback);
+
+                                                    
+
+ + + +
+

+using System;
+using System.Diagnostics;
+using .Api;
+using .Client;
+using ;
+
+namespace Example
+{
+    public class deleteUserExample
+    {
+        public void main()
+        {
+            
+            var apiInstance = new UserApi();
+            var username = username_example;  // String | The name that needs to be deleted
+
+            try
+            {
+                // Delete user
+                apiInstance.deleteUser(username);
+            }
+            catch (Exception e)
+            {
+                Debug.Print("Exception when calling UserApi.deleteUser: " + e.Message );
+            }
+        }
+    }
+}
+
+                                                    
+
+ + +
+

+deleteUser($username);
+} catch (Exception $e) {
+    echo 'Exception when calling UserApi->deleteUser: ', $e->getMessage(), PHP_EOL;
+}
+
+                                                  
+
+ +
+ + + + + +

Parameters

+ + + +
Path parameters
+ + + + + + + + + + +
NameDescription
username* + + + +
+
+ + + + + +

Responses

+ +

Status: 400 - Invalid username supplied

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + +

Status: 404 - User not found

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + + + + + + +
+ +
+ +
+ + + + + + + + +
+ +
+
+

getUserByName

+
+
+ +
+
+ +

+

+

+
+ +
/user/{username}
+ +

+

Usage and SDK Samples

+

+ + + +
+
+

+curl -X get "http://petstore.swagger.io/v2/user/{username}"
+
+
+
+
+ +
+

+import io.swagger.client.*;
+import io.swagger.client.auth.*;
+import io.swagger.client.model.*;
+import .UserApi;
+
+import java.io.File;
+import java.util.*;
+
+public class UserApiExample {
+
+    public static void main(String[] args) {
+        
+        UserApi apiInstance = new UserApi();
+        String username = username_example; // String | The name that needs to be fetched. Use user1 for testing. 
+        try {
+            User result = apiInstance.getUserByName(username);
+            System.out.println(result);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling UserApi#getUserByName");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + +
+

+import .UserApi;
+
+public class UserApiExample {
+
+    public static void main(String[] args) {
+        UserApi apiInstance = new UserApi();
+        String username = username_example; // String | The name that needs to be fetched. Use user1 for testing. 
+        try {
+            User result = apiInstance.getUserByName(username);
+            System.out.println(result);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling UserApi#getUserByName");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + + + +
+

+
+String *username = username_example; // The name that needs to be fetched. Use user1 for testing. 
+
+UserApi *apiInstance = [[UserApi alloc] init];
+
+// Get user by user name
+[apiInstance getUserByNameWith:username
+              completionHandler: ^(User output, NSError* error) {
+                            if (output) {
+                                NSLog(@"%@", output);
+                            }
+                            if (error) {
+                                NSLog(@"Error: %@", error);
+                            }
+                        }];
+
+                                                    
+
+
+

+var  = require('');
+
+var api = new .UserApi()
+
+var username = username_example; // {String} The name that needs to be fetched. Use user1 for testing. 
+
+
+var callback = function(error, data, response) {
+  if (error) {
+    console.error(error);
+  } else {
+    console.log('API called successfully. Returned data: ' + data);
+  }
+};
+api.getUserByName(username, callback);
+
+                                                    
+
+ + + +
+

+using System;
+using System.Diagnostics;
+using .Api;
+using .Client;
+using ;
+
+namespace Example
+{
+    public class getUserByNameExample
+    {
+        public void main()
+        {
+            
+            var apiInstance = new UserApi();
+            var username = username_example;  // String | The name that needs to be fetched. Use user1 for testing. 
+
+            try
+            {
+                // Get user by user name
+                User result = apiInstance.getUserByName(username);
+                Debug.WriteLine(result);
+            }
+            catch (Exception e)
+            {
+                Debug.Print("Exception when calling UserApi.getUserByName: " + e.Message );
+            }
+        }
+    }
+}
+
+                                                    
+
+ + +
+

+getUserByName($username);
+    print_r($result);
+} catch (Exception $e) {
+    echo 'Exception when calling UserApi->getUserByName: ', $e->getMessage(), PHP_EOL;
+}
+
+                                                  
+
+ +
+ + + + + +

Parameters

+ + + +
Path parameters
+ + + + + + + + + + +
NameDescription
username* + + + +
+
+ + + + + +

Responses

+ +

Status: 200 - successful operation

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + +

Status: 400 - Invalid username supplied

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + +

Status: 404 - User not found

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + + + + + + +
+ +
+ +
+ + + + + + + + +
+ +
+
+

loginUser

+
+
+ +
+
+ +

+

+

+
+ +
/user/login
+ +

+

Usage and SDK Samples

+

+ + + +
+
+

+curl -X get "http://petstore.swagger.io/v2/user/login?username=&password="
+
+
+
+
+ +
+

+import io.swagger.client.*;
+import io.swagger.client.auth.*;
+import io.swagger.client.model.*;
+import .UserApi;
+
+import java.io.File;
+import java.util.*;
+
+public class UserApiExample {
+
+    public static void main(String[] args) {
+        
+        UserApi apiInstance = new UserApi();
+        String username = username_example; // String | The user name for login
+        String password = password_example; // String | The password for login in clear text
+        try {
+            'String' result = apiInstance.loginUser(username, password);
+            System.out.println(result);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling UserApi#loginUser");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + +
+

+import .UserApi;
+
+public class UserApiExample {
+
+    public static void main(String[] args) {
+        UserApi apiInstance = new UserApi();
+        String username = username_example; // String | The user name for login
+        String password = password_example; // String | The password for login in clear text
+        try {
+            'String' result = apiInstance.loginUser(username, password);
+            System.out.println(result);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling UserApi#loginUser");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + + + +
+

+
+String *username = username_example; // The user name for login
+String *password = password_example; // The password for login in clear text
+
+UserApi *apiInstance = [[UserApi alloc] init];
+
+// Logs user into the system
+[apiInstance loginUserWith:username
+    password:password
+              completionHandler: ^('String' output, NSError* error) {
+                            if (output) {
+                                NSLog(@"%@", output);
+                            }
+                            if (error) {
+                                NSLog(@"Error: %@", error);
+                            }
+                        }];
+
+                                                    
+
+
+

+var  = require('');
+
+var api = new .UserApi()
+
+var username = username_example; // {String} The user name for login
+
+var password = password_example; // {String} The password for login in clear text
+
+
+var callback = function(error, data, response) {
+  if (error) {
+    console.error(error);
+  } else {
+    console.log('API called successfully. Returned data: ' + data);
+  }
+};
+api.loginUser(username, password, callback);
+
+                                                    
+
+ + + +
+

+using System;
+using System.Diagnostics;
+using .Api;
+using .Client;
+using ;
+
+namespace Example
+{
+    public class loginUserExample
+    {
+        public void main()
+        {
+            
+            var apiInstance = new UserApi();
+            var username = username_example;  // String | The user name for login
+            var password = password_example;  // String | The password for login in clear text
+
+            try
+            {
+                // Logs user into the system
+                'String' result = apiInstance.loginUser(username, password);
+                Debug.WriteLine(result);
+            }
+            catch (Exception e)
+            {
+                Debug.Print("Exception when calling UserApi.loginUser: " + e.Message );
+            }
+        }
+    }
+}
+
+                                                    
+
+ + +
+

+loginUser($username, $password);
+    print_r($result);
+} catch (Exception $e) {
+    echo 'Exception when calling UserApi->loginUser: ', $e->getMessage(), PHP_EOL;
+}
+
+                                                  
+
+ +
+ + + + + +

Parameters

+ + + + + + + +
Query parameters
+ + + + + + + + + + + + + + +
NameDescription
username* + + + +
+
password* + + + +
+
+ +

Responses

+ +

Status: 200 - successful operation

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + +

Status: 400 - Invalid username/password supplied

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + + + + + + +
+ +
+ +
+ + + + + + + + +
+ +
+
+

logoutUser

+
+
+ +
+
+ +

+

+

+
+ +
/user/logout
+ +

+

Usage and SDK Samples

+

+ + + +
+
+

+curl -X get "http://petstore.swagger.io/v2/user/logout"
+
+
+
+
+ +
+

+import io.swagger.client.*;
+import io.swagger.client.auth.*;
+import io.swagger.client.model.*;
+import .UserApi;
+
+import java.io.File;
+import java.util.*;
+
+public class UserApiExample {
+
+    public static void main(String[] args) {
+        
+        UserApi apiInstance = new UserApi();
+        try {
+            apiInstance.logoutUser();
+        } catch (ApiException e) {
+            System.err.println("Exception when calling UserApi#logoutUser");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + +
+

+import .UserApi;
+
+public class UserApiExample {
+
+    public static void main(String[] args) {
+        UserApi apiInstance = new UserApi();
+        try {
+            apiInstance.logoutUser();
+        } catch (ApiException e) {
+            System.err.println("Exception when calling UserApi#logoutUser");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + + + +
+

+
+
+UserApi *apiInstance = [[UserApi alloc] init];
+
+// Logs out current logged in user session
+[apiInstance logoutUserWithCompletionHandler: 
+              ^(NSError* error) {
+                            if (error) {
+                                NSLog(@"Error: %@", error);
+                            }
+                        }];
+
+                                                    
+
+
+

+var  = require('');
+
+var api = new .UserApi()
+
+var callback = function(error, data, response) {
+  if (error) {
+    console.error(error);
+  } else {
+    console.log('API called successfully.');
+  }
+};
+api.logoutUser(callback);
+
+                                                    
+
+ + + +
+

+using System;
+using System.Diagnostics;
+using .Api;
+using .Client;
+using ;
+
+namespace Example
+{
+    public class logoutUserExample
+    {
+        public void main()
+        {
+            
+            var apiInstance = new UserApi();
+
+            try
+            {
+                // Logs out current logged in user session
+                apiInstance.logoutUser();
+            }
+            catch (Exception e)
+            {
+                Debug.Print("Exception when calling UserApi.logoutUser: " + e.Message );
+            }
+        }
+    }
+}
+
+                                                    
+
+ + +
+

+logoutUser();
+} catch (Exception $e) {
+    echo 'Exception when calling UserApi->logoutUser: ', $e->getMessage(), PHP_EOL;
+}
+
+                                                  
+
+ +
+ + + + + +

Parameters

+ + + + + + + + +

Responses

+ +

Status: 0 - successful operation

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + + + + + + +
+ +
+ +
+ + + + + + + + +
+ +
+
+

updateUser

+
+
+ +
+
+ +

+

This can only be done by the logged in user.

+

+
+ +
/user/{username}
+ +

+

Usage and SDK Samples

+

+ + + +
+
+

+curl -X put "http://petstore.swagger.io/v2/user/{username}"
+
+
+
+
+ +
+

+import io.swagger.client.*;
+import io.swagger.client.auth.*;
+import io.swagger.client.model.*;
+import .UserApi;
+
+import java.io.File;
+import java.util.*;
+
+public class UserApiExample {
+
+    public static void main(String[] args) {
+        
+        UserApi apiInstance = new UserApi();
+        String username = username_example; // String | name that need to be deleted
+        User body = ; // User | Updated user object
+        try {
+            apiInstance.updateUser(username, body);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling UserApi#updateUser");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + +
+

+import .UserApi;
+
+public class UserApiExample {
+
+    public static void main(String[] args) {
+        UserApi apiInstance = new UserApi();
+        String username = username_example; // String | name that need to be deleted
+        User body = ; // User | Updated user object
+        try {
+            apiInstance.updateUser(username, body);
+        } catch (ApiException e) {
+            System.err.println("Exception when calling UserApi#updateUser");
+            e.printStackTrace();
+        }
+    }
+}
+
+                                                  
+
+ + + + +
+

+
+String *username = username_example; // name that need to be deleted
+User *body = ; // Updated user object
+
+UserApi *apiInstance = [[UserApi alloc] init];
+
+// Updated user
+[apiInstance updateUserWith:username
+    body:body
+              completionHandler: ^(NSError* error) {
+                            if (error) {
+                                NSLog(@"Error: %@", error);
+                            }
+                        }];
+
+                                                    
+
+
+

+var  = require('');
+
+var api = new .UserApi()
+
+var username = username_example; // {String} name that need to be deleted
+
+var body = ; // {User} Updated user object
+
+
+var callback = function(error, data, response) {
+  if (error) {
+    console.error(error);
+  } else {
+    console.log('API called successfully.');
+  }
+};
+api.updateUser(username, body, callback);
+
+                                                    
+
+ + + +
+

+using System;
+using System.Diagnostics;
+using .Api;
+using .Client;
+using ;
+
+namespace Example
+{
+    public class updateUserExample
+    {
+        public void main()
+        {
+            
+            var apiInstance = new UserApi();
+            var username = username_example;  // String | name that need to be deleted
+            var body = new User(); // User | Updated user object
+
+            try
+            {
+                // Updated user
+                apiInstance.updateUser(username, body);
+            }
+            catch (Exception e)
+            {
+                Debug.Print("Exception when calling UserApi.updateUser: " + e.Message );
+            }
+        }
+    }
+}
+
+                                                    
+
+ + +
+

+updateUser($username, $body);
+} catch (Exception $e) {
+    echo 'Exception when calling UserApi->updateUser: ', $e->getMessage(), PHP_EOL;
+}
+
+                                                  
+
+ +
+ + + + + +

Parameters

+ + + +
Path parameters
+ + + + + + + + + + +
NameDescription
username* + + + +
+
+ + + +
Body parameters
+ + + + + + + + + + + +
NameDescription
body * + + + +
+
+ + +

Responses

+ +

Status: 400 - Invalid user supplied

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + +

Status: 404 - User not found

+ + + + + + + + + +
+ + + +
+ + + + +
+ + +
+ + + + + + + +
+ + + + +
+ + + + + + + + + +
+ +
+ +
+ +
+ + + + + + +
+ + + + + + + +
+
+ Generated 2016-09-29T11:08:44.942+08:00 +
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + From 19f1c7e0955b429f0f986ac10d5e7e8bfc5d813b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dalibor=20Karlovi=C4=87?= Date: Thu, 29 Sep 2016 08:48:24 +0200 Subject: [PATCH 399/470] feature(PHP QA) add initial PHP client template tweaks to improve emitted code quality --- .../src/main/resources/php/ApiClient.mustache | 154 ++++++++++-------- .../main/resources/php/ApiException.mustache | 6 +- .../resources/php/ObjectSerializer.mustache | 6 +- .../src/main/resources/php/api.mustache | 29 ++-- .../src/main/resources/php/api_test.mustache | 7 - .../main/resources/php/configuration.mustache | 35 +++- .../src/main/resources/php/model.mustache | 1 + .../main/resources/php/model_generic.mustache | 6 +- 8 files changed, 138 insertions(+), 106 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index effdbedb7f8..bbe7d20ad92 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -31,13 +31,13 @@ namespace {{invokerPackage}}; */ class ApiClient { - public static $PATCH = "PATCH"; - public static $POST = "POST"; - public static $GET = "GET"; - public static $HEAD = "HEAD"; - public static $OPTIONS = "OPTIONS"; - public static $PUT = "PUT"; - public static $DELETE = "DELETE"; + public static $PATCH = 'PATCH'; + public static $POST = 'POST'; + public static $GET = 'GET'; + public static $HEAD = 'HEAD'; + public static $OPTIONS = 'OPTIONS'; + public static $PUT = 'PUT'; + public static $DELETE = 'DELETE'; /** * Configuration @@ -58,7 +58,7 @@ class ApiClient * * @param Configuration $config config for this ApiClient */ - public function __construct(\{{invokerPackage}}\Configuration $config = null) + public function __construct(Configuration $config = null) { if ($config === null) { $config = Configuration::getDefaultConfiguration(); @@ -91,7 +91,7 @@ class ApiClient /** * Get API key (with prefix if set) * - * @param string $apiKeyIdentifier name of apikey + * @param string $apiKeyIdentifier name of API key * * @return string API key with the prefix */ @@ -100,14 +100,13 @@ class ApiClient $prefix = $this->config->getApiKeyPrefix($apiKeyIdentifier); $apiKey = $this->config->getApiKey($apiKeyIdentifier); - if (!isset($apiKey)) { + if ($apiKey === null) { return null; } - if (isset($prefix)) { - $keyWithPrefix = $prefix." ".$apiKey; - } else { - $keyWithPrefix = $apiKey; + $keyWithPrefix = $apiKey; + if ($prefix !== null) { + $keyWithPrefix = $prefix.' '.$apiKey; } return $keyWithPrefix; @@ -116,19 +115,24 @@ class ApiClient /** * Make the HTTP call (Sync) * - * @param string $resourcePath path to method endpoint - * @param string $method method to call - * @param array $queryParams parameters to be place in query URL - * @param array $postData parameters to be placed in POST body - * @param array $headerParams parameters to be place in request header - * @param string $responseType expected response type of the endpoint - * @param string $endpointPath path to method endpoint before expanding parameters + * @param string $resourcePath path to method endpoint + * @param string $method method to call + * @param array $queryParams parameters to be place in query URL + * @param array|string $postData parameters to be placed in POST body + * @param array $headerParams parameters to be place in request header + * @param string $responseType expected response type of the endpoint * - * @throws \{{invokerPackage}}\ApiException on a non 2xx response + * @throws ApiException on a non 2xx response * @return mixed */ - public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType = null, $endpointPath = null) - { + public function callApi( + $resourcePath, + $method, + array $queryParams, + $postData, + array $headerParams, + $responseType = null + ) { $headers = []; // construct the http header @@ -142,10 +146,10 @@ class ApiClient } // form data - if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers, true)) { + if (is_array($postData) && in_array('Content-Type: application/x-www-form-urlencoded', $headers, true)) { $postData = http_build_query($postData); - } elseif ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers, true)) { // json model - $postData = json_encode(\{{invokerPackage}}\ObjectSerializer::sanitizeForSerialization($postData)); + } elseif ((is_object($postData) || is_array($postData)) && !in_array('Content-Type: multipart/form-data', $headers, true)) { // json model + $postData = json_encode(ObjectSerializer::sanitizeForSerialization($postData)); } $url = $this->config->getHost() . $resourcePath; @@ -161,12 +165,12 @@ class ApiClient curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); // disable SSL verification, if needed - if ($this->config->getSSLVerification() === false) { + if ($this->config->isSSLVerification() === false) { curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); } - if (!empty($queryParams)) { + if ($queryParams !== null) { $url = ($url . '?' . http_build_query($queryParams)); } @@ -176,16 +180,16 @@ class ApiClient } elseif ($method === self::$HEAD) { curl_setopt($curl, CURLOPT_NOBODY, true); } elseif ($method === self::$OPTIONS) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "OPTIONS"); + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'OPTIONS'); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); } elseif ($method === self::$PATCH) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH"); + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PATCH'); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); } elseif ($method === self::$PUT) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); } elseif ($method === self::$DELETE) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE'); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); } elseif ($method !== self::$GET) { throw new ApiException('Method ' . $method . ' is not recognized.'); @@ -196,8 +200,12 @@ class ApiClient curl_setopt($curl, CURLOPT_USERAGENT, $this->config->getUserAgent()); // debugging for curl - if ($this->config->getDebug()) { - error_log("[DEBUG] HTTP Request body ~BEGIN~".PHP_EOL.print_r($postData, true).PHP_EOL."~END~".PHP_EOL, 3, $this->config->getDebugFile()); + if ($this->config->isDebug()) { + error_log( + '[DEBUG] HTTP Request body ~BEGIN~'.PHP_EOL.print_r($postData, true).PHP_EOL.'~END~'.PHP_EOL, + 3, + $this->config->getDebugFile() + ); curl_setopt($curl, CURLOPT_VERBOSE, 1); curl_setopt($curl, CURLOPT_STDERR, fopen($this->config->getDebugFile(), 'a')); @@ -210,55 +218,59 @@ class ApiClient // Make the request $response = curl_exec($curl); - $http_header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); - $http_header = $this->httpParseHeaders(substr($response, 0, $http_header_size)); - $http_body = substr($response, $http_header_size); - $response_info = curl_getinfo($curl); + $httpHeaderSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE); + $httpHeader = $this->httpParseHeaders(substr($response, 0, $httpHeaderSize)); + $httpBody = substr($response, $httpHeaderSize); + $responseInfo = curl_getinfo($curl); // debug HTTP response body - if ($this->config->getDebug()) { - error_log("[DEBUG] HTTP Response body ~BEGIN~".PHP_EOL.print_r($http_body, true).PHP_EOL."~END~".PHP_EOL, 3, $this->config->getDebugFile()); + if ($this->config->isDebug()) { + error_log( + '[DEBUG] HTTP Response body ~BEGIN~'.PHP_EOL.print_r($httpBody, true).PHP_EOL.'~END~'.PHP_EOL, + 3, + $this->config->getDebugFile() + ); } // Handle the response - if ($response_info['http_code'] === 0) { - $curl_error_message = curl_error($curl); + if ($responseInfo['http_code'] === 0) { + $curlErrorMessage = curl_error($curl); // curl_exec can sometimes fail but still return a blank message from curl_error(). - if (!empty($curl_error_message)) { - $error_message = "API call to $url failed: $curl_error_message"; + if ($curlErrorMessage !== '') { + $errorMessage = 'API call to '.$url.' failed: '.$curlErrorMessage; } else { - $error_message = "API call to $url failed, but for an unknown reason. " . - "This could happen if you are disconnected from the network."; + $errorMessage = 'API call to '.$url.' failed, but for an unknown reason. ' . + 'This could happen if you are disconnected from the network.'; } - $exception = new ApiException($error_message, 0, null, null); - $exception->setResponseObject($response_info); + $exception = new ApiException($errorMessage, 0, null, null); + $exception->setResponseObject($responseInfo); throw $exception; - } elseif ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299) { + } elseif ($responseInfo['http_code'] >= 200 && $responseInfo['http_code'] <= 299) { // return raw body if response is a file if ($responseType === '\SplFileObject' || $responseType === 'string') { - return [$http_body, $response_info['http_code'], $http_header]; + return [$httpBody, $responseInfo['http_code'], $httpHeader]; } - $data = json_decode($http_body); + $data = json_decode($httpBody); if (json_last_error() > 0) { // if response is a string - $data = $http_body; + $data = $httpBody; } } else { - $data = json_decode($http_body); + $data = json_decode($httpBody); if (json_last_error() > 0) { // if response is a string - $data = $http_body; + $data = $httpBody; } throw new ApiException( - "[".$response_info['http_code']."] Error connecting to the API ($url)", - $response_info['http_code'], - $http_header, + '['.$responseInfo['http_code'].'] Error connecting to the API ('.$url.')', + $responseInfo['http_code'], + $httpHeader, $data ); } - return [$data, $response_info['http_code'], $http_header]; + return [$data, $responseInfo['http_code'], $httpHeader]; } /** @@ -270,9 +282,9 @@ class ApiClient */ public function selectHeaderAccept($accept) { - if (count($accept) === 0 or (count($accept) === 1 and $accept[0] === '')) { + if (count($accept) === 0 || (count($accept) === 1 && $accept[0] === '')) { return null; - } elseif (preg_grep("/application\/json/i", $accept)) { + } elseif (preg_grep('/application\\/json/i', $accept)) { return 'application/json'; } else { return implode(',', $accept); @@ -282,35 +294,35 @@ class ApiClient /** * Return the content type based on an array of content-type provided * - * @param string[] $content_type Array fo content-type + * @param string[] $contentType Array for Content-type * * @return string Content-Type (e.g. application/json) */ - public function selectHeaderContentType($content_type) + public function selectHeaderContentType($contentType) { - if (count($content_type) === 0 or (count($content_type) === 1 and $content_type[0] === '')) { + if (count($contentType) === 0 || (count($contentType) === 1 && $contentType[0] === '')) { return 'application/json'; - } elseif (preg_grep("/application\/json/i", $content_type)) { + } elseif (preg_grep('/application\\/json/i', $contentType)) { return 'application/json'; } else { - return implode(',', $content_type); + return implode(',', $contentType); } } /** * Return an array of HTTP response headers * - * @param string $raw_headers A string of raw HTTP response headers + * @param string $rawHeaders A string of raw HTTP response headers * - * @return string[] Array of HTTP response heaers + * @return string[] Array of HTTP response headers */ - protected function httpParseHeaders($raw_headers) + protected function httpParseHeaders($rawHeaders) { // ref/credit: http://php.net/manual/en/function.http-parse-headers.php#112986 $headers = []; $key = ''; - foreach (explode("\n", $raw_headers) as $h) { + foreach (explode("\n", $rawHeaders) as $h) { $h = explode(':', $h, 2); if (isset($h[1])) { @@ -324,7 +336,7 @@ class ApiClient $key = $h[0]; } else { - if (substr($h[0], 0, 1) === "\t") { + if (strpos($h[0], "\t") === 0) { $headers[$key] .= "\r\n\t".trim($h[0]); } elseif (!$key) { $headers[0] = trim($h[0]); diff --git a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache index f99a793fbc6..2ec9079d555 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache @@ -62,7 +62,7 @@ class ApiException extends Exception * @param string $responseHeaders HTTP response header * @param mixed $responseBody HTTP body of the server response either as Json or string */ - public function __construct($message = "", $code = 0, $responseHeaders = null, $responseBody = null) + public function __construct($message = '', $code = 0, $responseHeaders = null, $responseBody = null) { parent::__construct($message, $code); $this->responseHeaders = $responseHeaders; @@ -90,7 +90,7 @@ class ApiException extends Exception } /** - * Sets the deseralized response object (during deserialization) + * Sets the deserialized response object (during deserialization) * * @param mixed $obj Deserialized response object * @@ -102,7 +102,7 @@ class ApiException extends Exception } /** - * Gets the deseralized response object (during deserialization) + * Gets the deserialized response object (during deserialization) * * @return mixed the deserialized response object */ diff --git a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache index 7208e4c7784..5495b4f4611 100644 --- a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache @@ -213,7 +213,7 @@ class ObjectSerializer } elseif (substr($class, 0, 4) === 'map[') { // for associative array e.g. map[string,int] $inner = substr($class, 4, -1); $deserialized = []; - if (strrpos($inner, ",") !== false) { + if (strrpos($inner, ',') !== false) { $subClass_array = explode(',', $inner, 2); $subClass = $subClass_array[1]; foreach ($data as $key => $value) { @@ -254,9 +254,9 @@ class ObjectSerializer } else { $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); } - $deserialized = new \SplFileObject($filename, "w"); + $deserialized = new \SplFileObject($filename, 'w'); $byte_written = $deserialized->fwrite($data); - if (Configuration::getDefaultConfiguration()->getDebug()) { + if (Configuration::getDefaultConfiguration()->isDebug()) { error_log("[DEBUG] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file after processing.".PHP_EOL, 3, Configuration::getDefaultConfiguration()->getDebugFile()); } diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 26583a6f3d1..ef0139e23fe 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -21,8 +21,6 @@ namespace {{apiPackage}}; use \{{invokerPackage}}\ApiClient; use \{{invokerPackage}}\ApiException; -use \{{invokerPackage}}\Configuration; -use \{{invokerPackage}}\ObjectSerializer; /** * {{classname}} Class Doc Comment @@ -38,29 +36,28 @@ use \{{invokerPackage}}\ObjectSerializer; /** * API Client * - * @var \{{invokerPackage}}\ApiClient instance of the ApiClient + * @var ApiClient instance of the ApiClient */ protected $apiClient; /** * Constructor * - * @param \{{invokerPackage}}\ApiClient|null $apiClient The api client to use + * @param ApiClient|null $apiClient The API client to use */ - public function __construct(\{{invokerPackage}}\ApiClient $apiClient = null) + public function __construct(ApiClient $apiClient = null) { if ($apiClient === null) { $apiClient = new ApiClient(); $apiClient->getConfig()->setHost('{{basePath}}'); } - - $this->apiClient = $apiClient; + $this->setApiClient($apiClient); } /** * Get API client * - * @return \{{invokerPackage}}\ApiClient get the API client + * @return ApiClient get the API client */ public function getApiClient() { @@ -70,11 +67,11 @@ use \{{invokerPackage}}\ObjectSerializer; /** * Set the API client * - * @param \{{invokerPackage}}\ApiClient $apiClient set the API client + * @param ApiClient $apiClient set the API client * * @return {{classname}} */ - public function setApiClient(\{{invokerPackage}}\ApiClient $apiClient) + public function setApiClient(ApiClient $apiClient) { $this->apiClient = $apiClient; return $this; @@ -115,6 +112,7 @@ use \{{invokerPackage}}\ObjectSerializer; * @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} {{/allParams}} * @throws \{{invokerPackage}}\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return array of {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}null{{/returnType}}, HTTP status code, HTTP response headers (array of strings) */ public function {{operationId}}WithHttpInfo({{#allParams}}${{paramName}}{{^required}} = null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) @@ -166,7 +164,7 @@ use \{{invokerPackage}}\ObjectSerializer; {{/hasValidation}} {{/allParams}} // parse inputs - $resourcePath = "{{path}}"; + $resourcePath = '{{path}}'; $httpBody = ''; $queryParams = []; $headerParams = []; @@ -208,14 +206,14 @@ use \{{invokerPackage}}\ObjectSerializer; {{/collectionFormat}} if (${{paramName}} !== null) { $resourcePath = str_replace( - "{" . "{{baseName}}" . "}", + '{'.'{{baseName}}'.'}', $this->apiClient->getSerializer()->toPathValue(${{paramName}}), $resourcePath ); } {{/pathParams}} // default format to json - $resourcePath = str_replace("{format}", "json", $resourcePath); + $resourcePath = str_replace('{format}', 'json', $resourcePath); {{#formParams}} // form params @@ -277,12 +275,11 @@ use \{{invokerPackage}}\ObjectSerializer; $httpBody, $headerParams, {{#returnType}} - '{{returnType}}', + '{{returnType}}' {{/returnType}} {{^returnType}} - null, + null {{/returnType}} - '{{path}}' ); {{#returnType}} diff --git a/modules/swagger-codegen/src/main/resources/php/api_test.mustache b/modules/swagger-codegen/src/main/resources/php/api_test.mustache index 99ad7065c9b..c4a549caace 100644 --- a/modules/swagger-codegen/src/main/resources/php/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api_test.mustache @@ -19,11 +19,6 @@ namespace {{invokerPackage}}; -use \{{invokerPackage}}\Configuration; -use \{{invokerPackage}}\ApiClient; -use \{{invokerPackage}}\ApiException; -use \{{invokerPackage}}\ObjectSerializer; - /** * {{classname}}Test Class Doc Comment * @@ -35,7 +30,6 @@ use \{{invokerPackage}}\ObjectSerializer; */ {{#operations}}class {{classname}}Test extends \PHPUnit_Framework_TestCase { - /** * Setup before running any test cases */ @@ -73,7 +67,6 @@ use \{{invokerPackage}}\ObjectSerializer; * Test case for {{{operationId}}} * * {{{summary}}}. - * */ public function test{{vendorExtensions.x-testOperationId}}() { diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/configuration.mustache index bae256b3bd3..94104b781b8 100644 --- a/modules/swagger-codegen/src/main/resources/php/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/configuration.mustache @@ -31,7 +31,10 @@ namespace {{invokerPackage}}; */ class Configuration { - private static $defaultConfiguration = null; + /** + * @var Configuration + */ + private static $defaultConfiguration; /** * Associate array to store API key(s) @@ -94,7 +97,7 @@ class Configuration * * @var string */ - protected $userAgent = "{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{#artifactVersion}}{{{.}}}{{/artifactVersion}}{{^artifactVersion}}1.0.0{{/artifactVersion}}/php{{/httpUserAgent}}"; + protected $userAgent = '{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{#artifactVersion}}{{{.}}}{{/artifactVersion}}{{^artifactVersion}}1.0.0{{/artifactVersion}}/php{{/httpUserAgent}}'; /** * Debug switch (default set to false) @@ -261,6 +264,7 @@ class Configuration * @param string $headerName header name (e.g. Token) * @param string $headerValue header value (e.g. 1z8wp3) * + * @throws \InvalidArgumentException * @return Configuration */ public function addDefaultHeader($headerName, $headerValue) @@ -293,6 +297,7 @@ class Configuration public function deleteDefaultHeader($headerName) { unset($this->defaultHeaders[$headerName]); + return $this; } /** @@ -323,6 +328,7 @@ class Configuration * * @param string $userAgent the user agent of the api client * + * @throws \InvalidArgumentException * @return Configuration */ public function setUserAgent($userAgent) @@ -350,6 +356,7 @@ class Configuration * * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] * + * @throws \InvalidArgumentException * @return Configuration */ public function setCurlTimeout($seconds) @@ -390,6 +397,17 @@ class Configuration * * @return bool */ + public function isDebug() + { + return $this->debug; + } + + /** + * Gets the debug flag + * + * @return bool + * @deprecated + */ public function getDebug() { return $this->debug; @@ -459,6 +477,17 @@ class Configuration * * @return boolean True if the certificate should be validated, false otherwise */ + public function isSSLVerification() + { + return $this->sslVerification; + } + + /** + * Gets if SSL verification should be enabled or disabled + * + * @return boolean True if the certificate should be validated, false otherwise + * @deprecated + */ public function getSSLVerification() { return $this->sslVerification; @@ -479,7 +508,7 @@ class Configuration } /** - * Sets the detault configuration instance + * Sets the default configuration instance * * @param Configuration $config An instance of the Configuration Object * diff --git a/modules/swagger-codegen/src/main/resources/php/model.mustache b/modules/swagger-codegen/src/main/resources/php/model.mustache index efecdf2e596..04f178091e5 100644 --- a/modules/swagger-codegen/src/main/resources/php/model.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model.mustache @@ -23,6 +23,7 @@ namespace {{modelPackage}}; use \ArrayAccess; +use \{{invokerPackage}}\ObjectSerializer; /** * {{classname}} Class Doc Comment diff --git a/modules/swagger-codegen/src/main/resources/php/model_generic.mustache b/modules/swagger-codegen/src/main/resources/php/model_generic.mustache index 1e221b78377..3937e8d9838 100644 --- a/modules/swagger-codegen/src/main/resources/php/model_generic.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model_generic.mustache @@ -183,7 +183,7 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple * validate all the properties in the model * return true if all passed * - * @return bool True if all properteis are valid + * @return bool True if all properties are valid */ public function valid() { @@ -365,9 +365,9 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple public function __toString() { if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print - return json_encode(\{{invokerPackage}}\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); + return json_encode(ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); } - return json_encode(\{{invokerPackage}}\ObjectSerializer::sanitizeForSerialization($this)); + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); } } \ No newline at end of file From f59c28d08a26204afbc823089069522ef3004d21 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 29 Sep 2016 17:41:47 +0800 Subject: [PATCH 400/470] escape callback parameter for java(okhttp) and python --- .../languages/AbstractJavaCodegen.java | 5 + .../languages/PythonClientCodegen.java | 5 + ...ith-fake-endpoints-models-for-testing.yaml | 4 + .../client/petstore/java/jersey1/gradlew.bat | 180 +++++++++--------- .../java/io/swagger/client/api/FakeApi.java | 2 +- .../java/io/swagger/client/api/PetApi.java | 2 +- .../petstore/java/okhttp-gson/docs/FakeApi.md | 6 +- .../petstore/java/okhttp-gson/gradlew.bat | 180 +++++++++--------- .../java/io/swagger/client/api/FakeApi.java | 21 +- .../java/io/swagger/client/api/PetApi.java | 2 +- .../client/petstore/python/docs/FakeApi.md | 6 +- .../python/petstore_api/apis/fake_api.py | 6 +- 12 files changed, 223 insertions(+), 196 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java index cabd2910353..9d4d16df9d4 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java @@ -377,6 +377,11 @@ public String toVarName(String name) { @Override public String toParamName(String name) { + // to avoid conflicts with 'callback' parameter for async call + if ("callback".equals(name)) { + return "paramCallback"; + } + // should be the same as variable name return toVarName(name); } 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 568ad8165c8..f0e9814fb12 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 @@ -349,6 +349,11 @@ public String toVarName(String name) { @Override public String toParamName(String name) { + // to avoid conflicts with 'callback' parameter for async call + if ("callback".equals(name)) { + return "param_callback"; + } + // should be the same as variable name return toVarName(name); } diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml index 2eab12fc9ba..c42dc774a22 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml @@ -771,6 +771,10 @@ paths: minLength: 10 in: formData description: None + - name: callback + type: string + in: formData + description: None responses: '400': description: Invalid username supplied diff --git a/samples/client/petstore/java/jersey1/gradlew.bat b/samples/client/petstore/java/jersey1/gradlew.bat index 72d362dafd8..5f192121eb4 100644 --- a/samples/client/petstore/java/jersey1/gradlew.bat +++ b/samples/client/petstore/java/jersey1/gradlew.bat @@ -1,90 +1,90 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -set CMD_LINE_ARGS=%$ - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java index bbf7b711513..c280869cccb 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java @@ -34,8 +34,8 @@ import io.swagger.client.model.Client; import org.joda.time.LocalDate; -import java.math.BigDecimal; import org.joda.time.DateTime; +import java.math.BigDecimal; import java.util.ArrayList; diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java index 90c256ee9ce..25185b214b1 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java @@ -33,8 +33,8 @@ import io.swagger.client.Pair; import io.swagger.client.model.Pet; -import io.swagger.client.model.ModelApiResponse; import java.io.File; +import io.swagger.client.model.ModelApiResponse; import java.util.ArrayList; diff --git a/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md b/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md index 9012aff618e..29813bd9349 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md +++ b/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md @@ -54,7 +54,7 @@ No authorization required # **testEndpointParameters** -> testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password) +> testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -90,8 +90,9 @@ byte[] binary = B; // byte[] | None LocalDate date = new LocalDate(); // LocalDate | None DateTime dateTime = new DateTime(); // DateTime | None String password = "password_example"; // String | None +String paramCallback = "paramCallback_example"; // String | None try { - apiInstance.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password); + apiInstance.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); } catch (ApiException e) { System.err.println("Exception when calling FakeApi#testEndpointParameters"); e.printStackTrace(); @@ -115,6 +116,7 @@ Name | Type | Description | Notes **date** | **LocalDate**| None | [optional] **dateTime** | **DateTime**| None | [optional] **password** | **String**| None | [optional] + **paramCallback** | **String**| None | [optional] ### Return type diff --git a/samples/client/petstore/java/okhttp-gson/gradlew.bat b/samples/client/petstore/java/okhttp-gson/gradlew.bat index 72d362dafd8..5f192121eb4 100644 --- a/samples/client/petstore/java/okhttp-gson/gradlew.bat +++ b/samples/client/petstore/java/okhttp-gson/gradlew.bat @@ -1,90 +1,90 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -set CMD_LINE_ARGS=%$ - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java index dda8d66e206..975bd34004c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java @@ -40,8 +40,8 @@ import io.swagger.client.model.Client; import org.joda.time.LocalDate; -import java.math.BigDecimal; import org.joda.time.DateTime; +import java.math.BigDecimal; import java.lang.reflect.Type; import java.util.ArrayList; @@ -175,7 +175,7 @@ public void onRequestProgress(long bytesWritten, long contentLength, boolean don return call; } /* Build call for testEndpointParameters */ - private com.squareup.okhttp.Call testEndpointParametersCall(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, DateTime dateTime, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + private com.squareup.okhttp.Call testEndpointParametersCall(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, DateTime dateTime, String password, String paramCallback, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; // verify the required parameter 'number' is set @@ -233,6 +233,8 @@ private com.squareup.okhttp.Call testEndpointParametersCall(BigDecimal number, D localVarFormParams.put("dateTime", dateTime); if (password != null) localVarFormParams.put("password", password); + if (paramCallback != null) + localVarFormParams.put("callback", paramCallback); final String[] localVarAccepts = { "application/xml; charset=utf-8", "application/json; charset=utf-8" @@ -278,10 +280,11 @@ public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Ch * @param date None (optional) * @param dateTime None (optional) * @param password None (optional) + * @param paramCallback None (optional) * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ - public void testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { - testEndpointParametersWithHttpInfo(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password); + public void testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, DateTime dateTime, String password, String paramCallback) throws ApiException { + testEndpointParametersWithHttpInfo(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); } /** @@ -300,11 +303,12 @@ public void testEndpointParameters(BigDecimal number, Double _double, String pat * @param date None (optional) * @param dateTime None (optional) * @param password None (optional) + * @param paramCallback None (optional) * @return ApiResponse<Void> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ - public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { - com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, null, null); + public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, DateTime dateTime, String password, String paramCallback) throws ApiException { + com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback, null, null); return apiClient.execute(call); } @@ -324,11 +328,12 @@ public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, D * @param date None (optional) * @param dateTime None (optional) * @param password None (optional) + * @param paramCallback None (optional) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ - public com.squareup.okhttp.Call testEndpointParametersAsync(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, DateTime dateTime, String password, final ApiCallback callback) throws ApiException { + public com.squareup.okhttp.Call testEndpointParametersAsync(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, DateTime dateTime, String password, String paramCallback, final ApiCallback callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; @@ -349,7 +354,7 @@ public void onRequestProgress(long bytesWritten, long contentLength, boolean don }; } - com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, progressListener, progressRequestListener); + com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback, progressListener, progressRequestListener); apiClient.executeAsync(call, callback); return call; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java index 6c459540701..aca7f0b02b0 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java @@ -39,8 +39,8 @@ import java.io.IOException; import io.swagger.client.model.Pet; -import io.swagger.client.model.ModelApiResponse; import java.io.File; +import io.swagger.client.model.ModelApiResponse; import java.lang.reflect.Type; import java.util.ArrayList; diff --git a/samples/client/petstore/python/docs/FakeApi.md b/samples/client/petstore/python/docs/FakeApi.md index bdece55c7a3..c6ed3ccfbfc 100644 --- a/samples/client/petstore/python/docs/FakeApi.md +++ b/samples/client/petstore/python/docs/FakeApi.md @@ -56,7 +56,7 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **test_endpoint_parameters** -> test_endpoint_parameters(number, double, pattern_without_delimiter, byte, integer=integer, int32=int32, int64=int64, float=float, string=string, binary=binary, date=date, date_time=date_time, password=password) +> test_endpoint_parameters(number, double, pattern_without_delimiter, byte, integer=integer, int32=int32, int64=int64, float=float, string=string, binary=binary, date=date, date_time=date_time, password=password, param_callback=param_callback) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -89,10 +89,11 @@ binary = 'B' # str | None (optional) date = '2013-10-20' # date | None (optional) date_time = '2013-10-20T19:20:30+01:00' # datetime | None (optional) password = 'password_example' # str | None (optional) +param_callback = 'param_callback_example' # str | None (optional) try: # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - api_instance.test_endpoint_parameters(number, double, pattern_without_delimiter, byte, integer=integer, int32=int32, int64=int64, float=float, string=string, binary=binary, date=date, date_time=date_time, password=password) + api_instance.test_endpoint_parameters(number, double, pattern_without_delimiter, byte, integer=integer, int32=int32, int64=int64, float=float, string=string, binary=binary, date=date, date_time=date_time, password=password, param_callback=param_callback) except ApiException as e: print("Exception when calling FakeApi->test_endpoint_parameters: %s\n" % e) ``` @@ -114,6 +115,7 @@ Name | Type | Description | Notes **date** | **date**| None | [optional] **date_time** | **datetime**| None | [optional] **password** | **str**| None | [optional] + **param_callback** | **str**| None | [optional] ### Return type diff --git a/samples/client/petstore/python/petstore_api/apis/fake_api.py b/samples/client/petstore/python/petstore_api/apis/fake_api.py index dd8873cc0f9..944396a9fdc 100644 --- a/samples/client/petstore/python/petstore_api/apis/fake_api.py +++ b/samples/client/petstore/python/petstore_api/apis/fake_api.py @@ -187,6 +187,7 @@ def test_endpoint_parameters(self, number, double, pattern_without_delimiter, by :param date date: None :param datetime date_time: None :param str password: None + :param str param_callback: None :return: None If the method is called asynchronously, returns the request thread. @@ -226,12 +227,13 @@ def test_endpoint_parameters_with_http_info(self, number, double, pattern_withou :param date date: None :param datetime date_time: None :param str password: None + :param str param_callback: None :return: None If the method is called asynchronously, returns the request thread. """ - all_params = ['number', 'double', 'pattern_without_delimiter', 'byte', 'integer', 'int32', 'int64', 'float', 'string', 'binary', 'date', 'date_time', 'password'] + all_params = ['number', 'double', 'pattern_without_delimiter', 'byte', 'integer', 'int32', 'int64', 'float', 'string', 'binary', 'date', 'date_time', 'password', 'param_callback'] all_params.append('callback') all_params.append('_return_http_data_only') @@ -321,6 +323,8 @@ def test_endpoint_parameters_with_http_info(self, number, double, pattern_withou form_params.append(('dateTime', params['date_time'])) if 'password' in params: form_params.append(('password', params['password'])) + if 'param_callback' in params: + form_params.append(('callback', params['param_callback'])) body_params = None From 07df71e9596c3a77c5e1f9d008f84cf1c24a92ad Mon Sep 17 00:00:00 2001 From: Alex Nolasco Date: Thu, 29 Sep 2016 09:28:44 -0400 Subject: [PATCH 401/470] Issue#3829. Objective-C client code, discriminator generated in both base and child. --- .../java/io/swagger/codegen/languages/ObjcClientCodegen.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 46732703c34..c80cc129b62 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 @@ -46,7 +46,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { public ObjcClientCodegen() { super(); - + supportsInheritance = true; outputFolder = "generated-code" + File.separator + "objc"; modelTemplateFiles.put("model-header.mustache", ".h"); modelTemplateFiles.put("model-body.mustache", ".m"); From b2e2643fd2f18386520b39179f8a6b3defaeabb2 Mon Sep 17 00:00:00 2001 From: Scott Richter Date: Thu, 29 Sep 2016 22:31:24 -0400 Subject: [PATCH 402/470] [Cpprest] Fixing issue #3773 (#3876) * Fixed errors with cpprest client generation when generating a client that uses arrays of primitive types (vector) and file responses (HttpContent). * Updated the petstore sample using script. * Removed debug code. * Removed extra newline to match master. * Fixed binary file handling in cpprest. Updated petstore samples. * Update readme to add Cummins to list * Cleaning up for pull. Removing unnecessary changes. * Fixing petstore * Fixing error in build. * Fixed error in stream copy for binary data * Replaced tab with 4 spaces in all modified files. Replaced tab with 4 spaces in all modified files. --- README.md | 1 + .../languages/CppRestClientCodegen.java | 9 +- .../resources/cpprest/api-source.mustache | 47 ++++-- .../cpprest/httpcontent-header.mustache | 4 +- .../resources/cpprest/model-source.mustache | 66 ++++----- samples/client/petstore/cpprest/ApiClient.cpp | 4 +- samples/client/petstore/cpprest/ApiClient.h | 4 +- .../petstore/cpprest/ApiConfiguration.cpp | 4 +- .../petstore/cpprest/ApiConfiguration.h | 4 +- .../client/petstore/cpprest/ApiException.cpp | 4 +- .../client/petstore/cpprest/ApiException.h | 4 +- .../client/petstore/cpprest/HttpContent.cpp | 4 +- samples/client/petstore/cpprest/HttpContent.h | 6 +- samples/client/petstore/cpprest/IHttpBody.h | 4 +- samples/client/petstore/cpprest/JsonBody.cpp | 4 +- samples/client/petstore/cpprest/JsonBody.h | 4 +- samples/client/petstore/cpprest/ModelBase.cpp | 4 +- samples/client/petstore/cpprest/ModelBase.h | 6 +- .../petstore/cpprest/MultipartFormData.cpp | 4 +- .../petstore/cpprest/MultipartFormData.h | 4 +- .../client/petstore/cpprest/api/PetApi.cpp | 137 +++++++----------- samples/client/petstore/cpprest/api/PetApi.h | 21 ++- .../client/petstore/cpprest/api/StoreApi.cpp | 57 ++++---- .../client/petstore/cpprest/api/StoreApi.h | 8 +- .../client/petstore/cpprest/api/UserApi.cpp | 112 +++++++------- samples/client/petstore/cpprest/api/UserApi.h | 14 +- .../petstore/cpprest/model/Category.cpp | 6 +- .../client/petstore/cpprest/model/Category.h | 4 +- .../client/petstore/cpprest/model/Order.cpp | 8 +- samples/client/petstore/cpprest/model/Order.h | 4 +- samples/client/petstore/cpprest/model/Pet.cpp | 6 +- samples/client/petstore/cpprest/model/Pet.h | 8 +- samples/client/petstore/cpprest/model/Tag.cpp | 6 +- samples/client/petstore/cpprest/model/Tag.h | 4 +- .../client/petstore/cpprest/model/User.cpp | 6 +- samples/client/petstore/cpprest/model/User.h | 4 +- 36 files changed, 289 insertions(+), 307 deletions(-) diff --git a/README.md b/README.md index c5f769ccbbc..f75aa258941 100644 --- a/README.md +++ b/README.md @@ -753,6 +753,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [Cachet Financial](http://www.cachetfinancial.com/) - [CloudBoost](https://www.CloudBoost.io/) - [Conplement](http://www.conplement.de/) +- [Cummins] (http://www.cummins.com/) - [Cupix](http://www.cupix.com) - [DBBest Technologies](https://www.dbbest.com) - [DecentFoX](http://decentfox.com/) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CppRestClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CppRestClientCodegen.java index c6715b22fb2..4c7cc7c1f0b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CppRestClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CppRestClientCodegen.java @@ -217,6 +217,10 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation if (methodResponse.getSchema() != null) { CodegenProperty cm = fromProperty("response", methodResponse.getSchema()); op.vendorExtensions.put("x-codegen-response", cm); + if(cm.datatype == "HttpContent") + { + op.vendorExtensions.put("x-codegen-response-ishttpcontent", true); + } } } } @@ -267,7 +271,8 @@ public String getTypeDeclaration(Property p) { Property inner = mp.getAdditionalProperties(); return getSwaggerType(p) + ""; } - if (p instanceof StringProperty || p instanceof DateProperty || p instanceof DateTimeProperty + if (p instanceof StringProperty || p instanceof DateProperty + || p instanceof DateTimeProperty || p instanceof FileProperty || languageSpecificPrimitives.contains(swaggerType)) { return toModelName(swaggerType); } @@ -289,7 +294,7 @@ public String toDefaultValue(Property p) { return "0.0"; } else if (p instanceof FloatProperty) { return "0.0f"; - } else if (p instanceof IntegerProperty) { + } else if (p instanceof IntegerProperty || p instanceof BaseIntegerProperty) { return "0"; } else if (p instanceof LongProperty) { return "0L"; diff --git a/modules/swagger-codegen/src/main/resources/cpprest/api-source.mustache b/modules/swagger-codegen/src/main/resources/cpprest/api-source.mustache index b6312e37a7f..21c5eff5553 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/api-source.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/api-source.mustache @@ -62,10 +62,19 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r { responseHttpContentType = U("multipart/form-data"); } + {{#vendorExtensions.x-codegen-response-ishttpcontent}} + else + { + //It's going to be binary, so just use the first one. + responseHttpContentType = *responseHttpContentTypes.begin(); + } + {{/vendorExtensions.x-codegen-response-ishttpcontent}} + {{^vendorExtensions.x-codegen-response-ishttpcontent}} else { throw ApiException(400, U("{{classname}}->{{operationId}} does not produce any supported media type")); } + {{/vendorExtensions.x-codegen-response-ishttpcontent}} headerParams[U("Accept")] = responseHttpContentType; @@ -189,17 +198,17 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r return m_ApiClient->callApi(path, U("{{httpMethod}}"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { - // 1xx - informational : OK - // 2xx - successful : OK - // 3xx - redirection : OK - // 4xx - client error : not OK - // 5xx - client error : not OK - if (response.status_code() >= 400) - { - throw ApiException(response.status_code() - , U("error calling {{operationId}}: ") + response.reason_phrase() - , std::make_shared(response.extract_utf8string(true).get())); - } + // 1xx - informational : OK + // 2xx - successful : OK + // 3xx - redirection : OK + // 4xx - client error : not OK + // 5xx - client error : not OK + if (response.status_code() >= 400) + { + throw ApiException(response.status_code() + , U("error calling {{operationId}}: ") + response.reason_phrase() + , std::make_shared(response.extract_utf8string(true).get())); + } // check response content type if(response.headers().has(U("Content-Type"))) @@ -213,6 +222,17 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r } } + {{#vendorExtensions.x-codegen-response-ishttpcontent}} + return response.extract_vector(); + }) + .then([=](std::vector response) + { + HttpContent result; + std::shared_ptr stream = std::make_shared(std::string(response.begin(), response.end())); + result.setData(stream); + return result; + {{/vendorExtensions.x-codegen-response-ishttpcontent}} + {{^vendorExtensions.x-codegen-response-ishttpcontent}} return response.extract_string(); }) .then([=](utility::string_t response) @@ -253,12 +273,13 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r // } else { - throw ApiException(500 - , U("error calling findPetsByStatus: unsupported response type")); + throw ApiException(500 + , U("error calling findPetsByStatus: unsupported response type")); } return result; {{/returnType}} + {{/vendorExtensions.x-codegen-response-ishttpcontent}} }); } {{/operation}} diff --git a/modules/swagger-codegen/src/main/resources/cpprest/httpcontent-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/httpcontent-header.mustache index e79f575061f..27f53b8e0c1 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/httpcontent-header.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/httpcontent-header.mustache @@ -40,9 +40,9 @@ public: virtual void setData( std::shared_ptr value ); virtual void writeTo( std::ostream& stream ); - + protected: - // NOTE: no utility::string_t here because those strings can only contain ascii + // NOTE: no utility::string_t here because those strings can only contain ascii utility::string_t m_ContentDisposition; utility::string_t m_Name; utility::string_t m_FileName; diff --git a/modules/swagger-codegen/src/main/resources/cpprest/model-source.mustache b/modules/swagger-codegen/src/main/resources/cpprest/model-source.mustache index a1985735d4a..26970c20d8d 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/model-source.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/model-source.mustache @@ -29,12 +29,12 @@ web::json::value {{classname}}::toJson() const { web::json::value val = web::json::value::object(); - {{#vars}}{{#isPrimitiveType}}{{^required}}if(m_{{name}}IsSet) + {{#vars}}{{#isPrimitiveType}}{{^isListContainer}}{{^required}}if(m_{{name}}IsSet) { val[U("{{baseName}}")] = ModelBase::toJson(m_{{name}}); } {{/required}}{{#required}}val[U("{{baseName}}")] = ModelBase::toJson(m_{{name}}); - {{/required}}{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isListContainer}}{ + {{/required}}{{/isListContainer}}{{/isPrimitiveType}}{{#isListContainer}}{ std::vector jsonArray; for( auto& item : m_{{name}} ) { @@ -48,24 +48,24 @@ web::json::value {{classname}}::toJson() const } {{/required}} } - {{/isListContainer}}{{^isListContainer}}{{^required}}if(m_{{name}}IsSet) + {{/isListContainer}}{{^isListContainer}}{{^isPrimitiveType}}{{^required}}if(m_{{name}}IsSet) { val[U("{{baseName}}")] = ModelBase::toJson(m_{{name}}); } {{/required}}{{#required}}val[U("{{baseName}}")] = ModelBase::toJson(m_{{name}}); - {{/required}}{{/isListContainer}}{{/isPrimitiveType}}{{/vars}} + {{/required}}{{/isPrimitiveType}}{{/isListContainer}}{{/vars}} return val; } void {{classname}}::fromJson(web::json::value& val) { - {{#vars}}{{#isPrimitiveType}}{{^required}}if(val.has_field(U("{{baseName}}"))) + {{#vars}}{{#isPrimitiveType}}{{^isListContainer}}{{^required}}if(val.has_field(U("{{baseName}}"))) { {{setter}}(ModelBase::{{baseType}}FromJson(val[U("{{baseName}}")])); } {{/required}}{{#required}}{{setter}}(ModelBase::{{baseType}}FromJson(val[U("{{baseName}}")])); - {{/required}}{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isListContainer}}{ + {{/required}}{{/isListContainer}}{{/isPrimitiveType}}{{#isListContainer}}{ m_{{name}}.clear(); std::vector jsonArray; {{^required}}if(val.has_field(U("{{baseName}}"))) @@ -73,8 +73,8 @@ void {{classname}}::fromJson(web::json::value& val) {{/required}} for( auto& item : val[U("{{baseName}}")].as_array() ) { - {{#items.isPrimitiveType}}m_{{name}}.push_back(ModelBase::{{baseType}}FromJson(item)); - {{/items.isPrimitiveType}}{{^items.isPrimitiveType}}{{#items.isString}}m_{{name}}.push_back(ModelBase::stringFromJson(item)); + {{#isPrimitiveType}}m_{{name}}.push_back(ModelBase::{{items.baseType}}FromJson(item)); + {{/isPrimitiveType}}{{^isPrimitiveType}}{{#items.isString}}m_{{name}}.push_back(ModelBase::stringFromJson(item)); {{/items.isString}}{{^items.isString}}{{#items.isDateTime}}m_{{name}}.push_back(ModelBase::dateFromJson(item)); {{/items.isDateTime}}{{^items.isDateTime}} if(item.is_null()) @@ -87,13 +87,13 @@ void {{classname}}::fromJson(web::json::value& val) newItem->fromJson(item); m_{{name}}.push_back( newItem ); } - {{/items.isDateTime}}{{/items.isString}}{{/items.isPrimitiveType}} + {{/items.isDateTime}}{{/items.isString}}{{/isPrimitiveType}} } {{^required}} } {{/required}} } - {{/isListContainer}}{{^isListContainer}}{{^required}}if(val.has_field(U("{{baseName}}"))) + {{/isListContainer}}{{^isListContainer}}{{^isPrimitiveType}}{{^required}}if(val.has_field(U("{{baseName}}"))) { {{#isString}}{{setter}}(ModelBase::stringFromJson(val[U("{{baseName}}")])); {{/isString}}{{^isString}}{{#isDateTime}}{{setter}}(ModelBase::dateFromJson(val[U("{{baseName}}")])); @@ -111,23 +111,23 @@ void {{classname}}::fromJson(web::json::value& val) {{/vendorExtensions.x-codegen-file}}{{^vendorExtensions.x-codegen-file}}{{{datatype}}} new{{name}}({{{defaultValue}}}); new{{name}}->fromJson(val[U("{{baseName}}")]); {{setter}}( newItem ); - {{/vendorExtensions.x-codegen-file}}{{/isDateTime}}{{/isString}}{{/required}}{{/isListContainer}}{{/isPrimitiveType}}{{/vars}} + {{/vendorExtensions.x-codegen-file}}{{/isDateTime}}{{/isString}}{{/required}}{{/isPrimitiveType}}{{/isListContainer}}{{/vars}} } void {{classname}}::toMultipart(std::shared_ptr multipart, const utility::string_t& prefix) const { utility::string_t namePrefix = prefix; - if(namePrefix.size() > 0 && namePrefix[namePrefix.size() - 1] != U('.')) - { - namePrefix += U("."); - } + if(namePrefix.size() > 0 && namePrefix[namePrefix.size() - 1] != U('.')) + { + namePrefix += U("."); + } - {{#vars}}{{#isPrimitiveType}}{{^required}}if(m_{{name}}IsSet) + {{#vars}}{{#isPrimitiveType}}{{^isListContainer}}{{^required}}if(m_{{name}}IsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}})); } {{/required}}{{#required}}multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}})); - {{/required}}{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isListContainer}}{ + {{/required}}{{/isListContainer}}{{/isPrimitiveType}}{{#isListContainer}}{ std::vector jsonArray; for( auto& item : m_{{name}} ) { @@ -141,7 +141,7 @@ void {{classname}}::toMultipart(std::shared_ptr multipart, co } {{/required}} } - {{/isListContainer}}{{^isListContainer}}{{^required}}if(m_{{name}}IsSet) + {{/isListContainer}}{{^isListContainer}}{{^isPrimitiveType}}{{^required}}if(m_{{name}}IsSet) { {{#isString}}multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}})); {{/isString}}{{^isString}}{{#isDateTime}}multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}})); @@ -155,23 +155,23 @@ void {{classname}}::toMultipart(std::shared_ptr multipart, co {{/isString}}{{^isString}}{{#isDateTime}}multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}})); {{/isDateTime}}{{^isDateTime}}{{#vendorExtensions.x-codegen-file}}multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}})); {{/vendorExtensions.x-codegen-file}}{{^vendorExtensions.x-codegen-file}}m_{{name}}->toMultipart(multipart, U("{{baseName}}.")); - {{/vendorExtensions.x-codegen-file}}{{/isDateTime}}{{/isString}}{{/required}}{{/isListContainer}}{{/isPrimitiveType}}{{/vars}} + {{/vendorExtensions.x-codegen-file}}{{/isDateTime}}{{/isString}}{{/required}}{{/isPrimitiveType}}{{/isListContainer}}{{/vars}} } void {{classname}}::fromMultiPart(std::shared_ptr multipart, const utility::string_t& prefix) { utility::string_t namePrefix = prefix; - if(namePrefix.size() > 0 && namePrefix[namePrefix.size() - 1] != U('.')) - { - namePrefix += U("."); - } + if(namePrefix.size() > 0 && namePrefix[namePrefix.size() - 1] != U('.')) + { + namePrefix += U("."); + } - {{#vars}}{{#isPrimitiveType}}{{^required}}if(multipart->hasContent(U("{{baseName}}"))) + {{#vars}}{{#isPrimitiveType}}{{^isListContainer}}{{^required}}if(multipart->hasContent(U("{{baseName}}"))) { {{setter}}(ModelBase::{{baseType}}FromHttpContent(multipart->getContent(U("{{baseName}}")))); } {{/required}}{{#required}}{{setter}}(ModelBase::{{baseType}}FromHttpContent(multipart->getContent(U("{{baseName}}")))); - {{/required}}{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isListContainer}}{ + {{/required}}{{/isListContainer}}{{/isPrimitiveType}}{{#isListContainer}}{ m_{{name}}.clear(); {{^required}}if(multipart->hasContent(U("{{baseName}}"))) { @@ -180,8 +180,8 @@ void {{classname}}::fromMultiPart(std::shared_ptr multipart, web::json::value jsonArray = web::json::value::parse(ModelBase::stringFromHttpContent(multipart->getContent(U("{{baseName}}")))); for( auto& item : jsonArray.as_array() ) { - {{#items.isPrimitiveType}}m_{{name}}.push_back(ModelBase::{{baseType}}FromJson(item)); - {{/items.isPrimitiveType}}{{^items.isPrimitiveType}}{{#items.isString}}m_{{name}}.push_back(ModelBase::stringFromJson(item)); + {{#isPrimitiveType}}m_{{name}}.push_back(ModelBase::{{items.baseType}}FromJson(item)); + {{/isPrimitiveType}}{{^isPrimitiveType}}{{#items.isString}}m_{{name}}.push_back(ModelBase::stringFromJson(item)); {{/items.isString}}{{^items.isString}}{{#items.isDateTime}}m_{{name}}.push_back(ModelBase::dateFromJson(item)); {{/items.isDateTime}}{{^items.isDateTime}} if(item.is_null()) @@ -194,13 +194,13 @@ void {{classname}}::fromMultiPart(std::shared_ptr multipart, newItem->fromJson(item); m_{{name}}.push_back( newItem ); } - {{/items.isDateTime}}{{/items.isString}}{{/items.isPrimitiveType}} + {{/items.isDateTime}}{{/items.isString}}{{/isPrimitiveType}} } {{^required}} } {{/required}} } - {{/isListContainer}}{{^isListContainer}}{{^required}}if(multipart->hasContent(U("{{baseName}}"))) + {{/isListContainer}}{{^isListContainer}}{{^isPrimitiveType}}{{^required}}if(multipart->hasContent(U("{{baseName}}"))) { {{#isString}}{{setter}}(ModelBase::stringFromHttpContent(multipart->getContent(U("{{baseName}}")))); {{/isString}}{{^isString}}{{#isDateTime}}{{setter}}(ModelBase::dateFromHttpContent(multipart->getContent(U("{{baseName}}")))); @@ -218,21 +218,21 @@ void {{classname}}::fromMultiPart(std::shared_ptr multipart, {{/vendorExtensions.x-codegen-file}}{{^vendorExtensions.x-codegen-file}}{{{datatype}}} new{{name}}({{{defaultValue}}}); new{{name}}->fromMultiPart(multipart, U("{{baseName}}.")); {{setter}}( new{{name}} ); - {{/vendorExtensions.x-codegen-file}}{{/isDateTime}}{{/isString}}{{/required}}{{/isListContainer}}{{/isPrimitiveType}}{{/vars}} + {{/vendorExtensions.x-codegen-file}}{{/isDateTime}}{{/isString}}{{/required}}{{/isPrimitiveType}}{{/isListContainer}}{{/vars}} } {{#vars}}{{^isNotContainer}}{{{datatype}}}& {{classname}}::{{getter}}() { - return m_{{name}}; + return m_{{name}}; } {{/isNotContainer}}{{#isNotContainer}}{{{datatype}}} {{classname}}::{{getter}}() const { - return m_{{name}}; + return m_{{name}}; } void {{classname}}::{{setter}}({{{datatype}}} value) { - m_{{name}} = value; + m_{{name}} = value; {{^required}}m_{{name}}IsSet = true;{{/required}} } {{/isNotContainer}} diff --git a/samples/client/petstore/cpprest/ApiClient.cpp b/samples/client/petstore/cpprest/ApiClient.cpp index 0fb3bc20301..b20eaf976b9 100644 --- a/samples/client/petstore/cpprest/ApiClient.cpp +++ b/samples/client/petstore/cpprest/ApiClient.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/ApiClient.h b/samples/client/petstore/cpprest/ApiClient.h index 54b0158eeb5..16e5ca125ae 100644 --- a/samples/client/petstore/cpprest/ApiClient.h +++ b/samples/client/petstore/cpprest/ApiClient.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/ApiConfiguration.cpp b/samples/client/petstore/cpprest/ApiConfiguration.cpp index 61bf1a5e16d..e85f43d848f 100644 --- a/samples/client/petstore/cpprest/ApiConfiguration.cpp +++ b/samples/client/petstore/cpprest/ApiConfiguration.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/ApiConfiguration.h b/samples/client/petstore/cpprest/ApiConfiguration.h index e9742d155fd..67cd2bf0178 100644 --- a/samples/client/petstore/cpprest/ApiConfiguration.h +++ b/samples/client/petstore/cpprest/ApiConfiguration.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/ApiException.cpp b/samples/client/petstore/cpprest/ApiException.cpp index 01ba891769e..8df3ce12400 100644 --- a/samples/client/petstore/cpprest/ApiException.cpp +++ b/samples/client/petstore/cpprest/ApiException.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/ApiException.h b/samples/client/petstore/cpprest/ApiException.h index beb2b5ea7e5..ef17912974d 100644 --- a/samples/client/petstore/cpprest/ApiException.h +++ b/samples/client/petstore/cpprest/ApiException.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/HttpContent.cpp b/samples/client/petstore/cpprest/HttpContent.cpp index a7a9b83aa59..2079be25aa4 100644 --- a/samples/client/petstore/cpprest/HttpContent.cpp +++ b/samples/client/petstore/cpprest/HttpContent.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/HttpContent.h b/samples/client/petstore/cpprest/HttpContent.h index 5db04412bd2..72545bf8ba5 100644 --- a/samples/client/petstore/cpprest/HttpContent.h +++ b/samples/client/petstore/cpprest/HttpContent.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -64,7 +64,7 @@ class HttpContent virtual void setData( std::shared_ptr value ); virtual void writeTo( std::ostream& stream ); - + protected: // NOTE: no utility::string_t here because those strings can only contain ascii utility::string_t m_ContentDisposition; diff --git a/samples/client/petstore/cpprest/IHttpBody.h b/samples/client/petstore/cpprest/IHttpBody.h index 365109f3dab..80090afee4a 100644 --- a/samples/client/petstore/cpprest/IHttpBody.h +++ b/samples/client/petstore/cpprest/IHttpBody.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/JsonBody.cpp b/samples/client/petstore/cpprest/JsonBody.cpp index f152a1e98ed..349bd6bfb1e 100644 --- a/samples/client/petstore/cpprest/JsonBody.cpp +++ b/samples/client/petstore/cpprest/JsonBody.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/JsonBody.h b/samples/client/petstore/cpprest/JsonBody.h index 7b139826e21..382004f6db5 100644 --- a/samples/client/petstore/cpprest/JsonBody.h +++ b/samples/client/petstore/cpprest/JsonBody.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/ModelBase.cpp b/samples/client/petstore/cpprest/ModelBase.cpp index 566d82657bf..c8b64e27ea1 100644 --- a/samples/client/petstore/cpprest/ModelBase.cpp +++ b/samples/client/petstore/cpprest/ModelBase.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/ModelBase.h b/samples/client/petstore/cpprest/ModelBase.h index 8386a4ac97b..8514ec1ba8a 100644 --- a/samples/client/petstore/cpprest/ModelBase.h +++ b/samples/client/petstore/cpprest/ModelBase.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -64,7 +64,7 @@ class ModelBase static web::json::value toJson( int32_t value ); static web::json::value toJson( int64_t value ); static web::json::value toJson( double value ); - + static int64_t int64_tFromJson(web::json::value& val); static int32_t int32_tFromJson(web::json::value& val); static utility::string_t stringFromJson(web::json::value& val); diff --git a/samples/client/petstore/cpprest/MultipartFormData.cpp b/samples/client/petstore/cpprest/MultipartFormData.cpp index 9fffdf22b02..ca4ca814ff5 100644 --- a/samples/client/petstore/cpprest/MultipartFormData.cpp +++ b/samples/client/petstore/cpprest/MultipartFormData.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/MultipartFormData.h b/samples/client/petstore/cpprest/MultipartFormData.h index 8fcd71ed011..01c1e7c0e8a 100644 --- a/samples/client/petstore/cpprest/MultipartFormData.h +++ b/samples/client/petstore/cpprest/MultipartFormData.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/api/PetApi.cpp b/samples/client/petstore/cpprest/api/PetApi.cpp index e573b9a08a6..9da8a514ef7 100644 --- a/samples/client/petstore/cpprest/api/PetApi.cpp +++ b/samples/client/petstore/cpprest/api/PetApi.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -51,12 +51,6 @@ PetApi::~PetApi() pplx::task PetApi::addPet(std::shared_ptr body) { - // verify the required parameter 'body' is set - if (body == nullptr) - { - throw ApiException(400, U("Missing required parameter 'body' when calling PetApi->addPet")); - } - std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/pet"); @@ -67,8 +61,8 @@ pplx::task PetApi::addPet(std::shared_ptr body) std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -82,7 +76,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("PetApi->addPet does not produce any supported media type")); } @@ -150,7 +144,7 @@ consumeHttpContentTypes.insert( U("application/xml") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -161,8 +155,8 @@ consumeHttpContentTypes.insert( U("application/xml") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { @@ -183,8 +177,8 @@ pplx::task PetApi::deletePet(int64_t petId, utility::string_t apiKey) std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -198,7 +192,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("PetApi->deletePet does not produce any supported media type")); } @@ -256,7 +250,7 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -267,8 +261,8 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { @@ -288,8 +282,8 @@ pplx::task>> PetApi::findPetsByStatus(std::vect std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -303,7 +297,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("PetApi->findPetsByStatus does not produce any supported media type")); } @@ -357,7 +351,7 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -368,8 +362,8 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { @@ -415,8 +409,8 @@ pplx::task>> PetApi::findPetsByTags(std::vector std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -430,7 +424,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("PetApi->findPetsByTags does not produce any supported media type")); } @@ -484,7 +478,7 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -495,8 +489,8 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { @@ -543,8 +537,8 @@ pplx::task> PetApi::getPetById(int64_t petId) std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -558,7 +552,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("PetApi->getPetById does not produce any supported media type")); } @@ -593,6 +587,8 @@ responseHttpContentTypes.insert( U("application/json") ); throw ApiException(415, U("PetApi->getPetById does not consume any supported media type")); } + // authentication (petstore_auth) required + // oauth2 authentication is added automatically as part of the http_client_config // authentication (api_key) required { utility::string_t apiKey = apiConfiguration->getApiKey(U("api_key")); @@ -617,7 +613,7 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -628,8 +624,8 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { @@ -657,12 +653,6 @@ responseHttpContentTypes.insert( U("application/json") ); pplx::task PetApi::updatePet(std::shared_ptr body) { - // verify the required parameter 'body' is set - if (body == nullptr) - { - throw ApiException(400, U("Missing required parameter 'body' when calling PetApi->updatePet")); - } - std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/pet"); @@ -673,8 +663,8 @@ pplx::task PetApi::updatePet(std::shared_ptr body) std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -688,7 +678,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("PetApi->updatePet does not produce any supported media type")); } @@ -756,7 +746,7 @@ consumeHttpContentTypes.insert( U("application/xml") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -767,15 +757,15 @@ consumeHttpContentTypes.insert( U("application/xml") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { return void(); }); } -pplx::task PetApi::updatePetWithForm(int64_t petId, utility::string_t name, utility::string_t status) +pplx::task PetApi::updatePetWithForm(utility::string_t petId, utility::string_t name, utility::string_t status) { @@ -789,8 +779,8 @@ pplx::task PetApi::updatePetWithForm(int64_t petId, utility::string_t name std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -804,7 +794,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("PetApi->updatePetWithForm does not produce any supported media type")); } @@ -868,7 +858,7 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -879,15 +869,15 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { return void(); }); } -pplx::task> PetApi::uploadFile(int64_t petId, utility::string_t additionalMetadata, std::shared_ptr file) +pplx::task PetApi::uploadFile(int64_t petId, utility::string_t additionalMetadata, std::shared_ptr file) { @@ -902,6 +892,7 @@ pplx::task> PetApi::uploadFile(int64_t petId, utili std::unordered_set responseHttpContentTypes; responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -915,7 +906,7 @@ pplx::task> PetApi::uploadFile(int64_t petId, utili { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("PetApi->uploadFile does not produce any supported media type")); } @@ -979,7 +970,7 @@ pplx::task> PetApi::uploadFile(int64_t petId, utili , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -990,31 +981,13 @@ pplx::task> PetApi::uploadFile(int64_t petId, utili , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { - std::shared_ptr result(new ApiResponse()); - - if(responseHttpContentType == U("application/json")) - { - web::json::value json = web::json::value::parse(response); - - result->fromJson(json); - } - // else if(responseHttpContentType == U("multipart/form-data")) - // { - // TODO multipart response parsing - // } - else - { - throw ApiException(500 - , U("error calling findPetsByStatus: unsupported response type")); - } - - return result; - }); + return void(); + }); } } diff --git a/samples/client/petstore/cpprest/api/PetApi.h b/samples/client/petstore/cpprest/api/PetApi.h index 0ee2bf64fe3..e3d1b40a3a8 100644 --- a/samples/client/petstore/cpprest/api/PetApi.h +++ b/samples/client/petstore/cpprest/api/PetApi.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -36,7 +36,6 @@ #include "Pet.h" #include -#include "ApiResponse.h" #include "HttpContent.h" namespace io { @@ -57,7 +56,7 @@ class PetApi /// /// /// - /// Pet object that needs to be added to the store + /// Pet object that needs to be added to the store (optional) pplx::task addPet(std::shared_ptr body); /// /// Deletes a pet @@ -73,7 +72,7 @@ class PetApi /// /// Multiple status values can be provided with comma separated strings /// - /// Status values that need to be considered for filter + /// Status values that need to be considered for filter (optional, default to available) pplx::task>> findPetsByStatus(std::vector status); /// /// Finds Pets by tags @@ -81,15 +80,15 @@ class PetApi /// /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. /// - /// Tags to filter by + /// Tags to filter by (optional) pplx::task>> findPetsByTags(std::vector tags); /// /// Find pet by ID /// /// - /// Returns a single pet + /// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions /// - /// ID of pet to return + /// ID of pet that needs to be fetched pplx::task> getPetById(int64_t petId); /// /// Update an existing pet @@ -97,7 +96,7 @@ class PetApi /// /// /// - /// Pet object that needs to be added to the store + /// Pet object that needs to be added to the store (optional) pplx::task updatePet(std::shared_ptr body); /// /// Updates a pet in the store with form data @@ -106,7 +105,7 @@ class PetApi /// /// /// ID of pet that needs to be updated/// Updated name of the pet (optional)/// Updated status of the pet (optional) - pplx::task updatePetWithForm(int64_t petId, utility::string_t name, utility::string_t status); + pplx::task updatePetWithForm(utility::string_t petId, utility::string_t name, utility::string_t status); /// /// uploads an image /// @@ -114,7 +113,7 @@ class PetApi /// /// /// ID of pet to update/// Additional data to pass to server (optional)/// file to upload (optional) - pplx::task> uploadFile(int64_t petId, utility::string_t additionalMetadata, std::shared_ptr file); + pplx::task uploadFile(int64_t petId, utility::string_t additionalMetadata, std::shared_ptr file); protected: std::shared_ptr m_ApiClient; diff --git a/samples/client/petstore/cpprest/api/StoreApi.cpp b/samples/client/petstore/cpprest/api/StoreApi.cpp index dae3f04a985..406e6d0a909 100644 --- a/samples/client/petstore/cpprest/api/StoreApi.cpp +++ b/samples/client/petstore/cpprest/api/StoreApi.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -62,8 +62,8 @@ pplx::task StoreApi::deleteOrder(utility::string_t orderId) std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -77,7 +77,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("StoreApi->deleteOrder does not produce any supported media type")); } @@ -128,7 +128,7 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -139,8 +139,8 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { @@ -161,6 +161,7 @@ pplx::task> StoreApi::getInventory() std::unordered_set responseHttpContentTypes; responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -174,7 +175,7 @@ pplx::task> StoreApi::getInventory() { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("StoreApi->getInventory does not produce any supported media type")); } @@ -229,7 +230,7 @@ pplx::task> StoreApi::getInventory() , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -240,8 +241,8 @@ pplx::task> StoreApi::getInventory() , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { @@ -272,7 +273,7 @@ pplx::task> StoreApi::getInventory() return result; }); } -pplx::task> StoreApi::getOrderById(int64_t orderId) +pplx::task> StoreApi::getOrderById(utility::string_t orderId) { @@ -286,8 +287,8 @@ pplx::task> StoreApi::getOrderById(int64_t orderId) std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -301,7 +302,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("StoreApi->getOrderById does not produce any supported media type")); } @@ -352,7 +353,7 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -363,8 +364,8 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { @@ -392,12 +393,6 @@ responseHttpContentTypes.insert( U("application/json") ); pplx::task> StoreApi::placeOrder(std::shared_ptr body) { - // verify the required parameter 'body' is set - if (body == nullptr) - { - throw ApiException(400, U("Missing required parameter 'body' when calling StoreApi->placeOrder")); - } - std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/store/order"); @@ -408,8 +403,8 @@ pplx::task> StoreApi::placeOrder(std::shared_ptr b std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -423,7 +418,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("StoreApi->placeOrder does not produce any supported media type")); } @@ -487,7 +482,7 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -498,8 +493,8 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { diff --git a/samples/client/petstore/cpprest/api/StoreApi.h b/samples/client/petstore/cpprest/api/StoreApi.h index 0b843e6e47b..e9c2ae6ca8c 100644 --- a/samples/client/petstore/cpprest/api/StoreApi.h +++ b/samples/client/petstore/cpprest/api/StoreApi.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -73,14 +73,14 @@ class StoreApi /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions /// /// ID of pet that needs to be fetched - pplx::task> getOrderById(int64_t orderId); + pplx::task> getOrderById(utility::string_t orderId); /// /// Place an order for a pet /// /// /// /// - /// order placed for purchasing the pet + /// order placed for purchasing the pet (optional) pplx::task> placeOrder(std::shared_ptr body); protected: diff --git a/samples/client/petstore/cpprest/api/UserApi.cpp b/samples/client/petstore/cpprest/api/UserApi.cpp index d376311036b..8259ef6ef9b 100644 --- a/samples/client/petstore/cpprest/api/UserApi.cpp +++ b/samples/client/petstore/cpprest/api/UserApi.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -51,12 +51,6 @@ UserApi::~UserApi() pplx::task UserApi::createUser(std::shared_ptr body) { - // verify the required parameter 'body' is set - if (body == nullptr) - { - throw ApiException(400, U("Missing required parameter 'body' when calling UserApi->createUser")); - } - std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/user"); @@ -67,8 +61,8 @@ pplx::task UserApi::createUser(std::shared_ptr body) std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -82,7 +76,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("UserApi->createUser does not produce any supported media type")); } @@ -146,7 +140,7 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -157,8 +151,8 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { @@ -178,8 +172,8 @@ pplx::task UserApi::createUsersWithArrayInput(std::vector> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -193,7 +187,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("UserApi->createUsersWithArrayInput does not produce any supported media type")); } @@ -271,7 +265,7 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -282,8 +276,8 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { @@ -303,8 +297,8 @@ pplx::task UserApi::createUsersWithListInput(std::vector> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -318,7 +312,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("UserApi->createUsersWithListInput does not produce any supported media type")); } @@ -396,7 +390,7 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -407,8 +401,8 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { @@ -429,8 +423,8 @@ pplx::task UserApi::deleteUser(utility::string_t username) std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -444,7 +438,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("UserApi->deleteUser does not produce any supported media type")); } @@ -495,7 +489,7 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -506,8 +500,8 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { @@ -528,8 +522,8 @@ pplx::task> UserApi::getUserByName(utility::string_t usern std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -543,7 +537,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("UserApi->getUserByName does not produce any supported media type")); } @@ -594,7 +588,7 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -605,8 +599,8 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { @@ -644,8 +638,8 @@ pplx::task UserApi::loginUser(utility::string_t username, uti std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -659,7 +653,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("UserApi->loginUser does not produce any supported media type")); } @@ -716,7 +710,7 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -727,8 +721,8 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { @@ -767,8 +761,8 @@ pplx::task UserApi::logoutUser() std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -782,7 +776,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("UserApi->logoutUser does not produce any supported media type")); } @@ -829,7 +823,7 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -840,8 +834,8 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { @@ -851,12 +845,6 @@ responseHttpContentTypes.insert( U("application/json") ); pplx::task UserApi::updateUser(utility::string_t username, std::shared_ptr body) { - // verify the required parameter 'body' is set - if (body == nullptr) - { - throw ApiException(400, U("Missing required parameter 'body' when calling UserApi->updateUser")); - } - std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/user/{username}"); @@ -868,8 +856,8 @@ pplx::task UserApi::updateUser(utility::string_t username, std::shared_ptr std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; @@ -883,7 +871,7 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } - else + else { throw ApiException(400, U("UserApi->updateUser does not produce any supported media type")); } @@ -951,7 +939,7 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } - // check response content type + // check response content type if(response.headers().has(U("Content-Type"))) { utility::string_t contentType = response.headers()[U("Content-Type")]; @@ -962,8 +950,8 @@ responseHttpContentTypes.insert( U("application/json") ); , std::make_shared(response.extract_utf8string(true).get())); } } - - return response.extract_string(); + + return response.extract_string(); }) .then([=](utility::string_t response) { diff --git a/samples/client/petstore/cpprest/api/UserApi.h b/samples/client/petstore/cpprest/api/UserApi.h index 5f6214f16ab..34425d67a77 100644 --- a/samples/client/petstore/cpprest/api/UserApi.h +++ b/samples/client/petstore/cpprest/api/UserApi.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -56,7 +56,7 @@ class UserApi /// /// This can only be done by the logged in user. /// - /// Created user object + /// Created user object (optional) pplx::task createUser(std::shared_ptr body); /// /// Creates list of users with given input array @@ -64,7 +64,7 @@ class UserApi /// /// /// - /// List of user object + /// List of user object (optional) pplx::task createUsersWithArrayInput(std::vector> body); /// /// Creates list of users with given input array @@ -72,7 +72,7 @@ class UserApi /// /// /// - /// List of user object + /// List of user object (optional) pplx::task createUsersWithListInput(std::vector> body); /// /// Delete user @@ -96,7 +96,7 @@ class UserApi /// /// /// - /// The user name for login/// The password for login in clear text + /// The user name for login (optional)/// The password for login in clear text (optional) pplx::task loginUser(utility::string_t username, utility::string_t password); /// /// Logs out current logged in user session @@ -112,7 +112,7 @@ class UserApi /// /// This can only be done by the logged in user. /// - /// name that need to be deleted/// Updated user object + /// name that need to be deleted/// Updated user object (optional) pplx::task updateUser(utility::string_t username, std::shared_ptr body); protected: diff --git a/samples/client/petstore/cpprest/model/Category.cpp b/samples/client/petstore/cpprest/model/Category.cpp index 8221b52237a..f8cb2ec6bb4 100644 --- a/samples/client/petstore/cpprest/model/Category.cpp +++ b/samples/client/petstore/cpprest/model/Category.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -33,7 +33,7 @@ namespace model { Category::Category() { - m_Id = 0L; + m_Id = 0; m_IdIsSet = false; m_Name = U(""); m_NameIsSet = false; diff --git a/samples/client/petstore/cpprest/model/Category.h b/samples/client/petstore/cpprest/model/Category.h index 63bf2907d31..690cf8bcf43 100644 --- a/samples/client/petstore/cpprest/model/Category.h +++ b/samples/client/petstore/cpprest/model/Category.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/model/Order.cpp b/samples/client/petstore/cpprest/model/Order.cpp index 43105712525..0a2ffdec9fd 100644 --- a/samples/client/petstore/cpprest/model/Order.cpp +++ b/samples/client/petstore/cpprest/model/Order.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -33,9 +33,9 @@ namespace model { Order::Order() { - m_Id = 0L; + m_Id = 0; m_IdIsSet = false; - m_PetId = 0L; + m_PetId = 0; m_PetIdIsSet = false; m_Quantity = 0; m_QuantityIsSet = false; diff --git a/samples/client/petstore/cpprest/model/Order.h b/samples/client/petstore/cpprest/model/Order.h index 4af8f83d2d8..3c8bd62568f 100644 --- a/samples/client/petstore/cpprest/model/Order.h +++ b/samples/client/petstore/cpprest/model/Order.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/model/Pet.cpp b/samples/client/petstore/cpprest/model/Pet.cpp index 578570305f7..3604e63659a 100644 --- a/samples/client/petstore/cpprest/model/Pet.cpp +++ b/samples/client/petstore/cpprest/model/Pet.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -33,7 +33,7 @@ namespace model { Pet::Pet() { - m_Id = 0L; + m_Id = 0; m_IdIsSet = false; m_CategoryIsSet = false; m_Name = U(""); diff --git a/samples/client/petstore/cpprest/model/Pet.h b/samples/client/petstore/cpprest/model/Pet.h index 88a6fe19f7e..8127ed16132 100644 --- a/samples/client/petstore/cpprest/model/Pet.h +++ b/samples/client/petstore/cpprest/model/Pet.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -34,10 +34,10 @@ #include "ModelBase.h" -#include "Category.h" +#include "Tag.h" #include +#include "Category.h" #include -#include "Tag.h" namespace io { namespace swagger { diff --git a/samples/client/petstore/cpprest/model/Tag.cpp b/samples/client/petstore/cpprest/model/Tag.cpp index 3f51e7069c9..2cb33ba48cc 100644 --- a/samples/client/petstore/cpprest/model/Tag.cpp +++ b/samples/client/petstore/cpprest/model/Tag.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -33,7 +33,7 @@ namespace model { Tag::Tag() { - m_Id = 0L; + m_Id = 0; m_IdIsSet = false; m_Name = U(""); m_NameIsSet = false; diff --git a/samples/client/petstore/cpprest/model/Tag.h b/samples/client/petstore/cpprest/model/Tag.h index 9a9381add81..ced6bdc5c4a 100644 --- a/samples/client/petstore/cpprest/model/Tag.h +++ b/samples/client/petstore/cpprest/model/Tag.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/model/User.cpp b/samples/client/petstore/cpprest/model/User.cpp index 87ebe24916a..9beb9422a40 100644 --- a/samples/client/petstore/cpprest/model/User.cpp +++ b/samples/client/petstore/cpprest/model/User.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -33,7 +33,7 @@ namespace model { User::User() { - m_Id = 0L; + m_Id = 0; m_IdIsSet = false; m_Username = U(""); m_UsernameIsSet = false; diff --git a/samples/client/petstore/cpprest/model/User.h b/samples/client/petstore/cpprest/model/User.h index 48fdb7d60f6..8baaeaed353 100644 --- a/samples/client/petstore/cpprest/model/User.h +++ b/samples/client/petstore/cpprest/model/User.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git From d4f9a16cf63664dd1226def47bab6152ac1df076 Mon Sep 17 00:00:00 2001 From: Charles Date: Sun, 2 Oct 2016 01:32:17 -0700 Subject: [PATCH 403/470] Cgardens nested object regex (#3879) * stop parsing key of object at first comma. * update samples --- .../src/main/resources/ruby/base_object.mustache | 2 +- .../ruby/lib/petstore/models/additional_properties_class.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/animal.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/animal_farm.rb | 2 +- .../client/petstore/ruby/lib/petstore/models/api_response.rb | 2 +- .../ruby/lib/petstore/models/array_of_array_of_number_only.rb | 2 +- .../petstore/ruby/lib/petstore/models/array_of_number_only.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/array_test.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/cat.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/category.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/client.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/dog.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/enum_arrays.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/enum_test.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/format_test.rb | 2 +- .../petstore/ruby/lib/petstore/models/has_only_read_only.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/list.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/map_test.rb | 2 +- .../models/mixed_properties_and_additional_properties_class.rb | 2 +- .../petstore/ruby/lib/petstore/models/model_200_response.rb | 2 +- .../client/petstore/ruby/lib/petstore/models/model_return.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/name.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/number_only.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/order.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/pet.rb | 2 +- .../client/petstore/ruby/lib/petstore/models/read_only_first.rb | 2 +- .../petstore/ruby/lib/petstore/models/special_model_name.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/tag.rb | 2 +- samples/client/petstore/ruby/lib/petstore/models/user.rb | 2 +- 29 files changed, 29 insertions(+), 29 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache index eb66ef6ff72..44a10211cc3 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache @@ -46,7 +46,7 @@ when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/additional_properties_class.rb b/samples/client/petstore/ruby/lib/petstore/models/additional_properties_class.rb index 97c85707a45..46829be071e 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/additional_properties_class.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/additional_properties_class.rb @@ -151,7 +151,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/animal.rb b/samples/client/petstore/ruby/lib/petstore/models/animal.rb index d71a06a294c..7dad66580fa 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/animal.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/animal.rb @@ -150,7 +150,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/animal_farm.rb b/samples/client/petstore/ruby/lib/petstore/models/animal_farm.rb index f86eb1b9eb1..65b57cca515 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/animal_farm.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/animal_farm.rb @@ -129,7 +129,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/api_response.rb b/samples/client/petstore/ruby/lib/petstore/models/api_response.rb index 7fcc61a148c..21c6bdbc157 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/api_response.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/api_response.rb @@ -156,7 +156,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/array_of_array_of_number_only.rb b/samples/client/petstore/ruby/lib/petstore/models/array_of_array_of_number_only.rb index d5fb71a5f35..ec00b4648fd 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/array_of_array_of_number_only.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/array_of_array_of_number_only.rb @@ -140,7 +140,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/array_of_number_only.rb b/samples/client/petstore/ruby/lib/petstore/models/array_of_number_only.rb index a6d5e081ae5..0febe89641a 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/array_of_number_only.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/array_of_number_only.rb @@ -140,7 +140,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/array_test.rb b/samples/client/petstore/ruby/lib/petstore/models/array_test.rb index b9f784a59de..93c5403c9a6 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/array_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/array_test.rb @@ -162,7 +162,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/cat.rb b/samples/client/petstore/ruby/lib/petstore/models/cat.rb index 8d0d801fbc2..7ed6e12ddd0 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/cat.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/cat.rb @@ -159,7 +159,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/category.rb b/samples/client/petstore/ruby/lib/petstore/models/category.rb index dc3fa09c4b1..c1256bf9564 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/category.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/category.rb @@ -147,7 +147,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/client.rb b/samples/client/petstore/ruby/lib/petstore/models/client.rb index 1931b314d12..26e59e35885 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/client.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/client.rb @@ -138,7 +138,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/dog.rb b/samples/client/petstore/ruby/lib/petstore/models/dog.rb index ff44da76a68..0e8a993caea 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/dog.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/dog.rb @@ -159,7 +159,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/enum_arrays.rb b/samples/client/petstore/ruby/lib/petstore/models/enum_arrays.rb index a437cfab42b..27b63a806e0 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/enum_arrays.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/enum_arrays.rb @@ -182,7 +182,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb b/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb index 8df4d2daad5..e4d0caa19ae 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb @@ -213,7 +213,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/format_test.rb b/samples/client/petstore/ruby/lib/petstore/models/format_test.rb index ba633d3c6ca..f734b42b993 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/format_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/format_test.rb @@ -435,7 +435,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/has_only_read_only.rb b/samples/client/petstore/ruby/lib/petstore/models/has_only_read_only.rb index 9721f6b7e65..4060aacc767 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/has_only_read_only.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/has_only_read_only.rb @@ -147,7 +147,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/list.rb b/samples/client/petstore/ruby/lib/petstore/models/list.rb index a5804aac06d..4924d2f82b5 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/list.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/list.rb @@ -138,7 +138,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/map_test.rb b/samples/client/petstore/ruby/lib/petstore/models/map_test.rb index c9304f024c8..1cbde73b242 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/map_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/map_test.rb @@ -172,7 +172,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/mixed_properties_and_additional_properties_class.rb b/samples/client/petstore/ruby/lib/petstore/models/mixed_properties_and_additional_properties_class.rb index 0e49fd3e2a0..edcdc5493a4 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/mixed_properties_and_additional_properties_class.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/mixed_properties_and_additional_properties_class.rb @@ -158,7 +158,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/model_200_response.rb b/samples/client/petstore/ruby/lib/petstore/models/model_200_response.rb index 9876e3dd3ea..08035465418 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/model_200_response.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/model_200_response.rb @@ -147,7 +147,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/model_return.rb b/samples/client/petstore/ruby/lib/petstore/models/model_return.rb index 7278d4171bd..2b5db8872ee 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/model_return.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/model_return.rb @@ -138,7 +138,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/name.rb b/samples/client/petstore/ruby/lib/petstore/models/name.rb index 24d7e27aff2..27a37cdc19c 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/name.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/name.rb @@ -166,7 +166,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/number_only.rb b/samples/client/petstore/ruby/lib/petstore/models/number_only.rb index 1ac0f0217f5..b1bdd34e3ca 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/number_only.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/number_only.rb @@ -138,7 +138,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/order.rb b/samples/client/petstore/ruby/lib/petstore/models/order.rb index 802961e7a9a..2dcd1b6063e 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/order.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/order.rb @@ -219,7 +219,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/pet.rb b/samples/client/petstore/ruby/lib/petstore/models/pet.rb index 88a3dc43aed..52191258d7a 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/pet.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/pet.rb @@ -223,7 +223,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/read_only_first.rb b/samples/client/petstore/ruby/lib/petstore/models/read_only_first.rb index b816c21633d..3124c15f6ed 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/read_only_first.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/read_only_first.rb @@ -147,7 +147,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/special_model_name.rb b/samples/client/petstore/ruby/lib/petstore/models/special_model_name.rb index 6a31e57643b..b7e2c9262f0 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/special_model_name.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/special_model_name.rb @@ -138,7 +138,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/tag.rb b/samples/client/petstore/ruby/lib/petstore/models/tag.rb index fa89d2c72a7..2174ba9a1b7 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/tag.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/tag.rb @@ -147,7 +147,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| diff --git a/samples/client/petstore/ruby/lib/petstore/models/user.rb b/samples/client/petstore/ruby/lib/petstore/models/user.rb index 92d335c68d0..0553d61e85d 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/user.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/user.rb @@ -202,7 +202,7 @@ def _deserialize(type, value) when /\AArray<(?.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } - when /\AHash<(?.+), (?.+)>\z/ + when /\AHash<(?.+?), (?.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| From 40a18797971e0ed4ea326a83728ecbe8db47fb73 Mon Sep 17 00:00:00 2001 From: Bartek Kryza Date: Sun, 2 Oct 2016 11:02:03 +0200 Subject: [PATCH 404/470] Bugfix/issue 3723 (#3726) * Extended request generation logic with support for serialized body content types other than Json * Updated the Petstore Python client tests * Fixed body content type identification for strings --- .../src/main/resources/python/rest.mustache | 17 +++++++++++++++-- .../client/petstore/python/petstore_api/rest.py | 17 +++++++++++++++-- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/rest.mustache b/modules/swagger-codegen/src/main/resources/python/rest.mustache index d5133ac84f4..9bdddc91904 100644 --- a/modules/swagger-codegen/src/main/resources/python/rest.mustache +++ b/modules/swagger-codegen/src/main/resources/python/rest.mustache @@ -122,12 +122,12 @@ class RESTClientObject(object): r = self.pool_manager.request(method, url, body=request_body, headers=headers) - if headers['Content-Type'] == 'application/x-www-form-urlencoded': + elif headers['Content-Type'] == 'application/x-www-form-urlencoded': r = self.pool_manager.request(method, url, fields=post_params, encode_multipart=False, headers=headers) - if headers['Content-Type'] == 'multipart/form-data': + elif headers['Content-Type'] == 'multipart/form-data': # must del headers['Content-Type'], or the correct Content-Type # which generated by urllib3 will be overwritten. del headers['Content-Type'] @@ -135,6 +135,19 @@ class RESTClientObject(object): fields=post_params, encode_multipart=True, headers=headers) + # Pass a `string` parameter directly in the body to support + # other content types than Json when `body` argument is provided + # in serialized form + elif isinstance(body, str): + request_body = body + r = self.pool_manager.request(method, url, + body=request_body, + headers=headers) + else: + # Cannot generate the request from given parameters + msg = """Cannot prepare a request message for provided arguments. + Please check that your arguments match declared content type.""" + raise ApiException(status=0, reason=msg) # For `GET`, `HEAD` else: r = self.pool_manager.request(method, url, diff --git a/samples/client/petstore/python/petstore_api/rest.py b/samples/client/petstore/python/petstore_api/rest.py index e5bfae61aa1..2a9e97d5490 100644 --- a/samples/client/petstore/python/petstore_api/rest.py +++ b/samples/client/petstore/python/petstore_api/rest.py @@ -142,12 +142,12 @@ def request(self, method, url, query_params=None, headers=None, r = self.pool_manager.request(method, url, body=request_body, headers=headers) - if headers['Content-Type'] == 'application/x-www-form-urlencoded': + elif headers['Content-Type'] == 'application/x-www-form-urlencoded': r = self.pool_manager.request(method, url, fields=post_params, encode_multipart=False, headers=headers) - if headers['Content-Type'] == 'multipart/form-data': + elif headers['Content-Type'] == 'multipart/form-data': # must del headers['Content-Type'], or the correct Content-Type # which generated by urllib3 will be overwritten. del headers['Content-Type'] @@ -155,6 +155,19 @@ def request(self, method, url, query_params=None, headers=None, fields=post_params, encode_multipart=True, headers=headers) + # Pass a `string` parameter directly in the body to support + # other content types than Json when `body` argument is provided + # in serialized form + elif isinstance(body, basestring): + request_body = body + r = self.pool_manager.request(method, url, + body=request_body, + headers=headers) + else: + # Cannot generate the request from given parameters + msg = """Cannot prepare a request message for provided arguments. + Please check that your arguments match declared content type.""" + raise ApiException(status=0, reason=msg) # For `GET`, `HEAD` else: r = self.pool_manager.request(method, url, From b7708a44bf828c266135d0679ab907407e936942 Mon Sep 17 00:00:00 2001 From: Jim Schubert Date: Sun, 2 Oct 2016 09:56:19 -0400 Subject: [PATCH 405/470] [aspnet5] Fix basePath application to operations (#3911) * [aspnet5] Fix basePath application to operations * [aspnet5] Regenerate sample --- .../main/resources/aspnet5/controller.mustache | 7 +++---- .../aspnet5/src/IO.Swagger/Controllers/PetApi.cs | 16 ++++++++-------- .../src/IO.Swagger/Controllers/StoreApi.cs | 8 ++++---- .../src/IO.Swagger/Controllers/UserApi.cs | 16 ++++++++-------- .../aspnet5/src/IO.Swagger/Models/ApiResponse.cs | 2 +- .../aspnet5/src/IO.Swagger/Models/Category.cs | 2 +- .../aspnet5/src/IO.Swagger/Models/Order.cs | 2 +- .../aspnet5/src/IO.Swagger/Models/Pet.cs | 2 +- .../aspnet5/src/IO.Swagger/Models/Tag.cs | 2 +- .../aspnet5/src/IO.Swagger/Models/User.cs | 2 +- 10 files changed, 29 insertions(+), 30 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/controller.mustache b/modules/swagger-codegen/src/main/resources/aspnet5/controller.mustache index bfeb2307ff8..72c5480ad0d 100644 --- a/modules/swagger-codegen/src/main/resources/aspnet5/controller.mustache +++ b/modules/swagger-codegen/src/main/resources/aspnet5/controller.mustache @@ -16,9 +16,8 @@ namespace {{packageName}}.Controllers { {{#operations}} /// /// {{description}} - /// {{#description}}{{#basePath}} - [Route("{{{basePath}}}")] - {{/basePath}}[Description("{{description}}")]{{/description}} + /// {{#description}} + [Description("{{description}}")]{{/description}} public class {{classname}}Controller : Controller { {{#operation}} @@ -29,7 +28,7 @@ namespace {{packageName}}.Controllers /// {{description}}{{/allParams}}{{#responses}} /// {{message}}{{/responses}} [{{httpMethod}}] - [Route("{{path}}")] + [Route("{{basePathWithoutHost}}{{path}}")] [SwaggerOperation("{{operationId}}")]{{#returnType}} [SwaggerResponse(200, type: typeof({{&returnType}}))]{{/returnType}} public virtual {{#returnType}}IActionResult{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}}({{#allParams}}{{>pathParam}}{{>queryParam}}{{>bodyParam}}{{>formParam}}{{>headerParam}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/PetApi.cs b/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/PetApi.cs index 8b6c8f3e09f..abac9871dc7 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/PetApi.cs +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/PetApi.cs @@ -48,7 +48,7 @@ public class PetApiController : Controller /// Pet object that needs to be added to the store /// Invalid input [HttpPost] - [Route("/pet")] + [Route("/v2/pet")] [SwaggerOperation("AddPet")] public virtual void AddPet([FromBody]Pet body) { @@ -64,7 +64,7 @@ public virtual void AddPet([FromBody]Pet body) /// /// Invalid pet value [HttpDelete] - [Route("/pet/{petId}")] + [Route("/v2/pet/{petId}")] [SwaggerOperation("DeletePet")] public virtual void DeletePet([FromRoute]long? petId, [FromHeader]string apiKey) { @@ -80,7 +80,7 @@ public virtual void DeletePet([FromRoute]long? petId, [FromHeader]string apiKey) /// successful operation /// Invalid status value [HttpGet] - [Route("/pet/findByStatus")] + [Route("/v2/pet/findByStatus")] [SwaggerOperation("FindPetsByStatus")] [SwaggerResponse(200, type: typeof(List))] public virtual IActionResult FindPetsByStatus([FromQuery]List status) @@ -102,7 +102,7 @@ public virtual IActionResult FindPetsByStatus([FromQuery]List status) /// successful operation /// Invalid tag value [HttpGet] - [Route("/pet/findByTags")] + [Route("/v2/pet/findByTags")] [SwaggerOperation("FindPetsByTags")] [SwaggerResponse(200, type: typeof(List))] public virtual IActionResult FindPetsByTags([FromQuery]List tags) @@ -125,7 +125,7 @@ public virtual IActionResult FindPetsByTags([FromQuery]List tags) /// Invalid ID supplied /// Pet not found [HttpGet] - [Route("/pet/{petId}")] + [Route("/v2/pet/{petId}")] [SwaggerOperation("GetPetById")] [SwaggerResponse(200, type: typeof(Pet))] public virtual IActionResult GetPetById([FromRoute]long? petId) @@ -148,7 +148,7 @@ public virtual IActionResult GetPetById([FromRoute]long? petId) /// Pet not found /// Validation exception [HttpPut] - [Route("/pet")] + [Route("/v2/pet")] [SwaggerOperation("UpdatePet")] public virtual void UpdatePet([FromBody]Pet body) { @@ -165,7 +165,7 @@ public virtual void UpdatePet([FromBody]Pet body) /// Updated status of the pet /// Invalid input [HttpPost] - [Route("/pet/{petId}")] + [Route("/v2/pet/{petId}")] [SwaggerOperation("UpdatePetWithForm")] public virtual void UpdatePetWithForm([FromRoute]long? petId, [FromForm]string name, [FromForm]string status) { @@ -182,7 +182,7 @@ public virtual void UpdatePetWithForm([FromRoute]long? petId, [FromForm]string n /// file to upload /// successful operation [HttpPost] - [Route("/pet/{petId}/uploadImage")] + [Route("/v2/pet/{petId}/uploadImage")] [SwaggerOperation("UploadFile")] [SwaggerResponse(200, type: typeof(ApiResponse))] public virtual IActionResult UploadFile([FromRoute]long? petId, [FromForm]string additionalMetadata, [FromForm]System.IO.Stream file) diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/StoreApi.cs b/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/StoreApi.cs index 26784668ba6..da0b7b0d67a 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/StoreApi.cs +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/StoreApi.cs @@ -49,7 +49,7 @@ public class StoreApiController : Controller /// Invalid ID supplied /// Order not found [HttpDelete] - [Route("/store/order/{orderId}")] + [Route("/v2/store/order/{orderId}")] [SwaggerOperation("DeleteOrder")] public virtual void DeleteOrder([FromRoute]string orderId) { @@ -63,7 +63,7 @@ public virtual void DeleteOrder([FromRoute]string orderId) /// Returns a map of status codes to quantities /// successful operation [HttpGet] - [Route("/store/inventory")] + [Route("/v2/store/inventory")] [SwaggerOperation("GetInventory")] [SwaggerResponse(200, type: typeof(Dictionary))] public virtual IActionResult GetInventory() @@ -86,7 +86,7 @@ public virtual IActionResult GetInventory() /// Invalid ID supplied /// Order not found [HttpGet] - [Route("/store/order/{orderId}")] + [Route("/v2/store/order/{orderId}")] [SwaggerOperation("GetOrderById")] [SwaggerResponse(200, type: typeof(Order))] public virtual IActionResult GetOrderById([FromRoute]long? orderId) @@ -108,7 +108,7 @@ public virtual IActionResult GetOrderById([FromRoute]long? orderId) /// successful operation /// Invalid Order [HttpPost] - [Route("/store/order")] + [Route("/v2/store/order")] [SwaggerOperation("PlaceOrder")] [SwaggerResponse(200, type: typeof(Order))] public virtual IActionResult PlaceOrder([FromBody]Order body) diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/UserApi.cs b/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/UserApi.cs index 1cfacdd09a7..023fc4366bc 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/UserApi.cs +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Controllers/UserApi.cs @@ -48,7 +48,7 @@ public class UserApiController : Controller /// Created user object /// successful operation [HttpPost] - [Route("/user")] + [Route("/v2/user")] [SwaggerOperation("CreateUser")] public virtual void CreateUser([FromBody]User body) { @@ -63,7 +63,7 @@ public virtual void CreateUser([FromBody]User body) /// List of user object /// successful operation [HttpPost] - [Route("/user/createWithArray")] + [Route("/v2/user/createWithArray")] [SwaggerOperation("CreateUsersWithArrayInput")] public virtual void CreateUsersWithArrayInput([FromBody]List body) { @@ -78,7 +78,7 @@ public virtual void CreateUsersWithArrayInput([FromBody]List body) /// List of user object /// successful operation [HttpPost] - [Route("/user/createWithList")] + [Route("/v2/user/createWithList")] [SwaggerOperation("CreateUsersWithListInput")] public virtual void CreateUsersWithListInput([FromBody]List body) { @@ -94,7 +94,7 @@ public virtual void CreateUsersWithListInput([FromBody]List body) /// Invalid username supplied /// User not found [HttpDelete] - [Route("/user/{username}")] + [Route("/v2/user/{username}")] [SwaggerOperation("DeleteUser")] public virtual void DeleteUser([FromRoute]string username) { @@ -111,7 +111,7 @@ public virtual void DeleteUser([FromRoute]string username) /// Invalid username supplied /// User not found [HttpGet] - [Route("/user/{username}")] + [Route("/v2/user/{username}")] [SwaggerOperation("GetUserByName")] [SwaggerResponse(200, type: typeof(User))] public virtual IActionResult GetUserByName([FromRoute]string username) @@ -134,7 +134,7 @@ public virtual IActionResult GetUserByName([FromRoute]string username) /// successful operation /// Invalid username/password supplied [HttpGet] - [Route("/user/login")] + [Route("/v2/user/login")] [SwaggerOperation("LoginUser")] [SwaggerResponse(200, type: typeof(string))] public virtual IActionResult LoginUser([FromQuery]string username, [FromQuery]string password) @@ -154,7 +154,7 @@ public virtual IActionResult LoginUser([FromQuery]string username, [FromQuery]st /// /// successful operation [HttpGet] - [Route("/user/logout")] + [Route("/v2/user/logout")] [SwaggerOperation("LogoutUser")] public virtual void LogoutUser() { @@ -171,7 +171,7 @@ public virtual void LogoutUser() /// Invalid user supplied /// User not found [HttpPut] - [Route("/user/{username}")] + [Route("/v2/user/{username}")] [SwaggerOperation("UpdateUser")] public virtual void UpdateUser([FromRoute]string username, [FromBody]User body) { diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/ApiResponse.cs b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/ApiResponse.cs index e34c3edf374..ab83518032c 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/ApiResponse.cs +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/ApiResponse.cs @@ -33,7 +33,7 @@ namespace IO.Swagger.Models { /// - /// + /// Describes the result of uploading an image resource /// [DataContract] public partial class ApiResponse : IEquatable diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Category.cs b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Category.cs index 15f10eb9aa7..8e1404c7338 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Category.cs +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Category.cs @@ -33,7 +33,7 @@ namespace IO.Swagger.Models { /// - /// + /// A category for a pet /// [DataContract] public partial class Category : IEquatable diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Order.cs b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Order.cs index a49276583c6..b20143353cc 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Order.cs +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Order.cs @@ -33,7 +33,7 @@ namespace IO.Swagger.Models { /// - /// + /// An order for a pets from the pet store /// [DataContract] public partial class Order : IEquatable diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Pet.cs b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Pet.cs index 6c4afd3b95e..9a6f87a2945 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Pet.cs +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Pet.cs @@ -33,7 +33,7 @@ namespace IO.Swagger.Models { /// - /// + /// A pet for sale in the pet store /// [DataContract] public partial class Pet : IEquatable diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Tag.cs b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Tag.cs index 4f2cc3e5cef..55269f40675 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Tag.cs +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/Tag.cs @@ -33,7 +33,7 @@ namespace IO.Swagger.Models { /// - /// + /// A tag for a pet /// [DataContract] public partial class Tag : IEquatable diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/User.cs b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/User.cs index 8933e370956..1dbde78cb0b 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Models/User.cs +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Models/User.cs @@ -33,7 +33,7 @@ namespace IO.Swagger.Models { /// - /// + /// A User who is purchasing from the pet store /// [DataContract] public partial class User : IEquatable From 4a74e788ec0256c48a5944f851dcce7fa0abd29c Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 3 Oct 2016 09:32:20 +0800 Subject: [PATCH 406/470] fix python flask controller without tag (default_controller) --- .../codegen/languages/FlaskConnexionCodegen.java | 6 +----- .../petstore/flaskConnexion/swagger/swagger.yaml | 12 ++++++++++++ 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java index 919435f747a..2ac51c7e9e1 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java @@ -145,10 +145,6 @@ public void processOpts() { } if(!new java.io.File(controllerPackage + File.separator + defaultController + ".py").exists()) { - //supportingFiles.add(new SupportingFile("controller.mustache", - // controllerPackage, - // defaultController + ".py") - //); supportingFiles.add(new SupportingFile("__init__.mustache", controllerPackage, "__init__.py") @@ -269,7 +265,7 @@ public void preprocessSwagger(Swagger swagger) { } else { // no tag found, use "default_controller" as the default - String tag = "default_controller"; + String tag = "default"; operation.setTags(Arrays.asList(tag)); controllerName = tag + "_controller"; } diff --git a/samples/server/petstore/flaskConnexion/swagger/swagger.yaml b/samples/server/petstore/flaskConnexion/swagger/swagger.yaml index af17161ec2a..7b412611171 100644 --- a/samples/server/petstore/flaskConnexion/swagger/swagger.yaml +++ b/samples/server/petstore/flaskConnexion/swagger/swagger.yaml @@ -644,6 +644,8 @@ definitions: complete: type: "boolean" default: false + title: "Pet Order" + description: "An order for a pets from the pet store" xml: name: "Order" Category: @@ -654,6 +656,8 @@ definitions: format: "int64" name: type: "string" + title: "Pet catehgry" + description: "A category for a pet" xml: name: "Category" User: @@ -678,6 +682,8 @@ definitions: type: "integer" format: "int32" description: "User Status" + title: "a User" + description: "A User who is purchasing from the pet store" xml: name: "User" Tag: @@ -688,6 +694,8 @@ definitions: format: "int64" name: type: "string" + title: "Pet Tag" + description: "A tag for a pet" xml: name: "Tag" Pet: @@ -725,6 +733,8 @@ definitions: - "available" - "pending" - "sold" + title: "a Pet" + description: "A pet for sale in the pet store" xml: name: "Pet" ApiResponse: @@ -737,6 +747,8 @@ definitions: type: "string" message: type: "string" + title: "An uploaded response" + description: "Describes the result of uploading an image resource" externalDocs: description: "Find out more about Swagger" url: "http://swagger.io" From e633073082ecb575627c3ba0b7b757b19c86e326 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20Garc=C3=ADa?= Date: Mon, 3 Oct 2016 11:14:54 +0200 Subject: [PATCH 407/470] Add a new cli command to output version information (2nd attempt) #3892 (#3899) * Properly git-ignore all nbactions.xml files. * Add a command line action to print the program version (#3892). I am using maven resource filtering capabilities so that an existing version.properties resource file gets filtered upon build and populated with the project version tag. This resource is then read at runtime as required. * Using a different version tag when unreadable. --- .gitignore | 3 +- modules/swagger-codegen-cli/pom.xml | 1 + .../io/swagger/codegen/SwaggerCodegen.java | 9 +++- .../java/io/swagger/codegen/cmd/Meta.java | 8 +--- .../java/io/swagger/codegen/cmd/Version.java | 45 +++++++++++++++++++ .../src/main/resources/version.properties | 1 + 6 files changed, 58 insertions(+), 9 deletions(-) create mode 100644 modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Version.java create mode 100644 modules/swagger-codegen-cli/src/main/resources/version.properties diff --git a/.gitignore b/.gitignore index 18fc2b3035b..6433492c0f3 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,7 @@ out/ *.iws classpath.txt version.properties +!modules/swagger-codegen-cli/src/main/resources/version.properties .project .classpath lib/* @@ -33,7 +34,7 @@ packages/ /target /generated-files -/nbactions.xml +nbactions.xml # scalatra samples/server-generator/scalatra/output diff --git a/modules/swagger-codegen-cli/pom.xml b/modules/swagger-codegen-cli/pom.xml index e484393bb14..6b56d5a6f56 100644 --- a/modules/swagger-codegen-cli/pom.xml +++ b/modules/swagger-codegen-cli/pom.xml @@ -18,6 +18,7 @@ src/main/resources + true logback.xml diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/SwaggerCodegen.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/SwaggerCodegen.java index 98c0b8c05b5..94b64be8d02 100644 --- a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/SwaggerCodegen.java +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/SwaggerCodegen.java @@ -6,6 +6,7 @@ import io.swagger.codegen.cmd.Generate; import io.swagger.codegen.cmd.Langs; import io.swagger.codegen.cmd.Meta; +import io.swagger.codegen.cmd.Version; /** * User: lanwen @@ -21,16 +22,20 @@ public class SwaggerCodegen { public static void main(String[] args) { + String version = Version.readVersionFromResources(); @SuppressWarnings("unchecked") Cli.CliBuilder builder = Cli.builder("swagger-codegen-cli") - .withDescription("Swagger code generator CLI. More info on swagger.io") + .withDescription(String.format( + "Swagger code generator CLI (version %s). More info on swagger.io", + version)) .withDefaultCommand(Langs.class) .withCommands( Generate.class, Meta.class, Langs.class, Help.class, - ConfigHelp.class + ConfigHelp.class, + Version.class ); builder.build().parse(args).run(); diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Meta.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Meta.java index c2dffbe6200..3b5d71eec9f 100644 --- a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Meta.java +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Meta.java @@ -68,12 +68,8 @@ public void run() { "src/main/resources/META-INF/services", "io.swagger.codegen.CodegenConfig") ); - String swaggerVersion = this.getClass().getPackage().getImplementationVersion(); - // if the code is running outside of the jar (i.e. from the IDE), it will not have the version available. - // let's default it with something. - if (swaggerVersion==null) { - swaggerVersion = "2.1.3"; - } + String swaggerVersion = Version.readVersionFromResources(); + Map data = new ImmutableMap.Builder() .put("generatorPackage", targetPackage) .put("generatorClass", mainClass) diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Version.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Version.java new file mode 100644 index 00000000000..c39b54a30a3 --- /dev/null +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Version.java @@ -0,0 +1,45 @@ +package io.swagger.codegen.cmd; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +import io.airlift.airline.Command; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Command(name = "version", description = "Show version information") +public class Version implements Runnable { + + private static final Logger LOGGER = LoggerFactory.getLogger(Meta.class); + + private static final String VERSION_PLACEHOLDER = "${project.version}"; + + private static final String UNREADABLE_VERSION = "unreadable"; + private static final String UNSET_VERSION = "unset"; + private static final String UNKNOWN_VERSION = "unknown"; + + public static String readVersionFromResources() { + Properties versionProperties = new Properties(); + try (InputStream is = Version.class.getResourceAsStream("/version.properties")) { + versionProperties.load(is); + } catch (IOException ex) { + LOGGER.error("Error loading version properties", ex); + return UNREADABLE_VERSION; + } + + String version = versionProperties.getProperty("version", UNKNOWN_VERSION).trim(); + if (VERSION_PLACEHOLDER.equals(version)) { + return UNSET_VERSION; + } else { + return version; + } + } + + @Override + public void run() { + String version = readVersionFromResources(); + System.out.println(version); + } + +} diff --git a/modules/swagger-codegen-cli/src/main/resources/version.properties b/modules/swagger-codegen-cli/src/main/resources/version.properties new file mode 100644 index 00000000000..410af8cc687 --- /dev/null +++ b/modules/swagger-codegen-cli/src/main/resources/version.properties @@ -0,0 +1 @@ +version = ${project.version} From 2aadbee8edc4f27d72756f99ced5d326d18c148f Mon Sep 17 00:00:00 2001 From: Adam Panzer Date: Fri, 30 Sep 2016 11:56:12 -0700 Subject: [PATCH 408/470] validate(s)_presence_of Migration should create pluralized table names Change controller filenames --- .../codegen/languages/Rails5ServerCodegen.java | 4 ++-- .../src/main/resources/rails5/migrate.mustache | 2 +- .../src/main/resources/rails5/model.mustache | 2 +- .../{pet_controllers.rb => pets_controller.rb} | 0 .../{store_controllers.rb => stores_controller.rb} | 0 .../{user_controllers.rb => users_controller.rb} | 0 samples/server/petstore/rails5/app/models/pet.rb | 4 ++-- .../petstore/rails5/db/migrate/0_init_tables.rb | 12 ++++++------ 8 files changed, 12 insertions(+), 12 deletions(-) rename samples/server/petstore/rails5/app/controllers/{pet_controllers.rb => pets_controller.rb} (100%) rename samples/server/petstore/rails5/app/controllers/{store_controllers.rb => stores_controller.rb} (100%) rename samples/server/petstore/rails5/app/controllers/{user_controllers.rb => users_controller.rb} (100%) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java index e03622b5919..5147d4a5b00 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java @@ -281,8 +281,8 @@ public String toApiFilename(String name) { // replace - with _ e.g. created-at => created_at name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - // e.g. PhoneNumberApi.rb => phone_number_api.rb - return underscore(name) + "_controllers"; + // e.g. DefaultController => defaults_controller.rb + return underscore(name) + "s_controller"; } @Override diff --git a/modules/swagger-codegen/src/main/resources/rails5/migrate.mustache b/modules/swagger-codegen/src/main/resources/rails5/migrate.mustache index 508b0ce7ede..d9d5db407be 100644 --- a/modules/swagger-codegen/src/main/resources/rails5/migrate.mustache +++ b/modules/swagger-codegen/src/main/resources/rails5/migrate.mustache @@ -4,7 +4,7 @@ class InitTables < ActiveRecord::Migration def change{{#models}}{{#model}} - create_table :{{classFilename}}, id: false do |t|{{#vars}}{{#isContainer}} + create_table "{{classFilename}}".pluralize.to_sym, id: false do |t|{{#vars}}{{#isContainer}} t.string :{{name}}{{/isContainer}}{{^isContainer}} t.{{datatype}} :{{{name}}}{{/isContainer}}{{/vars}} diff --git a/modules/swagger-codegen/src/main/resources/rails5/model.mustache b/modules/swagger-codegen/src/main/resources/rails5/model.mustache index edfe9fac56c..8fc9455c2b7 100644 --- a/modules/swagger-codegen/src/main/resources/rails5/model.mustache +++ b/modules/swagger-codegen/src/main/resources/rails5/model.mustache @@ -5,7 +5,7 @@ {{#models}}{{#model}} class {{classname}} < ApplicationRecord {{#requiredVars}} - validate_presence_of :{{name}} + validates_presence_of :{{name}} {{/requiredVars}}{{#vars}}{{#isListContainer}} serialize :{{name}}, Array{{/isListContainer}}{{#isMapContainer}} serialize :{{name}}, Hash{{/isMapContainer}}{{/vars}} diff --git a/samples/server/petstore/rails5/app/controllers/pet_controllers.rb b/samples/server/petstore/rails5/app/controllers/pets_controller.rb similarity index 100% rename from samples/server/petstore/rails5/app/controllers/pet_controllers.rb rename to samples/server/petstore/rails5/app/controllers/pets_controller.rb diff --git a/samples/server/petstore/rails5/app/controllers/store_controllers.rb b/samples/server/petstore/rails5/app/controllers/stores_controller.rb similarity index 100% rename from samples/server/petstore/rails5/app/controllers/store_controllers.rb rename to samples/server/petstore/rails5/app/controllers/stores_controller.rb diff --git a/samples/server/petstore/rails5/app/controllers/user_controllers.rb b/samples/server/petstore/rails5/app/controllers/users_controller.rb similarity index 100% rename from samples/server/petstore/rails5/app/controllers/user_controllers.rb rename to samples/server/petstore/rails5/app/controllers/users_controller.rb diff --git a/samples/server/petstore/rails5/app/models/pet.rb b/samples/server/petstore/rails5/app/models/pet.rb index da927b6260e..e077b528bc7 100644 --- a/samples/server/petstore/rails5/app/models/pet.rb +++ b/samples/server/petstore/rails5/app/models/pet.rb @@ -23,8 +23,8 @@ class Pet < ApplicationRecord - validate_presence_of :name - validate_presence_of :photo_urls + validates_presence_of :name + validates_presence_of :photo_urls serialize :photo_urls, Array serialize :tags, Array diff --git a/samples/server/petstore/rails5/db/migrate/0_init_tables.rb b/samples/server/petstore/rails5/db/migrate/0_init_tables.rb index 5fa060fb4dc..7bc2663f162 100644 --- a/samples/server/petstore/rails5/db/migrate/0_init_tables.rb +++ b/samples/server/petstore/rails5/db/migrate/0_init_tables.rb @@ -23,7 +23,7 @@ class InitTables < ActiveRecord::Migration def change - create_table :api_response, id: false do |t| + create_table "api_response".pluralize.to_sym, id: false do |t| t.integer :code t.string :type t.string :message @@ -31,14 +31,14 @@ def change t.timestamps end - create_table :category, id: false do |t| + create_table "category".pluralize.to_sym, id: false do |t| t.integer :id t.string :name t.timestamps end - create_table :order, id: false do |t| + create_table "order".pluralize.to_sym, id: false do |t| t.integer :id t.integer :pet_id t.integer :quantity @@ -49,7 +49,7 @@ def change t.timestamps end - create_table :pet, id: false do |t| + create_table "pet".pluralize.to_sym, id: false do |t| t.integer :id t.string :category t.string :name @@ -60,14 +60,14 @@ def change t.timestamps end - create_table :tag, id: false do |t| + create_table "tag".pluralize.to_sym, id: false do |t| t.integer :id t.string :name t.timestamps end - create_table :user, id: false do |t| + create_table "user".pluralize.to_sym, id: false do |t| t.integer :id t.string :username t.string :first_name From 3ca98930132ccc7dad21dd2c96991cc53395d7f3 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 4 Oct 2016 11:18:10 +0800 Subject: [PATCH 409/470] add undertow --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index f75aa258941..93f84437bf6 100644 --- a/README.md +++ b/README.md @@ -881,6 +881,7 @@ Here is a list of template creators: * Erlang Server: @galaxie * Go Server: @guohuang * Haskell Servant: @algas + * Java Undertow: @stevehu * Java Spring Boot: @diyfr * JAX-RS RestEasy: @chameleon82 * JAX-RS CXF: @hiveship From ed4200f5c6bde0d6a9a40f770202ce0cd230d3f2 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 5 Oct 2016 10:51:54 +0800 Subject: [PATCH 410/470] add http://onedata.org --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 93f84437bf6..9c3bf295fdb 100644 --- a/README.md +++ b/README.md @@ -782,6 +782,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [Mporium](http://mporium.com/) - [nViso](http://www.nviso.ch/) - [Okiok](https://www.okiok.com) +- [Onedata](http://onedata.org) - [OSDN](https://osdn.jp) - [PagerDuty](https://www.pagerduty.com) - [Pepipost](https://www.pepipost.com) From 1aeceead99bb0e6e053befb27e1d0cb415599f22 Mon Sep 17 00:00:00 2001 From: Griffin Schneider Date: Thu, 7 Jul 2016 12:13:56 -0400 Subject: [PATCH 411/470] [Java] Make generated models Parcelable for okhttp-gson if the -DparcelableModel=true option is provided. --- .../codegen/languages/JavaClientCodegen.java | 11 ++++- .../src/main/resources/Java/model.mustache | 2 + .../src/main/resources/Java/pojo.mustache | 44 ++++++++++++++++++- .../options/JavaClientOptionsProvider.java | 1 + 4 files changed, 56 insertions(+), 2 deletions(-) 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 db181498586..835dc63d1ca 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 @@ -14,12 +14,14 @@ public class JavaClientCodegen extends AbstractJavaCodegen { private static final Logger LOGGER = LoggerFactory.getLogger(JavaClientCodegen.class); public static final String USE_RX_JAVA = "useRxJava"; + public static final String PARCELABLE_MODEL = "parcelableModel"; public static final String RETROFIT_1 = "retrofit"; public static final String RETROFIT_2 = "retrofit2"; protected String gradleWrapperPackage = "gradle.wrapper"; protected boolean useRxJava = false; + protected boolean parcelableModel = false; public JavaClientCodegen() { super(); @@ -31,11 +33,12 @@ public JavaClientCodegen() { modelPackage = "io.swagger.client.model"; cliOptions.add(CliOption.newBoolean(USE_RX_JAVA, "Whether to use the RxJava adapter with the retrofit2 library.")); + cliOptions.add(CliOption.newBoolean(PARCELABLE_MODEL, "Whether to generate models for Android that implement Parcelable with the okhttp-gson library.")); supportedLibraries.put("jersey1", "HTTP client: Jersey client 1.19.1. JSON processing: Jackson 2.7.0"); supportedLibraries.put("feign", "HTTP client: Netflix Feign 8.16.0. JSON processing: Jackson 2.7.0"); supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.22.2. JSON processing: Jackson 2.7.0"); - supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.6.2"); + supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.6.2. Enable Parcelable modles on Android using '-DparcelableModel=true'"); supportedLibraries.put(RETROFIT_1, "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.3.1 (Retrofit 1.9.0). IMPORTANT NOTE: retrofit1.x is no longer actively maintained so please upgrade to 'retrofit2' instead."); supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 3.2.0. JSON processing: Gson 2.6.1 (Retrofit 2.0.2). Enable the RxJava adapter using '-DuseRxJava=true'. (RxJava 1.1.3)"); @@ -70,6 +73,9 @@ public void processOpts() { if (additionalProperties.containsKey(USE_RX_JAVA)) { this.setUseRxJava(Boolean.valueOf(additionalProperties.get(USE_RX_JAVA).toString())); } + if (additionalProperties.containsKey(PARCELABLE_MODEL)) { + this.setParcelableModels(Boolean.valueOf(additionalProperties.get(PARCELABLE_MODEL).toString())); + } final String invokerFolder = (sourceFolder + '/' + invokerPackage).replace(".", "/"); final String authFolder = (sourceFolder + '/' + invokerPackage + ".auth").replace(".", "/"); @@ -217,4 +223,7 @@ public void setUseRxJava(boolean useRxJava) { this.useRxJava = useRxJava; } + public void setParcelableModels(boolean parcelableModel) { + this.parcelableModel = parcelableModel; + } } diff --git a/modules/swagger-codegen/src/main/resources/Java/model.mustache b/modules/swagger-codegen/src/main/resources/Java/model.mustache index 1143fc413df..fa9bc359024 100644 --- a/modules/swagger-codegen/src/main/resources/Java/model.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/model.mustache @@ -8,6 +8,8 @@ import {{import}}; {{/imports}} {{#serializableModel}}import java.io.Serializable;{{/serializableModel}} +{{#parcelableModel}}import android.os.Parcelable; +import android.os.Parcel;{{/parcelableModel}} {{#models}} {{#model}} {{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{>pojo}}{{/isEnum}} diff --git a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache index f32a4e9b823..0ecfcd3609c 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache @@ -3,7 +3,7 @@ */{{#description}} @ApiModel(description = "{{{description}}}"){{/description}} {{>generatedAnnotation}} -public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { +public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#parcelableModel}}implements Parcelable{{#serializableModel}}, Serializable{{/serializableModel}}{{/parcelableModel}}{{#serializableModel}}implements Serializable{{/serializableModel}} { {{#vars}} {{#isEnum}} {{^isContainer}} @@ -119,4 +119,46 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali } return o.toString().replace("\n", "\n "); } + + {{#parcelableModel}} + public void writeToParcel(Parcel out, int flags) { + {{#parent}} super.writeToParcel(out, flags); {{/parent}} {{#vars}} + out.writeValue({{name}}); + {{/vars}} + } + + public {{classname}}() { + super(); + } + + {{classname}}(Parcel in) { + {{#parent}} super(in); {{/parent}} + {{#vars}} + {{#isContainer}} + {{#complexType}} + {{name}} = ({{{datatypeWithEnum}}})in.readValue({{complexType}}.class.getClassLoader()); + {{/complexType}} + {{^complexType}} + {{name}} = ({{{datatypeWithEnum}}})in.readValue(null); + {{/complexType}} + {{/isContainer}} + {{^isContainer}} + {{name}} = ({{{datatypeWithEnum}}})in.readValue(null); + {{/isContainer}} + {{/vars}} + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator<{{classname}}> CREATOR = new Parcelable.Creator<{{classname}}>() { + public {{classname}} createFromParcel(Parcel in) { + return new {{classname}}(in); + } + public {{classname}}[] newArray(int size) { + return new {{classname}}[size]; + } + }; + {{/parcelableModel}} } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaClientOptionsProvider.java index 53cfe826d36..a1da4cfd808 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaClientOptionsProvider.java @@ -16,6 +16,7 @@ public Map createOptions() { Map options = new HashMap(super.createOptions()); options.put(CodegenConstants.LIBRARY, DEFAULT_LIBRARY_VALUE); options.put(JavaClientCodegen.USE_RX_JAVA, "false"); + options.put(JavaClientCodegen.PARCELABLE_MODEL, "false"); return options; } From 0844496bad04f9cf1877ac0c03770dd5e34c585a Mon Sep 17 00:00:00 2001 From: Griffin Schneider Date: Thu, 7 Jul 2016 13:56:09 -0400 Subject: [PATCH 412/470] [Java] Fix bug in generated code if parcelableModel and serializableModel are both true. --- modules/swagger-codegen/src/main/resources/Java/pojo.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache index 0ecfcd3609c..e4058beca39 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache @@ -3,7 +3,7 @@ */{{#description}} @ApiModel(description = "{{{description}}}"){{/description}} {{>generatedAnnotation}} -public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#parcelableModel}}implements Parcelable{{#serializableModel}}, Serializable{{/serializableModel}}{{/parcelableModel}}{{#serializableModel}}implements Serializable{{/serializableModel}} { +public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#parcelableModel}}implements Parcelable{{#serializableModel}}, Serializable{{/serializableModel}}{{/parcelableModel}}{{^parcelableModel}}{{#serializableModel}}implements Serializable{{/serializableModel}}{{/parcelableModel}} { {{#vars}} {{#isEnum}} {{^isContainer}} From 8ce8082f7f92b6c295c84e78cb7f67fcd02b69f3 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 5 Oct 2016 19:41:38 +0800 Subject: [PATCH 413/470] fix bug with parcelable --- bin/java-petstore-okhttp-gson-parcelable.sh | 33 ++ .../codegen/languages/JavaClientCodegen.java | 6 +- .../src/main/resources/Java/model.mustache | 10 +- .../.gitignore | 0 .../.swagger-codegen-ignore | 0 .../.travis.yml | 0 .../LICENSE | 0 .../okhttp-gson-parcelableModel/README.md | 183 +++++++ .../build.gradle | 0 .../build.sbt | 0 .../docs/AdditionalPropertiesClass.md | 11 + .../docs/Animal.md | 11 + .../docs/AnimalFarm.md | 9 + .../docs/ArrayOfArrayOfNumberOnly.md | 10 + .../docs/ArrayOfNumberOnly.md | 10 + .../docs/ArrayTest.md | 12 + .../okhttp-gson-parcelableModel/docs/Cat.md | 12 + .../docs/Category.md | 11 + .../okhttp-gson-parcelableModel/docs/Dog.md | 12 + .../docs/EnumClass.md | 14 + .../docs/EnumTest.md | 36 ++ .../docs/FakeApi.md | 122 +++++ .../docs/FormatTest.md | 22 + .../docs/HasOnlyReadOnly.md | 11 + .../docs/MapTest.md | 17 + ...dPropertiesAndAdditionalPropertiesClass.md | 12 + .../docs/Model200Response.md | 11 + .../docs/ModelApiResponse.md | 12 + .../docs/ModelReturn.md | 10 + .../okhttp-gson-parcelableModel/docs/Name.md | 13 + .../docs/NumberOnly.md | 10 + .../okhttp-gson-parcelableModel/docs/Order.md | 24 + .../okhttp-gson-parcelableModel/docs/Pet.md | 24 + .../docs/PetApi.md | 448 ++++++++++++++++++ .../docs/ReadOnlyFirst.md | 11 + .../docs/SpecialModelName.md | 10 + .../docs/StoreApi.md | 197 ++++++++ .../okhttp-gson-parcelableModel/docs/Tag.md | 11 + .../okhttp-gson-parcelableModel/docs/User.md | 17 + .../docs/UserApi.md | 370 +++++++++++++++ .../git_push.sh | 0 .../gradle.properties | 0 .../gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 53639 bytes .../gradle/wrapper/gradle-wrapper.properties | 6 + .../gradlew | 0 .../gradlew.bat | 0 .../pom.xml | 0 .../settings.gradle | 0 .../src/main/AndroidManifest.xml | 0 .../java/io/swagger/client/ApiCallback.java | 0 .../java/io/swagger/client/ApiClient.java | 0 .../java/io/swagger/client/ApiException.java | 0 .../java/io/swagger/client/ApiResponse.java | 0 .../java/io/swagger/client/Configuration.java | 0 .../src/main/java/io/swagger/client/JSON.java | 0 .../src/main/java/io/swagger/client/Pair.java | 0 .../swagger/client/ProgressRequestBody.java | 0 .../swagger/client/ProgressResponseBody.java | 0 .../java/io/swagger/client/StringUtil.java | 0 .../java/io/swagger/client/api/FakeApi.java | 0 .../java/io/swagger/client/api/PetApi.java | 0 .../java/io/swagger/client/api/StoreApi.java | 0 .../java/io/swagger/client/api/UserApi.java | 0 .../io/swagger/client/auth/ApiKeyAuth.java | 0 .../swagger/client/auth/Authentication.java | 0 .../io/swagger/client/auth/HttpBasicAuth.java | 0 .../java/io/swagger/client/auth/OAuth.java | 0 .../io/swagger/client/auth/OAuthFlow.java | 0 .../model/AdditionalPropertiesClass.java | 35 +- .../java/io/swagger/client/model/Animal.java | 35 +- .../io/swagger/client/model/AnimalFarm.java | 29 +- .../model/ArrayOfArrayOfNumberOnly.java | 32 +- .../client/model/ArrayOfNumberOnly.java | 32 +- .../io/swagger/client/model/ArrayTest.java | 38 +- .../java/io/swagger/client/model/Cat.java | 45 +- .../io/swagger/client/model/Category.java | 35 +- .../java/io/swagger/client/model/Dog.java | 45 +- .../io/swagger/client/model/EnumClass.java | 3 +- .../io/swagger/client/model/EnumTest.java | 38 +- .../io/swagger/client/model/FormatTest.java | 68 ++- .../swagger/client/model/HasOnlyReadOnly.java | 35 +- .../java/io/swagger/client/model/MapTest.java | 35 +- ...ropertiesAndAdditionalPropertiesClass.java | 38 +- .../client/model/Model200Response.java | 35 +- .../client/model/ModelApiResponse.java | 38 +- .../io/swagger/client/model/ModelReturn.java | 32 +- .../java/io/swagger/client/model/Name.java | 41 +- .../io/swagger/client/model/NumberOnly.java | 32 +- .../java/io/swagger/client/model/Order.java | 47 +- .../java/io/swagger/client/model/Pet.java | 47 +- .../swagger/client/model/ReadOnlyFirst.java | 35 +- .../client/model/SpecialModelName.java | 32 +- .../java/io/swagger/client/model/Tag.java | 35 +- .../java/io/swagger/client/model/User.java | 53 ++- .../io/swagger/client/api/FakeApiTest.java | 92 ++++ .../io/swagger/client/api/PetApiTest.java | 180 +++++++ .../io/swagger/client/api/StoreApiTest.java | 108 +++++ .../io/swagger/client/api/UserApiTest.java | 174 +++++++ 98 files changed, 3206 insertions(+), 56 deletions(-) create mode 100755 bin/java-petstore-okhttp-gson-parcelable.sh rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/.gitignore (100%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/.swagger-codegen-ignore (100%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/.travis.yml (100%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/LICENSE (100%) create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/README.md rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/build.gradle (100%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/build.sbt (100%) create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/docs/AdditionalPropertiesClass.md create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Animal.md create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/docs/AnimalFarm.md create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ArrayOfArrayOfNumberOnly.md create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ArrayOfNumberOnly.md create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ArrayTest.md create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Cat.md create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Category.md create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Dog.md create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/docs/EnumClass.md create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/docs/EnumTest.md create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/docs/FakeApi.md create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/docs/FormatTest.md create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/docs/HasOnlyReadOnly.md create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/docs/MapTest.md create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/docs/MixedPropertiesAndAdditionalPropertiesClass.md create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Model200Response.md create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ModelApiResponse.md create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ModelReturn.md create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Name.md create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/docs/NumberOnly.md create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Order.md create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Pet.md create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/docs/PetApi.md create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ReadOnlyFirst.md create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/docs/SpecialModelName.md create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/docs/StoreApi.md create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Tag.md create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/docs/User.md create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/docs/UserApi.md rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/git_push.sh (100%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/gradle.properties (100%) create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/gradle/wrapper/gradle-wrapper.jar create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/gradle/wrapper/gradle-wrapper.properties rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/gradlew (100%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/gradlew.bat (100%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/pom.xml (100%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/settings.gradle (100%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/AndroidManifest.xml (100%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/ApiCallback.java (100%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/ApiClient.java (100%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/ApiException.java (100%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/ApiResponse.java (100%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/Configuration.java (100%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/JSON.java (100%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/Pair.java (100%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/ProgressRequestBody.java (100%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/ProgressResponseBody.java (100%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/StringUtil.java (100%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/api/FakeApi.java (100%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/api/PetApi.java (100%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/api/StoreApi.java (100%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/api/UserApi.java (100%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/auth/ApiKeyAuth.java (100%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/auth/Authentication.java (100%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/auth/HttpBasicAuth.java (100%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/auth/OAuth.java (100%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/auth/OAuthFlow.java (100%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java (81%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/model/Animal.java (81%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/model/AnimalFarm.java (75%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java (78%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java (79%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/model/ArrayTest.java (83%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/model/Cat.java (71%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/model/Category.java (80%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/model/Dog.java (70%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/model/EnumClass.java (96%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/model/EnumTest.java (85%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/model/FormatTest.java (85%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java (77%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/model/MapTest.java (84%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java (78%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/model/Model200Response.java (80%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/model/ModelApiResponse.java (80%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/model/ModelReturn.java (79%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/model/Name.java (82%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/model/NumberOnly.java (79%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/model/Order.java (85%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/model/Pet.java (85%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/model/ReadOnlyFirst.java (78%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/model/SpecialModelName.java (79%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/model/Tag.java (81%) rename samples/client/petstore/java/{okhttp-gson => okhttp-gson-parcelableModel}/src/main/java/io/swagger/client/model/User.java (84%) create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/FakeApiTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/PetApiTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/StoreApiTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/UserApiTest.java diff --git a/bin/java-petstore-okhttp-gson-parcelable.sh b/bin/java-petstore-okhttp-gson-parcelable.sh new file mode 100755 index 00000000000..e3fcd52c478 --- /dev/null +++ b/bin/java-petstore-okhttp-gson-parcelable.sh @@ -0,0 +1,33 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-okhttp-gson.json -o samples/client/petstore/java/okhttp-gson-parcelableModel -DhideGenerationTimestamp=true,parcelableModel=true" + +rm -rf samples/client/petstore/java/okhttp-gson/src/main +find samples/client/petstore/java/okhttp-gson -maxdepth 1 -type f ! -name "README.md" -exec rm {} + +java $JAVA_OPTS -jar $executable $ags diff --git a/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 835dc63d1ca..3fe56dcd203 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 @@ -74,8 +74,10 @@ public void processOpts() { this.setUseRxJava(Boolean.valueOf(additionalProperties.get(USE_RX_JAVA).toString())); } if (additionalProperties.containsKey(PARCELABLE_MODEL)) { - this.setParcelableModels(Boolean.valueOf(additionalProperties.get(PARCELABLE_MODEL).toString())); + this.setParcelableModel(Boolean.valueOf(additionalProperties.get(PARCELABLE_MODEL).toString())); } + // put the boolean value back to PARCELABLE_MODEL in additionalProperties + additionalProperties.put(PARCELABLE_MODEL, parcelableModel); final String invokerFolder = (sourceFolder + '/' + invokerPackage).replace(".", "/"); final String authFolder = (sourceFolder + '/' + invokerPackage + ".auth").replace(".", "/"); @@ -223,7 +225,7 @@ public void setUseRxJava(boolean useRxJava) { this.useRxJava = useRxJava; } - public void setParcelableModels(boolean parcelableModel) { + public void setParcelableModel(boolean parcelableModel) { this.parcelableModel = parcelableModel; } } diff --git a/modules/swagger-codegen/src/main/resources/Java/model.mustache b/modules/swagger-codegen/src/main/resources/Java/model.mustache index fa9bc359024..31148bafcec 100644 --- a/modules/swagger-codegen/src/main/resources/Java/model.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/model.mustache @@ -6,10 +6,14 @@ import java.util.Objects; {{#imports}} import {{import}}; {{/imports}} +{{#serializableModel}} +import java.io.Serializable; +{{/serializableModel}} +{{#parcelableModel}} +import android.os.Parcelable; +import android.os.Parcel; +{{/parcelableModel}} -{{#serializableModel}}import java.io.Serializable;{{/serializableModel}} -{{#parcelableModel}}import android.os.Parcelable; -import android.os.Parcel;{{/parcelableModel}} {{#models}} {{#model}} {{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{>pojo}}{{/isEnum}} diff --git a/samples/client/petstore/java/okhttp-gson/.gitignore b/samples/client/petstore/java/okhttp-gson-parcelableModel/.gitignore similarity index 100% rename from samples/client/petstore/java/okhttp-gson/.gitignore rename to samples/client/petstore/java/okhttp-gson-parcelableModel/.gitignore diff --git a/samples/client/petstore/java/okhttp-gson/.swagger-codegen-ignore b/samples/client/petstore/java/okhttp-gson-parcelableModel/.swagger-codegen-ignore similarity index 100% rename from samples/client/petstore/java/okhttp-gson/.swagger-codegen-ignore rename to samples/client/petstore/java/okhttp-gson-parcelableModel/.swagger-codegen-ignore diff --git a/samples/client/petstore/java/okhttp-gson/.travis.yml b/samples/client/petstore/java/okhttp-gson-parcelableModel/.travis.yml similarity index 100% rename from samples/client/petstore/java/okhttp-gson/.travis.yml rename to samples/client/petstore/java/okhttp-gson-parcelableModel/.travis.yml diff --git a/samples/client/petstore/java/okhttp-gson/LICENSE b/samples/client/petstore/java/okhttp-gson-parcelableModel/LICENSE similarity index 100% rename from samples/client/petstore/java/okhttp-gson/LICENSE rename to samples/client/petstore/java/okhttp-gson-parcelableModel/LICENSE diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/README.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/README.md new file mode 100644 index 00000000000..8266ae87a9c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/README.md @@ -0,0 +1,183 @@ +# swagger-petstore-okhttp-gson + +## Requirements + +Building the API client library requires [Maven](https://maven.apache.org/) to be installed. + +## Installation + +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. + +### Maven users + +Add this dependency to your project's POM: + +```xml + + io.swagger + swagger-petstore-okhttp-gson + 1.0.0 + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy +compile "io.swagger:swagger-petstore-okhttp-gson:1.0.0" +``` + +### Others + +At first generate the JAR by executing: + + mvn package + +Then manually install the following JARs: + +* target/swagger-petstore-okhttp-gson-1.0.0.jar +* target/lib/*.jar + +## Getting Started + +Please follow the [installation](#installation) instruction and execute the following Java code: + +```java + +import io.swagger.client.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; +import io.swagger.client.api.FakeApi; + +import java.io.File; +import java.util.*; + +public class FakeApiExample { + + public static void main(String[] args) { + + FakeApi apiInstance = new FakeApi(); + BigDecimal number = new BigDecimal(); // BigDecimal | None + Double _double = 3.4D; // Double | None + String string = "string_example"; // String | None + byte[] _byte = B; // byte[] | None + Integer integer = 56; // Integer | None + Integer int32 = 56; // Integer | None + Long int64 = 789L; // Long | None + Float _float = 3.4F; // Float | None + byte[] binary = B; // byte[] | None + LocalDate date = new LocalDate(); // LocalDate | None + DateTime dateTime = new DateTime(); // DateTime | None + String password = "password_example"; // String | None + try { + apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEndpointParameters"); + e.printStackTrace(); + } + } +} + +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*FakeApi* | [**testEndpointParameters**](docs/FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeApi* | [**testEnumQueryParameters**](docs/FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters +*PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**deletePet**](docs/PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByStatus**](docs/PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**findPetsByTags**](docs/PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**getPetById**](docs/PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**updatePet**](docs/PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +*PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**uploadFile**](docs/PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**getInventory**](docs/StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**getOrderById**](docs/StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**placeOrder**](docs/StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**createUser**](docs/UserApi.md#createUser) | **POST** /user | Create user +*UserApi* | [**createUsersWithArrayInput**](docs/UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**createUsersWithListInput**](docs/UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**deleteUser**](docs/UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**getUserByName**](docs/UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +*UserApi* | [**loginUser**](docs/UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +*UserApi* | [**logoutUser**](docs/UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**updateUser**](docs/UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + +## Documentation for Models + + - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) + - [Animal](docs/Animal.md) + - [AnimalFarm](docs/AnimalFarm.md) + - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) + - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) + - [ArrayTest](docs/ArrayTest.md) + - [Cat](docs/Cat.md) + - [Category](docs/Category.md) + - [Dog](docs/Dog.md) + - [EnumClass](docs/EnumClass.md) + - [EnumTest](docs/EnumTest.md) + - [FormatTest](docs/FormatTest.md) + - [HasOnlyReadOnly](docs/HasOnlyReadOnly.md) + - [MapTest](docs/MapTest.md) + - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) + - [Model200Response](docs/Model200Response.md) + - [ModelApiResponse](docs/ModelApiResponse.md) + - [ModelReturn](docs/ModelReturn.md) + - [Name](docs/Name.md) + - [NumberOnly](docs/NumberOnly.md) + - [Order](docs/Order.md) + - [Pet](docs/Pet.md) + - [ReadOnlyFirst](docs/ReadOnlyFirst.md) + - [SpecialModelName](docs/SpecialModelName.md) + - [Tag](docs/Tag.md) + - [User](docs/User.md) + + +## Documentation for Authorization + +Authentication schemes defined for the API: +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + +### petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorizatoin URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - write:pets: modify pets in your account + - read:pets: read your pets + + +## 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/okhttp-gson/build.gradle b/samples/client/petstore/java/okhttp-gson-parcelableModel/build.gradle similarity index 100% rename from samples/client/petstore/java/okhttp-gson/build.gradle rename to samples/client/petstore/java/okhttp-gson-parcelableModel/build.gradle diff --git a/samples/client/petstore/java/okhttp-gson/build.sbt b/samples/client/petstore/java/okhttp-gson-parcelableModel/build.sbt similarity index 100% rename from samples/client/petstore/java/okhttp-gson/build.sbt rename to samples/client/petstore/java/okhttp-gson-parcelableModel/build.sbt diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/AdditionalPropertiesClass.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..0437c4dd8cc --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/AdditionalPropertiesClass.md @@ -0,0 +1,11 @@ + +# AdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapProperty** | **Map<String, String>** | | [optional] +**mapOfMapProperty** | [**Map<String, Map<String, String>>**](Map.md) | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Animal.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Animal.md new file mode 100644 index 00000000000..b3f325c3524 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Animal.md @@ -0,0 +1,11 @@ + +# Animal + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/AnimalFarm.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/AnimalFarm.md new file mode 100644 index 00000000000..c7c7f1ddcce --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/AnimalFarm.md @@ -0,0 +1,9 @@ + +# AnimalFarm + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 00000000000..77292549927 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ArrayOfArrayOfNumberOnly.md @@ -0,0 +1,10 @@ + +# ArrayOfArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayArrayNumber** | [**List<List<BigDecimal>>**](List.md) | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ArrayOfNumberOnly.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ArrayOfNumberOnly.md new file mode 100644 index 00000000000..e8cc4cd36dc --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ArrayOfNumberOnly.md @@ -0,0 +1,10 @@ + +# ArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayNumber** | [**List<BigDecimal>**](BigDecimal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ArrayTest.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ArrayTest.md new file mode 100644 index 00000000000..9feee16427f --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ArrayTest.md @@ -0,0 +1,12 @@ + +# ArrayTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayOfString** | **List<String>** | | [optional] +**arrayArrayOfInteger** | [**List<List<Long>>**](List.md) | | [optional] +**arrayArrayOfModel** | [**List<List<ReadOnlyFirst>>**](List.md) | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Cat.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Cat.md new file mode 100644 index 00000000000..be6e56fa8ce --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Cat.md @@ -0,0 +1,12 @@ + +# Cat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | [optional] +**declawed** | **Boolean** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Category.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Category.md new file mode 100644 index 00000000000..e2df0803278 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Category.md @@ -0,0 +1,11 @@ + +# Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**name** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Dog.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Dog.md new file mode 100644 index 00000000000..71a7dbe809e --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Dog.md @@ -0,0 +1,12 @@ + +# Dog + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | [optional] +**breed** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/EnumClass.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/EnumClass.md new file mode 100644 index 00000000000..c746edc3cb1 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/EnumClass.md @@ -0,0 +1,14 @@ + +# EnumClass + +## Enum + + +* `_ABC` (value: `"_abc"`) + +* `_EFG` (value: `"-efg"`) + +* `_XYZ_` (value: `"(xyz)"`) + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/EnumTest.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/EnumTest.md new file mode 100644 index 00000000000..deb1951c552 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/EnumTest.md @@ -0,0 +1,36 @@ + +# EnumTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enumString** | [**EnumStringEnum**](#EnumStringEnum) | | [optional] +**enumInteger** | [**EnumIntegerEnum**](#EnumIntegerEnum) | | [optional] +**enumNumber** | [**EnumNumberEnum**](#EnumNumberEnum) | | [optional] + + + +## Enum: EnumStringEnum +Name | Value +---- | ----- +UPPER | "UPPER" +LOWER | "lower" + + + +## Enum: EnumIntegerEnum +Name | Value +---- | ----- +NUMBER_1 | 1 +NUMBER_MINUS_1 | -1 + + + +## Enum: EnumNumberEnum +Name | Value +---- | ----- +NUMBER_1_DOT_1 | 1.1 +NUMBER_MINUS_1_DOT_2 | -1.2 + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/FakeApi.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/FakeApi.md new file mode 100644 index 00000000000..21a4db7c377 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/FakeApi.md @@ -0,0 +1,122 @@ +# FakeApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters + + + +# **testEndpointParameters** +> testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +BigDecimal number = new BigDecimal(); // BigDecimal | None +Double _double = 3.4D; // Double | None +String string = "string_example"; // String | None +byte[] _byte = B; // byte[] | None +Integer integer = 56; // Integer | None +Integer int32 = 56; // Integer | None +Long int64 = 789L; // Long | None +Float _float = 3.4F; // Float | None +byte[] binary = B; // byte[] | None +LocalDate date = new LocalDate(); // LocalDate | None +DateTime dateTime = new DateTime(); // DateTime | None +String password = "password_example"; // String | None +try { + apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEndpointParameters"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **number** | **BigDecimal**| None | + **_double** | **Double**| None | + **string** | **String**| None | + **_byte** | **byte[]**| None | + **integer** | **Integer**| None | [optional] + **int32** | **Integer**| None | [optional] + **int64** | **Long**| None | [optional] + **_float** | **Float**| None | [optional] + **binary** | **byte[]**| None | [optional] + **date** | **LocalDate**| None | [optional] + **dateTime** | **DateTime**| None | [optional] + **password** | **String**| None | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/xml; charset=utf-8, application/json; charset=utf-8 + - **Accept**: application/xml; charset=utf-8, application/json; charset=utf-8 + + +# **testEnumQueryParameters** +> testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble) + +To test enum query parameters + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +String enumQueryString = "-efg"; // String | Query parameter enum test (string) +BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | Query parameter enum test (double) +Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) +try { + apiInstance.testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEnumQueryParameters"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + **enumQueryInteger** | **BigDecimal**| Query parameter enum test (double) | [optional] + **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/FormatTest.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/FormatTest.md new file mode 100644 index 00000000000..44de7d9511a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/FormatTest.md @@ -0,0 +1,22 @@ + +# FormatTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**integer** | **Integer** | | [optional] +**int32** | **Integer** | | [optional] +**int64** | **Long** | | [optional] +**number** | [**BigDecimal**](BigDecimal.md) | | +**_float** | **Float** | | [optional] +**_double** | **Double** | | [optional] +**string** | **String** | | [optional] +**_byte** | **byte[]** | | +**binary** | **byte[]** | | [optional] +**date** | [**LocalDate**](LocalDate.md) | | +**dateTime** | [**DateTime**](DateTime.md) | | [optional] +**uuid** | **String** | | [optional] +**password** | **String** | | + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/HasOnlyReadOnly.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/HasOnlyReadOnly.md new file mode 100644 index 00000000000..c1d0aac5672 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/HasOnlyReadOnly.md @@ -0,0 +1,11 @@ + +# HasOnlyReadOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] +**foo** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/MapTest.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/MapTest.md new file mode 100644 index 00000000000..c671e97ffbc --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/MapTest.md @@ -0,0 +1,17 @@ + +# MapTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapMapOfString** | [**Map<String, Map<String, String>>**](Map.md) | | [optional] +**mapOfEnumString** | [**Map<String, InnerEnum>**](#Map<String, InnerEnum>) | | [optional] + + + +## Enum: Map<String, InnerEnum> +Name | Value +---- | ----- + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..e3487bcc501 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,12 @@ + +# MixedPropertiesAndAdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | **String** | | [optional] +**dateTime** | [**DateTime**](DateTime.md) | | [optional] +**map** | [**Map<String, Animal>**](Animal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Model200Response.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Model200Response.md new file mode 100644 index 00000000000..b47618b28cc --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Model200Response.md @@ -0,0 +1,11 @@ + +# Model200Response + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Integer** | | [optional] +**PropertyClass** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ModelApiResponse.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ModelApiResponse.md new file mode 100644 index 00000000000..3eec8686cc9 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ModelApiResponse.md @@ -0,0 +1,12 @@ + +# ModelApiResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **Integer** | | [optional] +**type** | **String** | | [optional] +**message** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ModelReturn.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ModelReturn.md new file mode 100644 index 00000000000..a679b04953e --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ModelReturn.md @@ -0,0 +1,10 @@ + +# ModelReturn + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_return** | **Integer** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Name.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Name.md new file mode 100644 index 00000000000..ce2fb4dee50 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Name.md @@ -0,0 +1,13 @@ + +# Name + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Integer** | | +**snakeCase** | **Integer** | | [optional] +**property** | **String** | | [optional] +**_123Number** | **Integer** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/NumberOnly.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/NumberOnly.md new file mode 100644 index 00000000000..a3feac7fadc --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/NumberOnly.md @@ -0,0 +1,10 @@ + +# NumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**justNumber** | [**BigDecimal**](BigDecimal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Order.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Order.md new file mode 100644 index 00000000000..a1089f5384e --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Order.md @@ -0,0 +1,24 @@ + +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**petId** | **Long** | | [optional] +**quantity** | **Integer** | | [optional] +**shipDate** | [**DateTime**](DateTime.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] +**complete** | **Boolean** | | [optional] + + + +## Enum: StatusEnum +Name | Value +---- | ----- +PLACED | "placed" +APPROVED | "approved" +DELIVERED | "delivered" + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Pet.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Pet.md new file mode 100644 index 00000000000..5b63109ef92 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Pet.md @@ -0,0 +1,24 @@ + +# Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**name** | **String** | | +**photoUrls** | **List<String>** | | +**tags** | [**List<Tag>**](Tag.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] + + + +## Enum: StatusEnum +Name | Value +---- | ----- +AVAILABLE | "available" +PENDING | "pending" +SOLD | "sold" + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/PetApi.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/PetApi.md new file mode 100644 index 00000000000..e0314e20e51 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/PetApi.md @@ -0,0 +1,448 @@ +# PetApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image + + + +# **addPet** +> addPet(body) + +Add a new pet to the store + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Pet body = new Pet(); // Pet | Pet object that needs to be added to the store +try { + apiInstance.addPet(body); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#addPet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/xml, application/json + + +# **deletePet** +> deletePet(petId, apiKey) + +Deletes a pet + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | Pet id to delete +String apiKey = "apiKey_example"; // String | +try { + apiInstance.deletePet(petId, apiKey); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#deletePet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| Pet id to delete | + **apiKey** | **String**| | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **findPetsByStatus** +> List<Pet> findPetsByStatus(status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +List status = Arrays.asList("status_example"); // List | Status values that need to be considered for filter +try { + List result = apiInstance.findPetsByStatus(status); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByStatus"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **findPetsByTags** +> List<Pet> findPetsByTags(tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +List tags = Arrays.asList("tags_example"); // List | Tags to filter by +try { + List result = apiInstance.findPetsByTags(tags); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByTags"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**List<String>**](String.md)| Tags to filter by | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **getPetById** +> Pet getPetById(petId) + +Find pet by ID + +Returns a single pet + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure API key authorization: api_key +ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); +api_key.setApiKey("YOUR API KEY"); +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//api_key.setApiKeyPrefix("Token"); + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | ID of pet to return +try { + Pet result = apiInstance.getPetById(petId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#getPetById"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **updatePet** +> updatePet(body) + +Update an existing pet + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Pet body = new Pet(); // Pet | Pet object that needs to be added to the store +try { + apiInstance.updatePet(body); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/xml, application/json + + +# **updatePetWithForm** +> updatePetWithForm(petId, name, status) + +Updates a pet in the store with form data + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | ID of pet that needs to be updated +String name = "name_example"; // String | Updated name of the pet +String status = "status_example"; // String | Updated status of the pet +try { + apiInstance.updatePetWithForm(petId, name, status); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePetWithForm"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet that needs to be updated | + **name** | **String**| Updated name of the pet | [optional] + **status** | **String**| Updated status of the pet | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: application/xml, application/json + + +# **uploadFile** +> ModelApiResponse uploadFile(petId, additionalMetadata, file) + +uploads an image + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | ID of pet to update +String additionalMetadata = "additionalMetadata_example"; // String | Additional data to pass to server +File file = new File("/path/to/file.txt"); // File | file to upload +try { + ModelApiResponse result = apiInstance.uploadFile(petId, additionalMetadata, file); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#uploadFile"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to update | + **additionalMetadata** | **String**| Additional data to pass to server | [optional] + **file** | **File**| file to upload | [optional] + +### Return type + +[**ModelApiResponse**](ModelApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ReadOnlyFirst.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..426b7cde95a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/ReadOnlyFirst.md @@ -0,0 +1,11 @@ + +# ReadOnlyFirst + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] +**baz** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/SpecialModelName.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/SpecialModelName.md new file mode 100644 index 00000000000..c2c6117c552 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/SpecialModelName.md @@ -0,0 +1,10 @@ + +# SpecialModelName + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**specialPropertyName** | **Long** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/StoreApi.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/StoreApi.md new file mode 100644 index 00000000000..0b30791725a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/StoreApi.md @@ -0,0 +1,197 @@ +# StoreApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet + + + +# **deleteOrder** +> deleteOrder(orderId) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +String orderId = "orderId_example"; // String | ID of the order that needs to be deleted +try { + apiInstance.deleteOrder(orderId); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#deleteOrder"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **String**| ID of the order that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **getInventory** +> Map<String, Integer> getInventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.StoreApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure API key authorization: api_key +ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); +api_key.setApiKey("YOUR API KEY"); +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//api_key.setApiKeyPrefix("Token"); + +StoreApi apiInstance = new StoreApi(); +try { + Map result = apiInstance.getInventory(); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getInventory"); + e.printStackTrace(); +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**Map<String, Integer>**](Map.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +# **getOrderById** +> Order getOrderById(orderId) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +Long orderId = 789L; // Long | ID of pet that needs to be fetched +try { + Order result = apiInstance.getOrderById(orderId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getOrderById"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **Long**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **placeOrder** +> Order placeOrder(body) + +Place an order for a pet + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +Order body = new Order(); // Order | order placed for purchasing the pet +try { + Order result = apiInstance.placeOrder(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#placeOrder"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Tag.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Tag.md new file mode 100644 index 00000000000..de6814b55d5 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/Tag.md @@ -0,0 +1,11 @@ + +# Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**name** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/User.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/User.md new file mode 100644 index 00000000000..8b6753dd284 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/User.md @@ -0,0 +1,17 @@ + +# User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**username** | **String** | | [optional] +**firstName** | **String** | | [optional] +**lastName** | **String** | | [optional] +**email** | **String** | | [optional] +**password** | **String** | | [optional] +**phone** | **String** | | [optional] +**userStatus** | **Integer** | User Status | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/UserApi.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/UserApi.md new file mode 100644 index 00000000000..8cdc15992ee --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/UserApi.md @@ -0,0 +1,370 @@ +# UserApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createUser**](UserApi.md#createUser) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + + +# **createUser** +> createUser(body) + +Create user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +User body = new User(); // User | Created user object +try { + apiInstance.createUser(body); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md)| Created user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **createUsersWithArrayInput** +> createUsersWithArrayInput(body) + +Creates list of users with given input array + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +List body = Arrays.asList(new User()); // List | List of user object +try { + apiInstance.createUsersWithArrayInput(body); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithArrayInput"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List<User>**](User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **createUsersWithListInput** +> createUsersWithListInput(body) + +Creates list of users with given input array + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +List body = Arrays.asList(new User()); // List | List of user object +try { + apiInstance.createUsersWithListInput(body); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithListInput"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List<User>**](User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **deleteUser** +> deleteUser(username) + +Delete user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The name that needs to be deleted +try { + apiInstance.deleteUser(username); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#deleteUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **getUserByName** +> User getUserByName(username) + +Get user by user name + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The name that needs to be fetched. Use user1 for testing. +try { + User result = apiInstance.getUserByName(username); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#getUserByName"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **loginUser** +> String loginUser(username, password) + +Logs user into the system + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The user name for login +String password = "password_example"; // String | The password for login in clear text +try { + String result = apiInstance.loginUser(username, password); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#loginUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The user name for login | + **password** | **String**| The password for login in clear text | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **logoutUser** +> logoutUser() + +Logs out current logged in user session + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +try { + apiInstance.logoutUser(); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#logoutUser"); + e.printStackTrace(); +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **updateUser** +> updateUser(username, body) + +Updated user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | name that need to be deleted +User body = new User(); // User | Updated user object +try { + apiInstance.updateUser(username, body); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#updateUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| name that need to be deleted | + **body** | [**User**](User.md)| Updated user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + diff --git a/samples/client/petstore/java/okhttp-gson/git_push.sh b/samples/client/petstore/java/okhttp-gson-parcelableModel/git_push.sh similarity index 100% rename from samples/client/petstore/java/okhttp-gson/git_push.sh rename to samples/client/petstore/java/okhttp-gson-parcelableModel/git_push.sh diff --git a/samples/client/petstore/java/okhttp-gson/gradle.properties b/samples/client/petstore/java/okhttp-gson-parcelableModel/gradle.properties similarity index 100% rename from samples/client/petstore/java/okhttp-gson/gradle.properties rename to samples/client/petstore/java/okhttp-gson-parcelableModel/gradle.properties diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/java/okhttp-gson-parcelableModel/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..2c6137b87896c8f70315ae454e00a969ef5f6019 GIT binary patch literal 53639 zcmafaW0a=B^559DjdyI@wr$%scWm3Xy<^+Pj_sKpY&N+!|K#4>Bz;ajPk*RBjZ;RV75EK*;qpZCo(BB5~-#>pF^k0$_Qx&3rs}{XFZ)$uJU-ZpbB>L3?|knJ{J+ge{%=bI`#Yn9v&Fxx>fd=_|H)(FY-DO{ z_Wxu>{a02GXCp^PGw1(fh-I*;dGTM?mA^##pNEJ#c-Y%I7@3kW(VN&Bxw!bn$iWOU zB8BZ)vT4(}GX%q~h3EYwbR?$d6|xnvg_e@4>dl5l+%FtPbGqa`;Uk##t$#g&CK4GO zz%my0ZR1Fv@~b2_>T0cBP)ECz-Uc^nW9e+`W4!=mSJPopgoe3A(NMzBd0mR?$&3XA zRL1}bJ2Q%R#bWHrC`j_)tPKMEyHuGSpdJMhT(Ob(e9H+#=Skp%#jzj=BVvc(-RSWB z{_T`UcEeWD{z`!3-y;_N|Ljr4%f;2qPSM%n?_s%GnYsM!d3p)CxmudpyIPqTxjH!i z;}A+!>>N;pko++K5n~I7m4>yco2%Zc$59RohB(l%KcJc9s^nw^?2JGy>O4#x5+CZH zqU~7kA>WE)ngvsdfKhLUX0Lc3r+In0Uyn}LZhm?n){&LHNJws546du%pia=j zyH8CD{^Qx%kFe@kX*$B!DxLa(Y?BO32sm8%#_ynjU-m>PJbabL`~0Ai zeJm<6okftSJUd2!X(>}i#KAh-NR2!Kg%c2JD=G|T%@Q0JQzqKB)Qc4E-{ZF=#PGZg zior4-caRB-Jj;l}Xb_!)TjB`jC}})6z~3AsRE&t~CO&)g{dqM0iK;lvav8?kE1< zmCrHxDZe?&rEK7M4tG-i!`Zk-*IzSk0M0&Ul8+J>*UD(A^;bAFDcz>d&lzAlw}b## zjfu@)rAou-86EN%8_Nv;%bNUmy*<6sbgB9)ZCihdSh_VT2iGFv+T8p&Z&wO02nKtdx?eZh^=*<>SZHSn(Pv)bgn{ zb15>YnVnJ^PO025c~^uK&W1C1XTs1az44L~-9Z-fU3{VvA?T& zdpi&S`mZ|$tMuN{{i|O}fAx#*KkroHe;6z^7c*x`2Rk!a2L~HB$A4@(Rz*hvM+og( zJW+4;S-A$#+Gec-rn8}at+q5gRrNy^iU?Z4Gz_|qzS~sG_EV#m%-VW!jQ>f3jc-Vq zW;~>OqI1Th&*fx#`c^=|A4GGoDp+ZH!n0_fDo-ks3d&GlT=(qzr(?Qw`PHvo3PoU6YJE zu{35)=P`LRm@+=ziAI)7jktM6KHx*v&WHVBYp<~UtR3c?Wv_{a0(k&NF!o#+@|Y6Y z>{||-i0v8N2ntXRrVx~#Z1JMA3C2ki}OkJ4W`WjZIuLByNUEL2HqqKrbi{9a8` zk-w0I$a<6;W6&X<&EbIqul`;nvc+D~{g5al{0oOSp~ zhg;6nG1Bh-XyOBM63jb_z`7apSsta``K{!Q{}mZ!m4rTmWi^<*BN2dh#PLZ)oXIJY zl#I3@$+8Fvi)m<}lK_}7q~VN%BvT^{q~ayRA7mwHO;*r0ePSK*OFv_{`3m+96HKgt z=nD-=Pv90Ae1p)+SPLT&g(Fdqbcc(Vnk5SFyc|Tq08qS;FJ1K4rBmtns%Su=GZchE zR(^9W-y!{QfeVPBeHpaBA{TZpQ*(d$H-*GI)Y}>X2Lk&27aFkqXE7D?G_iGav2r&P zx3V=8GBGi8agj5!H?lDMr`1nYmvKZj!~0{GMPb!tM=VIJXbTk9q8JRoSPD*CH@4I+ zfG-6{Z=Yb->)MIUmXq-#;=lNCyF1G*W+tW6gdD||kQfW$J_@=Y9KmMD!(t#9-fPcJ z>%&KQC-`%E`{y^i!1u=rJP_hhGErM$GYE3Y@ZzzA2a-PC>yaoDziZT#l+y)tfyR}U z5Epq`ACY|VUVISHESM5$BpWC0FpDRK&qi?G-q%Rd8UwIq&`d(Mqa<@(fH!OfNIgFICEG?j_Gj7FS()kY^P(I!zbl`%HB z7Rx=q2vZFjy^XypORT$^NJv_`Vm7-gkJWYsN5xg>snt5%oG?w1K#l_UH<>4@d0G@3 z)r?|yba6;ksyc+5+8YZ?)NZ+ER!4fIzK>>cs^(;ib7M}asT&)+J=J@U^~ffJ>65V# zt_lyUp52t`vT&gcQ%a6Ca)p8u6v}3iJzf?zsx#e9t)-1OtqD$Mky&Lpz6_v?p0|y4 zI{Nq9z89OxQbsqX)UYj z(BGu`28f8C^e9R2jf0Turq;v+fPCWD*z8!8-Q-_s`ILgwo@mtnjpC_D$J zCz7-()9@8rQ{4qy<5;*%bvX3k$grUQ{Bt;B#w))A+7ih631uN?!_~?i^g+zO^lGK$>O1T1$6VdF~%FKR6~Px%M`ibJG*~uQ>o^r9qLo*`@^ry@KX^$LH0>NGPL%MG8|;8 z@_)h2uvB1M!qjGtZgy~7-O=GUa`&;xEFvC zwIt?+O;Fjwgn3aE%`_XfZEw5ayP+JS8x?I|V3ARbQ5@{JAl1E*5a{Ytc(UkoDKtD# zu)K4XIYno7h3)0~5&93}pMJMDr*mcYM|#(FXS@Pj)(2!cl$)R-GwwrpOW!zZ2|wN) zE|B38xr4_NBv|%_Lpnm$We<_~S{F1x42tph3PAS`0saF^PisF6EDtce+9y6jdITmu zqI-CLeTn2%I3t3z_=e=YGzUX6i5SEujY`j|=aqv#(Q=iWPkKhau@g|%#xVC2$6<{2 zAoimy5vLq6rvBo3rv&^VqtaKt_@Vx^gWN{f4^@i6H??!ra^_KC-ShWC(GBNt3o~T^ zudX<0v!;s$rIflR?~Tu4-D=%~E=glv+1|pg*ea30re-2K@8EqQ{8#WY4X-br_!qpq zL;PRCi^e~EClLpGb1MrsXCqfD2m615mt;EyR3W6XKU=4(A^gFCMMWgn#5o1~EYOH* zOlolGlD;B!j%lRFaoc)q_bOH-O!r}g1Bhlhy*dRoTf-bI%`A`kU)Q=HA9HgCKqq&A z2$_rtL-uIA7`PiJfw380j@M4Fff-?(Xe(aR`4>BZyDN2$2E7QQ1}95@X819fnA(}= za=5VF-%;l}aHSRHCfs(#Qf%dPue~fGpy7qPs*eLX2Aa0+@mPxnS4Wm8@kP7KEL)8s z@tNmawLHST-FS4h%20%lVvd zkXpxWa43E`zX{6-{2c+L9C`l(ZRG8`kO9g7t&hx?>j~5_C;y5u*Bvl79)Bq?@T7bN z=G2?QDa0J3VwCfZG0BjOFP>xz4jtv3LS>jz#1x~b9u1*n9>Y6?u8W?I^~;N{GC<1y} zc&Wz{L`kJUSt=oA=5ZHtNj3PSB%w5^=0(U7GC^zUgcdkujo>ruzyBurtTjKuNf1-+ zzn~oZFXCbR&xq&W{ar~T`@fNef5M$u^-C92HMBo=*``D8Q^ktX z(qT{_R=*EI?-R9nNUFNR#{(Qb;27bM14bjI`c#4RiinHbnS445Jy^%krK%kpE zFw%RVQd6kqsNbiBtH*#jiPu3(%}P7Vhs0G9&Dwb4E-hXO!|whZ!O$J-PU@j#;GrzN zwP9o=l~Nv}4OPvv5rVNoFN>Oj0TC%P>ykicmFOx*dyCs@7XBH|w1k2hb`|3|i^GEL zyg7PRl9eV ztQ1z)v~NwH$ebcMSKc-4D=?G^3sKVG47ZWldhR@SHCr}SwWuj5t!W$&HAA*Wo_9tM zw5vs`2clw`z@~R-#W8d4B8!rFtO}+-$-{6f_`O-^-EhGraqg%$D618&<9KG``D|Rb zQJ&TSE3cfgf8i}I^DLu+-z{{;QM>K3I9~3R9!0~=Y`A1=6`CF#XVH@MWO?3@xa6ev zdw08_9L=>3%)iXA(_CE@ipRQ{Tb+@mxoN^3ktgmt^mJ(u#=_Plt?5qMZOA3&I1&NU zOG+0XTsIkbhGsp(ApF2MphRG^)>vqagn!-%pRnppa%`-l@DLS0KUm8*e9jGT0F%0J z*-6E@Z*YyeZ{eP7DGmxQedo}^+w zM~>&E$5&SW6MxP##J56Eo@0P34XG})MLCuhMyDFf**?tziO?_Ad&Jhd z`jok^B{3ff*7cydrxYjdxX`14`S+34kW^$fxDmNn2%fsQ6+Zou0%U{3Y>L}UIbQbw z*E#{Von}~UEAL?vvihW)4?Kr-R?_?JSN?B?QzhUWj==1VNEieTMuTJ#-nl*c@qP+` zGk@aE0oAD5!9_fO=tDQAt9g0rKTr{Z0t~S#oy5?F3&aWm+igqKi| zK9W3KRS|1so|~dx%90o9+FVuN7)O@by^mL=IX_m^M87i&kT1^#9TCpI@diZ_p$uW3 zbA+-ER9vJ{ii?QIZF=cfZT3#vJEKC|BQhNd zGmxBDLEMnuc*AET~k8g-P-K+S~_(+GE9q6jyIMka(dr}(H% z$*z;JDnyI@6BQ7KGcrv03Hn(abJ_-vqS>5~m*;ZJmH$W`@csQ8ejiC8S#sYTB;AoF zXsd!kDTG#3FOo-iJJpd$C~@8}GQJ$b1A85MXp?1#dHWQu@j~i4L*LG40J}+V=&-(g zh~Hzk(l1$_y}PX}Ypluyiib0%vwSqPaJdy9EZ;?+;lFF8%Kb7cwPD17C}@N z2OF;}QCM4;CDx~d;XnunQAx5mQbL#);}H57I+uB9^v|cmZwuXGkoH-cAJ%nIjSO$E z{BpYdC9poyO5pvdL+ZPWFuK}c8WGEq-#I3myONq^BL%uG`RIoSBTEK9sAeU4UBh7f zzM$s|&NtAGN&>`lp5Ruc%qO^oL;VGnzo9A8{fQn@YoORA>qw;^n2pydq>;Ji9(sPH zLGsEeTIH?_6C3uyWoW(gkmM(RhFkiDuQPXmL7Oes(+4)YIHt+B@i`*%0KcgL&A#ua zAjb8l_tO^Ag!ai3f54t?@{aoW%&Hdst}dglRzQlS=M{O!=?l z*xY2vJ?+#!70RO8<&N^R4p+f=z z*&_e}QT%6-R5Wt66moGfvorp$yE|3=-2_(y`FnL0-7A?h%4NMZ#F#Rcb^}971t5ib zw<20w|C?HVv%|)Q)Pef8tGjwQ+!+<{>IVjr@&SRVO*PyC?Efnsq;Eq{r;U2)1+tgp z)@pZ}gJmzf{m=K@7YA_8X#XK+)F465h%z38{V-K8k%&_GF+g^s&9o6^B-&|MDFI)H zj1ofQL>W(MJLOu3xkkJZV@$}GEG~XBz~WvRjxhT0$jKKZKjuKi$rmR-al}Hb3xDL) z^xGG2?5+vUAo4I;$(JgeVQe9+e)vvJ={pO~05f|J={%dsSLVcF>@F9p4|nYK&hMua zWjNvRod}l~WmGo|LX2j#w$r$y?v^H?Gu(_?(WR_%D@1I@$yMTKqD=Ca2) zWBQmx#A$gMrHe^A8kxAgB}c2R5)14G6%HfpDf$(Di|p8ntcN;Hnk)DR1;toC9zo77 zcWb?&&3h65(bLAte%hstI9o%hZ*{y=8t$^!y2E~tz^XUY2N2NChy;EIBmf(Kl zfU~&jf*}p(r;#MP4x5dI>i`vjo`w?`9^5(vfFjmWp`Ch!2Ig}rkpS|T%g@2h-%V~R zg!*o7OZSU-%)M8D>F^|z+2F|!u1mOt?5^zG%;{^CrV^J?diz9AmF!UsO?Pl79DKvD zo-2==yjbcF5oJY!oF?g)BKmC8-v|iL6VT|Gj!Gk5yaXfhs&GeR)OkZ}=q{exBPv)& zV!QTQBMNs>QQ))>(rZOn0PK+-`|7vKvrjky3-Kmuf8uJ`x6&wsA5S(tMf=m;79Hzv za%lZ(OhM&ZUCHtM~FRd#Uk3Iy%oXe^)!Jci39D(a$51WER+%gIZYP)!}nDtDw_FgPL3e>1ilFN=M(j~V` zjOtRhOB8bX8}*FD0oy}+s@r4XQT;OFH__cEn-G#aYHpJDI4&Zo4y2>uJdbPYe zOMGMvbA6#(p00i1{t~^;RaHmgZtE@we39mFaO0r|CJ0zUk$|1Pp60Q&$A;dm>MfP# zkfdw?=^9;jsLEXsccMOi<+0-z|NZb(#wwkcO)nVxJxkF3g(OvW4`m36ytfPx5e-ujFXf($)cVOn|qt9LL zNr!InmcuVkxEg8=_;E)+`>n2Y0eAIDrklnE=T9Pyct>^4h$VDDy>}JiA=W9JE79<6 zv%hpzeJC)TGX|(gP!MGWRhJV}!fa1mcvY%jC^(tbG3QIcQnTy&8UpPPvIekWM!R?R zKQanRv+YZn%s4bqv1LBgQ1PWcEa;-MVeCk`$^FLYR~v%9b-@&M%giqnFHV;5P5_et z@R`%W>@G<6GYa=JZ)JsNMN?47)5Y3@RY`EVOPzxj;z6bn#jZv|D?Fn#$b}F!a}D9{ ztB_roYj%34c-@~ehWM_z;B{G5;udhY`rBH0|+u#!&KLdnw z;!A%tG{%Ua;}OW$BG`B#^8#K$1wX2K$m`OwL-6;hmh{aiuyTz;U|EKES= z9UsxUpT^ZZyWk0;GO;Fe=hC`kPSL&1GWS7kGX0>+votm@V-lg&OR>0*!Iay>_|5OT zF0w~t01mupvy4&HYKnrG?sOsip%=<>nK}Bxth~}g)?=Ax94l_=mC{M@`bqiKtV5vf zIP!>8I;zHdxsaVt9K?{lXCc$%kKfIwh&WM__JhsA?o$!dzxP znoRU4ZdzeN3-W{6h~QQSos{-!W@sIMaM z4o?97?W5*cL~5%q+T@>q%L{Yvw(a2l&68hI0Ra*H=ZjU!-o@3(*7hIKo?I7$gfB(Vlr!62-_R-+T;I0eiE^><*1_t|scfB{r9+a%UxP~CBr zl1!X^l01w8o(|2da~Mca)>Mn}&rF!PhsP_RIU~7)B~VwKIruwlUIlOI5-yd4ci^m{ zBT(H*GvKNt=l7a~GUco)C*2t~7>2t?;V{gJm=WNtIhm4x%KY>Rm(EC^w3uA{0^_>p zM;Na<+I<&KwZOUKM-b0y6;HRov=GeEi&CqEG9^F_GR*0RSM3ukm2c2s{)0<%{+g78 zOyKO%^P(-(U09FO!75Pg@xA{p+1$*cD!3=CgW4NO*p}&H8&K`(HL&$TH2N-bf%?JL zVEWs;@_UDD7IoM&P^(k-U?Gs*sk=bLm+f1p$ggYKeR_7W>Zz|Dl{{o*iYiB1LHq`? ztT)b^6Pgk!Kn~ozynV`O(hsUI52|g{0{cwdQ+=&@$|!y8{pvUC_a5zCemee6?E{;P zVE9;@3w92Nu9m_|x24gtm23{ST8Bp;;iJlhaiH2DVcnYqot`tv>!xiUJXFEIMMP(ZV!_onqyQtB_&x}j9 z?LXw;&z%kyYjyP8CQ6X);-QW^?P1w}&HgM}irG~pOJ()IwwaDp!i2$|_{Ggvw$-%K zp=8N>0Fv-n%W6{A8g-tu7{73N#KzURZl;sb^L*d%leKXp2Ai(ZvO96T#6*!73GqCU z&U-NB*0p@?f;m~1MUN}mfdpBS5Q-dbhZ$$OWW=?t8bT+R5^vMUy$q$xY}ABi60bb_ z9;fj~2T2Ogtg8EDNr4j96{@+9bRP#Li7YDK1Jh8|Mo%NON|bYXi~D(W8oiC2SSE#p z=yQ0EP*}Z)$K$v?MJp8s=xroI@gSp&y!De;aik!U7?>3!sup&HY{6!eElc+?ZW*|3 zjJ;Nx>Kn@)3WP`{R821FpY6p1)yeJPi6yfq=EffesCZjO$#c;p!sc8{$>M-i#@fCt zw?GQV4MTSvDH(NlD2S*g-YnxCDp*%|z9^+|HQ(#XI0Pa8-Io=pz8C&Lp?23Y5JopL z!z_O3s+AY&`HT%KO}EB73{oTar{hg)6J7*KI;_Gy%V%-oO3t+vcyZ?;&%L z3t4A%Ltf=2+f8qITmoRfolL;I__Q8Z&K9*+_f#Sue$2C;xTS@%Z*z-lOAF-+gj1C$ zKEpt`_qg;q^41dggeNsJv#n=5i+6Wyf?4P_a=>s9n(ET_K|*zvh633Mv3Xm3OE!n` zFk^y65tStyk4aamG*+=5V^UePR2e0Fbt7g$({L1SjOel~1^9SmP2zGJ)RZX(>6u4^ zQ78wF_qtS~6b+t&mKM=w&Dt=k(oWMA^e&V#&Y5dFDc>oUn+OU0guB~h3};G1;X=v+ zs_8IR_~Y}&zD^=|P;U_xMA{Ekj+lHN@_n-4)_cHNj0gY4(Lx1*NJ^z9vO>+2_lm4N zo5^}vL2G%7EiPINrH-qX77{y2c*#;|bSa~fRN2)v=)>U@;YF}9H0XR@(+=C+kT5_1 zy?ZhA&_&mTY7O~ad|LX+%+F{GTgE0K8OKaC2@NlC1{j4Co8;2vcUbGpA}+hBiDGCS zl~yxngtG}PI$M*JZYOi{Ta<*0f{3dzV0R}yIV7V>M$aX=TNPo|kS;!!LP3-kbKWj` zR;R%bSf%+AA#LMkG$-o88&k4bF-uIO1_OrXb%uFp((Pkvl@nVyI&^-r5p}XQh`9wL zKWA0SMJ9X|rBICxLwhS6gCTVUGjH&)@nofEcSJ-t4LTj&#NETb#Z;1xu(_?NV@3WH z;c(@t$2zlY@$o5Gy1&pvja&AM`YXr3aFK|wc+u?%JGHLRM$J2vKN~}5@!jdKBlA>;10A(*-o2>n_hIQ7&>E>TKcQoWhx7um zx+JKx)mAsP3Kg{Prb(Z7b};vw&>Tl_WN)E^Ew#Ro{-Otsclp%Ud%bb`8?%r>kLpjh z@2<($JO9+%V+To>{K?m76vT>8qAxhypYw;Yl^JH@v9^QeU01$3lyvRt^C#(Kr#1&2 ziOa@LG9p6O=jO6YCVm-d1OB+_c858dtHm>!h6DUQ zj?dKJvwa2OUJ@qv4!>l1I?bS$Rj zdUU&mofGqgLqZ2jGREYM>;ubg@~XE>T~B)9tM*t-GmFJLO%^tMWh-iWD9tiYqN>eZ zuCTF%GahsUr#3r3I5D*SaA75=3lfE!SpchB~1Xk>a7Ik!R%vTAqhO z#H?Q}PPN8~@>ZQ^rAm^I=*z>a(M4Hxj+BKrRjJcRr42J@DkVoLhUeVWjEI~+)UCRs zja$08$Ff@s9!r47##j1A5^B6br{<%L5uW&8t%_te(t@c|4Fane;UzM{jKhXfC zQa|k^)d*t}!<)K)(nnDxQh+Q?e@YftzoGIIG?V?~$cDY_;kPF>N}C9u7YcZzjzc7t zx3Xi|M5m@PioC>dCO$ia&r=5ZLdGE8PXlgab`D}>z`dy(+;Q%tz^^s*@5D)gll+QL z6@O3@K6&zrhitg~{t*EQ>-YN zy&k{89XF*^mdeRJp{#;EAFi_U<7}|>dl^*QFg**9wzlA#N9!`Qnc68+XRbO-Za=t zy@wz`mi0MmgE?4b>L$q&!%B!6MC7JjyG#Qvwj{d8)bdF`hA`LWSv+lBIs(3~hKSQ^0Se!@QOt;z5`!;Wjy1l8w=(|6%GPeK)b)2&Ula zoJ#7UYiJf>EDwi%YFd4u5wo;2_gb`)QdsyTm-zIX954I&vLMw&_@qLHd?I~=2X}%1 zcd?XuDYM)(2^~9!3z)1@hrW`%-TcpKB1^;IEbz=d0hv4+jtH;wX~%=2q7YW^C67Fk zyxhyP=Au*oC7n_O>l)aQgISa=B$Be8x3eCv5vzC%fSCn|h2H#0`+P1D*PPuPJ!7Hs z{6WlvyS?!zF-KfiP31)E&xYs<)C03BT)N6YQYR*Be?;bPp>h?%RAeQ7@N?;|sEoQ% z4FbO`m}Ae_S79!jErpzDJ)d`-!A8BZ+ASx>I%lITl;$st<;keU6oXJgVi?CJUCotEY>)blbj&;Qh zN*IKSe7UpxWPOCl1!d0I*VjT?k6n3opl8el=lonT&1Xt8T{(7rpV(?%jE~nEAx_mK z2x=-+Sl-h<%IAsBz1ciQ_jr9+nX57O=bO_%VtCzheWyA}*Sw!kN-S9_+tM}G?KEqqx1H036ELVw3Ja0!*Kr-Qo>)t*?aj2$x;CajQ@t`vbVbNp1Oczu@ zIKB+{5l$S;n(ny4#$RSd#g$@+V+qpAU&pBORg2o@QMHYLxS;zGOPnTA`lURgS{%VA zujqnT8gx7vw18%wg2)A>Kn|F{yCToqC2%)srDX&HV#^`^CyAG4XBxu7QNb(Ngc)kN zPoAhkoqR;4KUlU%%|t2D8CYQ2tS2|N#4ya9zsd~cIR=9X1m~a zq1vs3Y@UjgzTk#$YOubL*)YvaAO`Tw+x8GwYPEqbiAH~JNB?Q@9k{nAuAbv)M=kKn zMgOOeEKdf8OTO|`sVCnx_UqR>pFDlXMXG*KdhoM9NRiwYgkFg7%1%0B2UWn_9{BBW zi(Ynp7L|1~Djhg=G&K=N`~Bgoz}Bu0TR6WsI&MC@&)~>7%@S4zHRZxEpO(sp7d)R- zTm)))1Z^NHOYIU?+b2HZL0u1k>{4VGqQJAQ(V6y6+O+>ftKzA`v~wyV{?_@hx>Wy# zE(L|zidSHTux00of7+wJ4YHnk%)G~x)Cq^7ADk{S-wSpBiR2u~n=gpqG~f=6Uc7^N zxd$7)6Cro%?=xyF>PL6z&$ik^I_QIRx<=gRAS8P$G0YnY@PvBt$7&%M`ao@XGWvuE zi5mkN_5kYHJCgC;f_Ho&!s%CF7`#|B`tbUp4>88a8m$kE_O+i@pmEOT*_r0PhCjRvYxN*d5+w5 z<+S)w+1pvfxU6u{0}0sknRj8t^$uf?FCLg<%7SQ-gR~Y6u|f!Abx5U{*KyZ8o(S{G znhQx#Zs_b8jEk`5jd9CUYo>05&e69Ys&-x_*|!PoX$msbdBEGgPSpIl93~>ndH;t5 z?g>S+H^$HtoWcj4>WYo*Gu;Y#8LcoaP!HO?SFS&F9TkZnX`WBhh2jea0Vy%vVx~36 z-!7X*!Tw{Zdsl3qOsK&lf!nnI(lud){Cp$j$@cKrIh@#?+cEyC*m$8tnZIbhG~Zb8 z95)0Fa=3ddJQjW)9W+G{80kq`gZT`XNM=8eTkr^fzdU%d5p>J}v#h&h$)O+oYYaiC z7~hr4Q0PtTg(Xne6E%E@0lhv-CW^o0@EI3>0ZbxAwd2Q zkaU2c{THdFUnut_q0l+0DpJ5KMWNTa^i@v%r`~}fxdmmVFzq6{%vbv?MJ+Q86h6qf zKiGz6Vrb>!7)}8~9}bEy^#HSP)Z^_vqKg2tAfO^GWSN3hV4YzUz)N3m`%I&UEux{a z>>tz9rJBg(&!@S9o5=M@E&|@v2N+w+??UBa3)CDVmgO9(CkCr+a1(#edYE( z7=AAYEV$R1hHyNrAbMnG^0>@S_nLgY&p9vv_XH7|y*X)!GnkY0Fc_(e)0~)Y5B0?S zO)wZqg+nr7PiYMe}!Rb@(l zV=3>ZI(0z_siWqdi(P_*0k&+_l5k``E8WC(s`@v6N3tCfOjJkZ3E2+js++(KEL|!7 z6JZg>9o=$0`A#$_E(Rn7Q78lD1>F}$MhL@|()$cYY`aSA3FK&;&tk3-Fn$m?|G11= z8+AqH86^TNcY64-<)aD>Edj$nbSh>V#yTIi)@m1b2n%j-NCQ51$9C^L6pt|!FCI>S z>LoMC0n<0)p?dWQRLwQC%6wI02x4wAos$QHQ-;4>dBqO9*-d+<429tbfq7d4!Bz~A zw@R_I;~C=vgM@4fK?a|@=Zkm=3H1<#sg`7IM7zB#6JKC*lUC)sA&P)nfwMko15q^^TlLnl5fY75&oPQ4IH{}dT3fc% z!h+Ty;cx9$M$}mW~k$k(($-MeP_DwDJ zXi|*ZdNa$(kiU?}x0*G^XK!i{P4vJzF|aR+T{)yA8LBH!cMjJGpt~YNM$%jK0HK@r z-Au8gN>$8)y;2q-NU&vH`htwS%|ypsMWjg@&jytzR(I|Tx_0(w74iE~aGx%A^s*&- zk#_zHpF8|67{l$Xc;OU^XI`QB5XTUxen~bSmAL6J;tvJSkCU0gM3d#(oWW$IfQXE{ zn3IEWgD|FFf_r2i$iY`bA~B0m zA9y069nq|>2M~U#o)a3V_J?v!I5Y|FZVrj|IbzwDCPTFEP<}#;MDK$4+z+?k5&t!TFS*)Iw)D3Ij}!|C2=Jft4F4=K74tMRar>_~W~mxphIne& zf8?4b?Aez>?UUN5sA$RU7H7n!cG5_tRB*;uY!|bNRwr&)wbrjfH#P{MU;qH>B0Lf_ zQL)-~p>v4Hz#@zh+}jWS`$15LyVn_6_U0`+_<*bI*WTCO+c&>4pO0TIhypN%y(kYy zbpG4O13DpqpSk|q=%UyN5QY2pTAgF@?ck2}gbs*@_?{L>=p77^(s)ltdP1s4hTvR# zbVEL-oMb~j$4?)op8XBJM1hEtuOdwkMwxzOf!Oc63_}v2ZyCOX3D-l+QxJ?adyrSiIJ$W&@WV>oH&K3-1w<073L3DpnPP)xVQVzJG{i)57QSd0e;Nk z4Nk0qcUDTVj@R-&%Z>&u6)a5x3E!|b;-$@ezGJ?J9L zJ#_Lt*u#&vpp2IxBL7fA$a~aJ*1&wKioHc#eC(TR9Q<>9ymdbA?RFnaPsa)iPg7Z; zid$y8`qji`WmJ5nDcKSVb}G$9yOPDUv?h1UiI_S=v%J8%S<83{;qMd0({c8>lc=7V zv$okC+*w{557!ohpAUMyBHhKLAwzs&D11ENhrvr_OtsnS!U{B+CmDH-C=+po+uSqt z+WVVXl8fKe5iCZoP;>}4OVen6_|uw8*ff-r;)O2W+6p7BPT7sT<|Qv=6lgV#3`Ch${(-Wy#6NA$YanDSFV_3aa=PAn%l@^l(XxVdh!TyFFE&->QRkk@GKyy( zC3N%PhyJf^y9iSI;o|)q9U-;Akk>;M>C8E6=3T!vc?1( zyKE(2vV5X_-HDSB2>a6LR9MvCfda}}+bZ>X z+S(fTl)S})HZM`YM`uzRw>!i~X71Kb^FnwAlOM;!g_+l~ri;+f44XrdZb4Lj% zLnTNWm+yi8c7CSidV%@Y+C$j{{Yom*(15277jE z9jJKoT4E%31A+HcljnWqvFsatET*zaYtpHAWtF|1s_}q8!<94D>pAzlt1KT6*zLQF z+QCva$ffV8NM}D4kPEFY+viR{G!wCcp_=a#|l?MwO^f4^EqV7OCWWFn3rmjW=&X+g|Pp(!m2b#9mg zf|*G(z#%g%U^ET)RCAU^ki|7_Do17Ada$cv$~( zHG#hw*H+aJSX`fwUs+fCgF0bc3Yz3eQqR@qIogSt10 znM-VrdE@vOy!0O4tT{+7Ds-+4yp}DT-60aRoqOe@?ZqeW1xR{Vf(S+~+JYGJ&R1-*anVaMt_zSKsob;XbReSb02#(OZ z#D3Aev@!944qL=76Ns-<0PJ;dXn&sw6vB9Wte1{(ah0OPDEDY9J!WVsm`axr_=>uc zQRIf|m;>km2Ivs`a<#Kq@8qn&IeDumS6!2y$8=YgK;QNDcTU}8B zepl6erp@*v{>?ixmx1RS_1rkQC<(hHfN%u_tsNcRo^O<2n71wFlb-^F2vLUoIfB|Hjxm#aY&*+um7eR@%00 zR;6vT(zb2ewr$(CwbHgKRf#X(?%wBgzk8qWw=d@1x>$40h?wIUG2;Jxys__b)vnPF z{VWvLyXGjG4LRo}MH@AP-GOti6rPu^F04vaIukReB|8<7&5cebX<)Zk(VysCOLBuL zW9pEvRa--4vwT?k6P??+#lGMUYE;EsaU~=i_|j!1qCVS_UjMVhKT%CuovR;6*~rP0)s5eX zxVhGZv+qtpZ{_FDf9p{m`ravh=h>mPMVR7J-U@%MaAOU2eY@`s-M3Oi>oRtT?Y&9o({nn~qU4FaEq|l^qnkXer)Cf0IZw;GaBt)}EIen=1lqeg zAHD~nbloktsjFh&*2iYVZ=l1yo%{RK#rgTg8a2WRS8>kl03$CS(p3}E-18`!UpyOg zcH=`UYwn0b@K1`E&aQ%*riO|F-hq;S;kE7UwYd~Ox(u)>VyaE7DA6h_V3_kW2vAR} zBZi_RC*l3!t;JPD;<*z1FiZt;=KK-xuZ`j>?c5oxC^E2R=d`f68!-X=Xw2ONC@;@V zu|Svg4StiAD$#wGarWU~exyzzchb#8=V6F<6*nAca@x}!zXN}k1t78xaOX1yloahl zC4{Ifib;g}#xqD)@Jej<+wsP+JlAn)&WO=qSu>9eKRnm6IOjwOiU=bzd;3R{^cl5* zc9kR~Gd9x`Q$_G^uwc4T9JQhvz3~XG+XpwCgz98Z>Pez=J{DD)((r(!ICFKrmR-;} zL^`7lPsSmZT?p&QpVY&Ps~!n($zaAM8X@%z!}!>;B|CbIl!Y={$prE7WS)cgB{?+| zFnW-KRB-9zM5!L+t{e~B$5lu-N8Yvbu<+|l;OcJH_P;}LdB~2?zAK67?L8YvX})BM zW1=g!&!aNylEkx#95zN~R=D=_+g^bvi(`m0Cxv2EiSJ>&ruObdT4&wfCLa2Vm*a{H z8w@~1h9cs&FqyLbv7}{R)aH=Bo80E3&u_CAxNMrTy_$&cgxR10Gj9c7F~{hm#j+lj z#){r0Qz?MaCV}f2TyRvb=Eh|GNa8M(rqpMPVxnYugYHqe!G`M@x(;>F%H46LGM_cU z{*0k6-F!7r3;j{KOaDxrV16WUIiFAfcx?^t*}ca4B8!-d?R|$UxwV8tyHdKL zhx;7%0Zn#qtx;S)REtEP-meAlV8*1qGFbRJ*eeX&+hsiLF*g9%r0Zl`L^Kn`4I)ul z32#3pg6Mu$LEI@hssUb?T$di_z zHgaB3zw;*0Lnzo$a~T_cFT&y%rdb*kR`|6opI#Pbq~F%t%*KnyUNu|G?-I#~C=i#L zEfu}ckXK+#bWo11e+-E$oobK=nX!q;YZhp}LSm6&Qe-w0XCN{-KL}l?AOUNppM-)A zyTRT@xvO=k&Zj|3XKebEPKZrJDrta?GFKYrlpnSt zA8VzCoU+3vT$%E;kH)pzIV7ZD6MIRB#w`0dViS6g^&rI_mEQjP!m=f>u=Hd04PU^cb>f|JhZ19Vl zkx66rj+G-*9z{b6?PBfYnZ4m6(y*&kN`VB?SiqFiJ#@hegDUqAh4f!+AXW*NgLQGs z>XrzVFqg&m>FT^*5DAgmMCMuFkN4y*!rK^eevG!HFvs7nC672ACBBu5h(+#G@{0J- zPLsJ{ohQEr2N|PmEHw9 znQ`qe-xyv93I;Ym=WnoVU8dau&S^(*Wp=}PSGw;&DtaKz-);y)zjD|@-RT`*6nowj z7B%)h3>Lro-}5THC@BLymuL&3~kh8M}ZrZGtYKAmrT^cym$^O!$eeK$q5X2JF1w5a}4Z6yJ<=8&J?(m6U?;+ z{+*B;P@yGffMz;OSfm7NDhkGR5|7&~FNvel8Yj{F!DWnHG>%?ReZ$1w5I$Bt_u|4v z-ow>!SF!pCGrD&K8=-<;Gp@oB<@9C&%>vPHrp4sQEJj2FdedjC=0FqD>EG?NCf=KQKVd^stDZP7KNCAP-uEO*!?vgwvdp&Dm3h5Cldn!cIOL@u>1!HSfK+~kn-9Ekr|MWNApAJCJ5&5#izmjm z$CI|Boo@;O?Z(Bo9ejP>bbH|jRKn7W3y0L1!O6v$RUtt;%5R#**`+39c$JuO`SMU+ zbzu$7Eu`JQ+ri_ap{w(R_juHcw0X8~e$48TzBX%Yd+HkSSYt2){)+rYm48G^^G#W* zFiC0%tJs0q3%fX_Mt8A=!ODeM?}KLDt@ot6_%aAdLgJ7jCqh_1O`#DT`IGhP2LIMhF* z=l?}r%Tl#)!CpcItYE2!^N8bo`z9X(%0NK9Dgg^cA|rsz?aR+dD6=;#tvNhT5W}1; zFG@_F2cO&7Pdp1;lJ8?TYlI(VI8nbx_FIGRX^Z(d zyWyJi58uPgr>8w$ugIGhX1kr*po@^F>fntO1j&ocjyK za8Z*GGvQt+q~@R@Y=LdQt&v=8-&4WOU^_-YOuT9Fx-H7c;7%(nzWD(B%>dgQ^ zU6~0sR24(ANJ?U>HZ#m8%EmD1X{uL{igUzdbi+JN=G9t`kZMGk!iLCQQiVMhOP&(*~gU(d+&V4$(z=>4zqh(GX+9C&;~g2 z9K2$`gyTRJpG_)fYq=9sG^1I{*I=s%0NX^}8!mJVc?y$OYM^n!x(2jw$$;}n&dh%D;St+FA;eW=+28j#G^YLi@Gdk*H#r-#6u?7sF7#_pv?WS^K7feY1F^;!;$rgU%J zS$lZ(hmo$F>zg$V^`25cS|=QKO1Qj((VZ;&RB*9tS;OXa7 zy(n<$4O;q>q5{{H>n}1-PoFt;=5Ap+$K8LoiaJV7w8Gb%y5icLxGD~6=6hgYQv`ZI z2Opn57nS-1{bJUr(syi^;dv+XcX8?rQRLbhfk1py8M(gkz{TH#=lTd;K=dr!mwk2s z#XnC){9$x)tjD0cUQ90|hE2BkJ9+_tIVobRGD6OQ-uKJ#4fQy!4P;tSC6Az)q?c>E zXt(59YUKD?U}Ssn(3hs&fD$i3I*L_Et-%lx%HDe%#|)*q+ZM-v%Ds3u1LPpPKe-q} zc!9Rt)FvptekA2s+NXxF7I;sH1CNPpN@RT+-*|6h*ZWL{jgu9vth{q)u=E<7D(F06 zN~UUfzhsK)`=W%Z-vr#IIVwmdb(q7k+FX-lciYO%NE!xl25SV53Hwdql-3>8y5X1U zWa3_Qfp2Z;jVX+N+1?`(dx-EJL)%oQsI0G3S=ad&v{dzNal~flHvq(0HjY!v;oE>n z4gQSa2FdJI52Weu$+lED4VYSW;D`5Zn`C#@7Hxa1Ls*#TLBjje(%NYFF+4uOc~dK! zlnyxE4NWVz0c8yx`=sP2t)fHW(PPKZPp{SCwT-on2sEM9tyGO4AW7|R;Iw5|n1KpV zR^S>`h}rxcNv2u+7H6rCvMLMV3p*H#WcN}}t0@Us{w}{20i<-v> zyos+Ev_>@CA**@JrZ6Jzm=pWd6ys`c!7-@jf<~3;!|A_`221MFp-IPg28ABf6kj-Y#eaRcQ!t!|0SRtkQK^pz;YiTC@@lJ4MDpI(++=}nTC zRb4Ak&K16t*d-P(s5zPs+vbqk1u>e5Y&a!;cO(x;E4A4}_Cgp_VoIFwhA z-o^7)=BRYu)zLT8>-5os4@Ss8R&I^?#p?bY1H-c;$NNdXK%RNCJHh)2LhC?B9yL2y z(P-1t9f~NV0_bQ{4zF|-e^9LG9qqevchug76wtFn95+@{PtD)XESnR2u}QuG0jYoh z0df4#&dz_FStgOPG0?LVGW&{znCUzHU%*b1f~F+)7aefg7_j76Vb|2WuG#1oYH_~4 zrzy#g1WMQ#gof`)Ar((3)4m3mARX~3(Ij=>-BC zR@&7dF70|)q>tI$wIr?&;>+!pE`i6CkomA1zEb&JOkmg9!>#z-nB{%!&T@S-2@Q)9 z)ekri>9QUuaHM{bWu&pZ+3|z@e2YjVG^?8F$0qad4oO9UI|R~2)ujGKZiX)9P2;pk z-kPg%FQ23x*$PhgM_1uIBbuz3YC z#9Rz(hzqTU{b28?PeO)PZWzB~VXM5)*}eUt_|uff_A8M4v&@iY{kshk{7dHX1vgHs zC%vd9vD^c;%!7NNz=JX9Q{?$~G@6h!`N>72MR*!Q{xE7IV*?trmw>3qWCP*?>qb01 zqe|3!Y0nv7sp|Md9c z4J5EJA%TD-;emh%|L2kLpA^g>)i56v6HIU8h7M+KSWYw~HHz3`ILj*{==jD(l33>r zmOdINZ8^Jo?ll^~q@{^5l#*3f`ETncJmo?iRLz*=W=o3MJ!K^xjVcw*H}p63#p4XX z1)|C%{Y&)IpRIk5oMVsUi6oyKAFy8MH$@|Zpjr^lxlMX3O{0AZTjc{gso{KRuo30V zUJxq2K=_CwV*Qx_D!hJCBTuQ}5oMNrWUBNVaa8zyMg5lrXgv8Zw@rm5NAcFplYa>P zmUNB>EB|r?#Z!Gq^`(HZl__UJ*K5 z=>`{UTlt0;Y+LmP1Wb19IWK(SIWDrqh=+K81c`t@BCS|2#@K0u5eEwQ7CG92=Axx4 zQ?CPaVE5!XY`2r!Ce@m(tRtB=&+c>a09WzP-Ys!~i;V0hEq}PU8n1a;bVbJ17rYW1 zjz|KkLZoO7-S6oQp_ocIzS43P@CJJxQ$k;$!fS3*V)m|VtBIEgCtU@W`AG9VMU_d znB-Zs3I)I(Wg=xj)Wcx03h}U3i5{D@*udPLg?Jx7dp&KEIwJiW=eh}Ps#FxbsS?F}7z<;<5RP6-UAD+_An$s3y-JAC zh{JlAX3e^CDJl1gJDbH`e=hD88ER_6+Mw8CwK&^|$BnzA|AvDV`#xF^z9b6iWb)0@ z+gir=oSUaVcJi%1k+9!pd`(3|h~4}!NM7NHPNV6rI(W4~Ie5 zl@(Xg2`OSq|HJRUg3qgr-c!}9@W?pEJXKtxP7f(aE2Es33gRSu#~XiCIpV-J;JLM{(@qK2wEvsi@6-9(cyXX!6YS0n7;TK0Ldf*JGmlvrF0 zGQ+Z509rmWa)O}r`z2W3!6u{^ZQrY`KR#VlTRmllG2v$R!7%B~IU@XnNi!E1qM$J8 z%{XFU4vy_*M0tKjDY3E*7N!d%&vnx5qr#=!IKWZfoRo8j=7ji1{xW?g^)A|7 zaaA5Rg6rwCF?y33Kz-90z!ze`@5N916S)(fHPa>{F`UEF8N5PTNjbo)PF5W_YLB*# z?o`qxQTIzokhSdBa1QGmn9b;O#g}y_4d*j*j`cx^bk(=%QwiFxlAhFSNhO0$g|ue> zDh=p|hUow5Knbclx8V;+^H6N_GHwOi!S>Qxv&}FeG-?F7bbOWud`NCE6Tv-~ud&PS6 z;F*l>WT4zvv39&RTmCZQLE67$bwxRykz(UkGzx}(C23?iLR}S-43{WT80c$J*Q`XT zVy-3mu&#j}wp^p0G%NAiIVP2_PN{*!R%t7*IJBVvWVD#wxNRyF9aXsIAl)YpxfQr$d%Rt20U@UE}@w?|8^FMT%k36 zcGi_Mw+vMvA@#}0SfIiy0KEKwQ|`iR++|PF2;LtiH7ea($I{z z32QPp-FlEQ**K_A@OC943z`Qy7wC~&v z*a`z;(`5(e#M|qb4bkN6sWR_|(7W~8<)GnX)cJAt``gu8gqP(AheO-SjJMYlQsGs0 z!;RBZwy>bfw)!(Abmna(pwAh^-;&+#$vChUEXs5QOQi8TZfgQHK$tspm+rc%ee0gy zjTq5y20IJ`i{ogd8l?~8Sbt^R_6Fx*!n6~Jl#rIt@w@qu2eHeyEKhrzqLtEPdFrzy z9*I^6dIZ z)8Gdw1V^@xGue9trS?=(#e5(O#tCJv9fRvP=`a{mnOTboq<-W$-ES7)!Xhi*#}R#6 zS&7hR(QeUetr=$Pt6uV%N&}tC;(iKI>U!y$j6RW&%@8W|29wXe@~{QlQ0OjzS;_>q z(B!=A71r|@CmR7eWdu9n0;OJ zP@VOOo#T+N$s{`3m`3Li+HA4owg&>YqCwsA5|E$b;J&v#6RbT$D!x$Yaflo92wU?A zvgD8g(aY`g7}Y2^2i31ocm&k9Km`NQipEsjU>MuRzD35*Jk7^Q(O;M32!gt1cEB@- zBOHd@@Qo{fQ^7o{FiNdS)_vTiP8toqZ`iNi^1-4(hp+s751}Tf34b z_UYQ1q0~*jIp9pRIpI8ue}$|~uu0#p>-y8t{yEwB(8yAjMXrJ{`{rp7*-wlh8&bso zHV`LnAF7Bw+w}Wm9ii3U@lEvcc-i$0&h+eUmlQuREzg!ao)ZjwThhqIKA})}akyX7 zcbuIw9K}9aUZ;hvAxk~rqpk?bYMWr-@b-pMTR8))ggQa$kBv=IinobKCR0?S&g*+Al2J`VR7he{}0Pu zae7LYa!OoTOk8?ma)M@Ta%NxQacV~KMw&)}fkmF7wvmagnTbWo))`Kofr)`-pNe99 zMnam7vRRs5LTXHWNqTzhfQo90dTdg<=@9teXaX2tyziuRI?UOxKZ5fmd%yNGf%Kis zEDdSxjSP&;Y#smYU$Dk>Sr0J42D)@hAo|7QaAGz(Qp*{d%{I-#UsBYP2*yY8d0&$4 zI^(l62Q-y4>!>S{ zn;iO%>={D42;(0h@P{>EZnIzpFV|^F%-OJADQz(1GpUqqg#t!*i zcK}eD_qV$RmK}-y_}f$Xy7B+hY~f4s{iCD7zq%C|SepGu`+>h6TI}dUGS3%oOYsZ0 z#rWTU&aeMhM%=(r(8kK@3rr|wW^MFE;dK5&^Z!>`JV{CWi^Gq?3jz~C-5hFFwLJ@e zSm3z9mnI+vIcF+RjyOL!VuZP3rJDjPSm4vYolnm)H;BIz!?dLyE0^5(pm)5*>2clW zaI^*Z;p6iGZW~Gr0(Eh+%8Jkz{S9{}=}Ewi6W0wF3|BbVb?CR2x>4xST?woP;Mz8L zDfs+0L9ga3jcM)zCC=`-ah9#oulxt9bZq9zH*fJK$bhT=%(2bPMY~}cPfTyE{_4p+ zc}3pPX`B04z+T>XwRQ4$(`U~037JrmN`)3F8vu_OcBE}M&B;1Vd%|I|1tni?f_b&$ z5wpdJ6F*oif)r=IzB$ytT72GuZi$y>H0p_#amQcJLZ^4KZySOUrRyXy3A2(i=$zB9 znZnGFLC34k?N@s@`)u8aZN({9Hfe}|^@Xk(TmCqNBR*Bter>opM!SGiDU8ShK6FNp zvod~z>Tj!GOXB^#R>6}_D@j67f5cNc#P;yMV}`S*A_OmXk_BIq3I$C}3M~aPU)agY zWC+0JA-)}O@e4XTtjzen&g=J0GIVNjG`_gS6ErXj3cGxeDN*4xEk0PNzfzO@6gb&N zB$S-WV-@efQWs%UX$AVjFN5M@8U>+?Mcqg?@=Z-R`~n~;mQGVJT_vBL|3^fHxZ?#T zE(Sd`8%2WHG)TcNaCHmv_Id%D+K}H3s&c`bxKs(_ScZzyCTpvU zHv~yhtKF9G{s+GC*7>_D@F+qEq@YmXiKTV(j#X7^?WpvIg!Yxi6uBAhh7<91{8vFL zfT?Y~vwmE;(WOL!V5Ag&#@U$mP~T=*#_ ze#QynX>tO#4IJqSj^UB>8ubSEn>Nk!Z?jZE01CJCYuY`1S3 zf%2eyXaWoAQUw)KYO;wi<&+R3_7E%h(7F?xq!8l>!^3Jqj_tNPrG= z+y2S-0j;(AilOo;>SCQu#;Cn?y4Eu za`??!yHz)qFH1Z(3KMqgn+B$&t+5s0zY|}<1kB^Q8FEAumh;^;Yr~amTx1K2%2JUk z@7uIE&0DVch|1R=ro5rjr)w!iU{_09PqfhnGqhAN^$^oz#wVNdTRQ!8^nF};4);Jz#=dTBTMMW7icnZ$dK1E0UEgP4&DNk9MFoKOhtAkVUR`d_vc!x zc|1mY&%{PBxepp^JPHmFDBQ8t@DD-3!C)-ZhGJt)?{)^0MvC%RzI;4}>XoOUF;6~j z{S20Ra%PaiGvM$pFbH;N6)b1J(N;{+Gp^^Qk34JAuPKH}Ap}fen!WlC5vrQ0$pnyq z5poi8VG>>PnGw2^-CY3XdG3<;|0xU}#WBPqn{mO=z0RwL=MXn3=;oA(1C@V^6F;ogwB4EBUpltu=)(MC@To2kSPbL zDdGz|C<@`&!MmQ*e>H>2Qkwa~K%;yZw;SnM<=qwNHu-Dh$r(}-d}T}u!=UOAkzvEOiZ6>{)t$$# zlAmjO$1)&1Zh^zdh8uhmZ>OBA1T4%s9Jex_y4|ifY_=XoX6UzpP;MuC5su(6%;)NI z4d#4aW<*)L6o7w?MY2+jRx6-3S4i zC(~)A`|)5(s?)pBvTfYjwvr@Z-Dx-F7uq}z#WJB6&}0TIi6sGXFWOxD!As%cUg)_A zI)sRCf-5kPBU|rVm0A{!s=W2){AJwvShr6Tsvbg|NrXi!7zoMde_n>-+XFX0fiQy~ zjRp|;6~pR()0a>ETtC7mZD|i$Emj!r-gq!yhAFdV1uR*M<4O?t83N1JRT~8Cy8Vha z+STlcw&CoCJt$k^#ar+~DBmvtC5tr{(>|W6wHq*NSE!^#8*rs>!oYj%fl9~Nu*d4t zdk!|mGJehKW8xJE5ZOcHRfp4plI+l1Pct;rK={=P`YH8&1hNW*YE)4yF2@wa7JFaL zLHJH6ZWc1j|nQ55Znh#>tV`!~N7lY_05Cq%|8I-yN}yf@EzDG zBL z(b0sjh+ui^*s(rg)=l8fU<%cPfba<7y?>}j3R83$2KHzWbVF*`!x^V8JY`D0itC?ZSTYH|w3lUD#$5G$@!v(Lphex2O1;%>w;Qh$t7YF3EjFuySPC$>~%EspW}@Ctn1Bghd5*HVJ=tZK~8oMiZ@9IxfFLSk~>p9cT9gOSPLyP!^bOah`U-6{}C_ zmyhS7S_-tYDm|9C6(Wu2Qe=*g5@{**z@#Ekz3Y{o7fw!^4z$yi z&=a^zmtOpsRO0lFr&c=khr)cL2v9LFKXRDdE}tWlOgpR%}oWHCeJ4;(9U_HeJYl! zwz$p|t6?#eCju@0{IF0gbk>So3C{Ror~JTpuOW!G@^?lBVrf zf?%rDK2E3x=xGC)J_lEk{(ESh-Uw*#k-n4l42f3oC3BJX0-2NMZo?P)-6y1v+?|+< zfFHX8(bw;H@;6K!?=!B#eZrkowcdn7)roPT=WM@MK?>T-cUa$oQdYp&3YRdWu~rhA z@rZKmqj8Ftz-*@`&iH|) zC(H;QiqYx4{Mz@rm`qs~*Ue~4EHM^J7i{QnL~t)O)tnwIQC;23p}TBoc=9rcuS!cQ zQgl)_F@t9{c)ESLtAcg1AbCXqVS%i1ZZRiy$*?Bu=r2ad13e|ZeWV=3pSL>YAk>X& zQZAY4kJD`CYrK-nNti&;uJ*e{cRILOFk@z?B@fNO(exjUhf!b=yuC`@(RS#ko1HA+ zOwsym7?F)}ufcD5&IV+qr+i7Mo3)6M2oI)*3?@-%ah^0rL#0PIn}XmOTP9Xsg5C;t zqkFe6yT##_ZG5KuhVQY)89LfWOeXpXVNWX2PmiRqq<$C!<^WlyO~Q=pk${$DsWY-7 zZ->4<+c@KPgKzKosGPF+&Q*>L>WaN6_FC~SP~3gH7bvg6>QgPzp`&QTpf3W>HjxDxj!y zZb`O;&XZzI2YJ4!^Mq5~Vz7lLv`StN|TSP@jdF}@9;ql?u*#Q+_E}~hak(3B%AQNq)t7PKgAWTYp>EJz^VIj67KcZ3^vvZ7{b;; zcOOArcAw2$T+$UwIib|pt3i#NAuP#3?Z@Oaz?Mt(H&u7HZu!03kV7`t5IRcf7hwck zf{Ujp*YsH;dvcW0q|=o$;z#Cg52;n5t1phY44To!sQ99h`iVzXd+v(L%?A$Ks|Ne; z7fby7IVUXqN8gzsnL-s?uIv>=Qh!qAxoe{fRaI&EcSGCTdggq-Qq?DU%SBOummO5cRa9NW}V>A0IH#pxch)!$2p8=^-XYjsB%$S$U5nI zlJEMBb!BZ_O4@87cEYUBH7}Y_MF$+(~gdf-!7)D-D)+O{*18TC{HGZFF+`%IPcmK{O{YxR> zSfJHSeQCChuPUAWe_x~gy*f!!wvt_tL-Dp=nUm+juu;4L6N1IIG4dsVMat#T^p7p1n*Tx2a!YaivBTqLsSJAF=kJej?@QWf)Y-8Ks>WkC456{B#hW-ML zI+f23(}F=MeSdbWQ>R98TOzv#Haw}ua+17H=P5|~#BDmoEPkzl#lBTvCoyj`XU|IS zHn?dXbq>rqUW8^kQN01zL~6!Vxn4!$Pu|F&#XbiF{{>T z)&khW&2Y?d8^jC|phWKQ4!CM9b66+l*HTdPm+)M|e5yT)I32Q~2ENVJ*ZH;JF^Y907{XNHLoQ+85J~!w@3h_5d04o=~|1 zCBAvjnXMn`S#qMkPZE}9#RX`%al{`J=oFKk(aJYT&Ss`4iBrXa_pQ=3lS1IUFA|Rr zgnh;c8nkGH)|*yyoUZ?tE1XKwkF$n6`sdkf^7)(wZ52xtm86N>o&&jG_@#ue(B`xPM|8oGz94>*kl17-|d^y0`D=&hScq6gGQ%Z6|LU zG@<~h-R{xW)y7k1x7XFw!TWW~HPC^bCO_;xG#A4he?=xkLjS=~U!uR+q>vqJxCN~J z+I}|P5RTv*qRT{k2N^Kz8OX*mz$hYR!aYq-f5bN4R4=omUVP19L|)EZq?O0#B9 z<3G&oAZ`UeIqZWlujz8UNNSK#{=_c`*(&TwlIr3ZpC0sfS5Jy?;t+&wb1g4Q91rRNiEt1|L zisgH;)V()S&(TSB|1yAxZLH%BY`nnhUw_6sz~zdKCCc!ZV*Ws6`U4u|CBpv4pYIX1 z5*)5C*N#D}gj<@pdZxtw!`5aFVQ^Jj?1W z+EsBx6>WV`%wnP@Fp{XlqFkbHf%LfCgIi_|w?uPPjHAgOF+lDnAb+WEB+i_53PFmu zj!=umx@ez9mVxC&jA_RtKRfQG>Cz`A77S2SpOt7%Rt*}fG|yO+2t7CMuK$^}D#i}k zZmO9yUwK6%!LbRsULVnxUxfxso5KFES=!WCm>y&YSR@0CS|iON0v59pkQ7dVA{j*+ zmcRtD@lxXuFq@#$DKKSal#ApSJLw58m_NIJ?z;eD3Z8u*-#}EaK zyG~L>-7laE`Y}{g#FPs9YA-wT4>X>xRNtTHp8_rhvWA|eJH(!o-G~C&tvHB9$UEJI{ngD>QjBz=wl~x-j1MB z4)L_#jZSvaQkbmVbN)4{#^r&ZmfhhV%?tet3`xJ;#jI}DsS94qc&s)#2kXv5pkt;K zaY6emqzF1JWMxI(7h}mk*MQ5C8WLAol60!DPj|u0jMrLTkU7G?ud**S@bYx-vp$+r zMVXWc4H}2=yF+YML9!k~LT(|<#By?F2bS~weMi9dD@DA&k#0e&MM1YT!qoQDeNLwB zA;{KvwSzP?-K(>@_b@4vTkIX7xwj}ckrusCw!k=#;Krt6;}3q4d*)?c{>I|C2I^4p zR(o48TqHbw?4Z`c`>?P{`cT;FpJoFW1wJ3IVO#5Q`wsB>o>zsRDDATmct`aaYQbTL zJVlHeok9_?w83#Z*J(_BMs-;N;mNeq{;f3S zSy{i5hNY5s`c#)~KhQZ{0_hNmrMD2b7CLC2+x#EmLcNa8V1Q=jz@e~VV)Yq!Z|$nv$TEG3j6K4opW+mH z3~z?*H$qobb652kQ}ZHFHUVj$%JAwS-Ie=Vh&Iivx3hjMCZ1k)4dRjdhxRb17P;Gz zZCsB4J=l1S8`O|(g!8c$aOMaYeUoCJj&n#kbDxe(^GQ)E)$Rq+i-wbPKeaQvL!`Y- zcL=QOLcWBdDq_`HLow9P5BG2EMY$v;w9cR$C{ zMv)5zrmYv!uzHFAxDI>aftAp&ad>GYoPt!d;A*$s)^6E5l5ct#&O7A0p^8J1ceXa) znIq{NgKbbOSC`6E_af2bCoI(gD@(krDr^mDVw>cRz3zJ^&9kbuf6)J@Cd#zbnko5m zdyD^j^!9J7`oH!u{~wlOl7jYM(OcdI^#*5Y>BjUumq_g&tx<#_pkzQL3{!g?50d=#eCov*uIw$N*glXJe1F{FuUF_wCElS)Z2X= z8&w0?WkCX%HfL)#n-m1tiLy!jDMqH$LikJF=#lu@k5%&vN zOEmQQ^n*t^76E;JhHPzQqbY0+m8GQ9;~dJLLZ@*sqVX0ui5yz%8Hyn87vqUisY_0- zDtUu5haWdOvDBOX9Y;=s;7ul^_xLxfU(?k(HStRfk0Ab!pY(scal?Nz{Qu?etFHNA ztD=60Y>dte)hUle1IUyYIFgMxgGpvx%Odv4q;WPV?Zj<0pph+zWMfSd=SIUcB_#7^ zgNlm4(v!WIBm4?kpvZnCvp?TXW7~Azs3LT8Gh<0Ew=&W*e+4X_xQ{(e+UCESTaWwz zd1ly>%|#A|W%fgeL_3gAwxjeb?Wi3rAR3U#9Rie*)dfz7YxUK;ex+a4F>@qyQAL0^ zZncndzG56R$F&?R4SOX>&%UDdBid6 zIn=GRfcto+s-%gMB)Wx7!_Z+SS)f3IG!&s%P2eNfHI6~E*=>e`^RpvJQY?T95IOKL zeX-_BCdRE#f06_QAoDyMH;#IIBnT#PWSOtks+PCo`04X-brsea32I~@X(Bwl*Q`$c z{Al@04k=Mmd0}}ts=u%dCO;qn-;qh>Hr7bB6!NOVxy@Yi#GK2vusj7iU9757HTqN~ zNMoKeZY}o)nA*{CqTTPKnWi*JgZFZj&EjD$V;O9zqHV#tB#r5Ur$V3To8iP-bO*Gl_d%qc2$SoU`Hu-6*hWbuWzAn(83_jZ%>P{PY3XVV!q$~ALE^GC( zdIGgR(HnV8Rn*P^7b8#AzONo*U_W}{Ne!=#*qNJIRZzapu_fOkvki(|8NDg>&D=OZ zL3G)1WS*8CFh`-sb*#8*hIN7WDjw6<$D&T|B>JPi`K!*5DF(O*^A+r*Jfnt))c8|M zQKtgEytAqpy@~XZGnVYMJmZSG0U~uvP?i*?DhgDOSYtx6s%6u*vL$SW87`&xJ9cmDLrPHI@G7Pb*cizPGf|!5th41a2ijel>Xfk3i?7Bd*{|)@>|ZBi zH6gO9a2Yd&_ZeKmNQC^e&S$cl!3D2oBCX)C;Ve{0qc|4+*fwK!x{=QYtb#3QD1|Yi z%r?t<$-Mjbli1fF(C?V&w#;Gq3-**PgsGPPsXN(0fb?pIDc{s6b<9{t%6D*47A9ZHlc4rEGU<}u;tiom3^lA-&)1i=j z|I#)cctK)AH-b2*a3Wm%Gt*;#GWjNF6q0q^Evid`6G2yhMg_4TaMUK&x*D*5+KtlF#!)86A7pn~&yvD-Rh%`@(o!Wc#9t=t;(9_y*(MWS;4cPU&cJcE+h} z6fZHrjH@7{6~n40#qgL(yA-oVrt;Kcu=fV1WQ0QY`_I8lVds$PYR7KDvhsTbkC8q6 zct`{-n;z2!($SBZ?;(ZMu1sY(VY)KJ@%p)!LEBL+M{ck-$kHEx=3N+%$#msc!LKD> z?(7`Owu6Iuf-Nb|5wFxCm}U)Du@JO|nHV?%8lk(y3x-=F_d}u8>#AU~iWtSD6|VuV&YM=#_v-HDjZ4mS|L2%K2K}Mhz zVb)f#Q>%4Du>|ea6cbNYrpi<6A!rSmbeh7+xGZ{-TPG);DG9qg=>9!44ScDdh49-_ z;|KUp*RQ-So$jyV%Ss5FnJa^|LYAl%8niBhd%(W!x$Rpq@pcp6(XF^fHFRF2KQP>$ zo@`Qi&QlkFxp%0@2)7RlN4+NzCWo{?_x}5$E?kh!!UM3Vg9R+=xPLWty|S}5Gt_qg z+-v~8k*0?Bf0^Q+IZS56Ny~Q$pap&c2NUt&f7P9P+zEz*>bOO!5J8(uhIJ#%lgMNl z3;y^@Yht z_Dko1D=J@nc@`zIXz6dWsr`Kdt!m8`gGlx59A(t5ZjDVmrsjl#0wT@It~$j=uGRM! z@XJK@Q})NA_sQpEZkNduP-h{cP|l+Qqwr{g--LeHY2&||4dJFD34ZCj7@+4ZH4}La zjfr1gHXr8j#ppOa+gkiuHYf$a+VGA${f!~LtdO!~|X+>{b zY8=`^(0d9`z1f!nNzD`;4&65cNlg)@h5m5oOj&gG%mslXlc+jou#n#`d_l6}hwB+CG5k*Sr36Yrz zP2B)Pq#G?*Iwb)FJiXU@lTvTrdR&WRpV8sUz(Sx3C%f;BHSLY@I$!TqSg!%IetroG zD$gu&K<>-imH@Bh&}f!zwO-`w8Dt>MMZ>8V@{X1g?!2BS0S;GtXTW(%@{L=6uC*fB znj>TvA9Cj80~Hn`A5GSVpyqA$*6rlEa`u=Z!{-DRtCo0{jnK|3KxpDEi3&^DwWNg4 z%|~wf=EtEq^ku$fbX{@*EYr&TP@j@?OyLdVKVk*&H23K=xzmgV8p0Y|jK+@cNaPE1 zovLSR73MssgV04G7S-h7L}ID!!8|-X7U6-7?t~caWg)yk6*s=m)9us~kZ7pC6I1+@ zd&wXWPx{8Z>47wN=yJJ;BgQ&`z)H7hxm}Jq_9GiAq)9R- z7(@1=H+oqdJ(YFEq(LiJW=s}h(Yx~}5%_cQ&3xV0VUT%{sXE!% zVMqItDE@pLL%E2I2<48s8InBVbnt|shpL|$wrvbdWe!LJMr$c+e86OWy77OJ6k_2&3KMqL9=QFd2QUVwwR8X*sgj}5OpiFWK zkiv)DX__mAlH9kRszqfgqLLvBrDbP&mL;Amd=_UXSF4&!?$+*0ZswW?9oH!-BQgjS z*IQf1yzUikvx`UPXLZi2UvHaGMOee-cPA0C5fni_Q zcj2Hhbit;RZ5t^!?2;o_*D4W$VcsfIc+m?Z?b!Uv2;-s&XYSCUiczc2-b0I0g-hNj z@xi1}g6j<*=Dr7UMa-%w&YN`cBbWT>BQ~p;QyS!^#eQ>q9dy!?Nrh+?bfo*_kEe;nyR%9=3OTAD90?RT8#Bk}X#Pkr(TqBF2&!V=` z^iWLr%Yk96POnG@bEb?cv#Uk)5}bP0=~;%g>Sm{t#hoNp#yeFj7UxuD?en)EXw2%= zTS`>YY)#O023TqIXj@8o2KAM29NQM4QH=;sYP$pcqtRoxg?ZK@CWy{=P7(uI7%TOp; zP-^!0wmMVv-f2E>6tEj7ZTG#-KaZMuUUgl1|nl&p%3Dc8tZ4 zW{0iAY38oin5YwiQlKRrH8RP-h95fX$>v!l2*6R~)3vTQ7V(gjstAxGVc>U<8Jwb) zPTqZIfoIV>X`vA2EuAW0Ghj||3;hwn0w`nHnL~5Xr-xuSDNmuyhoZWBBa|hf3)-7$ z6nhe93c?Vv(WT4=mKowy$9Fu8Y)h5yEW6z&zzB7;Yf(a|ei#jb>!ayFWo?MkgWxQK z47{-ws_k4#8xv#$x229MEUK#x*X1k=2QLLnaWhYREFj!ta9&)3I+w+wuB-hQ0SFLZ zlvuP9c*O0k+Bm_8bPyfY2o>Ts&0yRSIg4c@Rv71IVHGS{L3?%!54(HvY;tru5FCHC z9_ER%i7@?-Tq&gCLBVg_3g3?9Gu6P$T^70*)YqUQTN$IHtc4g5UG7WN_J&c!4-lZ& z0a=#~p%2D>Wvx?z(9bP0Z<&FgpEnI^CYsg{+)}t}Teb>kj&)7NNmPz4Zv@MJA2cA4 zE{uQ3IbdMxWrxK|%90Rdmx)yBJ3FI$YLuF4DF~35POQtBilKK{44PuvYIHjt?~mW& zzNwc$LazTnX6dO-hE|>Wu0KO)5xDdvCq>WTfkeI85j!LDvSNHy0&TTnCpr_Y@_=eYt;}dhqY5=4^QRl&pzt9Bed!EmviR=h>B6ynC7MGc`x^9c*)$$|imA)E z9KmcfaDlPY6j0i|;UW8=8oO5$aRyZaYTM*qBd?3;u=u(KdjqYJ_fLd`tRoym(-gX) zqoT2Ua$jR%Ibg0>jte$VWiyOhLaYcnGe^pQ(V0O%I}YnENL$+J%d>ulP(v~JZtnH_wYk$}A_OsQn5BbzOkG2(!baa2N({4d%BrLdzn_qpUhmGmod2kf3s)xrh|=VU=smdZ ze#hs3hAI5A(;4e45x>FbZjXU=hACbM{;p^HFvP31DFz6_lHCVuZC63Xv9`wzN@Y6rcuoPF<~3V<@&m2~m3D5&4GW7GA+XXs{sPo!wDK z85d-&4Og)(j6Q8x3f?Ooxm7VJf?Nw>3_s3fV9y_1xSDfCy31yBhkr2LI_&)xUpcLxXfuNl6z9z^w)MF}E8U)#3YWS4&8 z{-CVR?>0{F?ccm>oP#mMTY-&w90y~vwccFmV3Wd60@~aufc|xzwLI_AA^-goYhcMf z>+D@$bjnFLRX|X?6oMyaW_}(z!Ys&@5~HmlWUY|}!wJnBP8YPsWvf1%(iPjQZ2#s7 zd=-ANqy%pCwL5&H8Tzs{Ux(<1et1ny> z?C%$W*FgAI%!nl0a{QuH&7L*cr$DOVP-67{8fQkKPfPD$L+Lv zSnj#tSMG<%-tcmKzH8dSPFO)VC^+Dw0|si;bY^#=`Ilum3dEF5!JrA9J z^7-aQuXu7vwaQBlnT>)~G|scmodeOzMFBpiJ_`6WePZh+=vMX276uFz4Vd%}>sndc z95j(>Uq_*mC-r*$6iUb)5mCYRy8>n-Y?K==}9iFFRN zB_u(i5p)JpS@Is*ArpnM&nOOwsI6t6IAmTNaVm+)*gWI?2fN{+=&1n$oGYcUGS!0y znn-1azfTgI zyHQk7RQGW=l@WF&jO?B1KXJa9;4BdKcfcpq35}=O+x=GE;TGw}Ub3M+AbPW8_LG;zZ%{IenPEAQ0yCE`_ z5medk+}GQkcA+x*kGZgwAC&01r6-zspCxwld`4~iEZGot%8<4p%sS7d>FR_YB` z1Ifjyuvj`fc|U|FGJ>_SBP*e_IMD*V%9fftjgs&{b6*4#VT3Vun6n`CvL$#d*2ygL z)7eoDSMZ1NGifW#;&EW?%%%0BG5R6&cx8T(iz?c$ah{_eCRo%Dp%dN0c9w$xeo))f z!{R2?4ug`a98BH;1&H}cNC!iP7dTNKFKcpxcOl6#wP-SCOy% z!JYwOsHXEGr4S3cKrNjJ=%MF4T z@!bVaWe=0&6`nIQ;)FZc{l;u(ho}|4c%t0S8wEmM$g~?uCNTxxtk^R4o;IIHXg4Nb zZhIyY?230y#03^WP!{XWxKemhpfBjbwIDOpx8d|`8Pt~dI`s(SzLBSax8yVhRmu9{ zw$*00x8`h$)GaBWP=7&dA{3Isa5b890UcZ}9{lKpxjTOUjiBd@0mQR5q$sBg0u@Iy zwll8RkI|Pv!)|-}!4Q;*3w)M>CtQ|YfuY*dE7B89}m%)-8C#3~yUl6@M z@$xCS^_0V!62E%u6hMI}Baijc^H8CqqH=??%n$8DrN(@_lxx_H?j+3I+s>0uS4W-> zq0;-tBt+ZUCJDUZPCC#K`72}xS)J822;Tq5LaYD!CkRo6su~3oN zg&ag$fC3ZxSR5uvsAWN7eFh2^)f87O^;9TTDscs|OpfUC5ghp1K49VjDrt>4fKO=L zLxxhlumLD^ZNtMYZExK9PV1gvZsMjXa&<%d^2M4I|F-IW|5xsB0rGy*D60s$dYsg6 zMdyH$$qnp@ADG-=TiGN!GTMc$NnfrNngX>@GClAFT;EKG&5U1Bb*)IV83-ppR>OmP z;mE%>wS^m>hiH7_YYVSpTmR5U_95QXcNL(22X&|AmEtABFNSh^r+yF3YBOQc4!O80 zW_5fFeqSWTBALo%V#({BIC-%Lq^vp1z-V;gLfX5Rua>+TgW*Re+49!T|9sLVQu&ivPtDwn<# zB=%%^7~>Vd1WyRru7m;?SybRpuTdTkp!CqN?qy2_^y(`WSe9uYa9qE|o zcGg`Ff;qg;-$@F&9QY~YAiHAU+kZCb9ucTo{Gb6k#xmH@V2*O=2$V9hv3N!FG!${7 zTp-rnDN>xcgi;~=_Mxb*sFFSwD6?;CdR1Cbi8F3{DehvaW-t1+1l`nx@J2Uuss#I} z7YEQopO?lmS-vrY<18fFZQj;RUYHV1%R8M@0Tkd>SU5a}8CH-r{t1(N7NT#$sq)^w zmVCLx`_@z>k8uq?b|oJ{kgpSC_o3O$%4V2RH#rTN1lnS2uTuJCihJod=< zbK*bD&;BL?vnWrN{SD(*)sBR6Em-F63?LK}2oSl&aN^HYHdZan2q(BF z)D7uS5-tMDl2IECM|7gx%2> zc};Ho`i;kR%Dy)GUpF~6W1Ki*Wd%6#FMi5xBe)PX;SaussO4z3-v?U!u2?q%8AwgJaANO0!?)r6)*$^idCj}7^=gi;C5G{41QB@Q*c8MR zn@7|~dhs0<3%J0Tf=dI8%-XKKYj#sRI^D}q0b6V;M(o(HwO9@8wBzAG+cAYdGz_#F+444xshfBlAac=NZ;*fOTY9TtZ05z^pR5AEUigsEZVK|3P%EN69l9T#rt ztMj^w%zcjN9ADJ>WP_UYuZX&jZR@ji&u>=*IXGQau?w2zE-No+$nTgu_GgZsa&$M# zZYvI)dh>Bd=#L)dh+N*aEL{^5`qD^U_KpbEKUE%6$K7WS@R1G!nIcLmnv5J+Ack3a z2%04+f%{()h=i%kj`tsqCkKKoh%KE`ZGs_5p$zYHg~mcPi@d*l{hE-c6mFY*IgBX* zL6~^BD26Gh26+p)EPJ2IL;Sue$6HLwX#VB^s1h4Q+Hww|5(zlpA&M+;`=Svm=S+;v zJkHERRBWx#%q|GpK%F+Rc$V1Q(oO+`kKp_?Haa3}B9gaq1r)nI#4!25hPe^VDlLJ6 z5!=XtON&dC5`5o5js^}ccFq*%Q{E2ZcqcfHG;3~hzIV1Smr2JnUrzA}qvJS0pHByD zCj6^D|3`QKV-Mkn7l`7C+;{KiDa87OI_;q(s#HJaMS4T(P0Ely98^+ZR5*wy_!G56 z3+J?z-u?HtV2|%ah$ea4I0FGlLpsR$NLzoiQt?zYqY;)WuKzk zX&zj^7gwX#;?y|AsCmpgmqu;LL}sQV%xExYp;~&@;1uwbc*ZH@^yP4QVY8iniz)@m z`NT(X?G-$aA(h8Yb5{k|ODM1t4fD*k+EhMk&aPsfdgTiZ`crm;aE@iffH$0xl)xzk zP;cf1mo~EIT*L1pFr>c)6bMypnY#=C1chd$F z%xSI__^fdrclZD!Ywh;nrQKS)Gv4n`Ga?-lrHjRFhZVaU8$}1Fr&DC&0+5EHg+pD* z&pKO@6Taone5>3KFT+$B7Il<7`8grSj`|R;58(C6d48Z%;pV6 zj;G<~o22D(mZ@K0+17Z31aLV+Ib~<-!z5SSzQzTB0}{rh&2duz%ly zaG}^#dJ9k$#eoF^;`w!0|1(z1zu5!@L z@tL*vL%QefR>d1{NE>i|3C`dpl0@?KUi{TkiN6mGNRUDey67%i8-Y4@?C?4BK3S) zfr7HErec}l`_~GWBpfXk`;cTxqhQ@?lDsP1%O4g~b66sRNmD#`1VWS0+t5BO78E2& zICkZ`iPxc*m11BQxRt7dE1Ik0(P7<}s}!ezaiQ@+*Mlw==xGFmqi$4i>jy2&9mUsA z*j>?_P%uwoz{pMh_#KrelvNTR1Opo6mb0SRdK0M!Onk`Fp z=ys4!Z0vaFCTK~5b`EdIQS#2A*Qxqp3-@B7aA|=0WBE1wz(P~(nkuXl$tH%v&|#9R zeLm0olbua(?JgZv2G?R6yz3gVQMwP#Y?)mq-k6@gOK|{k8!R#T#dqf~3JgcyYV_!1 zp9v$!CMgIg^wGUhsG`m7QN0#1VZJ^W5m6TdZ-x>ULth(W{8-URkIild7h~&lW-x6# zkamVW=Fm$^>gUSsTS%jcc8$w;GJ85Mm6ERkFl=0h8YO#a*X7vZdhL(NZ^$yXf-l)ch{DbY`+M4q6{fN>WVq;uQz|Q)ZP2YT2wh+vZ+$wOqNyK`2r(RlH>uebaK2avbVcg z{@;W^5h;qUc)ExRI?u}9`&={vL4h#9%kfVg8oSDKpXrtx)=Dkv95RS`c6_Ya%CPQC zTS5MSS`B|Ys|SBOr^kwpi#7i^XAT5X7Z2tT*1m^K5{>uKVM+tlmjz}bI(8LGIh*ms zsMRF~)Z zhf64Z9SiFjJH1?Ww#3?_{~Ehqr&!d1@{PteLg{| z77qv)uM`QvK+3m{7!R~TPcnJ&7Vd@$JSpSW?&Q|)()t24_zF+GMe1DJe9u=JL((pz z4@A;xoiw;3?LGCEciG5$Z{N|`rA>OUUZZTmgJoTfSjMXtou~^{@2Gdt3#}aVPkp&$ z;<#mYqWv~IR4PWq6R@TK>G(xHnxscc2G>Kz zna3IzOUIMP6YyJPT55w=uM}j6{e%$j8MAVCg2K`y>GEQHGW+Q1C~P&o&OS8KcHC@N z=WVu!LBgQ8k675M3KmokUnj4A2`EwxIHITBFM{dT(;41?F>3Zo@~au76RvQJs*KoS z&L@-VLeWtdWPLNQgrr$_l(4LdjNv_DW?{dFzQj%)S2oXPWW_8#V2>5y%Hx-?Of->d(WT$~az&0U;asF!k=o??sn0dY zP~Sai?n7|WSX9ty2<<9(n`Ys=AX@RNRjzxYcMjsFZ?*klo(9`Xy0pz%+dO3^(+0== zbA1P2Ogj6>A;Xc#xtnp7B~iZ?OK=h>aDmEqi5QqA&V7UYaQwbvoMw%fid2k?v=$&W zU9LC1N7!8#Q-WfmkA|V1){F$W1nSN@5^O7TnxTnpys|30Y$U>gDEnU0u7`$EzCUgxKF=SKK zc(M!e{m6AkXWHEu3NF(2SA@7<23J^(Jg^;%h5KGp(c)gN$N7PNs6sUOs-M(%hY-0? z|B;LE-P5z_yS}s1J{j;76a!AP{;PNwe>?_)&boGne>lMWCEi7uGGMK$fW+GXaJzP@ zLeKG9htxxEMuTA+D1<>_B7;wzX8q{haH4_P(6W0v8!dhg{dEgbRwR;)&j-;kT{BT* zGF5alYiw*J#lFCK_w@1W)i+2V*HX%u9(Z`}>My23@3YcyD46nzA%%NuA6 z$lONl=$>A5cNf{XGkwN zKJmz+b(iE7?Za|mYx@aj!F+AgUP^!_!U^+IR_LR7^Wd6_?3V!V5M8Vknv-+Y*0=VB z3RDkWb~q(Xg>VWlaH=;l$s&6kowW8sh+In-9=`2&@$jt{s5oin8d<4-abf1&S1-yY z4Xll-Q5$CpVd1vYSL)4;BBv`+o2Uw73krO-6KUK|T~D`hx1+))!2)*!D_zF}$3nUF z@+Bco^6H5c!eU*o;#dsv6N7QlCIKiGMYk#s&zjCk;|@N&6P?8zHiT>2<9Z~6OW+dy z1;en?LH?maVakQZ=w<717oPTVD5{odQy#~CajBt5Rs?}0C1?oiNK3OWSt#y7$R%ayCbDQ7oAH<-&`Wp2>)fn@T+)hdW? zvE+)d2_$+7ALBDazH-i|WSMsT%KI8p;uxa*y6SzABt(4(r{>`#y^}+@uNBzb65Cdz zz%0=Yndh4^T4e5FymIOP2e;OLU$IhxNx)$Py!MR08zX)l`2XVJ z^~^~xQbAU_TL8%u;DbF~QB3)XgcU}tLY7)W0SyEOdbQ!8*+P<|dL`kJ9q|#!JE2iF z2P|F)Gcm)p=B!P3ckkv1x081a-vK`zC7nzWwj4fZ4YttY{*0j83 z`PT;>OuT#X3hZf2Y|#0OO*KdOdF<`w8GXTMqD!jidZDjP_B-7vFClC@%wCpeyiVBR z-jHXmyT>GNns9^GS}Ruz7(N+Gs|YythV2@4+Vsb`i=eGpP)ZXpdFz-;FN8{;cCt`v zc+QT8%U1bDX*pG@Uj@NNt;c*Ds=wF$3*_JHS9k(r_YmL_=>d2n_*Y@vV3A``LM;>6=Nn|z zre+N07A%UrbNF+fy2fh#6N|1jjqmfH-t*^9**oh)QB;1kEqHS}+ypo@-}EWd{rd6h z%$flx&-P89`bb8uk&YOaJsvhT3Wg!wx(1MRS$J~<4L!=WM+XbG8e#Rw9dqM9!@ z+#_6QHns5>W898fQL8nHugDl&2EBr0Q&x_YDt@cktT5=HQP5iCd`p4gHB$_A!2NZi zfd&6%=r+PKcF zcD>}A2!}ZrljP{g7lSURAIQNm87b5}hmrWXJFAsVr&+soJYUbIW<3f`8Rn&64AN|n zSdEEN^c|s2!F}}qI+8?SVwkqY15P7FqL;E!ycf$J%{gv!1HO@T*!_;91hNgu4&Yv_ zLVv=T^B%)U-s|Imj%(pjRp^!<7P~u*P@4{oI(<@|8!tD9aMICh#2eS4$eGG3v%|!D z3A9hb5HtqpqehMMa#N!Ts_sj&kZ`-;{^vSa$2KvUzQTu(^Rn+6Ub!urJ5;1XyfGF+ zPk&ug5Jz{R?Xt?FQ>0Rd;JiS)`RxM2aDHoU{Tt$KM~`fJ4=u@MHp~=H1h{{0>(l^Z z)`#oM8@Fg94%5>@ozPzIKn4u?Z9^Kdq zb>z6+;*Il{_Z$%8;%)VaMOgBcyqA`}UcP78_o$yfdftM9!cK-_c98twa zHqXs$;lCQr75r$Jq!!*D1TBMN$&{KKiwJy76aO*8aAD0)##01^2jiQZ=S6PyL9z`dPCX(PcIvRFR%Q%oq&J*9@-?yiy6KV#!b`ri50d zRQ+HHJA+XuO_7QOd(_ieE+CfY<*sY!`#?Q6B zy5398or>DtM&>Pt;fqQzX%#y7TO~D@!Q8N`jsznSaHVV@QII_GY`mUV{igy`NP(A}J%X}?5&&wsZWPQiBz zc?)>svRp9m2Q!__B)myK^VmyYTJ!dL1hE0?7sFX%XPzI+HQT~=qMN2?g-TJ)yv&^o zP-?RkV&wTaPG0K7dqAKQ@lbwGb9HunYmN}@dk%i*Y6CgtG26<8lS=_zY90qI7DfB}ire6El{#mc z;nEwoLQ&~Dc`v!lIOL$!8Cqc^q1h(sj5ncZeba?%Dy69??%`Jp?ZZZ>TN*R4Ep}sI zw{?js2HG>`K26%gY%2}$aMg~J`MfG&2;w$5vc%2GLM?tmm92FD7>Lt&#@luqnUb7n zMTH2f?x*aH%6_dW3+wKB{N5x-bY8Q7_w;nlC+dFhl!&BN&Ff1*S?}lyRicHzJ65=f zO#y?AA+n$PMh7kEH#NpfC>Lnwc{{Z)Vlk`VfVXgIAuJw^YU76nsxsw4)XG69SOl3M zXsToc7Sjz)_Km2o@OS4l8Pk|X#8Bcodlqp{eX(rt5%t!Csf6D|iO(IUR*jxn8u2KO zQ2ElC42(){N+?>x3X&7oo+mgooiaS zIvzb95Qu_Akw-&VCsEKR{6ZwE1sQ^Dq&q8pmb6%CggTRbctH9@U2Nq8LLNW}pd=Wl z)2ye3h=#^9CL^`Tj0Z|w$>T;#V)NRoh|No=l@&1z-e+UkRuibQ&9wG2&Ky}hRs@pk z&{u^6Votln-4}O_cY$AM;?jnlE9nfz_he1h*m+5^E44Gg@Gffy)%TbyGEpeMe`{2) z5*7nD8Bstj#>{{T1EU_vd5^`35WIP5gh(GPDeFoGC)=FJWY{fZomyNDEx}y7*y@Q+ zE!*X`kfss8HWb@hx{mGnzB$zNE*{{roGJ) z74vfpFx-*xmyL|>aP{5|H_RRB2nK&RUyU)Q5Nyxk0h)N4isUHfG~i4EXs`76b>R{p zaTE$B^0yjYa0Dz4T!#L-BNMU4i_Hbr=KTo*#^mn;q#H-@)7~#Sw!WzJVyR2QRWHPVe)!r_j!+mZ)-gCwne;e2sekE2s#u zBB@|AlL)>RmIfI%!jyQ9yJ=36Y=kjt3Ss$!7>SBfYIXZ3iz10mkjP@voHl-|)^tIh z#IY2OH0SyP1y$O`Gex+}Lv)?dR?e$O)x$1IK~cET zQ>(H{FhP9X=x~9~8;=t1n2V;CyWI65+}B__iGq-W+!Er~oYCPvy%Po`*xl&OqhjBD zAY4Ky{Ib^XLF8{~54CQ6@9!S7KA#DyA;cCC4>(OU)A_lDLI*%?VKI zVF7!a^&(NWCGBf}7T177CBQTaEqJ;4=I>8sWt6@0_tP^XfDa+y^Fs#!aMb<(TLYk) zx#~9>06Tw+{0|I*1`1Fvhk^oP1X%b0y#E*V9xyumxR8KO1iyck6;%?Xmy{C&9Mu1N zvW7l2DgnShC<8udfX|;-p6~a!#s5ntD<~%^CaS3PLRRdr2;|R*0khqY3km3(U>e}N zwVm0c5a{ypIj35H*oP5cau-UI%12Jj*Mk^K9u z))ybJ{`#KRAIyIO{HY7|XQcJ#IqF>voJ9l7^EQBze{cRjuUcPVz+e9f@cF6^u)cF~ z6?Akk0mQyF)&CjT`8ng>v6_7`fMyBsA^DRIaIf`s2IS#4jFNwr;g6Th=XhX6ZYx@V zyea@v)Bg=m7ho&?4W782u7QQ2G9diCgteuijJ377qs{N3@iw)WdI2E!fL{82L-^0D z))&xce+LbS`D@{54>(sQW@=$5sIPBmZ!fEBrEC1B(!%q+kHG7QeUG4h2e9Y;J?{hn zQPbb#UG)!X4uGk{$kf;o5I!3aO8)nGSMbC)-2qeyHX!eee`XwTul2o0`YrVH_LKmK zMOgf|jOV*DHmd+K4g{#3?<2;aSFJBS#&6MOtd0L`EsWV6g`ordOsoK9{(da#&#TtA z6CeWen_Bpr?A`B+&$(K^f(v-Wjsc?p(Vu{Td#x`v;OB2J0fzz|bS*4?kG9e&6WRl) z%y)o+>F@1i2j~~SK@+mJcK9y4VI!++Y6Y;l{uJAI-UTFP8_1>rZA1zv>UYV6Kd)L} zU(Vk`|L6juE{6J!{}(;|Icfk-UP(0oRS1Ae^Cu+WUhA7G{9DvN9*Q5>-!uLDig>QM z`zLg*ZvsF><~J4bqgwyl@bg^b@F$)FU_k#3-rt)3zbPI*uZ`#Wc|TdaRDa9z&m+!r z*_@wnvv2-y^87IX|8@fXYyQ4(ZatU1`3Y$J_P>kZJV*JS>iZ-4{rWB&^T+jl9<$W_ zTPeSXuz8;Nxrof4$!mSne@*(7j@&*7g7gZzZ2H25WNe}Vn+a>?{-Z~R_w z&m}m1qM{o93)FuQ46!nEyV!!gHSIhx~u?BuD(h^XuU8ua5jb=X`!t`zNPZ^#A7k{c!c% zr}ii2dCvdF{Edh0^GrW?VEjq2llLzO{yIwiz68(R$9@tF6#hc+=PdDW48PAy^4#6y zCy{UIFGRm|*MEB4o^PT5L=LX_1^L&`^au3sH`JdO;`!F)Pb#&ybLsOPyPvR& zHU9+rW5D=_{k!J{cy8DK$wbij3)A!WhriU_|0vLNTk}tv^QK>D{sQ}>K!4o+VeETu zbo_}g(fTj&|GNqDd3`;%qx>XV1sDeYcrynq2!C%?c_j@FcnkclF2e+b1PDE++xh+1 F{{tUq7iIte literal 0 HcmV?d00001 diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/java/okhttp-gson-parcelableModel/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..b7a36473955 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue May 17 23:08:05 CST 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-bin.zip diff --git a/samples/client/petstore/java/okhttp-gson/gradlew b/samples/client/petstore/java/okhttp-gson-parcelableModel/gradlew similarity index 100% rename from samples/client/petstore/java/okhttp-gson/gradlew rename to samples/client/petstore/java/okhttp-gson-parcelableModel/gradlew diff --git a/samples/client/petstore/java/okhttp-gson/gradlew.bat b/samples/client/petstore/java/okhttp-gson-parcelableModel/gradlew.bat similarity index 100% rename from samples/client/petstore/java/okhttp-gson/gradlew.bat rename to samples/client/petstore/java/okhttp-gson-parcelableModel/gradlew.bat diff --git a/samples/client/petstore/java/okhttp-gson/pom.xml b/samples/client/petstore/java/okhttp-gson-parcelableModel/pom.xml similarity index 100% rename from samples/client/petstore/java/okhttp-gson/pom.xml rename to samples/client/petstore/java/okhttp-gson-parcelableModel/pom.xml diff --git a/samples/client/petstore/java/okhttp-gson/settings.gradle b/samples/client/petstore/java/okhttp-gson-parcelableModel/settings.gradle similarity index 100% rename from samples/client/petstore/java/okhttp-gson/settings.gradle rename to samples/client/petstore/java/okhttp-gson-parcelableModel/settings.gradle diff --git a/samples/client/petstore/java/okhttp-gson/src/main/AndroidManifest.xml b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/AndroidManifest.xml similarity index 100% rename from samples/client/petstore/java/okhttp-gson/src/main/AndroidManifest.xml rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/AndroidManifest.xml diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/ApiCallback.java similarity index 100% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/ApiCallback.java diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/ApiClient.java similarity index 100% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/ApiClient.java diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/ApiException.java similarity index 100% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/ApiException.java diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiResponse.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/ApiResponse.java similarity index 100% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiResponse.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/ApiResponse.java diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/Configuration.java similarity index 100% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/Configuration.java diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/JSON.java similarity index 100% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/JSON.java diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/Pair.java similarity index 100% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/Pair.java diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressRequestBody.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/ProgressRequestBody.java similarity index 100% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressRequestBody.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/ProgressRequestBody.java diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressResponseBody.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/ProgressResponseBody.java similarity index 100% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressResponseBody.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/ProgressResponseBody.java diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/StringUtil.java similarity index 100% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/StringUtil.java diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/FakeApi.java similarity index 100% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/FakeApi.java diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/PetApi.java similarity index 100% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/PetApi.java diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/StoreApi.java similarity index 100% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/StoreApi.java diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/UserApi.java similarity index 100% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/UserApi.java diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/auth/ApiKeyAuth.java similarity index 100% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/auth/ApiKeyAuth.java diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/auth/Authentication.java similarity index 100% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/auth/Authentication.java diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/auth/HttpBasicAuth.java similarity index 100% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/auth/HttpBasicAuth.java diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/auth/OAuth.java similarity index 100% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/auth/OAuth.java diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/auth/OAuthFlow.java similarity index 100% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuthFlow.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/auth/OAuthFlow.java diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java similarity index 81% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index d20b1402ce2..437a78be54c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -32,13 +32,14 @@ import java.util.HashMap; import java.util.List; import java.util.Map; - +import android.os.Parcelable; +import android.os.Parcel; /** * AdditionalPropertiesClass */ -public class AdditionalPropertiesClass { +public class AdditionalPropertiesClass implements Parcelable { @SerializedName("map_property") private Map mapProperty = new HashMap(); @@ -131,5 +132,35 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(mapProperty); + + out.writeValue(mapOfMapProperty); + } + + public AdditionalPropertiesClass() { + super(); + } + + AdditionalPropertiesClass(Parcel in) { + + mapProperty = (Map)in.readValue(null); + mapOfMapProperty = (Map>)in.readValue(Map.class.getClassLoader()); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public AdditionalPropertiesClass createFromParcel(Parcel in) { + return new AdditionalPropertiesClass(in); + } + public AdditionalPropertiesClass[] newArray(int size) { + return new AdditionalPropertiesClass[size]; + } + }; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Animal.java similarity index 81% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Animal.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Animal.java index 9b1ff3df1c5..4329ce2253c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Animal.java @@ -29,13 +29,14 @@ import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import android.os.Parcelable; +import android.os.Parcel; /** * Animal */ -public class Animal { +public class Animal implements Parcelable { @SerializedName("className") private String className = null; @@ -118,5 +119,35 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(className); + + out.writeValue(color); + } + + public Animal() { + super(); + } + + Animal(Parcel in) { + + className = (String)in.readValue(null); + color = (String)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public Animal createFromParcel(Parcel in) { + return new Animal(in); + } + public Animal[] newArray(int size) { + return new Animal[size]; + } + }; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/AnimalFarm.java similarity index 75% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AnimalFarm.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/AnimalFarm.java index 563476ccb3d..81d9cba7996 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -29,13 +29,14 @@ import io.swagger.client.model.Animal; import java.util.ArrayList; import java.util.List; - +import android.os.Parcelable; +import android.os.Parcel; /** * AnimalFarm */ -public class AnimalFarm extends ArrayList { +public class AnimalFarm extends ArrayList implements Parcelable { @Override public boolean equals(java.lang.Object o) { @@ -72,5 +73,29 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + + public void writeToParcel(Parcel out, int flags) { + super.writeToParcel(out, flags); } + + public AnimalFarm() { + super(); + } + + AnimalFarm(Parcel in) { + super(in); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public AnimalFarm createFromParcel(Parcel in) { + return new AnimalFarm(in); + } + public AnimalFarm[] newArray(int size) { + return new AnimalFarm[size]; + } + }; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java similarity index 78% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 4c2fa22800f..cbf5aaebacb 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -32,13 +32,14 @@ import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; - +import android.os.Parcelable; +import android.os.Parcel; /** * ArrayOfArrayOfNumberOnly */ -public class ArrayOfArrayOfNumberOnly { +public class ArrayOfArrayOfNumberOnly implements Parcelable { @SerializedName("ArrayArrayNumber") private List> arrayArrayNumber = new ArrayList>(); @@ -103,5 +104,32 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(arrayArrayNumber); + } + + public ArrayOfArrayOfNumberOnly() { + super(); + } + + ArrayOfArrayOfNumberOnly(Parcel in) { + + arrayArrayNumber = (List>)in.readValue(List.class.getClassLoader()); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public ArrayOfArrayOfNumberOnly createFromParcel(Parcel in) { + return new ArrayOfArrayOfNumberOnly(in); + } + public ArrayOfArrayOfNumberOnly[] newArray(int size) { + return new ArrayOfArrayOfNumberOnly[size]; + } + }; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java similarity index 79% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index 3c7d74dc3b5..f714b7660b7 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -32,13 +32,14 @@ import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; - +import android.os.Parcelable; +import android.os.Parcel; /** * ArrayOfNumberOnly */ -public class ArrayOfNumberOnly { +public class ArrayOfNumberOnly implements Parcelable { @SerializedName("ArrayNumber") private List arrayNumber = new ArrayList(); @@ -103,5 +104,32 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(arrayNumber); + } + + public ArrayOfNumberOnly() { + super(); + } + + ArrayOfNumberOnly(Parcel in) { + + arrayNumber = (List)in.readValue(BigDecimal.class.getClassLoader()); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public ArrayOfNumberOnly createFromParcel(Parcel in) { + return new ArrayOfNumberOnly(in); + } + public ArrayOfNumberOnly[] newArray(int size) { + return new ArrayOfNumberOnly[size]; + } + }; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ArrayTest.java similarity index 83% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ArrayTest.java index 7e08b24fa6e..c90ada4e4db 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ArrayTest.java @@ -32,13 +32,14 @@ import io.swagger.client.model.ReadOnlyFirst; import java.util.ArrayList; import java.util.List; - +import android.os.Parcelable; +import android.os.Parcel; /** * ArrayTest */ -public class ArrayTest { +public class ArrayTest implements Parcelable { @SerializedName("array_of_string") private List arrayOfString = new ArrayList(); @@ -159,5 +160,38 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(arrayOfString); + + out.writeValue(arrayArrayOfInteger); + + out.writeValue(arrayArrayOfModel); + } + + public ArrayTest() { + super(); + } + + ArrayTest(Parcel in) { + + arrayOfString = (List)in.readValue(null); + arrayArrayOfInteger = (List>)in.readValue(List.class.getClassLoader()); + arrayArrayOfModel = (List>)in.readValue(List.class.getClassLoader()); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public ArrayTest createFromParcel(Parcel in) { + return new ArrayTest(in); + } + public ArrayTest[] newArray(int size) { + return new ArrayTest[size]; + } + }; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Cat.java similarity index 71% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Cat.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Cat.java index 9c5cb39f648..b2de1391b39 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Cat.java @@ -30,13 +30,21 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; - +import android.os.Parcelable; +import android.os.Parcel; /** * Cat */ -public class Cat extends Animal { +public class Cat extends Animal implements Parcelable { + @SerializedName("className") + private String className = null; + + @SerializedName("color") + private String color = "red"; + +>>>>>>> fix bug with parcelable:samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Cat.java @SerializedName("declawed") private Boolean declawed = null; @@ -97,5 +105,38 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + + public void writeToParcel(Parcel out, int flags) { + super.writeToParcel(out, flags); + out.writeValue(className); + + out.writeValue(color); + + out.writeValue(declawed); + } + + public Cat() { + super(); + } + + Cat(Parcel in) { + super(in); + className = (String)in.readValue(null); + color = (String)in.readValue(null); + declawed = (Boolean)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public Cat createFromParcel(Parcel in) { + return new Cat(in); + } + public Cat[] newArray(int size) { + return new Cat[size]; + } + }; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Category.java similarity index 80% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Category.java index 44e76030eff..ae9a59adc9e 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Category.java @@ -29,13 +29,14 @@ import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import android.os.Parcelable; +import android.os.Parcel; /** * Category */ -public class Category { +public class Category implements Parcelable { @SerializedName("id") private Long id = null; @@ -118,5 +119,35 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(id); + + out.writeValue(name); + } + + public Category() { + super(); + } + + Category(Parcel in) { + + id = (Long)in.readValue(null); + name = (String)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public Category createFromParcel(Parcel in) { + return new Category(in); + } + public Category[] newArray(int size) { + return new Category[size]; + } + }; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Dog.java similarity index 70% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Dog.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Dog.java index 880c159616c..3e74dcb15ad 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Dog.java @@ -30,13 +30,21 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; - +import android.os.Parcelable; +import android.os.Parcel; /** * Dog */ -public class Dog extends Animal { +public class Dog extends Animal implements Parcelable { + @SerializedName("className") + private String className = null; + + @SerializedName("color") + private String color = "red"; + +>>>>>>> fix bug with parcelable:samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Dog.java @SerializedName("breed") private String breed = null; @@ -97,5 +105,38 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + + public void writeToParcel(Parcel out, int flags) { + super.writeToParcel(out, flags); + out.writeValue(className); + + out.writeValue(color); + + out.writeValue(breed); + } + + public Dog() { + super(); + } + + Dog(Parcel in) { + super(in); + className = (String)in.readValue(null); + color = (String)in.readValue(null); + breed = (String)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public Dog createFromParcel(Parcel in) { + return new Dog(in); + } + public Dog[] newArray(int size) { + return new Dog[size]; + } + }; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/EnumClass.java similarity index 96% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumClass.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/EnumClass.java index 7862a8b8952..9bbb91b93ae 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/EnumClass.java @@ -27,7 +27,8 @@ import java.util.Objects; import com.google.gson.annotations.SerializedName; - +import android.os.Parcelable; +import android.os.Parcel; /** diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/EnumTest.java similarity index 85% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/EnumTest.java index 83896fbd849..ce94e934b17 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/EnumTest.java @@ -29,13 +29,14 @@ import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import android.os.Parcelable; +import android.os.Parcel; /** * EnumTest */ -public class EnumTest { +public class EnumTest implements Parcelable { /** * Gets or Sets enumString */ @@ -207,5 +208,38 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(enumString); + + out.writeValue(enumInteger); + + out.writeValue(enumNumber); + } + + public EnumTest() { + super(); + } + + EnumTest(Parcel in) { + + enumString = (EnumStringEnum)in.readValue(null); + enumInteger = (EnumIntegerEnum)in.readValue(null); + enumNumber = (EnumNumberEnum)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public EnumTest createFromParcel(Parcel in) { + return new EnumTest(in); + } + public EnumTest[] newArray(int size) { + return new EnumTest[size]; + } + }; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/FormatTest.java similarity index 85% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/FormatTest.java index a05f1d5c811..6da8e63693d 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/FormatTest.java @@ -32,13 +32,14 @@ import java.math.BigDecimal; import org.joda.time.DateTime; import org.joda.time.LocalDate; - +import android.os.Parcelable; +import android.os.Parcel; /** * FormatTest */ -public class FormatTest { +public class FormatTest implements Parcelable { @SerializedName("integer") private Integer integer = null; @@ -384,5 +385,68 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(integer); + + out.writeValue(int32); + + out.writeValue(int64); + + out.writeValue(number); + + out.writeValue(_float); + + out.writeValue(_double); + + out.writeValue(string); + + out.writeValue(_byte); + + out.writeValue(binary); + + out.writeValue(date); + + out.writeValue(dateTime); + + out.writeValue(uuid); + + out.writeValue(password); + } + + public FormatTest() { + super(); + } + + FormatTest(Parcel in) { + + integer = (Integer)in.readValue(null); + int32 = (Integer)in.readValue(null); + int64 = (Long)in.readValue(null); + number = (BigDecimal)in.readValue(null); + _float = (Float)in.readValue(null); + _double = (Double)in.readValue(null); + string = (String)in.readValue(null); + _byte = (byte[])in.readValue(null); + binary = (byte[])in.readValue(null); + date = (LocalDate)in.readValue(null); + dateTime = (DateTime)in.readValue(null); + uuid = (String)in.readValue(null); + password = (String)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public FormatTest createFromParcel(Parcel in) { + return new FormatTest(in); + } + public FormatTest[] newArray(int size) { + return new FormatTest[size]; + } + }; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java similarity index 77% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java index e53b1a0d8be..287bada323c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -29,13 +29,14 @@ import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import android.os.Parcelable; +import android.os.Parcel; /** * HasOnlyReadOnly */ -public class HasOnlyReadOnly { +public class HasOnlyReadOnly implements Parcelable { @SerializedName("bar") private String bar = null; @@ -100,5 +101,35 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(bar); + + out.writeValue(foo); + } + + public HasOnlyReadOnly() { + super(); + } + + HasOnlyReadOnly(Parcel in) { + + bar = (String)in.readValue(null); + foo = (String)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public HasOnlyReadOnly createFromParcel(Parcel in) { + return new HasOnlyReadOnly(in); + } + public HasOnlyReadOnly[] newArray(int size) { + return new HasOnlyReadOnly[size]; + } + }; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/MapTest.java similarity index 84% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MapTest.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/MapTest.java index e7d394ed035..61e6fff8e4b 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/MapTest.java @@ -32,13 +32,14 @@ import java.util.HashMap; import java.util.List; import java.util.Map; - +import android.os.Parcelable; +import android.os.Parcel; /** * MapTest */ -public class MapTest { +public class MapTest implements Parcelable { @SerializedName("map_map_of_string") private Map> mapMapOfString = new HashMap>(); @@ -153,5 +154,35 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(mapMapOfString); + + out.writeValue(mapOfEnumString); + } + + public MapTest() { + super(); + } + + MapTest(Parcel in) { + + mapMapOfString = (Map>)in.readValue(Map.class.getClassLoader()); + mapOfEnumString = (Map)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public MapTest createFromParcel(Parcel in) { + return new MapTest(in); + } + public MapTest[] newArray(int size) { + return new MapTest[size]; + } + }; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java similarity index 78% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 887ba516d72..5121e62791b 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -34,13 +34,14 @@ import java.util.List; import java.util.Map; import org.joda.time.DateTime; - +import android.os.Parcelable; +import android.os.Parcel; /** * MixedPropertiesAndAdditionalPropertiesClass */ -public class MixedPropertiesAndAdditionalPropertiesClass { +public class MixedPropertiesAndAdditionalPropertiesClass implements Parcelable { @SerializedName("uuid") private String uuid = null; @@ -151,5 +152,38 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(uuid); + + out.writeValue(dateTime); + + out.writeValue(map); + } + + public MixedPropertiesAndAdditionalPropertiesClass() { + super(); + } + + MixedPropertiesAndAdditionalPropertiesClass(Parcel in) { + + uuid = (String)in.readValue(null); + dateTime = (DateTime)in.readValue(null); + map = (Map)in.readValue(Animal.class.getClassLoader()); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public MixedPropertiesAndAdditionalPropertiesClass createFromParcel(Parcel in) { + return new MixedPropertiesAndAdditionalPropertiesClass(in); + } + public MixedPropertiesAndAdditionalPropertiesClass[] newArray(int size) { + return new MixedPropertiesAndAdditionalPropertiesClass[size]; + } + }; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Model200Response.java similarity index 80% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Model200Response.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Model200Response.java index 980bc83e869..ba5997cc7dc 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Model200Response.java @@ -29,14 +29,15 @@ import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import android.os.Parcelable; +import android.os.Parcel; /** * Model for testing model name starting with number */ @ApiModel(description = "Model for testing model name starting with number") -public class Model200Response { +public class Model200Response implements Parcelable { @SerializedName("name") private Integer name = null; @@ -119,5 +120,35 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(name); + + out.writeValue(PropertyClass); + } + + public Model200Response() { + super(); + } + + Model200Response(Parcel in) { + + name = (Integer)in.readValue(null); + PropertyClass = (String)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public Model200Response createFromParcel(Parcel in) { + return new Model200Response(in); + } + public Model200Response[] newArray(int size) { + return new Model200Response[size]; + } + }; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ModelApiResponse.java similarity index 80% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelApiResponse.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ModelApiResponse.java index f9c162a7934..573f8c5a6ab 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -29,13 +29,14 @@ import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import android.os.Parcelable; +import android.os.Parcel; /** * ModelApiResponse */ -public class ModelApiResponse { +public class ModelApiResponse implements Parcelable { @SerializedName("code") private Integer code = null; @@ -141,5 +142,38 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(code); + + out.writeValue(type); + + out.writeValue(message); + } + + public ModelApiResponse() { + super(); + } + + ModelApiResponse(Parcel in) { + + code = (Integer)in.readValue(null); + type = (String)in.readValue(null); + message = (String)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public ModelApiResponse createFromParcel(Parcel in) { + return new ModelApiResponse(in); + } + public ModelApiResponse[] newArray(int size) { + return new ModelApiResponse[size]; + } + }; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ModelReturn.java similarity index 79% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelReturn.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ModelReturn.java index bbe7780055c..1d9cdbc1f05 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ModelReturn.java @@ -29,14 +29,15 @@ import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import android.os.Parcelable; +import android.os.Parcel; /** * Model for testing reserved words */ @ApiModel(description = "Model for testing reserved words") -public class ModelReturn { +public class ModelReturn implements Parcelable { @SerializedName("return") private Integer _return = null; @@ -96,5 +97,32 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(_return); + } + + public ModelReturn() { + super(); + } + + ModelReturn(Parcel in) { + + _return = (Integer)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public ModelReturn createFromParcel(Parcel in) { + return new ModelReturn(in); + } + public ModelReturn[] newArray(int size) { + return new ModelReturn[size]; + } + }; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Name.java similarity index 82% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Name.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Name.java index d51354ceffa..94c4fa78b05 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Name.java @@ -29,14 +29,15 @@ import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import android.os.Parcelable; +import android.os.Parcel; /** * Model for testing model name same as property name */ @ApiModel(description = "Model for testing model name same as property name") -public class Name { +public class Name implements Parcelable { @SerializedName("name") private Integer name = null; @@ -147,5 +148,41 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(name); + + out.writeValue(snakeCase); + + out.writeValue(property); + + out.writeValue(_123Number); + } + + public Name() { + super(); + } + + Name(Parcel in) { + + name = (Integer)in.readValue(null); + snakeCase = (Integer)in.readValue(null); + property = (String)in.readValue(null); + _123Number = (Integer)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public Name createFromParcel(Parcel in) { + return new Name(in); + } + public Name[] newArray(int size) { + return new Name[size]; + } + }; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/NumberOnly.java similarity index 79% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/NumberOnly.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/NumberOnly.java index 2b1817300a9..3b8fbd205b8 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/NumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/NumberOnly.java @@ -30,13 +30,14 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; - +import android.os.Parcelable; +import android.os.Parcel; /** * NumberOnly */ -public class NumberOnly { +public class NumberOnly implements Parcelable { @SerializedName("JustNumber") private BigDecimal justNumber = null; @@ -96,5 +97,32 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(justNumber); + } + + public NumberOnly() { + super(); + } + + NumberOnly(Parcel in) { + + justNumber = (BigDecimal)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public NumberOnly createFromParcel(Parcel in) { + return new NumberOnly(in); + } + public NumberOnly[] newArray(int size) { + return new NumberOnly[size]; + } + }; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Order.java similarity index 85% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Order.java index f52e7bd5db4..74ea704775c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Order.java @@ -30,13 +30,14 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.joda.time.DateTime; - +import android.os.Parcelable; +import android.os.Parcel; /** * Order */ -public class Order { +public class Order implements Parcelable { @SerializedName("id") private Long id = null; @@ -236,5 +237,47 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(id); + + out.writeValue(petId); + + out.writeValue(quantity); + + out.writeValue(shipDate); + + out.writeValue(status); + + out.writeValue(complete); + } + + public Order() { + super(); + } + + Order(Parcel in) { + + id = (Long)in.readValue(null); + petId = (Long)in.readValue(null); + quantity = (Integer)in.readValue(null); + shipDate = (DateTime)in.readValue(null); + status = (StatusEnum)in.readValue(null); + complete = (Boolean)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public Order createFromParcel(Parcel in) { + return new Order(in); + } + public Order[] newArray(int size) { + return new Order[size]; + } + }; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Pet.java similarity index 85% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Pet.java index 06443e56915..851cb446cec 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Pet.java @@ -33,13 +33,14 @@ import io.swagger.client.model.Tag; import java.util.ArrayList; import java.util.List; - +import android.os.Parcelable; +import android.os.Parcel; /** * Pet */ -public class Pet { +public class Pet implements Parcelable { @SerializedName("id") private Long id = null; @@ -249,5 +250,47 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(id); + + out.writeValue(category); + + out.writeValue(name); + + out.writeValue(photoUrls); + + out.writeValue(tags); + + out.writeValue(status); + } + + public Pet() { + super(); + } + + Pet(Parcel in) { + + id = (Long)in.readValue(null); + category = (Category)in.readValue(null); + name = (String)in.readValue(null); + photoUrls = (List)in.readValue(null); + tags = (List)in.readValue(Tag.class.getClassLoader()); + status = (StatusEnum)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public Pet createFromParcel(Parcel in) { + return new Pet(in); + } + public Pet[] newArray(int size) { + return new Pet[size]; + } + }; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ReadOnlyFirst.java similarity index 78% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ReadOnlyFirst.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index 75dbc55f9f5..45cde5d0d24 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -29,13 +29,14 @@ import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import android.os.Parcelable; +import android.os.Parcel; /** * ReadOnlyFirst */ -public class ReadOnlyFirst { +public class ReadOnlyFirst implements Parcelable { @SerializedName("bar") private String bar = null; @@ -109,5 +110,35 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(bar); + + out.writeValue(baz); + } + + public ReadOnlyFirst() { + super(); + } + + ReadOnlyFirst(Parcel in) { + + bar = (String)in.readValue(null); + baz = (String)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public ReadOnlyFirst createFromParcel(Parcel in) { + return new ReadOnlyFirst(in); + } + public ReadOnlyFirst[] newArray(int size) { + return new ReadOnlyFirst[size]; + } + }; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/SpecialModelName.java similarity index 79% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/SpecialModelName.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/SpecialModelName.java index 9744ad08268..8737aa82928 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -29,13 +29,14 @@ import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import android.os.Parcelable; +import android.os.Parcel; /** * SpecialModelName */ -public class SpecialModelName { +public class SpecialModelName implements Parcelable { @SerializedName("$special[property.name]") private Long specialPropertyName = null; @@ -95,5 +96,32 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(specialPropertyName); + } + + public SpecialModelName() { + super(); + } + + SpecialModelName(Parcel in) { + + specialPropertyName = (Long)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public SpecialModelName createFromParcel(Parcel in) { + return new SpecialModelName(in); + } + public SpecialModelName[] newArray(int size) { + return new SpecialModelName[size]; + } + }; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Tag.java similarity index 81% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Tag.java index 9eef0141c71..67bf5b0d7c7 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Tag.java @@ -29,13 +29,14 @@ import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import android.os.Parcelable; +import android.os.Parcel; /** * Tag */ -public class Tag { +public class Tag implements Parcelable { @SerializedName("id") private Long id = null; @@ -118,5 +119,35 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(id); + + out.writeValue(name); + } + + public Tag() { + super(); + } + + Tag(Parcel in) { + + id = (Long)in.readValue(null); + name = (String)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public Tag createFromParcel(Parcel in) { + return new Tag(in); + } + public Tag[] newArray(int size) { + return new Tag[size]; + } + }; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/User.java similarity index 84% rename from samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java rename to samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/User.java index 73584bfdccb..785747bfbd0 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/User.java @@ -29,13 +29,14 @@ import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import android.os.Parcelable; +import android.os.Parcel; /** * User */ -public class User { +public class User implements Parcelable { @SerializedName("id") private Long id = null; @@ -256,5 +257,53 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + + public void writeToParcel(Parcel out, int flags) { + + out.writeValue(id); + + out.writeValue(username); + + out.writeValue(firstName); + + out.writeValue(lastName); + + out.writeValue(email); + + out.writeValue(password); + + out.writeValue(phone); + + out.writeValue(userStatus); + } + + public User() { + super(); + } + + User(Parcel in) { + + id = (Long)in.readValue(null); + username = (String)in.readValue(null); + firstName = (String)in.readValue(null); + lastName = (String)in.readValue(null); + email = (String)in.readValue(null); + password = (String)in.readValue(null); + phone = (String)in.readValue(null); + userStatus = (Integer)in.readValue(null); + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public User createFromParcel(Parcel in) { + return new User(in); + } + public User[] newArray(int size) { + return new User[size]; + } + }; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/FakeApiTest.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/FakeApiTest.java new file mode 100644 index 00000000000..5a7d2e5aa80 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/FakeApiTest.java @@ -0,0 +1,92 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import org.joda.time.LocalDate; +import org.joda.time.DateTime; +import java.math.BigDecimal; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for FakeApi + */ +public class FakeApiTest { + + private final FakeApi api = new FakeApi(); + + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testEndpointParametersTest() throws ApiException { + BigDecimal number = null; + Double _double = null; + String string = null; + byte[] _byte = null; + Integer integer = null; + Integer int32 = null; + Long int64 = null; + Float _float = null; + byte[] binary = null; + LocalDate date = null; + DateTime dateTime = null; + String password = null; + // api.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + + // TODO: test validations + } + + /** + * To test enum query parameters + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testEnumQueryParametersTest() throws ApiException { + String enumQueryString = null; + BigDecimal enumQueryInteger = null; + Double enumQueryDouble = null; + // api.testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/PetApiTest.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/PetApiTest.java new file mode 100644 index 00000000000..373f7d287ad --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/PetApiTest.java @@ -0,0 +1,180 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.model.Pet; +import java.io.File; +import io.swagger.client.model.ModelApiResponse; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for PetApi + */ +public class PetApiTest { + + private final PetApi api = new PetApi(); + + + /** + * Add a new pet to the store + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void addPetTest() throws ApiException { + Pet body = null; + // api.addPet(body); + + // TODO: test validations + } + + /** + * Deletes a pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deletePetTest() throws ApiException { + Long petId = null; + String apiKey = null; + // api.deletePet(petId, apiKey); + + // TODO: test validations + } + + /** + * Finds Pets by status + * + * Multiple status values can be provided with comma separated strings + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void findPetsByStatusTest() throws ApiException { + List status = null; + // List response = api.findPetsByStatus(status); + + // TODO: test validations + } + + /** + * Finds Pets by tags + * + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void findPetsByTagsTest() throws ApiException { + List tags = null; + // List response = api.findPetsByTags(tags); + + // TODO: test validations + } + + /** + * Find pet by ID + * + * Returns a single pet + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getPetByIdTest() throws ApiException { + Long petId = null; + // Pet response = api.getPetById(petId); + + // TODO: test validations + } + + /** + * Update an existing pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updatePetTest() throws ApiException { + Pet body = null; + // api.updatePet(body); + + // TODO: test validations + } + + /** + * Updates a pet in the store with form data + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updatePetWithFormTest() throws ApiException { + Long petId = null; + String name = null; + String status = null; + // api.updatePetWithForm(petId, name, status); + + // TODO: test validations + } + + /** + * uploads an image + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void uploadFileTest() throws ApiException { + Long petId = null; + String additionalMetadata = null; + File file = null; + // ModelApiResponse response = api.uploadFile(petId, additionalMetadata, file); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/StoreApiTest.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/StoreApiTest.java new file mode 100644 index 00000000000..4bcdcbf8338 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/StoreApiTest.java @@ -0,0 +1,108 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.model.Order; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for StoreApi + */ +public class StoreApiTest { + + private final StoreApi api = new StoreApi(); + + + /** + * Delete purchase order by ID + * + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deleteOrderTest() throws ApiException { + String orderId = null; + // api.deleteOrder(orderId); + + // TODO: test validations + } + + /** + * Returns pet inventories by status + * + * Returns a map of status codes to quantities + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getInventoryTest() throws ApiException { + // Map response = api.getInventory(); + + // TODO: test validations + } + + /** + * Find purchase order by ID + * + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getOrderByIdTest() throws ApiException { + Long orderId = null; + // Order response = api.getOrderById(orderId); + + // TODO: test validations + } + + /** + * Place an order for a pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void placeOrderTest() throws ApiException { + Order body = null; + // Order response = api.placeOrder(body); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/UserApiTest.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/UserApiTest.java new file mode 100644 index 00000000000..832748dbb45 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/test/java/io/swagger/client/api/UserApiTest.java @@ -0,0 +1,174 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.model.User; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for UserApi + */ +public class UserApiTest { + + private final UserApi api = new UserApi(); + + + /** + * Create user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUserTest() throws ApiException { + User body = null; + // api.createUser(body); + + // TODO: test validations + } + + /** + * Creates list of users with given input array + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUsersWithArrayInputTest() throws ApiException { + List body = null; + // api.createUsersWithArrayInput(body); + + // TODO: test validations + } + + /** + * Creates list of users with given input array + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUsersWithListInputTest() throws ApiException { + List body = null; + // api.createUsersWithListInput(body); + + // TODO: test validations + } + + /** + * Delete user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deleteUserTest() throws ApiException { + String username = null; + // api.deleteUser(username); + + // TODO: test validations + } + + /** + * Get user by user name + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getUserByNameTest() throws ApiException { + String username = null; + // User response = api.getUserByName(username); + + // TODO: test validations + } + + /** + * Logs user into the system + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void loginUserTest() throws ApiException { + String username = null; + String password = null; + // String response = api.loginUser(username, password); + + // TODO: test validations + } + + /** + * Logs out current logged in user session + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void logoutUserTest() throws ApiException { + // api.logoutUser(); + + // TODO: test validations + } + + /** + * Updated user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updateUserTest() throws ApiException { + String username = null; + User body = null; + // api.updateUser(username, body); + + // TODO: test validations + } + +} From c915f8ecdcdcfc22f808dea0bdce7a57b54827b6 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 5 Oct 2016 20:30:54 +0800 Subject: [PATCH 414/470] update pom to test java okhttp-gson parcelable models --- pom.xml | 12 +++++++++++ .../java/okhttp-gson-parcelableModel/pom.xml | 21 ++++++++++++++++--- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index a06b416d98e..4f8a6f1219a 100644 --- a/pom.xml +++ b/pom.xml @@ -304,6 +304,18 @@ samples/client/petstore/java/okhttp-gson + + java-client-okhttp-gson-parcelable + + + env + java + + + + samples/client/petstore/java/okhttp-gson/parcelableModel + + java-client-retrofit diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/pom.xml b/samples/client/petstore/java/okhttp-gson-parcelableModel/pom.xml index 3d23d7ca06d..bcfd371c3d4 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/pom.xml +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/pom.xml @@ -97,9 +97,24 @@ - org.apache.maven.plugins - maven-javadoc-plugin - 2.10.4 + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + gradle-test + integration-test + + exec + + + gradle + + test + + + + From 8db0ec8b738d58c77ccd66002c226ced12faf58f Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 5 Oct 2016 20:56:50 +0800 Subject: [PATCH 415/470] fix pom duplicated id issue --- .../client/petstore/java/okhttp-gson-parcelableModel/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/pom.xml b/samples/client/petstore/java/okhttp-gson-parcelableModel/pom.xml index bcfd371c3d4..9998f398c10 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/pom.xml +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/pom.xml @@ -2,9 +2,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 io.swagger - swagger-petstore-okhttp-gson + petstore-okhttp-gson-parcelable jar - swagger-petstore-okhttp-gson + petstore-okhttp-gson-parcelable 1.0.0 scm:git:git@github.com:swagger-api/swagger-mustache.git From 6ef0209dea908ae5e95e17975982905efb3e2f35 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 5 Oct 2016 22:15:15 +0800 Subject: [PATCH 416/470] add back java okhttp petstore client --- .../src/main/resources/Java/pojo.mustache | 2 +- .../petstore/java/okhttp-gson/.gitignore | 21 + .../java/okhttp-gson/.swagger-codegen-ignore | 23 + .../petstore/java/okhttp-gson/.travis.yml | 29 + .../client/petstore/java/okhttp-gson/LICENSE | 201 +++ .../petstore/java/okhttp-gson/build.gradle | 103 ++ .../petstore/java/okhttp-gson/build.sbt | 20 + .../petstore/java/okhttp-gson/git_push.sh | 52 + .../java/okhttp-gson/gradle.properties | 2 + .../client/petstore/java/okhttp-gson/gradlew | 160 ++ .../petstore/java/okhttp-gson/gradlew.bat | 90 ++ .../client/petstore/java/okhttp-gson/pom.xml | 148 ++ .../petstore/java/okhttp-gson/settings.gradle | 1 + .../okhttp-gson/src/main/AndroidManifest.xml | 3 + .../java/io/swagger/client/ApiCallback.java | 74 + .../java/io/swagger/client/ApiClient.java | 1326 +++++++++++++++++ .../java/io/swagger/client/ApiException.java | 103 ++ .../java/io/swagger/client/ApiResponse.java | 71 + .../java/io/swagger/client/Configuration.java | 51 + .../src/main/java/io/swagger/client/JSON.java | 237 +++ .../src/main/java/io/swagger/client/Pair.java | 64 + .../swagger/client/ProgressRequestBody.java | 95 ++ .../swagger/client/ProgressResponseBody.java | 88 ++ .../java/io/swagger/client/StringUtil.java | 67 + .../java/io/swagger/client/api/FakeApi.java | 353 +++++ .../java/io/swagger/client/api/PetApi.java | 935 ++++++++++++ .../java/io/swagger/client/api/StoreApi.java | 482 ++++++ .../java/io/swagger/client/api/UserApi.java | 907 +++++++++++ .../io/swagger/client/auth/ApiKeyAuth.java | 87 ++ .../swagger/client/auth/Authentication.java | 41 + .../io/swagger/client/auth/HttpBasicAuth.java | 66 + .../java/io/swagger/client/auth/OAuth.java | 51 + .../io/swagger/client/auth/OAuthFlow.java | 30 + .../model/AdditionalPropertiesClass.java | 125 ++ .../java/io/swagger/client/model/Animal.java | 122 ++ .../io/swagger/client/model/AnimalFarm.java | 76 + .../model/ArrayOfArrayOfNumberOnly.java | 102 ++ .../client/model/ArrayOfNumberOnly.java | 102 ++ .../io/swagger/client/model/ArrayTest.java | 148 ++ .../java/io/swagger/client/model/Cat.java | 147 ++ .../io/swagger/client/model/Category.java | 122 ++ .../java/io/swagger/client/model/Dog.java | 147 ++ .../io/swagger/client/model/EnumClass.java | 56 + .../io/swagger/client/model/EnumTest.java | 211 +++ .../io/swagger/client/model/FormatTest.java | 388 +++++ .../swagger/client/model/HasOnlyReadOnly.java | 104 ++ .../java/io/swagger/client/model/MapTest.java | 147 ++ ...ropertiesAndAdditionalPropertiesClass.java | 150 ++ .../client/model/Model200Response.java | 123 ++ .../client/model/ModelApiResponse.java | 145 ++ .../io/swagger/client/model/ModelReturn.java | 100 ++ .../java/io/swagger/client/model/Name.java | 151 ++ .../io/swagger/client/model/NumberOnly.java | 100 ++ .../java/io/swagger/client/model/Order.java | 240 +++ .../java/io/swagger/client/model/Pet.java | 243 +++ .../swagger/client/model/ReadOnlyFirst.java | 113 ++ .../client/model/SpecialModelName.java | 99 ++ .../java/io/swagger/client/model/Tag.java | 122 ++ .../java/io/swagger/client/model/User.java | 260 ++++ 59 files changed, 9825 insertions(+), 1 deletion(-) create mode 100644 samples/client/petstore/java/okhttp-gson/.gitignore create mode 100644 samples/client/petstore/java/okhttp-gson/.swagger-codegen-ignore create mode 100644 samples/client/petstore/java/okhttp-gson/.travis.yml create mode 100644 samples/client/petstore/java/okhttp-gson/LICENSE create mode 100644 samples/client/petstore/java/okhttp-gson/build.gradle create mode 100644 samples/client/petstore/java/okhttp-gson/build.sbt create mode 100644 samples/client/petstore/java/okhttp-gson/git_push.sh create mode 100644 samples/client/petstore/java/okhttp-gson/gradle.properties create mode 100644 samples/client/petstore/java/okhttp-gson/gradlew create mode 100644 samples/client/petstore/java/okhttp-gson/gradlew.bat create mode 100644 samples/client/petstore/java/okhttp-gson/pom.xml create mode 100644 samples/client/petstore/java/okhttp-gson/settings.gradle create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/AndroidManifest.xml create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiResponse.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressRequestBody.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressResponseBody.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuthFlow.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Animal.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AnimalFarm.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Cat.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Dog.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumClass.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MapTest.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Model200Response.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelApiResponse.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelReturn.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Name.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/NumberOnly.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ReadOnlyFirst.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/SpecialModelName.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java diff --git a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache index e4058beca39..adb200bc449 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache @@ -3,7 +3,7 @@ */{{#description}} @ApiModel(description = "{{{description}}}"){{/description}} {{>generatedAnnotation}} -public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#parcelableModel}}implements Parcelable{{#serializableModel}}, Serializable{{/serializableModel}}{{/parcelableModel}}{{^parcelableModel}}{{#serializableModel}}implements Serializable{{/serializableModel}}{{/parcelableModel}} { +public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#parcelableModel}}implements Parcelable {{#serializableModel}}, Serializable {{/serializableModel}}{{/parcelableModel}}{{^parcelableModel}}{{#serializableModel}}implements Serializable {{/serializableModel}}{{/parcelableModel}}{ {{#vars}} {{#isEnum}} {{^isContainer}} diff --git a/samples/client/petstore/java/okhttp-gson/.gitignore b/samples/client/petstore/java/okhttp-gson/.gitignore new file mode 100644 index 00000000000..a530464afa1 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/.gitignore @@ -0,0 +1,21 @@ +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# exclude jar for gradle wrapper +!gradle/wrapper/*.jar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# build files +**/target +target +.gradle +build diff --git a/samples/client/petstore/java/okhttp-gson/.swagger-codegen-ignore b/samples/client/petstore/java/okhttp-gson/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/java/okhttp-gson/.travis.yml b/samples/client/petstore/java/okhttp-gson/.travis.yml new file mode 100644 index 00000000000..33e79472abd --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/.travis.yml @@ -0,0 +1,29 @@ +# +# Generated by: https://github.com/swagger-api/swagger-codegen.git +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +language: java +jdk: + - oraclejdk8 + - oraclejdk7 +before_install: + # ensure gradlew has proper permission + - chmod a+x ./gradlew +script: + # test using maven + - mvn test + # uncomment below to test using gradle + # - gradle test + # uncomment below to test using sbt + # - sbt test diff --git a/samples/client/petstore/java/okhttp-gson/LICENSE b/samples/client/petstore/java/okhttp-gson/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore/java/okhttp-gson/build.gradle b/samples/client/petstore/java/okhttp-gson/build.gradle new file mode 100644 index 00000000000..d7c6b63ea75 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/build.gradle @@ -0,0 +1,103 @@ +apply plugin: 'idea' +apply plugin: 'eclipse' + +group = 'io.swagger' +version = '1.0.0' + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.5.+' + classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3' + } +} + +repositories { + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 23 + buildToolsVersion '23.0.2' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 23 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = 'swagger-petstore-okhttp-gson' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +dependencies { + compile 'io.swagger:swagger-annotations:1.5.8' + compile 'com.squareup.okhttp:okhttp:2.7.5' + compile 'com.squareup.okhttp:logging-interceptor:2.7.5' + compile 'com.google.code.gson:gson:2.6.2' + compile 'joda-time:joda-time:2.9.3' + testCompile 'junit:junit:4.12' +} diff --git a/samples/client/petstore/java/okhttp-gson/build.sbt b/samples/client/petstore/java/okhttp-gson/build.sbt new file mode 100644 index 00000000000..01a1095f8a4 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/build.sbt @@ -0,0 +1,20 @@ +lazy val root = (project in file(".")). + settings( + organization := "io.swagger", + name := "swagger-petstore-okhttp-gson", + version := "1.0.0", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "io.swagger" % "swagger-annotations" % "1.5.8", + "com.squareup.okhttp" % "okhttp" % "2.7.5", + "com.squareup.okhttp" % "logging-interceptor" % "2.7.5", + "com.google.code.gson" % "gson" % "2.6.2", + "joda-time" % "joda-time" % "2.9.3" % "compile", + "junit" % "junit" % "4.12" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/samples/client/petstore/java/okhttp-gson/git_push.sh b/samples/client/petstore/java/okhttp-gson/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/client/petstore/java/okhttp-gson/gradle.properties b/samples/client/petstore/java/okhttp-gson/gradle.properties new file mode 100644 index 00000000000..05644f0754a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/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/okhttp-gson/gradlew b/samples/client/petstore/java/okhttp-gson/gradlew new file mode 100644 index 00000000000..9d82f789151 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/samples/client/petstore/java/okhttp-gson/gradlew.bat b/samples/client/petstore/java/okhttp-gson/gradlew.bat new file mode 100644 index 00000000000..72d362dafd8 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/java/okhttp-gson/pom.xml b/samples/client/petstore/java/okhttp-gson/pom.xml new file mode 100644 index 00000000000..2fe4b9d3a5e --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/pom.xml @@ -0,0 +1,148 @@ + + 4.0.0 + io.swagger + swagger-petstore-okhttp-gson + jar + swagger-petstore-okhttp-gson + 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 + 1.10 + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + + + + io.swagger + swagger-annotations + ${swagger-core-version} + + + com.squareup.okhttp + okhttp + ${okhttp-version} + + + com.squareup.okhttp + logging-interceptor + ${okhttp-version} + + + com.google.code.gson + gson + ${gson-version} + + + joda-time + joda-time + ${jodatime-version} + + + + + junit + junit + ${junit-version} + test + + + + 1.7 + ${java.version} + ${java.version} + 1.5.9 + 2.7.5 + 2.6.2 + 2.9.3 + 1.0.0 + 4.12 + UTF-8 + + diff --git a/samples/client/petstore/java/okhttp-gson/settings.gradle b/samples/client/petstore/java/okhttp-gson/settings.gradle new file mode 100644 index 00000000000..b73eec84591 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "swagger-petstore-okhttp-gson" \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson/src/main/AndroidManifest.xml b/samples/client/petstore/java/okhttp-gson/src/main/AndroidManifest.xml new file mode 100644 index 00000000000..465dcb520c4 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java new file mode 100644 index 00000000000..3ca33cf8017 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java @@ -0,0 +1,74 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import java.io.IOException; + +import java.util.Map; +import java.util.List; + +/** + * Callback for asynchronous API call. + * + * @param The return type + */ +public interface ApiCallback { + /** + * This is called when the API call fails. + * + * @param e The exception causing the failure + * @param statusCode Status code of the response if available, otherwise it would be 0 + * @param responseHeaders Headers of the response if available, otherwise it would be null + */ + void onFailure(ApiException e, int statusCode, Map> responseHeaders); + + /** + * This is called when the API call succeeded. + * + * @param result The result deserialized from response + * @param statusCode Status code of the response + * @param responseHeaders Headers of the response + */ + void onSuccess(T result, int statusCode, Map> responseHeaders); + + /** + * This is called when the API upload processing. + * + * @param bytesWritten bytes Written + * @param contentLength content length of request body + * @param done write end + */ + void onUploadProgress(long bytesWritten, long contentLength, boolean done); + + /** + * This is called when the API downlond processing. + * + * @param bytesRead bytes Read + * @param contentLength content lenngth of the response + * @param done Read end + */ + void onDownloadProgress(long bytesRead, long contentLength, boolean done); +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java new file mode 100644 index 00000000000..b7b04e3e4c5 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java @@ -0,0 +1,1326 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import com.squareup.okhttp.Call; +import com.squareup.okhttp.Callback; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Response; +import com.squareup.okhttp.RequestBody; +import com.squareup.okhttp.FormEncodingBuilder; +import com.squareup.okhttp.MultipartBuilder; +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.Headers; +import com.squareup.okhttp.internal.http.HttpMethod; +import com.squareup.okhttp.logging.HttpLoggingInterceptor; +import com.squareup.okhttp.logging.HttpLoggingInterceptor.Level; + +import java.lang.reflect.Type; + +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.Map.Entry; +import java.util.HashMap; +import java.util.List; +import java.util.ArrayList; +import java.util.Date; +import java.util.TimeZone; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import java.net.URLEncoder; +import java.net.URLConnection; + +import java.io.File; +import java.io.InputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; + +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.security.SecureRandom; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.text.ParseException; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.KeyManager; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509TrustManager; + +import okio.BufferedSink; +import okio.Okio; + +import io.swagger.client.auth.Authentication; +import io.swagger.client.auth.HttpBasicAuth; +import io.swagger.client.auth.ApiKeyAuth; +import io.swagger.client.auth.OAuth; + +public class ApiClient { + public static final double JAVA_VERSION; + public static final boolean IS_ANDROID; + public static final int ANDROID_SDK_VERSION; + + static { + JAVA_VERSION = Double.parseDouble(System.getProperty("java.specification.version")); + boolean isAndroid; + try { + Class.forName("android.app.Activity"); + isAndroid = true; + } catch (ClassNotFoundException e) { + isAndroid = false; + } + IS_ANDROID = isAndroid; + int sdkVersion = 0; + if (IS_ANDROID) { + try { + sdkVersion = Class.forName("android.os.Build$VERSION").getField("SDK_INT").getInt(null); + } catch (Exception e) { + try { + sdkVersion = Integer.parseInt((String) Class.forName("android.os.Build$VERSION").getField("SDK").get(null)); + } catch (Exception e2) { } + } + } + ANDROID_SDK_VERSION = sdkVersion; + } + + /** + * The datetime format to be used when lenientDatetimeFormat is enabled. + */ + public static final String LENIENT_DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; + + private String basePath = "http://petstore.swagger.io/v2"; + private boolean lenientOnJson = false; + private boolean debugging = false; + private Map defaultHeaderMap = new HashMap(); + private String tempFolderPath = null; + + private Map authentications; + + private DateFormat dateFormat; + private DateFormat datetimeFormat; + private boolean lenientDatetimeFormat; + private int dateLength; + + private InputStream sslCaCert; + private boolean verifyingSsl; + + private OkHttpClient httpClient; + private JSON json; + + private HttpLoggingInterceptor loggingInterceptor; + + /* + * Constructor for ApiClient + */ + public ApiClient() { + httpClient = new OkHttpClient(); + + verifyingSsl = true; + + json = new JSON(this); + + /* + * Use RFC3339 format for date and datetime. + * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + */ + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + // Always use UTC as the default time zone when dealing with date (without time). + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + initDatetimeFormat(); + + // Be lenient on datetime formats when parsing datetime from string. + // See parseDatetime. + this.lenientDatetimeFormat = true; + + // Set default User-Agent. + setUserAgent("Swagger-Codegen/1.0.0/java"); + + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap(); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("petstore_auth", new OAuth()); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + /** + * Get base path + * + * @return Baes path + */ + public String getBasePath() { + return basePath; + } + + /** + * Set base path + * + * @param basePath Base path of the URL (e.g http://petstore.swagger.io/v2 + * @return An instance of OkHttpClient + */ + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + /** + * Get HTTP client + * + * @return An instance of OkHttpClient + */ + public OkHttpClient getHttpClient() { + return httpClient; + } + + /** + * Set HTTP client + * + * @param httpClient An instance of OkHttpClient + * @return Api Client + */ + public ApiClient setHttpClient(OkHttpClient httpClient) { + this.httpClient = httpClient; + return this; + } + + /** + * Get JSON + * + * @return JSON object + */ + public JSON getJSON() { + return json; + } + + /** + * Set JSON + * + * @param json JSON object + * @return Api client + */ + public ApiClient setJSON(JSON json) { + this.json = json; + return this; + } + + /** + * True if isVerifyingSsl flag is on + * + * @return True if isVerifySsl flag is on + */ + public boolean isVerifyingSsl() { + return verifyingSsl; + } + + /** + * Configure whether to verify certificate and hostname when making https requests. + * Default to true. + * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. + * + * @param verifyingSsl True to verify TLS/SSL connection + * @return ApiClient + */ + public ApiClient setVerifyingSsl(boolean verifyingSsl) { + this.verifyingSsl = verifyingSsl; + applySslSettings(); + return this; + } + + /** + * Get SSL CA cert. + * + * @return Input stream to the SSL CA cert + */ + public InputStream getSslCaCert() { + return sslCaCert; + } + + /** + * Configure the CA certificate to be trusted when making https requests. + * Use null to reset to default. + * + * @param sslCaCert input stream for SSL CA cert + * @return ApiClient + */ + public ApiClient setSslCaCert(InputStream sslCaCert) { + this.sslCaCert = sslCaCert; + applySslSettings(); + return this; + } + + public DateFormat getDateFormat() { + return dateFormat; + } + + public ApiClient setDateFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + this.dateLength = this.dateFormat.format(new Date()).length(); + return this; + } + + public DateFormat getDatetimeFormat() { + return datetimeFormat; + } + + public ApiClient setDatetimeFormat(DateFormat datetimeFormat) { + this.datetimeFormat = datetimeFormat; + return this; + } + + /** + * Whether to allow various ISO 8601 datetime formats when parsing a datetime string. + * @see #parseDatetime(String) + * @return True if lenientDatetimeFormat flag is set to true + */ + public boolean isLenientDatetimeFormat() { + return lenientDatetimeFormat; + } + + public ApiClient setLenientDatetimeFormat(boolean lenientDatetimeFormat) { + this.lenientDatetimeFormat = lenientDatetimeFormat; + return this; + } + + /** + * Parse the given date string into Date object. + * The default dateFormat supports these ISO 8601 date formats: + * 2015-08-16 + * 2015-8-16 + * @param str String to be parsed + * @return Date + */ + public Date parseDate(String str) { + if (str == null) + return null; + try { + return dateFormat.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Parse the given datetime string into Date object. + * When lenientDatetimeFormat is enabled, the following ISO 8601 datetime formats are supported: + * 2015-08-16T08:20:05Z + * 2015-8-16T8:20:05Z + * 2015-08-16T08:20:05+00:00 + * 2015-08-16T08:20:05+0000 + * 2015-08-16T08:20:05.376Z + * 2015-08-16T08:20:05.376+00:00 + * 2015-08-16T08:20:05.376+00 + * Note: The 3-digit milli-seconds is optional. Time zone is required and can be in one of + * these formats: + * Z (same with +0000) + * +08:00 (same with +0800) + * -02 (same with -0200) + * -0200 + * @see ISO 8601 + * @param str Date time string to be parsed + * @return Date representation of the string + */ + public Date parseDatetime(String str) { + if (str == null) + return null; + + DateFormat format; + if (lenientDatetimeFormat) { + /* + * When lenientDatetimeFormat is enabled, normalize the date string + * into LENIENT_DATETIME_FORMAT to support various formats + * defined by ISO 8601. + */ + // normalize time zone + // trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000 + str = str.replaceAll("[zZ]\\z", "+0000"); + // remove colon in time zone: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000 + str = str.replaceAll("([+-]\\d{2}):(\\d{2})\\z", "$1$2"); + // expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000 + str = str.replaceAll("([+-]\\d{2})\\z", "$100"); + // add milliseconds when missing + // 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000 + str = str.replaceAll("(:\\d{1,2})([+-]\\d{4})\\z", "$1.000$2"); + format = new SimpleDateFormat(LENIENT_DATETIME_FORMAT); + } else { + format = this.datetimeFormat; + } + + try { + return format.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /* + * Parse date or date time in string format into Date object. + * + * @param str Date time string to be parsed + * @return Date representation of the string + */ + public Date parseDateOrDatetime(String str) { + if (str == null) + return null; + else if (str.length() <= dateLength) + return parseDate(str); + else + return parseDatetime(str); + } + + /** + * Format the given Date object into string (Date format). + * + * @param date Date object + * @return Formatted date in string representation + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } + + /** + * Format the given Date object into string (Datetime format). + * + * @param date Date object + * @return Formatted datetime in string representation + */ + public String formatDatetime(Date date) { + return datetimeFormat.format(date); + } + + /** + * Get authentications (key: authentication name, value: authentication). + * + * @return Map of authentication objects + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + * + * @param username Username + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + * + * @param password Password + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + * + * @param apiKey API key + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + * + * @param apiKeyPrefix API key prefix + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set access token for the first OAuth2 authentication. + * + * @param accessToken Access token + */ + public void setAccessToken(String accessToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); + return; + } + } + throw new RuntimeException("No OAuth2 authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + * + * @param userAgent HTTP request's user agent + * @return ApiClient + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + * @return ApiClient + */ + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + /** + * @see setLenient + * + * @return True if lenientOnJson is enabled, false otherwise. + */ + public boolean isLenientOnJson() { + return lenientOnJson; + } + + /** + * Set LenientOnJson + * + * @param lenient True to enable lenientOnJson + * @return ApiClient + */ + public ApiClient setLenientOnJson(boolean lenient) { + this.lenientOnJson = lenient; + return this; + } + + /** + * Check that whether debugging is enabled for this API client. + * + * @return True if debugging is enabled, false otherwise. + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + * @return ApiClient + */ + public ApiClient setDebugging(boolean debugging) { + if (debugging != this.debugging) { + if (debugging) { + loggingInterceptor = new HttpLoggingInterceptor(); + loggingInterceptor.setLevel(Level.BODY); + httpClient.interceptors().add(loggingInterceptor); + } else { + httpClient.interceptors().remove(loggingInterceptor); + loggingInterceptor = null; + } + } + this.debugging = debugging; + return this; + } + + /** + * The path of temporary folder used to store downloaded files from endpoints + * with file response. The default value is null, i.e. using + * the system's default tempopary folder. + * + * @see createTempFile + * @return Temporary folder path + */ + public String getTempFolderPath() { + return tempFolderPath; + } + + /** + * Set the tempoaray folder path (for downloading files) + * + * @param tempFolderPath Temporary folder path + * @return ApiClient + */ + public ApiClient setTempFolderPath(String tempFolderPath) { + this.tempFolderPath = tempFolderPath; + return this; + } + + /** + * Get connection timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getConnectTimeout() { + return httpClient.getConnectTimeout(); + } + + /** + * Sets the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * + * @param connectionTimeout connection timeout in milliseconds + * @return Api client + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + httpClient.setConnectTimeout(connectionTimeout, TimeUnit.MILLISECONDS); + return this; + } + + /** + * Format the given parameter object into string. + * + * @param param Parameter + * @return String representation of the parameter + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDatetime((Date) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for (Object o : (Collection)param) { + if (b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /** + * Format to {@code Pair} objects. + * + * @param collectionFormat collection format (e.g. csv, tsv) + * @param name Name + * @param value Value + * @return A list of Pair objects + */ + public List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + + // create the params based on the collection format + if (collectionFormat.equals("multi")) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); + } + + return params; + } + + String delimiter = ","; + + if (collectionFormat.equals("csv")) { + delimiter = ","; + } else if (collectionFormat.equals("ssv")) { + delimiter = " "; + } else if (collectionFormat.equals("tsv")) { + delimiter = "\t"; + } else if (collectionFormat.equals("pipes")) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + + return params; + } + + /** + * Sanitize filename by removing path. + * e.g. ../../sun.gif becomes sun.gif + * + * @param filename The filename to be sanitized + * @return The sanitized filename + */ + public String sanitizeFilename(String filename) { + return filename.replaceAll(".*[/\\\\]", ""); + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * + * @param mime MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public boolean isJsonMime(String mime) { + return mime != null && mime.matches("(?i)application\\/json(;.*)?"); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } + return contentTypes[0]; + } + + /** + * Escape the given string to be used as URL query value. + * + * @param str String to be escaped + * @return Escaped string + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Deserialize response body to Java object, according to the return type and + * the Content-Type response header. + * + * @param Type + * @param response HTTP response + * @param returnType The type of the Java object + * @return The deserialized Java object + * @throws ApiException If fail to deserialize response body, i.e. cannot read response body + * or the Content-Type of the response is not supported. + */ + @SuppressWarnings("unchecked") + public T deserialize(Response response, Type returnType) throws ApiException { + if (response == null || returnType == null) { + return null; + } + + if ("byte[]".equals(returnType.toString())) { + // Handle binary response (byte array). + try { + return (T) response.body().bytes(); + } catch (IOException e) { + throw new ApiException(e); + } + } else if (returnType.equals(File.class)) { + // Handle file downloading. + return (T) downloadFileFromResponse(response); + } + + String respBody; + try { + if (response.body() != null) + respBody = response.body().string(); + else + respBody = null; + } catch (IOException e) { + throw new ApiException(e); + } + + if (respBody == null || "".equals(respBody)) { + return null; + } + + String contentType = response.headers().get("Content-Type"); + if (contentType == null) { + // ensuring a default content type + contentType = "application/json"; + } + if (isJsonMime(contentType)) { + return json.deserialize(respBody, returnType); + } else if (returnType.equals(String.class)) { + // Expecting string, return the raw response body. + return (T) respBody; + } else { + throw new ApiException( + "Content type \"" + contentType + "\" is not supported for type: " + returnType, + response.code(), + response.headers().toMultimap(), + respBody); + } + } + + /** + * Serialize the given Java object into request body according to the object's + * class and the request Content-Type. + * + * @param obj The Java object + * @param contentType The request Content-Type + * @return The serialized request body + * @throws ApiException If fail to serialize the given object + */ + public RequestBody serialize(Object obj, String contentType) throws ApiException { + if (obj instanceof byte[]) { + // Binary (byte array) body parameter support. + return RequestBody.create(MediaType.parse(contentType), (byte[]) obj); + } else if (obj instanceof File) { + // File body parameter support. + return RequestBody.create(MediaType.parse(contentType), (File) obj); + } else if (isJsonMime(contentType)) { + String content; + if (obj != null) { + content = json.serialize(obj); + } else { + content = null; + } + return RequestBody.create(MediaType.parse(contentType), content); + } else { + throw new ApiException("Content type \"" + contentType + "\" is not supported"); + } + } + + /** + * Download file from the given response. + * + * @param response An instance of the Response object + * @throws ApiException If fail to read file content from response and write to disk + * @return Downloaded file + */ + public File downloadFileFromResponse(Response response) throws ApiException { + try { + File file = prepareDownloadFile(response); + BufferedSink sink = Okio.buffer(Okio.sink(file)); + sink.writeAll(response.body().source()); + sink.close(); + return file; + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * Prepare file for download + * + * @param response An instance of the Response object + * @throws IOException If fail to prepare file for download + * @return Prepared file for the download + */ + public File prepareDownloadFile(Response response) throws IOException { + String filename = null; + String contentDisposition = response.header("Content-Disposition"); + if (contentDisposition != null && !"".equals(contentDisposition)) { + // Get filename from the Content-Disposition header. + Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); + Matcher matcher = pattern.matcher(contentDisposition); + if (matcher.find()) { + filename = sanitizeFilename(matcher.group(1)); + } + } + + String prefix = null; + String suffix = null; + if (filename == null) { + prefix = "download-"; + suffix = ""; + } else { + int pos = filename.lastIndexOf("."); + if (pos == -1) { + prefix = filename + "-"; + } else { + prefix = filename.substring(0, pos) + "-"; + suffix = filename.substring(pos); + } + // File.createTempFile requires the prefix to be at least three characters long + if (prefix.length() < 3) + prefix = "download-"; + } + + if (tempFolderPath == null) + return File.createTempFile(prefix, suffix); + else + return File.createTempFile(prefix, suffix, new File(tempFolderPath)); + } + + /** + * {@link #execute(Call, Type)} + * + * @param Type + * @param call An instance of the Call object + * @throws ApiException If fail to execute the call + * @return ApiResponse<T> + */ + public ApiResponse execute(Call call) throws ApiException { + return execute(call, null); + } + + /** + * Execute HTTP call and deserialize the HTTP response body into the given return type. + * + * @param returnType The return type used to deserialize HTTP response body + * @param The return type corresponding to (same with) returnType + * @param call Call + * @return ApiResponse object containing response status, headers and + * data, which is a Java object deserialized from response body and would be null + * when returnType is null. + * @throws ApiException If fail to execute the call + */ + public ApiResponse execute(Call call, Type returnType) throws ApiException { + try { + Response response = call.execute(); + T data = handleResponse(response, returnType); + return new ApiResponse(response.code(), response.headers().toMultimap(), data); + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * {@link #executeAsync(Call, Type, ApiCallback)} + * + * @param Type + * @param call An instance of the Call object + * @param callback ApiCallback<T> + */ + public void executeAsync(Call call, ApiCallback callback) { + executeAsync(call, null, callback); + } + + /** + * Execute HTTP call asynchronously. + * + * @see #execute(Call, Type) + * @param Type + * @param call The callback to be executed when the API call finishes + * @param returnType Return type + * @param callback ApiCallback + */ + @SuppressWarnings("unchecked") + public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { + call.enqueue(new Callback() { + @Override + public void onFailure(Request request, IOException e) { + callback.onFailure(new ApiException(e), 0, null); + } + + @Override + public void onResponse(Response response) throws IOException { + T result; + try { + result = (T) handleResponse(response, returnType); + } catch (ApiException e) { + callback.onFailure(e, response.code(), response.headers().toMultimap()); + return; + } + callback.onSuccess(result, response.code(), response.headers().toMultimap()); + } + }); + } + + /** + * Handle the given response, return the deserialized object when the response is successful. + * + * @param Type + * @param response Response + * @param returnType Return type + * @throws ApiException If the response has a unsuccessful status code or + * fail to deserialize the response body + * @return Type + */ + public T handleResponse(Response response, Type returnType) throws ApiException { + if (response.isSuccessful()) { + if (returnType == null || response.code() == 204) { + // returning null if the returnType is not defined, + // or the status code is 204 (No Content) + return null; + } else { + return deserialize(response, returnType); + } + } else { + String respBody = null; + if (response.body() != null) { + try { + respBody = response.body().string(); + } catch (IOException e) { + throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); + } + } + throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); + } + } + + /** + * Build HTTP call with the given options. + * + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param formParams The form parameters + * @param authNames The authentications to apply + * @param progressRequestListener Progress request listener + * @return The HTTP call + * @throws ApiException If fail to serialize the request body object + */ + public Call buildCall(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + updateParamsForAuth(authNames, queryParams, headerParams); + + final String url = buildUrl(path, queryParams); + final Request.Builder reqBuilder = new Request.Builder().url(url); + processHeaderParams(headerParams, reqBuilder); + + String contentType = (String) headerParams.get("Content-Type"); + // ensuring a default content type + if (contentType == null) { + contentType = "application/json"; + } + + RequestBody reqBody; + if (!HttpMethod.permitsRequestBody(method)) { + reqBody = null; + } else if ("application/x-www-form-urlencoded".equals(contentType)) { + reqBody = buildRequestBodyFormEncoding(formParams); + } else if ("multipart/form-data".equals(contentType)) { + reqBody = buildRequestBodyMultipart(formParams); + } else if (body == null) { + if ("DELETE".equals(method)) { + // allow calling DELETE without sending a request body + reqBody = null; + } else { + // use an empty request body (for POST, PUT and PATCH) + reqBody = RequestBody.create(MediaType.parse(contentType), ""); + } + } else { + reqBody = serialize(body, contentType); + } + + Request request = null; + + if(progressRequestListener != null && reqBody != null) { + ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener); + request = reqBuilder.method(method, progressRequestBody).build(); + } else { + request = reqBuilder.method(method, reqBody).build(); + } + + return httpClient.newCall(request); + } + + /** + * Build full URL by concatenating base path, the given sub path and query parameters. + * + * @param path The sub path + * @param queryParams The query parameters + * @return The full URL + */ + public String buildUrl(String path, List queryParams) { + final StringBuilder url = new StringBuilder(); + url.append(basePath).append(path); + + if (queryParams != null && !queryParams.isEmpty()) { + // support (constant) query string in `path`, e.g. "/posts?draft=1" + String prefix = path.contains("?") ? "&" : "?"; + for (Pair param : queryParams) { + if (param.getValue() != null) { + if (prefix != null) { + url.append(prefix); + prefix = null; + } else { + url.append("&"); + } + String value = parameterToString(param.getValue()); + url.append(escapeString(param.getName())).append("=").append(escapeString(value)); + } + } + } + + return url.toString(); + } + + /** + * Set header parameters to the request builder, including default headers. + * + * @param headerParams Header parameters in the ofrm of Map + * @param reqBuilder Reqeust.Builder + */ + public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { + for (Entry param : headerParams.entrySet()) { + reqBuilder.header(param.getKey(), parameterToString(param.getValue())); + } + for (Entry header : defaultHeaderMap.entrySet()) { + if (!headerParams.containsKey(header.getKey())) { + reqBuilder.header(header.getKey(), parameterToString(header.getValue())); + } + } + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + */ + public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); + auth.applyToParams(queryParams, headerParams); + } + } + + /** + * Build a form-encoding request body with the given form parameters. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyFormEncoding(Map formParams) { + FormEncodingBuilder formBuilder = new FormEncodingBuilder(); + for (Entry param : formParams.entrySet()) { + formBuilder.add(param.getKey(), parameterToString(param.getValue())); + } + return formBuilder.build(); + } + + /** + * Build a multipart (file uploading) request body with the given form parameters, + * which could contain text fields and file fields. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyMultipart(Map formParams) { + MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); + for (Entry param : formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\""); + MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); + mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file)); + } else { + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\""); + mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue()))); + } + } + return mpBuilder.build(); + } + + /** + * Guess Content-Type header from the given file (defaults to "application/octet-stream"). + * + * @param file The given file + * @return The guessed Content-Type + */ + public String guessContentTypeFromFile(File file) { + String contentType = URLConnection.guessContentTypeFromName(file.getName()); + if (contentType == null) { + return "application/octet-stream"; + } else { + return contentType; + } + } + + /** + * Initialize datetime format according to the current environment, e.g. Java 1.7 and Android. + */ + private void initDatetimeFormat() { + String formatWithTimeZone = null; + if (IS_ANDROID) { + if (ANDROID_SDK_VERSION >= 18) { + // The time zone format "ZZZZZ" is available since Android 4.3 (SDK version 18) + formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"; + } + } else if (JAVA_VERSION >= 1.7) { + // The time zone format "XXX" is available since Java 1.7 + formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; + } + if (formatWithTimeZone != null) { + this.datetimeFormat = new SimpleDateFormat(formatWithTimeZone); + // NOTE: Use the system's default time zone (mainly for datetime formatting). + } else { + // Use a common format that works across all systems. + this.datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + // Always use the UTC time zone as we are using a constant trailing "Z" here. + this.datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + } + } + + /** + * Apply SSL related settings to httpClient according to the current values of + * verifyingSsl and sslCaCert. + */ + private void applySslSettings() { + try { + KeyManager[] keyManagers = null; + TrustManager[] trustManagers = null; + HostnameVerifier hostnameVerifier = null; + if (!verifyingSsl) { + TrustManager trustAll = new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} + @Override + public X509Certificate[] getAcceptedIssuers() { return null; } + }; + SSLContext sslContext = SSLContext.getInstance("TLS"); + trustManagers = new TrustManager[]{ trustAll }; + hostnameVerifier = new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { return true; } + }; + } else if (sslCaCert != null) { + char[] password = null; // Any password will work. + CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); + Collection certificates = certificateFactory.generateCertificates(sslCaCert); + if (certificates.isEmpty()) { + throw new IllegalArgumentException("expected non-empty set of trusted certificates"); + } + KeyStore caKeyStore = newEmptyKeyStore(password); + int index = 0; + for (Certificate certificate : certificates) { + String certificateAlias = "ca" + Integer.toString(index++); + caKeyStore.setCertificateEntry(certificateAlias, certificate); + } + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagerFactory.init(caKeyStore); + trustManagers = trustManagerFactory.getTrustManagers(); + } + + if (keyManagers != null || trustManagers != null) { + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(keyManagers, trustManagers, new SecureRandom()); + httpClient.setSslSocketFactory(sslContext.getSocketFactory()); + } else { + httpClient.setSslSocketFactory(null); + } + httpClient.setHostnameVerifier(hostnameVerifier); + } catch (GeneralSecurityException e) { + throw new RuntimeException(e); + } + } + + private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { + try { + KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + keyStore.load(null, password); + return keyStore; + } catch (IOException e) { + throw new AssertionError(e); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java new file mode 100644 index 00000000000..3bed001f002 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java @@ -0,0 +1,103 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import java.util.Map; +import java.util.List; + + +public class ApiException extends Exception { + private int code = 0; + private Map> responseHeaders = null; + private String responseBody = null; + + public ApiException() {} + + public ApiException(Throwable throwable) { + super(throwable); + } + + public ApiException(String message) { + super(message); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } + + public ApiException(int code, Map> responseHeaders, String responseBody) { + this((String) null, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(int code, String message) { + super(message); + this.code = code; + } + + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this(code, message); + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + /** + * Get the HTTP status code. + * + * @return HTTP status code + */ + public int getCode() { + return code; + } + + /** + * Get the HTTP response headers. + * + * @return A map of list of string + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + + /** + * Get the HTTP response body. + * + * @return Response body in the form of string + */ + public String getResponseBody() { + return responseBody; + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiResponse.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiResponse.java new file mode 100644 index 00000000000..d7dde1ee939 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiResponse.java @@ -0,0 +1,71 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import java.util.List; +import java.util.Map; + +/** + * API response returned by API call. + * + * @param T The type of data that is deserialized from response body + */ +public class ApiResponse { + final private int statusCode; + final private Map> headers; + final private T data; + + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + */ + public ApiResponse(int statusCode, Map> headers) { + this(statusCode, headers, null); + } + + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + * @param data The object deserialized from response bod + */ + public ApiResponse(int statusCode, Map> headers, T data) { + this.statusCode = statusCode; + this.headers = headers; + this.data = data; + } + + public int getStatusCode() { + return statusCode; + } + + public Map> getHeaders() { + return headers; + } + + public T getData() { + return data; + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java new file mode 100644 index 00000000000..5191b9b73c6 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java @@ -0,0 +1,51 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + + +public class Configuration { + private static ApiClient defaultApiClient = new ApiClient(); + + /** + * Get the default API client, which would be used when creating API + * instances without providing an API client. + * + * @return Default API client + */ + public static ApiClient getDefaultApiClient() { + return defaultApiClient; + } + + /** + * Set the default API client, which would be used when creating API + * instances without providing an API client. + * + * @param apiClient API client + */ + public static void setDefaultApiClient(ApiClient apiClient) { + defaultApiClient = apiClient; + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java new file mode 100644 index 00000000000..540611eab9d --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java @@ -0,0 +1,237 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonNull; +import com.google.gson.JsonParseException; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +import java.io.IOException; +import java.io.StringReader; +import java.lang.reflect.Type; +import java.util.Date; + +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; + +public class JSON { + private ApiClient apiClient; + private Gson gson; + + /** + * JSON constructor. + * + * @param apiClient An instance of ApiClient + */ + public JSON(ApiClient apiClient) { + this.apiClient = apiClient; + gson = new GsonBuilder() + .registerTypeAdapter(Date.class, new DateAdapter(apiClient)) + .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) + .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) + .create(); + } + + /** + * Get Gson. + * + * @return Gson + */ + public Gson getGson() { + return gson; + } + + /** + * Set Gson. + * + * @param gson Gson + */ + public void setGson(Gson gson) { + this.gson = gson; + } + + /** + * Serialize the given Java object into JSON string. + * + * @param obj Object + * @return String representation of the JSON + */ + public String serialize(Object obj) { + return gson.toJson(obj); + } + + /** + * Deserialize the given JSON string to Java object. + * + * @param Type + * @param body The JSON string + * @param returnType The type to deserialize inot + * @return The deserialized Java object + */ + @SuppressWarnings("unchecked") + public T deserialize(String body, Type returnType) { + try { + if (apiClient.isLenientOnJson()) { + JsonReader jsonReader = new JsonReader(new StringReader(body)); + // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) + jsonReader.setLenient(true); + return gson.fromJson(jsonReader, returnType); + } else { + return gson.fromJson(body, returnType); + } + } catch (JsonParseException e) { + // Fallback processing when failed to parse JSON form response body: + // return the response body string directly for the String return type; + // parse response body into date or datetime for the Date return type. + if (returnType.equals(String.class)) + return (T) body; + else if (returnType.equals(Date.class)) + return (T) apiClient.parseDateOrDatetime(body); + else throw(e); + } + } +} + +class DateAdapter implements JsonSerializer, JsonDeserializer { + private final ApiClient apiClient; + + /** + * Constructor for DateAdapter + * + * @param apiClient Api client + */ + public DateAdapter(ApiClient apiClient) { + super(); + this.apiClient = apiClient; + } + + /** + * Serialize + * + * @param src Date + * @param typeOfSrc Type + * @param context Json Serialization Context + * @return Json Element + */ + @Override + public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { + if (src == null) { + return JsonNull.INSTANCE; + } else { + return new JsonPrimitive(apiClient.formatDatetime(src)); + } + } + + /** + * Deserialize + * + * @param json Json element + * @param date Type + * @param typeOfSrc Type + * @param context Json Serialization Context + * @return Date + * @throw JsonParseException if fail to parse + */ + @Override + public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException { + String str = json.getAsJsonPrimitive().getAsString(); + try { + return apiClient.parseDateOrDatetime(str); + } catch (RuntimeException e) { + throw new JsonParseException(e); + } + } +} + +/** + * Gson TypeAdapter for Joda DateTime type + */ +class DateTimeTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + + @Override + public void write(JsonWriter out, DateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public DateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseDateTime(date); + } + } +} + +/** + * Gson TypeAdapter for Joda LocalDate type + */ +class LocalDateTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.date(); + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseLocalDate(date); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java new file mode 100644 index 00000000000..15b247eea93 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java @@ -0,0 +1,64 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + + +public class Pair { + private String name = ""; + private String value = ""; + + public Pair (String name, String value) { + setName(name); + setValue(value); + } + + private void setName(String name) { + if (!isValidString(name)) return; + + this.name = name; + } + + private void setValue(String value) { + if (!isValidString(value)) return; + + this.value = value; + } + + public String getName() { + return this.name; + } + + public String getValue() { + return this.value; + } + + private boolean isValidString(String arg) { + if (arg == null) return false; + if (arg.trim().isEmpty()) return false; + + return true; + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressRequestBody.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressRequestBody.java new file mode 100644 index 00000000000..d9ca742ecd2 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressRequestBody.java @@ -0,0 +1,95 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.RequestBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSink; +import okio.ForwardingSink; +import okio.Okio; +import okio.Sink; + +public class ProgressRequestBody extends RequestBody { + + public interface ProgressRequestListener { + void onRequestProgress(long bytesWritten, long contentLength, boolean done); + } + + private final RequestBody requestBody; + + private final ProgressRequestListener progressListener; + + private BufferedSink bufferedSink; + + public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) { + this.requestBody = requestBody; + this.progressListener = progressListener; + } + + @Override + public MediaType contentType() { + return requestBody.contentType(); + } + + @Override + public long contentLength() throws IOException { + return requestBody.contentLength(); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + if (bufferedSink == null) { + bufferedSink = Okio.buffer(sink(sink)); + } + + requestBody.writeTo(bufferedSink); + bufferedSink.flush(); + + } + + private Sink sink(Sink sink) { + return new ForwardingSink(sink) { + + long bytesWritten = 0L; + long contentLength = 0L; + + @Override + public void write(Buffer source, long byteCount) throws IOException { + super.write(source, byteCount); + if (contentLength == 0) { + contentLength = contentLength(); + } + + bytesWritten += byteCount; + progressListener.onRequestProgress(bytesWritten, contentLength, bytesWritten == contentLength); + } + }; + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressResponseBody.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressResponseBody.java new file mode 100644 index 00000000000..f8af685999d --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressResponseBody.java @@ -0,0 +1,88 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.ResponseBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSource; +import okio.ForwardingSource; +import okio.Okio; +import okio.Source; + +public class ProgressResponseBody extends ResponseBody { + + public interface ProgressListener { + void update(long bytesRead, long contentLength, boolean done); + } + + private final ResponseBody responseBody; + private final ProgressListener progressListener; + private BufferedSource bufferedSource; + + public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) { + this.responseBody = responseBody; + this.progressListener = progressListener; + } + + @Override + public MediaType contentType() { + return responseBody.contentType(); + } + + @Override + public long contentLength() throws IOException { + return responseBody.contentLength(); + } + + @Override + public BufferedSource source() throws IOException { + if (bufferedSource == null) { + bufferedSource = Okio.buffer(source(responseBody.source())); + } + return bufferedSource; + } + + private Source source(Source source) { + return new ForwardingSource(source) { + long totalBytesRead = 0L; + + @Override + public long read(Buffer sink, long byteCount) throws IOException { + long bytesRead = super.read(sink, byteCount); + // read() returns the number of bytes read, or -1 if this source is exhausted. + totalBytesRead += bytesRead != -1 ? bytesRead : 0; + progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1); + return bytesRead; + } + }; + } +} + + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java new file mode 100644 index 00000000000..fdcef6b1010 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java @@ -0,0 +1,67 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + + +public class 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(); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java new file mode 100644 index 00000000000..52dce361e2a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java @@ -0,0 +1,353 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + +import org.joda.time.LocalDate; +import org.joda.time.DateTime; +import java.math.BigDecimal; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class FakeApi { + private ApiClient apiClient; + + public FakeApi() { + this(Configuration.getDefaultApiClient()); + } + + public FakeApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for testEndpointParameters */ + private com.squareup.okhttp.Call testEndpointParametersCall(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'number' is set + if (number == null) { + throw new ApiException("Missing the required parameter 'number' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter '_double' is set + if (_double == null) { + throw new ApiException("Missing the required parameter '_double' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter 'string' is set + if (string == null) { + throw new ApiException("Missing the required parameter 'string' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter '_byte' is set + if (_byte == null) { + throw new ApiException("Missing the required parameter '_byte' when calling testEndpointParameters(Async)"); + } + + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (integer != null) + localVarFormParams.put("integer", integer); + if (int32 != null) + localVarFormParams.put("int32", int32); + if (int64 != null) + localVarFormParams.put("int64", int64); + if (number != null) + localVarFormParams.put("number", number); + if (_float != null) + localVarFormParams.put("float", _float); + if (_double != null) + localVarFormParams.put("double", _double); + if (string != null) + localVarFormParams.put("string", string); + if (_byte != null) + localVarFormParams.put("byte", _byte); + if (binary != null) + localVarFormParams.put("binary", binary); + if (date != null) + localVarFormParams.put("date", date); + if (dateTime != null) + localVarFormParams.put("dateTime", dateTime); + if (password != null) + localVarFormParams.put("password", password); + + final String[] localVarAccepts = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param string None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { + testEndpointParametersWithHttpInfo(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param string None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { + com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password, null, null); + return apiClient.execute(call); + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 (asynchronously) + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param string None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call testEndpointParametersAsync(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for testEnumQueryParameters */ + private com.squareup.okhttp.Call testEnumQueryParametersCall(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (enumQueryInteger != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_integer", enumQueryInteger)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (enumQueryString != null) + localVarFormParams.put("enum_query_string", enumQueryString); + if (enumQueryDouble != null) + localVarFormParams.put("enum_query_double", enumQueryDouble); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * To test enum query parameters + * + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void testEnumQueryParameters(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { + testEnumQueryParametersWithHttpInfo(enumQueryString, enumQueryInteger, enumQueryDouble); + } + + /** + * To test enum query parameters + * + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse testEnumQueryParametersWithHttpInfo(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { + com.squareup.okhttp.Call call = testEnumQueryParametersCall(enumQueryString, enumQueryInteger, enumQueryDouble, null, null); + return apiClient.execute(call); + } + + /** + * To test enum query parameters (asynchronously) + * + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call testEnumQueryParametersAsync(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = testEnumQueryParametersCall(enumQueryString, enumQueryInteger, enumQueryDouble, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java new file mode 100644 index 00000000000..2039a8842c1 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java @@ -0,0 +1,935 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + +import io.swagger.client.model.Pet; +import java.io.File; +import io.swagger.client.model.ModelApiResponse; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class PetApi { + private ApiClient apiClient; + + public PetApi() { + this(Configuration.getDefaultApiClient()); + } + + public PetApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for addPet */ + private com.squareup.okhttp.Call addPetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling addPet(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void addPet(Pet body) throws ApiException { + addPetWithHttpInfo(body); + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse addPetWithHttpInfo(Pet body) throws ApiException { + com.squareup.okhttp.Call call = addPetCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Add a new pet to the store (asynchronously) + * + * @param body Pet object that needs to be added to the store (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call addPetAsync(Pet body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = addPetCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for deletePet */ + private com.squareup.okhttp.Call deletePetCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling deletePet(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + if (apiKey != null) + localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deletePet(Long petId, String apiKey) throws ApiException { + deletePetWithHttpInfo(petId, apiKey); + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deletePetWithHttpInfo(Long petId, String apiKey) throws ApiException { + com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, null, null); + return apiClient.execute(call); + } + + /** + * Deletes a pet (asynchronously) + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deletePetAsync(Long petId, String apiKey, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for findPetsByStatus */ + private com.squareup.okhttp.Call findPetsByStatusCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'status' is set + if (status == null) { + throw new ApiException("Missing the required parameter 'status' when calling findPetsByStatus(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/findByStatus".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (status != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "status", status)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return List<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public List findPetsByStatus(List status) throws ApiException { + ApiResponse> resp = findPetsByStatusWithHttpInfo(status); + return resp.getData(); + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return ApiResponse<List<Pet>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> findPetsByStatusWithHttpInfo(List status) throws ApiException { + com.squareup.okhttp.Call call = findPetsByStatusCall(status, null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Finds Pets by status (asynchronously) + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call findPetsByStatusAsync(List status, final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = findPetsByStatusCall(status, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for findPetsByTags */ + private com.squareup.okhttp.Call findPetsByTagsCall(List tags, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'tags' is set + if (tags == null) { + throw new ApiException("Missing the required parameter 'tags' when calling findPetsByTags(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/findByTags".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (tags != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "tags", tags)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return List<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public List findPetsByTags(List tags) throws ApiException { + ApiResponse> resp = findPetsByTagsWithHttpInfo(tags); + return resp.getData(); + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return ApiResponse<List<Pet>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> findPetsByTagsWithHttpInfo(List tags) throws ApiException { + com.squareup.okhttp.Call call = findPetsByTagsCall(tags, null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Finds Pets by tags (asynchronously) + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call findPetsByTagsAsync(List tags, final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = findPetsByTagsCall(tags, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for getPetById */ + private com.squareup.okhttp.Call getPetByIdCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling getPetById(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "api_key" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return Pet + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Pet getPetById(Long petId) throws ApiException { + ApiResponse resp = getPetByIdWithHttpInfo(petId); + return resp.getData(); + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return ApiResponse<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getPetByIdWithHttpInfo(Long petId) throws ApiException { + com.squareup.okhttp.Call call = getPetByIdCall(petId, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Find pet by ID (asynchronously) + * Returns a single pet + * @param petId ID of pet to return (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getPetByIdAsync(Long petId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getPetByIdCall(petId, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for updatePet */ + private com.squareup.okhttp.Call updatePetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling updatePet(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updatePet(Pet body) throws ApiException { + updatePetWithHttpInfo(body); + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updatePetWithHttpInfo(Pet body) throws ApiException { + com.squareup.okhttp.Call call = updatePetCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Update an existing pet (asynchronously) + * + * @param body Pet object that needs to be added to the store (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updatePetAsync(Pet body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updatePetCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for updatePetWithForm */ + private com.squareup.okhttp.Call updatePetWithFormCall(Long petId, String name, String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling updatePetWithForm(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (name != null) + localVarFormParams.put("name", name); + if (status != null) + localVarFormParams.put("status", status); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/x-www-form-urlencoded" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updatePetWithForm(Long petId, String name, String status) throws ApiException { + updatePetWithFormWithHttpInfo(petId, name, status); + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updatePetWithFormWithHttpInfo(Long petId, String name, String status) throws ApiException { + com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, null, null); + return apiClient.execute(call); + } + + /** + * Updates a pet in the store with form data (asynchronously) + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updatePetWithFormAsync(Long petId, String name, String status, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for uploadFile */ + private com.squareup.okhttp.Call uploadFileCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling uploadFile(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (additionalMetadata != null) + localVarFormParams.put("additionalMetadata", additionalMetadata); + if (file != null) + localVarFormParams.put("file", file); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ModelApiResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { + ApiResponse resp = uploadFileWithHttpInfo(petId, additionalMetadata, file); + return resp.getData(); + } + + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ApiResponse<ModelApiResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file) throws ApiException { + com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * uploads an image (asynchronously) + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call uploadFileAsync(Long petId, String additionalMetadata, File file, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java new file mode 100644 index 00000000000..0768744c263 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java @@ -0,0 +1,482 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + +import io.swagger.client.model.Order; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class StoreApi { + private ApiClient apiClient; + + public StoreApi() { + this(Configuration.getDefaultApiClient()); + } + + public StoreApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for deleteOrder */ + private com.squareup.okhttp.Call deleteOrderCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling deleteOrder(Async)"); + } + + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deleteOrder(String orderId) throws ApiException { + deleteOrderWithHttpInfo(orderId); + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deleteOrderWithHttpInfo(String orderId) throws ApiException { + com.squareup.okhttp.Call call = deleteOrderCall(orderId, null, null); + return apiClient.execute(call); + } + + /** + * Delete purchase order by ID (asynchronously) + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deleteOrderAsync(String orderId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = deleteOrderCall(orderId, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for getInventory */ + private com.squareup.okhttp.Call getInventoryCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + + // create path and map variables + String localVarPath = "/store/inventory".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "api_key" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return Map<String, Integer> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Map getInventory() throws ApiException { + ApiResponse> resp = getInventoryWithHttpInfo(); + return resp.getData(); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return ApiResponse<Map<String, Integer>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> getInventoryWithHttpInfo() throws ApiException { + com.squareup.okhttp.Call call = getInventoryCall(null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Returns pet inventories by status (asynchronously) + * Returns a map of status codes to quantities + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getInventoryAsync(final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getInventoryCall(progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for getOrderById */ + private com.squareup.okhttp.Call getOrderByIdCall(Long orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling getOrderById(Async)"); + } + + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @return Order + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Order getOrderById(Long orderId) throws ApiException { + ApiResponse resp = getOrderByIdWithHttpInfo(orderId); + return resp.getData(); + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @return ApiResponse<Order> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getOrderByIdWithHttpInfo(Long orderId) throws ApiException { + com.squareup.okhttp.Call call = getOrderByIdCall(orderId, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Find purchase order by ID (asynchronously) + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getOrderByIdAsync(Long orderId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getOrderByIdCall(orderId, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for placeOrder */ + private com.squareup.okhttp.Call placeOrderCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling placeOrder(Async)"); + } + + + // create path and map variables + String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet (required) + * @return Order + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Order placeOrder(Order body) throws ApiException { + ApiResponse resp = placeOrderWithHttpInfo(body); + return resp.getData(); + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet (required) + * @return ApiResponse<Order> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse placeOrderWithHttpInfo(Order body) throws ApiException { + com.squareup.okhttp.Call call = placeOrderCall(body, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Place an order for a pet (asynchronously) + * + * @param body order placed for purchasing the pet (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call placeOrderAsync(Order body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = placeOrderCall(body, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java new file mode 100644 index 00000000000..1c4fc3101a1 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java @@ -0,0 +1,907 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + +import io.swagger.client.model.User; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class UserApi { + private ApiClient apiClient; + + public UserApi() { + this(Configuration.getDefaultApiClient()); + } + + public UserApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for createUser */ + private com.squareup.okhttp.Call createUserCall(User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUser(User body) throws ApiException { + createUserWithHttpInfo(body); + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUserWithHttpInfo(User body) throws ApiException { + com.squareup.okhttp.Call call = createUserCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Create user (asynchronously) + * This can only be done by the logged in user. + * @param body Created user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUserAsync(User body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = createUserCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for createUsersWithArrayInput */ + private com.squareup.okhttp.Call createUsersWithArrayInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUsersWithArrayInput(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/createWithArray".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUsersWithArrayInput(List body) throws ApiException { + createUsersWithArrayInputWithHttpInfo(body); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUsersWithArrayInputWithHttpInfo(List body) throws ApiException { + com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Creates list of users with given input array (asynchronously) + * + * @param body List of user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUsersWithArrayInputAsync(List body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for createUsersWithListInput */ + private com.squareup.okhttp.Call createUsersWithListInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUsersWithListInput(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUsersWithListInput(List body) throws ApiException { + createUsersWithListInputWithHttpInfo(body); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUsersWithListInputWithHttpInfo(List body) throws ApiException { + com.squareup.okhttp.Call call = createUsersWithListInputCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Creates list of users with given input array (asynchronously) + * + * @param body List of user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUsersWithListInputAsync(List body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = createUsersWithListInputCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for deleteUser */ + private com.squareup.okhttp.Call deleteUserCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling deleteUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deleteUser(String username) throws ApiException { + deleteUserWithHttpInfo(username); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deleteUserWithHttpInfo(String username) throws ApiException { + com.squareup.okhttp.Call call = deleteUserCall(username, null, null); + return apiClient.execute(call); + } + + /** + * Delete user (asynchronously) + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deleteUserAsync(String username, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = deleteUserCall(username, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for getUserByName */ + private com.squareup.okhttp.Call getUserByNameCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling getUserByName(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return User + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public User getUserByName(String username) throws ApiException { + ApiResponse resp = getUserByNameWithHttpInfo(username); + return resp.getData(); + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return ApiResponse<User> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getUserByNameWithHttpInfo(String username) throws ApiException { + com.squareup.okhttp.Call call = getUserByNameCall(username, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Get user by user name (asynchronously) + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getUserByNameAsync(String username, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getUserByNameCall(username, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for loginUser */ + private com.squareup.okhttp.Call loginUserCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling loginUser(Async)"); + } + + // verify the required parameter 'password' is set + if (password == null) { + throw new ApiException("Missing the required parameter 'password' when calling loginUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/login".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (username != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "username", username)); + if (password != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "password", password)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return String + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public String loginUser(String username, String password) throws ApiException { + ApiResponse resp = loginUserWithHttpInfo(username, password); + return resp.getData(); + } + + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return ApiResponse<String> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse loginUserWithHttpInfo(String username, String password) throws ApiException { + com.squareup.okhttp.Call call = loginUserCall(username, password, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Logs user into the system (asynchronously) + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call loginUserAsync(String username, String password, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = loginUserCall(username, password, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for logoutUser */ + private com.squareup.okhttp.Call logoutUserCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + + // create path and map variables + String localVarPath = "/user/logout".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Logs out current logged in user session + * + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void logoutUser() throws ApiException { + logoutUserWithHttpInfo(); + } + + /** + * Logs out current logged in user session + * + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse logoutUserWithHttpInfo() throws ApiException { + com.squareup.okhttp.Call call = logoutUserCall(null, null); + return apiClient.execute(call); + } + + /** + * Logs out current logged in user session (asynchronously) + * + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call logoutUserAsync(final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = logoutUserCall(progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for updateUser */ + private com.squareup.okhttp.Call updateUserCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling updateUser(Async)"); + } + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling updateUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updateUser(String username, User body) throws ApiException { + updateUserWithHttpInfo(username, body); + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updateUserWithHttpInfo(String username, User body) throws ApiException { + com.squareup.okhttp.Call call = updateUserCall(username, body, null, null); + return apiClient.execute(call); + } + + /** + * Updated user (asynchronously) + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updateUserAsync(String username, User body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updateUserCall(username, body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java new file mode 100644 index 00000000000..a125fff5f24 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -0,0 +1,87 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + + +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + if (apiKey == null) { + return; + } + String value; + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if (location == "query") { + queryParams.add(new Pair(paramName, value)); + } else if (location == "header") { + headerParams.put(paramName, value); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java new file mode 100644 index 00000000000..221a7d9dd1f --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java @@ -0,0 +1,41 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + +public interface Authentication { + /** + * Apply authentication settings to header and query params. + * + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + */ + void applyToParams(List queryParams, Map headerParams); +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java new file mode 100644 index 00000000000..4eb2300b69d --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -0,0 +1,66 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import com.squareup.okhttp.Credentials; + +import java.util.Map; +import java.util.List; + +import java.io.UnsupportedEncodingException; + +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + if (username == null && password == null) { + return; + } + headerParams.put("Authorization", Credentials.basic( + username == null ? "" : username, + password == null ? "" : password)); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java new file mode 100644 index 00000000000..14521f6ed7e --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java @@ -0,0 +1,51 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + + +public class OAuth implements Authentication { + private String accessToken; + + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + if (accessToken != null) { + headerParams.put("Authorization", "Bearer " + accessToken); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuthFlow.java new file mode 100644 index 00000000000..50d5260cfd9 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -0,0 +1,30 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.auth; + +public enum OAuthFlow { + accessCode, implicit, password, application +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..93e0a64052e --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -0,0 +1,125 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * AdditionalPropertiesClass + */ + +public class AdditionalPropertiesClass { + @SerializedName("map_property") + private Map mapProperty = new HashMap(); + + @SerializedName("map_of_map_property") + private Map> mapOfMapProperty = new HashMap>(); + + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + /** + * Get mapProperty + * @return mapProperty + **/ + @ApiModelProperty(example = "null", value = "") + public Map getMapProperty() { + return mapProperty; + } + + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + return this; + } + + /** + * Get mapOfMapProperty + * @return mapOfMapProperty + **/ + @ApiModelProperty(example = "null", value = "") + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; + return Objects.equals(this.mapProperty, additionalPropertiesClass.mapProperty) && + Objects.equals(this.mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); + } + + @Override + public int hashCode() { + return Objects.hash(mapProperty, mapOfMapProperty); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Animal.java new file mode 100644 index 00000000000..9eb654aa381 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Animal.java @@ -0,0 +1,122 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Animal + */ + +public class Animal { + @SerializedName("className") + private String className = null; + + @SerializedName("color") + private String color = "red"; + + public Animal className(String className) { + this.className = className; + return this; + } + + /** + * Get className + * @return className + **/ + @ApiModelProperty(example = "null", required = true, value = "") + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + public Animal color(String color) { + this.color = color; + return this; + } + + /** + * Get color + * @return color + **/ + @ApiModelProperty(example = "null", value = "") + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Animal animal = (Animal) o; + return Objects.equals(this.className, animal.className) && + Objects.equals(this.color, animal.color); + } + + @Override + public int hashCode() { + return Objects.hash(className, color); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Animal {\n"); + + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AnimalFarm.java new file mode 100644 index 00000000000..94b3af4bea6 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -0,0 +1,76 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.client.model.Animal; +import java.util.ArrayList; +import java.util.List; + +/** + * AnimalFarm + */ + +public class AnimalFarm extends ArrayList { + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + return true; + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 00000000000..ad8b7bab8ca --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,102 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +/** + * ArrayOfArrayOfNumberOnly + */ + +public class ArrayOfArrayOfNumberOnly { + @SerializedName("ArrayArrayNumber") + private List> arrayArrayNumber = new ArrayList>(); + + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + /** + * Get arrayArrayNumber + * @return arrayArrayNumber + **/ + @ApiModelProperty(example = "null", value = "") + public List> getArrayArrayNumber() { + return arrayArrayNumber; + } + + public void setArrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly = (ArrayOfArrayOfNumberOnly) o; + return Objects.equals(this.arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayArrayNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfArrayOfNumberOnly {\n"); + + sb.append(" arrayArrayNumber: ").append(toIndentedString(arrayArrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java new file mode 100644 index 00000000000..1378b3d7d6a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -0,0 +1,102 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +/** + * ArrayOfNumberOnly + */ + +public class ArrayOfNumberOnly { + @SerializedName("ArrayNumber") + private List arrayNumber = new ArrayList(); + + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + /** + * Get arrayNumber + * @return arrayNumber + **/ + @ApiModelProperty(example = "null", value = "") + public List getArrayNumber() { + return arrayNumber; + } + + public void setArrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfNumberOnly arrayOfNumberOnly = (ArrayOfNumberOnly) o; + return Objects.equals(this.arrayNumber, arrayOfNumberOnly.arrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfNumberOnly {\n"); + + sb.append(" arrayNumber: ").append(toIndentedString(arrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java new file mode 100644 index 00000000000..afd071dbf54 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java @@ -0,0 +1,148 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.ReadOnlyFirst; +import java.util.ArrayList; +import java.util.List; + +/** + * ArrayTest + */ + +public class ArrayTest { + @SerializedName("array_of_string") + private List arrayOfString = new ArrayList(); + + @SerializedName("array_array_of_integer") + private List> arrayArrayOfInteger = new ArrayList>(); + + @SerializedName("array_array_of_model") + private List> arrayArrayOfModel = new ArrayList>(); + + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + /** + * Get arrayOfString + * @return arrayOfString + **/ + @ApiModelProperty(example = "null", value = "") + public List getArrayOfString() { + return arrayOfString; + } + + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + return this; + } + + /** + * Get arrayArrayOfInteger + * @return arrayArrayOfInteger + **/ + @ApiModelProperty(example = "null", value = "") + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + return this; + } + + /** + * Get arrayArrayOfModel + * @return arrayArrayOfModel + **/ + @ApiModelProperty(example = "null", value = "") + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayTest arrayTest = (ArrayTest) o; + return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && + Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); + } + + @Override + public int hashCode() { + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Cat.java new file mode 100644 index 00000000000..fcf291e658c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Cat.java @@ -0,0 +1,147 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Animal; + +/** + * Cat + */ + +public class Cat extends Animal { + @SerializedName("className") + private String className = null; + + @SerializedName("color") + private String color = "red"; + + @SerializedName("declawed") + private Boolean declawed = null; + + public Cat className(String className) { + this.className = className; + return this; + } + + /** + * Get className + * @return className + **/ + @ApiModelProperty(example = "null", required = true, value = "") + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + public Cat color(String color) { + this.color = color; + return this; + } + + /** + * Get color + * @return color + **/ + @ApiModelProperty(example = "null", value = "") + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + + public Cat declawed(Boolean declawed) { + this.declawed = declawed; + return this; + } + + /** + * Get declawed + * @return declawed + **/ + @ApiModelProperty(example = "null", value = "") + public Boolean getDeclawed() { + return declawed; + } + + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Cat cat = (Cat) o; + return Objects.equals(this.className, cat.className) && + Objects.equals(this.color, cat.color) && + Objects.equals(this.declawed, cat.declawed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(className, color, declawed, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Cat {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java new file mode 100644 index 00000000000..aee4cd3c607 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java @@ -0,0 +1,122 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Category + */ + +public class Category { + @SerializedName("id") + private Long id = null; + + @SerializedName("name") + private String name = null; + + public Category id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(example = "null", value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Category name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(example = "null", value = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Dog.java new file mode 100644 index 00000000000..a0160714c2f --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Dog.java @@ -0,0 +1,147 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Animal; + +/** + * Dog + */ + +public class Dog extends Animal { + @SerializedName("className") + private String className = null; + + @SerializedName("color") + private String color = "red"; + + @SerializedName("breed") + private String breed = null; + + public Dog className(String className) { + this.className = className; + return this; + } + + /** + * Get className + * @return className + **/ + @ApiModelProperty(example = "null", required = true, value = "") + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + public Dog color(String color) { + this.color = color; + return this; + } + + /** + * Get color + * @return color + **/ + @ApiModelProperty(example = "null", value = "") + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + + public Dog breed(String breed) { + this.breed = breed; + return this; + } + + /** + * Get breed + * @return breed + **/ + @ApiModelProperty(example = "null", value = "") + public String getBreed() { + return breed; + } + + public void setBreed(String breed) { + this.breed = breed; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Dog dog = (Dog) o; + return Objects.equals(this.className, dog.className) && + Objects.equals(this.color, dog.color) && + Objects.equals(this.breed, dog.breed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(className, color, breed, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Dog {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumClass.java new file mode 100644 index 00000000000..2f93aaeda63 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumClass.java @@ -0,0 +1,56 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; + +/** + * Gets or Sets EnumClass + */ +public enum EnumClass { + + @SerializedName("_abc") + _ABC("_abc"), + + @SerializedName("-efg") + _EFG("-efg"), + + @SerializedName("(xyz)") + _XYZ_("(xyz)"); + + private String value; + + EnumClass(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java new file mode 100644 index 00000000000..16025ba6d5c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java @@ -0,0 +1,211 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * EnumTest + */ + +public class EnumTest { + /** + * Gets or Sets enumString + */ + public enum EnumStringEnum { + @SerializedName("UPPER") + UPPER("UPPER"), + + @SerializedName("lower") + LOWER("lower"); + + private String value; + + EnumStringEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + @SerializedName("enum_string") + private EnumStringEnum enumString = null; + + /** + * Gets or Sets enumInteger + */ + public enum EnumIntegerEnum { + @SerializedName("1") + NUMBER_1(1), + + @SerializedName("-1") + NUMBER_MINUS_1(-1); + + private Integer value; + + EnumIntegerEnum(Integer value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + @SerializedName("enum_integer") + private EnumIntegerEnum enumInteger = null; + + /** + * Gets or Sets enumNumber + */ + public enum EnumNumberEnum { + @SerializedName("1.1") + NUMBER_1_DOT_1(1.1), + + @SerializedName("-1.2") + NUMBER_MINUS_1_DOT_2(-1.2); + + private Double value; + + EnumNumberEnum(Double value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + @SerializedName("enum_number") + private EnumNumberEnum enumNumber = null; + + public EnumTest enumString(EnumStringEnum enumString) { + this.enumString = enumString; + return this; + } + + /** + * Get enumString + * @return enumString + **/ + @ApiModelProperty(example = "null", value = "") + public EnumStringEnum getEnumString() { + return enumString; + } + + public void setEnumString(EnumStringEnum enumString) { + this.enumString = enumString; + } + + public EnumTest enumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + return this; + } + + /** + * Get enumInteger + * @return enumInteger + **/ + @ApiModelProperty(example = "null", value = "") + public EnumIntegerEnum getEnumInteger() { + return enumInteger; + } + + public void setEnumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + } + + public EnumTest enumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + return this; + } + + /** + * Get enumNumber + * @return enumNumber + **/ + @ApiModelProperty(example = "null", value = "") + public EnumNumberEnum getEnumNumber() { + return enumNumber; + } + + public void setEnumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumTest enumTest = (EnumTest) o; + return Objects.equals(this.enumString, enumTest.enumString) && + Objects.equals(this.enumInteger, enumTest.enumInteger) && + Objects.equals(this.enumNumber, enumTest.enumNumber); + } + + @Override + public int hashCode() { + return Objects.hash(enumString, enumInteger, enumNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java new file mode 100644 index 00000000000..377f2ecf0ee --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java @@ -0,0 +1,388 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; + +/** + * FormatTest + */ + +public class FormatTest { + @SerializedName("integer") + private Integer integer = null; + + @SerializedName("int32") + private Integer int32 = null; + + @SerializedName("int64") + private Long int64 = null; + + @SerializedName("number") + private BigDecimal number = null; + + @SerializedName("float") + private Float _float = null; + + @SerializedName("double") + private Double _double = null; + + @SerializedName("string") + private String string = null; + + @SerializedName("byte") + private byte[] _byte = null; + + @SerializedName("binary") + private byte[] binary = null; + + @SerializedName("date") + private LocalDate date = null; + + @SerializedName("dateTime") + private DateTime dateTime = null; + + @SerializedName("uuid") + private String uuid = null; + + @SerializedName("password") + private String password = null; + + public FormatTest integer(Integer integer) { + this.integer = integer; + return this; + } + + /** + * Get integer + * minimum: 10.0 + * maximum: 100.0 + * @return integer + **/ + @ApiModelProperty(example = "null", value = "") + public Integer getInteger() { + return integer; + } + + public void setInteger(Integer integer) { + this.integer = integer; + } + + public FormatTest int32(Integer int32) { + this.int32 = int32; + return this; + } + + /** + * Get int32 + * minimum: 20.0 + * maximum: 200.0 + * @return int32 + **/ + @ApiModelProperty(example = "null", value = "") + public Integer getInt32() { + return int32; + } + + public void setInt32(Integer int32) { + this.int32 = int32; + } + + public FormatTest int64(Long int64) { + this.int64 = int64; + return this; + } + + /** + * Get int64 + * @return int64 + **/ + @ApiModelProperty(example = "null", value = "") + public Long getInt64() { + return int64; + } + + public void setInt64(Long int64) { + this.int64 = int64; + } + + public FormatTest number(BigDecimal number) { + this.number = number; + return this; + } + + /** + * Get number + * minimum: 32.1 + * maximum: 543.2 + * @return number + **/ + @ApiModelProperty(example = "null", required = true, value = "") + public BigDecimal getNumber() { + return number; + } + + public void setNumber(BigDecimal number) { + this.number = number; + } + + public FormatTest _float(Float _float) { + this._float = _float; + return this; + } + + /** + * Get _float + * minimum: 54.3 + * maximum: 987.6 + * @return _float + **/ + @ApiModelProperty(example = "null", value = "") + public Float getFloat() { + return _float; + } + + public void setFloat(Float _float) { + this._float = _float; + } + + public FormatTest _double(Double _double) { + this._double = _double; + return this; + } + + /** + * Get _double + * minimum: 67.8 + * maximum: 123.4 + * @return _double + **/ + @ApiModelProperty(example = "null", value = "") + public Double getDouble() { + return _double; + } + + public void setDouble(Double _double) { + this._double = _double; + } + + public FormatTest string(String string) { + this.string = string; + return this; + } + + /** + * Get string + * @return string + **/ + @ApiModelProperty(example = "null", value = "") + public String getString() { + return string; + } + + public void setString(String string) { + this.string = string; + } + + public FormatTest _byte(byte[] _byte) { + this._byte = _byte; + return this; + } + + /** + * Get _byte + * @return _byte + **/ + @ApiModelProperty(example = "null", required = true, value = "") + public byte[] getByte() { + return _byte; + } + + public void setByte(byte[] _byte) { + this._byte = _byte; + } + + public FormatTest binary(byte[] binary) { + this.binary = binary; + return this; + } + + /** + * Get binary + * @return binary + **/ + @ApiModelProperty(example = "null", value = "") + public byte[] getBinary() { + return binary; + } + + public void setBinary(byte[] binary) { + this.binary = binary; + } + + public FormatTest date(LocalDate date) { + this.date = date; + return this; + } + + /** + * Get date + * @return date + **/ + @ApiModelProperty(example = "null", required = true, value = "") + public LocalDate getDate() { + return date; + } + + public void setDate(LocalDate date) { + this.date = date; + } + + public FormatTest dateTime(DateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(example = "null", value = "") + public DateTime getDateTime() { + return dateTime; + } + + public void setDateTime(DateTime dateTime) { + this.dateTime = dateTime; + } + + public FormatTest uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(example = "null", value = "") + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public FormatTest password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @ApiModelProperty(example = "null", required = true, value = "") + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + FormatTest formatTest = (FormatTest) o; + return Objects.equals(this.integer, formatTest.integer) && + Objects.equals(this.int32, formatTest.int32) && + Objects.equals(this.int64, formatTest.int64) && + Objects.equals(this.number, formatTest.number) && + Objects.equals(this._float, formatTest._float) && + Objects.equals(this._double, formatTest._double) && + Objects.equals(this.string, formatTest.string) && + Objects.equals(this._byte, formatTest._byte) && + Objects.equals(this.binary, formatTest.binary) && + Objects.equals(this.date, formatTest.date) && + Objects.equals(this.dateTime, formatTest.dateTime) && + Objects.equals(this.uuid, formatTest.uuid) && + Objects.equals(this.password, formatTest.password); + } + + @Override + public int hashCode() { + return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, uuid, password); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FormatTest {\n"); + + sb.append(" integer: ").append(toIndentedString(integer)).append("\n"); + sb.append(" int32: ").append(toIndentedString(int32)).append("\n"); + sb.append(" int64: ").append(toIndentedString(int64)).append("\n"); + sb.append(" number: ").append(toIndentedString(number)).append("\n"); + sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); + sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); + sb.append(" string: ").append(toIndentedString(string)).append("\n"); + sb.append(" _byte: ").append(toIndentedString(_byte)).append("\n"); + sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); + sb.append(" date: ").append(toIndentedString(date)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java new file mode 100644 index 00000000000..3f3d3cac61c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -0,0 +1,104 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * HasOnlyReadOnly + */ + +public class HasOnlyReadOnly { + @SerializedName("bar") + private String bar = null; + + @SerializedName("foo") + private String foo = null; + + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(example = "null", value = "") + public String getBar() { + return bar; + } + + /** + * Get foo + * @return foo + **/ + @ApiModelProperty(example = "null", value = "") + public String getFoo() { + return foo; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HasOnlyReadOnly hasOnlyReadOnly = (HasOnlyReadOnly) o; + return Objects.equals(this.bar, hasOnlyReadOnly.bar) && + Objects.equals(this.foo, hasOnlyReadOnly.foo); + } + + @Override + public int hashCode() { + return Objects.hash(bar, foo); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HasOnlyReadOnly {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" foo: ").append(toIndentedString(foo)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MapTest.java new file mode 100644 index 00000000000..5337fa33974 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MapTest.java @@ -0,0 +1,147 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * MapTest + */ + +public class MapTest { + @SerializedName("map_map_of_string") + private Map> mapMapOfString = new HashMap>(); + + /** + * Gets or Sets inner + */ + public enum InnerEnum { + @SerializedName("UPPER") + UPPER("UPPER"), + + @SerializedName("lower") + LOWER("lower"); + + private String value; + + InnerEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + @SerializedName("map_of_enum_string") + private Map mapOfEnumString = new HashMap(); + + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + /** + * Get mapMapOfString + * @return mapMapOfString + **/ + @ApiModelProperty(example = "null", value = "") + public Map> getMapMapOfString() { + return mapMapOfString; + } + + public void setMapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + } + + public MapTest mapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + return this; + } + + /** + * Get mapOfEnumString + * @return mapOfEnumString + **/ + @ApiModelProperty(example = "null", value = "") + public Map getMapOfEnumString() { + return mapOfEnumString; + } + + public void setMapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MapTest mapTest = (MapTest) o; + return Objects.equals(this.mapMapOfString, mapTest.mapMapOfString) && + Objects.equals(this.mapOfEnumString, mapTest.mapOfEnumString); + } + + @Override + public int hashCode() { + return Objects.hash(mapMapOfString, mapOfEnumString); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MapTest {\n"); + + sb.append(" mapMapOfString: ").append(toIndentedString(mapMapOfString)).append("\n"); + sb.append(" mapOfEnumString: ").append(toIndentedString(mapOfEnumString)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..19bb519f9ac --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,150 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Animal; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.joda.time.DateTime; + +/** + * MixedPropertiesAndAdditionalPropertiesClass + */ + +public class MixedPropertiesAndAdditionalPropertiesClass { + @SerializedName("uuid") + private String uuid = null; + + @SerializedName("dateTime") + private DateTime dateTime = null; + + @SerializedName("map") + private Map map = new HashMap(); + + public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(example = "null", value = "") + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public MixedPropertiesAndAdditionalPropertiesClass dateTime(DateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(example = "null", value = "") + public DateTime getDateTime() { + return dateTime; + } + + public void setDateTime(DateTime dateTime) { + this.dateTime = dateTime; + } + + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + this.map = map; + return this; + } + + /** + * Get map + * @return map + **/ + @ApiModelProperty(example = "null", value = "") + public Map getMap() { + return map; + } + + public void setMap(Map map) { + this.map = map; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; + return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(this.dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(this.map, mixedPropertiesAndAdditionalPropertiesClass.map); + } + + @Override + public int hashCode() { + return Objects.hash(uuid, dateTime, map); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Model200Response.java new file mode 100644 index 00000000000..bfc8e3ce46e --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Model200Response.java @@ -0,0 +1,123 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Model for testing model name starting with number + */ +@ApiModel(description = "Model for testing model name starting with number") + +public class Model200Response { + @SerializedName("name") + private Integer name = null; + + @SerializedName("class") + private String PropertyClass = null; + + public Model200Response name(Integer name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(example = "null", value = "") + public Integer getName() { + return name; + } + + public void setName(Integer name) { + this.name = name; + } + + public Model200Response PropertyClass(String PropertyClass) { + this.PropertyClass = PropertyClass; + return this; + } + + /** + * Get PropertyClass + * @return PropertyClass + **/ + @ApiModelProperty(example = "null", value = "") + public String getPropertyClass() { + return PropertyClass; + } + + public void setPropertyClass(String PropertyClass) { + this.PropertyClass = PropertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Model200Response _200Response = (Model200Response) o; + return Objects.equals(this.name, _200Response.name) && + Objects.equals(this.PropertyClass, _200Response.PropertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(name, PropertyClass); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" PropertyClass: ").append(toIndentedString(PropertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelApiResponse.java new file mode 100644 index 00000000000..f2c1858099c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -0,0 +1,145 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * ModelApiResponse + */ + +public class ModelApiResponse { + @SerializedName("code") + private Integer code = null; + + @SerializedName("type") + private String type = null; + + @SerializedName("message") + private String message = null; + + public ModelApiResponse code(Integer code) { + this.code = code; + return this; + } + + /** + * Get code + * @return code + **/ + @ApiModelProperty(example = "null", value = "") + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } + + public ModelApiResponse type(String type) { + this.type = type; + return this; + } + + /** + * Get type + * @return type + **/ + @ApiModelProperty(example = "null", value = "") + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public ModelApiResponse message(String message) { + this.message = message; + return this; + } + + /** + * Get message + * @return message + **/ + @ApiModelProperty(example = "null", value = "") + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelReturn.java new file mode 100644 index 00000000000..cb608f13f7d --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelReturn.java @@ -0,0 +1,100 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Model for testing reserved words + */ +@ApiModel(description = "Model for testing reserved words") + +public class ModelReturn { + @SerializedName("return") + private Integer _return = null; + + public ModelReturn _return(Integer _return) { + this._return = _return; + return this; + } + + /** + * Get _return + * @return _return + **/ + @ApiModelProperty(example = "null", value = "") + public Integer getReturn() { + return _return; + } + + public void setReturn(Integer _return) { + this._return = _return; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelReturn _return = (ModelReturn) o; + return Objects.equals(this._return, _return._return); + } + + @Override + public int hashCode() { + return Objects.hash(_return); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelReturn {\n"); + + sb.append(" _return: ").append(toIndentedString(_return)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Name.java new file mode 100644 index 00000000000..cfa453712ce --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Name.java @@ -0,0 +1,151 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Model for testing model name same as property name + */ +@ApiModel(description = "Model for testing model name same as property name") + +public class Name { + @SerializedName("name") + private Integer name = null; + + @SerializedName("snake_case") + private Integer snakeCase = null; + + @SerializedName("property") + private String property = null; + + @SerializedName("123Number") + private Integer _123Number = null; + + public Name name(Integer name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(example = "null", required = true, value = "") + public Integer getName() { + return name; + } + + public void setName(Integer name) { + this.name = name; + } + + /** + * Get snakeCase + * @return snakeCase + **/ + @ApiModelProperty(example = "null", value = "") + public Integer getSnakeCase() { + return snakeCase; + } + + public Name property(String property) { + this.property = property; + return this; + } + + /** + * Get property + * @return property + **/ + @ApiModelProperty(example = "null", value = "") + public String getProperty() { + return property; + } + + public void setProperty(String property) { + this.property = property; + } + + /** + * Get _123Number + * @return _123Number + **/ + @ApiModelProperty(example = "null", value = "") + public Integer get123Number() { + return _123Number; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Name name = (Name) o; + return Objects.equals(this.name, name.name) && + Objects.equals(this.snakeCase, name.snakeCase) && + Objects.equals(this.property, name.property) && + Objects.equals(this._123Number, name._123Number); + } + + @Override + public int hashCode() { + return Objects.hash(name, snakeCase, property, _123Number); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Name {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); + sb.append(" property: ").append(toIndentedString(property)).append("\n"); + sb.append(" _123Number: ").append(toIndentedString(_123Number)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/NumberOnly.java new file mode 100644 index 00000000000..29e9a9064a5 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/NumberOnly.java @@ -0,0 +1,100 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; + +/** + * NumberOnly + */ + +public class NumberOnly { + @SerializedName("JustNumber") + private BigDecimal justNumber = null; + + public NumberOnly justNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + return this; + } + + /** + * Get justNumber + * @return justNumber + **/ + @ApiModelProperty(example = "null", value = "") + public BigDecimal getJustNumber() { + return justNumber; + } + + public void setJustNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NumberOnly numberOnly = (NumberOnly) o; + return Objects.equals(this.justNumber, numberOnly.justNumber); + } + + @Override + public int hashCode() { + return Objects.hash(justNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NumberOnly {\n"); + + sb.append(" justNumber: ").append(toIndentedString(justNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java new file mode 100644 index 00000000000..d6ecceeb479 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java @@ -0,0 +1,240 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.joda.time.DateTime; + +/** + * Order + */ + +public class Order { + @SerializedName("id") + private Long id = null; + + @SerializedName("petId") + private Long petId = null; + + @SerializedName("quantity") + private Integer quantity = null; + + @SerializedName("shipDate") + private DateTime shipDate = null; + + /** + * Order Status + */ + public enum StatusEnum { + @SerializedName("placed") + PLACED("placed"), + + @SerializedName("approved") + APPROVED("approved"), + + @SerializedName("delivered") + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + @SerializedName("status") + private StatusEnum status = null; + + @SerializedName("complete") + private Boolean complete = false; + + public Order id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(example = "null", value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Order petId(Long petId) { + this.petId = petId; + return this; + } + + /** + * Get petId + * @return petId + **/ + @ApiModelProperty(example = "null", value = "") + public Long getPetId() { + return petId; + } + + public void setPetId(Long petId) { + this.petId = petId; + } + + public Order quantity(Integer quantity) { + this.quantity = quantity; + return this; + } + + /** + * Get quantity + * @return quantity + **/ + @ApiModelProperty(example = "null", value = "") + public Integer getQuantity() { + return quantity; + } + + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + public Order shipDate(DateTime shipDate) { + this.shipDate = shipDate; + return this; + } + + /** + * Get shipDate + * @return shipDate + **/ + @ApiModelProperty(example = "null", value = "") + public DateTime getShipDate() { + return shipDate; + } + + public void setShipDate(DateTime shipDate) { + this.shipDate = shipDate; + } + + public Order status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * Order Status + * @return status + **/ + @ApiModelProperty(example = "null", value = "Order Status") + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + public Order complete(Boolean complete) { + this.complete = complete; + return this; + } + + /** + * Get complete + * @return complete + **/ + @ApiModelProperty(example = "null", value = "") + public Boolean getComplete() { + return complete; + } + + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java new file mode 100644 index 00000000000..6124b404449 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java @@ -0,0 +1,243 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Category; +import io.swagger.client.model.Tag; +import java.util.ArrayList; +import java.util.List; + +/** + * Pet + */ + +public class Pet { + @SerializedName("id") + private Long id = null; + + @SerializedName("category") + private Category category = null; + + @SerializedName("name") + private String name = null; + + @SerializedName("photoUrls") + private List photoUrls = new ArrayList(); + + @SerializedName("tags") + private List tags = new ArrayList(); + + /** + * pet status in the store + */ + public enum StatusEnum { + @SerializedName("available") + AVAILABLE("available"), + + @SerializedName("pending") + PENDING("pending"), + + @SerializedName("sold") + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + @SerializedName("status") + private StatusEnum status = null; + + public Pet id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(example = "null", value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Pet category(Category category) { + this.category = category; + return this; + } + + /** + * Get category + * @return category + **/ + @ApiModelProperty(example = "null", value = "") + public Category getCategory() { + return category; + } + + public void setCategory(Category category) { + this.category = category; + } + + public Pet name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(example = "doggie", required = true, value = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Pet photoUrls(List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + /** + * Get photoUrls + * @return photoUrls + **/ + @ApiModelProperty(example = "null", required = true, value = "") + public List getPhotoUrls() { + return photoUrls; + } + + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + public Pet tags(List tags) { + this.tags = tags; + return this; + } + + /** + * Get tags + * @return tags + **/ + @ApiModelProperty(example = "null", value = "") + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + public Pet status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * pet status in the store + * @return status + **/ + @ApiModelProperty(example = "null", value = "pet status in the store") + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..4a90af87156 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -0,0 +1,113 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * ReadOnlyFirst + */ + +public class ReadOnlyFirst { + @SerializedName("bar") + private String bar = null; + + @SerializedName("baz") + private String baz = null; + + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(example = "null", value = "") + public String getBar() { + return bar; + } + + public ReadOnlyFirst baz(String baz) { + this.baz = baz; + return this; + } + + /** + * Get baz + * @return baz + **/ + @ApiModelProperty(example = "null", value = "") + public String getBaz() { + return baz; + } + + public void setBaz(String baz) { + this.baz = baz; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; + return Objects.equals(this.bar, readOnlyFirst.bar) && + Objects.equals(this.baz, readOnlyFirst.baz); + } + + @Override + public int hashCode() { + return Objects.hash(bar, baz); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/SpecialModelName.java new file mode 100644 index 00000000000..31b5862bb45 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -0,0 +1,99 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * SpecialModelName + */ + +public class SpecialModelName { + @SerializedName("$special[property.name]") + private Long specialPropertyName = null; + + public SpecialModelName specialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + return this; + } + + /** + * Get specialPropertyName + * @return specialPropertyName + **/ + @ApiModelProperty(example = "null", value = "") + public Long getSpecialPropertyName() { + return specialPropertyName; + } + + public void setSpecialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SpecialModelName specialModelName = (SpecialModelName) o; + return Objects.equals(this.specialPropertyName, specialModelName.specialPropertyName); + } + + @Override + public int hashCode() { + return Objects.hash(specialPropertyName); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SpecialModelName {\n"); + + sb.append(" specialPropertyName: ").append(toIndentedString(specialPropertyName)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java new file mode 100644 index 00000000000..5d3fbb6bae6 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java @@ -0,0 +1,122 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Tag + */ + +public class Tag { + @SerializedName("id") + private Long id = null; + + @SerializedName("name") + private String name = null; + + public Tag id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(example = "null", value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Tag name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(example = "null", value = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java new file mode 100644 index 00000000000..f2a409f35c4 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java @@ -0,0 +1,260 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * User + */ + +public class User { + @SerializedName("id") + private Long id = null; + + @SerializedName("username") + private String username = null; + + @SerializedName("firstName") + private String firstName = null; + + @SerializedName("lastName") + private String lastName = null; + + @SerializedName("email") + private String email = null; + + @SerializedName("password") + private String password = null; + + @SerializedName("phone") + private String phone = null; + + @SerializedName("userStatus") + private Integer userStatus = null; + + public User id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(example = "null", value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public User username(String username) { + this.username = username; + return this; + } + + /** + * Get username + * @return username + **/ + @ApiModelProperty(example = "null", value = "") + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public User firstName(String firstName) { + this.firstName = firstName; + return this; + } + + /** + * Get firstName + * @return firstName + **/ + @ApiModelProperty(example = "null", value = "") + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public User lastName(String lastName) { + this.lastName = lastName; + return this; + } + + /** + * Get lastName + * @return lastName + **/ + @ApiModelProperty(example = "null", value = "") + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public User email(String email) { + this.email = email; + return this; + } + + /** + * Get email + * @return email + **/ + @ApiModelProperty(example = "null", value = "") + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public User password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @ApiModelProperty(example = "null", value = "") + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public User phone(String phone) { + this.phone = phone; + return this; + } + + /** + * Get phone + * @return phone + **/ + @ApiModelProperty(example = "null", value = "") + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + public User userStatus(Integer userStatus) { + this.userStatus = userStatus; + return this; + } + + /** + * User Status + * @return userStatus + **/ + @ApiModelProperty(example = "null", value = "User Status") + public Integer getUserStatus() { + return userStatus; + } + + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + From 515fe33c2c3ac4153859a312be8077076ec73c93 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 6 Oct 2016 15:16:04 +0800 Subject: [PATCH 417/470] add more info about test with latest master --- CONTRIBUTING.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f1ef0aa469b..32195b7df92 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -4,7 +4,8 @@ - If you're not using the latest master to generate API clients or server stubs, please give it another try by pulling the latest master as the issue may have already been addressed. Ref: [Getting Started](https://github.com/swagger-api/swagger-codegen#getting-started) - Search the [open issue](https://github.com/swagger-api/swagger-codegen/issues) and [closed issue](https://github.com/swagger-api/swagger-codegen/issues?q=is%3Aissue+is%3Aclosed) to ensure no one else has reported something similar before. - - File an [issue ticket](https://github.com/swagger-api/swagger-codegen/issues/new) by providing all the required information. + - File an [issue ticket](https://github.com/swagger-api/swagger-codegen/issues/new) by providing all the required information. + - Test with the latest master by building the JAR locally to see if the issue has already been addressed. - You can also make a suggestion or ask a question by opening an "issue". ## Before submitting a PR From cd6b5fec20eb112dc099c91688c90855911672c9 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 6 Oct 2016 17:35:33 +0800 Subject: [PATCH 418/470] [Android][Volley] add serializeModel support to Android (#3933) * add serializeModel support to Android * add test for new android option --- .../codegen/languages/AndroidClientCodegen.java | 15 +++++++++++++++ .../android/libraries/volley/model.mustache | 12 ++++++++---- .../codegen/android/AndroidClientOptionsTest.java | 2 ++ .../options/AndroidClientOptionsProvider.java | 2 ++ .../client/petstore/android/volley/docs/PetApi.md | 2 +- .../main/java/io/swagger/client/api/PetApi.java | 4 ++-- .../java/io/swagger/client/model/Category.java | 4 +--- .../main/java/io/swagger/client/model/Order.java | 4 +--- .../main/java/io/swagger/client/model/Pet.java | 4 +--- .../main/java/io/swagger/client/model/Tag.java | 4 +--- .../main/java/io/swagger/client/model/User.java | 4 +--- 11 files changed, 35 insertions(+), 22 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java index 788223bec9b..e4dacc499bb 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java @@ -29,6 +29,7 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi protected String projectFolder = "src/main"; protected String sourceFolder = projectFolder + "/java"; protected Boolean useAndroidMavenGradlePlugin = true; + protected Boolean serializableModel = false; // requestPackage and authPackage are used by the "volley" template/library protected String requestPackage = "io.swagger.client.request"; @@ -90,6 +91,8 @@ public AndroidClientCodegen() { cliOptions.add(CliOption.newBoolean(USE_ANDROID_MAVEN_GRADLE_PLUGIN, "A flag to toggle android-maven gradle plugin.") .defaultValue(Boolean.TRUE.toString())); + cliOptions.add(CliOption.newBoolean(CodegenConstants.SERIALIZABLE_MODEL, CodegenConstants.SERIALIZABLE_MODEL_DESC)); + supportedLibraries.put("volley", "HTTP client: Volley 1.0.19 (default)"); supportedLibraries.put("httpclient", "HTTP client: Apache HttpClient 4.3.6. JSON processing: Gson 2.3.1. IMPORTANT: Android client using HttpClient is not actively maintained and will be depecreated in the next major release."); CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); @@ -378,6 +381,14 @@ public void processOpts() { this.setLibrary((String) additionalProperties.get(CodegenConstants.LIBRARY)); } + if (additionalProperties.containsKey(CodegenConstants.SERIALIZABLE_MODEL)) { + this.setSerializableModel(Boolean.valueOf(additionalProperties.get(CodegenConstants.SERIALIZABLE_MODEL).toString())); + } + + // need to put back serializableModel (boolean) into additionalProperties as value in additionalProperties is string + additionalProperties.put(CodegenConstants.SERIALIZABLE_MODEL, serializableModel); + LOGGER.info("CodegenConstants.SERIALIZABLE_MODEL = " + additionalProperties.get(CodegenConstants.SERIALIZABLE_MODEL)); + //make api and model doc path available in mustache template additionalProperties.put( "apiDocPath", apiDocPath ); additionalProperties.put( "modelDocPath", modelDocPath ); @@ -504,6 +515,10 @@ public void setSourceFolder(String sourceFolder) { this.sourceFolder = sourceFolder; } + public void setSerializableModel(Boolean serializableModel) { + this.serializableModel = serializableModel; + } + @Override public String escapeQuotationMark(String input) { // remove " to avoid code injection diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/model.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/model.mustache index 22d7435b325..e64bb09c8ab 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/model.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/model.mustache @@ -3,17 +3,21 @@ package {{package}}; {{#imports}}import {{import}}; {{/imports}} - import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; +{{#serializableModel}} +import java.io.Serializable; +{{/serializableModel}} {{#models}} -{{#model}}{{#description}} +{{#model}} +{{#description}} /** * {{description}} - **/{{/description}} + **/ +{{/description}} @ApiModel(description = "{{{description}}}") -public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { +public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#serializableModel}}implements Serializable {{/serializableModel}}{ {{#vars}}{{#isEnum}} public enum {{datatypeWithEnum}} { {{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/android/AndroidClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/android/AndroidClientOptionsTest.java index 538614436f4..b94ec49f361 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/android/AndroidClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/android/AndroidClientOptionsTest.java @@ -46,6 +46,8 @@ protected void setExpectations() { times = 1; clientCodegen.setLibrary(AndroidClientOptionsProvider.LIBRARY_VALUE); times = 1; + clientCodegen.setSerializableModel(Boolean.valueOf(AndroidClientOptionsProvider.SERIALIZABLE_MODEL_VALUE)); + times = 1; }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java index 82ffa437f2a..79e61844c8b 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java @@ -19,6 +19,7 @@ public class AndroidClientOptionsProvider implements OptionsProvider { public static final String SOURCE_FOLDER_VALUE = "src/main/java/test"; public static final String ANDROID_MAVEN_GRADLE_PLUGIN_VALUE = "true"; public static final String LIBRARY_VALUE = "httpclient"; + public static final String SERIALIZABLE_MODEL_VALUE = "false"; @Override public String getLanguage() { @@ -39,6 +40,7 @@ public Map createOptions() { .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) .put(AndroidClientCodegen.USE_ANDROID_MAVEN_GRADLE_PLUGIN, ANDROID_MAVEN_GRADLE_PLUGIN_VALUE) .put(CodegenConstants.LIBRARY, LIBRARY_VALUE) + .put(CodegenConstants.SERIALIZABLE_MODEL, SERIALIZABLE_MODEL_VALUE) .build(); } diff --git a/samples/client/petstore/android/volley/docs/PetApi.md b/samples/client/petstore/android/volley/docs/PetApi.md index ff596b3d918..e7b393c8ea7 100644 --- a/samples/client/petstore/android/volley/docs/PetApi.md +++ b/samples/client/petstore/android/volley/docs/PetApi.md @@ -222,7 +222,7 @@ Name | Type | Description | Notes ### Authorization -[petstore_auth](../README.md#petstore_auth), [api_key](../README.md#api_key) +[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) ### HTTP request headers diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/PetApi.java index 5ef1079981a..ae9bcead7c5 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/PetApi.java @@ -623,7 +623,7 @@ public Pet getPetById (Long petId) throws TimeoutException, ExecutionException, // normal form params } - String[] authNames = new String[] { "petstore_auth", "api_key" }; + String[] authNames = new String[] { "api_key", "petstore_auth" }; try { String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); @@ -693,7 +693,7 @@ public void getPetById (Long petId, final Response.Listener responseListene // normal form params } - String[] authNames = new String[] { "petstore_auth", "api_key" }; + String[] authNames = new String[] { "api_key", "petstore_auth" }; try { apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames, diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Category.java index 6e2348fa509..7cdc4f56473 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Category.java @@ -24,13 +24,11 @@ package io.swagger.client.model; - import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; - @ApiModel(description = "") -public class Category { +public class Category { @SerializedName("id") private Long id = null; diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Order.java index 50809231d23..7f8554374d7 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Order.java @@ -25,13 +25,11 @@ package io.swagger.client.model; import java.util.Date; - import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; - @ApiModel(description = "") -public class Order { +public class Order { @SerializedName("id") private Long id = null; diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Pet.java index 7a505ec4e70..492f54dcd58 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Pet.java @@ -27,13 +27,11 @@ import io.swagger.client.model.Category; import io.swagger.client.model.Tag; import java.util.*; - import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; - @ApiModel(description = "") -public class Pet { +public class Pet { @SerializedName("id") private Long id = null; diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Tag.java index d75041a573c..45d3b965226 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Tag.java @@ -24,13 +24,11 @@ package io.swagger.client.model; - import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; - @ApiModel(description = "") -public class Tag { +public class Tag { @SerializedName("id") private Long id = null; diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/User.java index fbaec6578dd..79ebc1d607c 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/User.java @@ -24,13 +24,11 @@ package io.swagger.client.model; - import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; - @ApiModel(description = "") -public class User { +public class User { @SerializedName("id") private Long id = null; From 94cd2cb6a023be4a20e04c001b54a52c752864f7 Mon Sep 17 00:00:00 2001 From: sylvain-abadie Date: Thu, 6 Oct 2016 17:29:55 +0200 Subject: [PATCH 419/470] [Objc] Added support for lower case discriminator (#3927) * [Objc] Added support for lower case discriminator * Updated Objc petstore samples * Fixed code style --- .../src/main/resources/objc/model-body.mustache | 3 +++ samples/client/petstore/objc/core-data/README.md | 1 - .../petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.m | 2 +- .../petstore/objc/default/SwaggerClient/Api/SWGPetApi.m | 2 +- samples/client/petstore/objc/default/docs/SWGPetApi.md | 8 ++++---- 5 files changed, 9 insertions(+), 7 deletions(-) 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 2a4a548458e..5ca9303e5a8 100644 --- a/modules/swagger-codegen/src/main/resources/objc/model-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/model-body.mustache @@ -28,6 +28,9 @@ return [super initWithDictionary:dict error:err]; } Class class = NSClassFromString([@"{{classPrefix}}" stringByAppendingString:discriminatedClassName]); + if(!class) { + class = NSClassFromString([@"{{classPrefix}}" stringByAppendingString:[discriminatedClassName capitalizedString]]); + } if([self class ] == class) { return [super initWithDictionary:dict error:err]; } diff --git a/samples/client/petstore/objc/core-data/README.md b/samples/client/petstore/objc/core-data/README.md index 4474fdf4ce1..20e27d6fa0a 100644 --- a/samples/client/petstore/objc/core-data/README.md +++ b/samples/client/petstore/objc/core-data/README.md @@ -6,7 +6,6 @@ This ObjC package is automatically generated by the [Swagger Codegen](https://gi - API version: 1.0.0 - Package version: -- Build date: 2016-08-28T17:01:51.939+03:00 - Build package: class io.swagger.codegen.languages.ObjcClientCodegen ## Requirements diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.m b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.m index 76d707cdb42..16d1541471b 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.m +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.m @@ -376,7 +376,7 @@ -(NSNumber*) getPetByIdWithPetId: (NSNumber*) petId NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting - NSArray *authSettings = @[@"api_key", @"petstore_auth"]; + NSArray *authSettings = @[@"petstore_auth", @"api_key"]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; diff --git a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.m b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.m index 76d707cdb42..16d1541471b 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.m @@ -376,7 +376,7 @@ -(NSNumber*) getPetByIdWithPetId: (NSNumber*) petId NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting - NSArray *authSettings = @[@"api_key", @"petstore_auth"]; + NSArray *authSettings = @[@"petstore_auth", @"api_key"]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; diff --git a/samples/client/petstore/objc/default/docs/SWGPetApi.md b/samples/client/petstore/objc/default/docs/SWGPetApi.md index 9971ffff450..27674ded241 100644 --- a/samples/client/petstore/objc/default/docs/SWGPetApi.md +++ b/samples/client/petstore/objc/default/docs/SWGPetApi.md @@ -246,14 +246,14 @@ Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error cond ```objc SWGConfiguration *apiConfig = [SWGConfiguration sharedConfig]; +// Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth) +[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; + // Configure API key authorization: (authentication scheme: api_key) [apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"api_key"]; // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed //[apiConfig setApiKeyPrefix:@"Bearer" forApiKeyIdentifier:@"api_key"]; -// Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth) -[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; - NSNumber* petId = @789; // ID of pet that needs to be fetched @@ -283,7 +283,7 @@ Name | Type | Description | Notes ### Authorization -[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) +[petstore_auth](../README.md#petstore_auth), [api_key](../README.md#api_key) ### HTTP request headers From 81a2b2c36fdb915675d554f75064c2706abe8888 Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 7 Oct 2016 00:20:50 +0800 Subject: [PATCH 420/470] support number enum for swift --- .../java/io/swagger/codegen/languages/SwiftCodegen.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java index c775c8ec8f2..dc5969fc4b3 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java @@ -384,10 +384,18 @@ public CodegenProperty fromProperty(String name, Property p) { @SuppressWarnings("static-method") public String toSwiftyEnumName(String value) { + if (value.matches("^-?\\d*\\.{0,1}\\d+.*")) { // starts with number + value = "Number" + value; + value = value.replaceAll("-", "Minus"); + value = value.replaceAll("\\+", "Plus"); + value = value.replaceAll("\\.", "Dot"); + } + // Prevent from breaking properly cased identifier if (value.matches("[A-Z][a-z0-9]+[a-zA-Z0-9]*")) { return value; } + char[] separators = {'-', '_', ' ', ':'}; return WordUtils.capitalizeFully(StringUtils.lowerCase(value), separators).replaceAll("[-_ :]", ""); } From 574349570a2d0df80261d0c12088c69eb1d222c5 Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 7 Oct 2016 00:47:05 +0800 Subject: [PATCH 421/470] fix number format for dart model --- .../io/swagger/codegen/languages/DartClientCodegen.java | 6 ++++-- samples/client/petstore/dart/swagger/lib/api_client.dart | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java index 3cf6c439aea..652ff759deb 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java @@ -58,6 +58,7 @@ public DartClientCodegen() { "String", "bool", "int", + "num", "double") ); instantiationTypes.put("array", "List"); @@ -69,11 +70,12 @@ public DartClientCodegen() { typeMapping.put("List", "List"); typeMapping.put("boolean", "bool"); typeMapping.put("string", "String"); + typeMapping.put("char", "String"); typeMapping.put("int", "int"); - typeMapping.put("float", "double"); typeMapping.put("long", "int"); typeMapping.put("short", "int"); - typeMapping.put("char", "String"); + typeMapping.put("number", "num"); + typeMapping.put("float", "double"); typeMapping.put("double", "double"); typeMapping.put("object", "Object"); typeMapping.put("integer", "int"); diff --git a/samples/client/petstore/dart/swagger/lib/api_client.dart b/samples/client/petstore/dart/swagger/lib/api_client.dart index 9087a80d8cc..73856b69d74 100644 --- a/samples/client/petstore/dart/swagger/lib/api_client.dart +++ b/samples/client/petstore/dart/swagger/lib/api_client.dart @@ -24,8 +24,8 @@ class ApiClient { ApiClient({this.basePath: "http://petstore.swagger.io/v2"}) { // Setup authentications (key: authentication name, value: authentication). - _authentications['petstore_auth'] = new OAuth(); _authentications['api_key'] = new ApiKeyAuth("header", "api_key"); + _authentications['petstore_auth'] = new OAuth(); } void addDefaultHeader(String key, String value) { From 0ca60352e20273a38e61640d5c4ee9d0e656a399 Mon Sep 17 00:00:00 2001 From: vishal khawarey Date: Fri, 7 Oct 2016 00:26:05 -0700 Subject: [PATCH 422/470] required tag is used in model, allows null values (#3923) * required tag is used in model, allows null values * updated petstore api for CI * dont raise exception for 0 or false --- .../src/main/resources/python/model.mustache | 9 +++++---- .../python/petstore_api/models/enum_arrays.py | 2 +- .../python/petstore_api/models/format_test.py | 17 ----------------- .../python/petstore_api/models/map_test.py | 2 +- .../client/petstore/python/petstore_api/rest.py | 2 +- samples/client/petstore/ruby/docs/FakeApi.md | 4 +++- .../petstore/ruby/lib/petstore/api/fake_api.rb | 3 +++ 7 files changed, 14 insertions(+), 25 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index aa4a9f2e90c..78fd187b2da 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -66,7 +66,7 @@ class {{classname}}(object): if not set({{{name}}}).issubset(set(allowed_values)): raise ValueError( "Invalid values for `{{{name}}}` [{0}], must be a subset of [{1}]" - .format(", ".join(map(str, set({{{name}}})-set(allowed_values))), + .format(", ".join(map(str, set({{{name}}})-set(allowed_values))), ", ".join(map(str, allowed_values))) ) {{/isListContainer}} @@ -74,7 +74,7 @@ class {{classname}}(object): if not set({{{name}}}.keys()).issubset(set(allowed_values)): raise ValueError( "Invalid keys in `{{{name}}}` [{0}], must be a subset of [{1}]" - .format(", ".join(map(str, set({{{name}}}.keys())-set(allowed_values))), + .format(", ".join(map(str, set({{{name}}}.keys())-set(allowed_values))), ", ".join(map(str, allowed_values))) ) {{/isMapContainer}} @@ -89,9 +89,10 @@ class {{classname}}(object): {{/isEnum}} {{^isEnum}} {{#hasValidation}} - - if not {{name}}: +{{#required}} + if {{name}} is None: raise ValueError("Invalid value for `{{name}}`, must not be `None`") +{{/required}} {{#maxLength}} if len({{name}}) > {{maxLength}}: raise ValueError("Invalid value for `{{name}}`, length must be less than or equal to `{{maxLength}}`") diff --git a/samples/client/petstore/python/petstore_api/models/enum_arrays.py b/samples/client/petstore/python/petstore_api/models/enum_arrays.py index a7b01873f87..5caaaa07497 100644 --- a/samples/client/petstore/python/petstore_api/models/enum_arrays.py +++ b/samples/client/petstore/python/petstore_api/models/enum_arrays.py @@ -108,7 +108,7 @@ def array_enum(self, array_enum): if not set(array_enum).issubset(set(allowed_values)): raise ValueError( "Invalid values for `array_enum` [{0}], must be a subset of [{1}]" - .format(", ".join(map(str, set(array_enum)-set(allowed_values))), + .format(", ".join(map(str, set(array_enum)-set(allowed_values))), ", ".join(map(str, allowed_values))) ) diff --git a/samples/client/petstore/python/petstore_api/models/format_test.py b/samples/client/petstore/python/petstore_api/models/format_test.py index d36ba498de6..b6dcf81f37f 100644 --- a/samples/client/petstore/python/petstore_api/models/format_test.py +++ b/samples/client/petstore/python/petstore_api/models/format_test.py @@ -108,9 +108,6 @@ def integer(self, integer): :param integer: The integer of this FormatTest. :type: int """ - - if not integer: - raise ValueError("Invalid value for `integer`, must not be `None`") if integer > 100.0: raise ValueError("Invalid value for `integer`, must be a value less than or equal to `100.0`") if integer < 10.0: @@ -138,9 +135,6 @@ def int32(self, int32): :param int32: The int32 of this FormatTest. :type: int """ - - if not int32: - raise ValueError("Invalid value for `int32`, must not be `None`") if int32 > 200.0: raise ValueError("Invalid value for `int32`, must be a value less than or equal to `200.0`") if int32 < 20.0: @@ -191,7 +185,6 @@ def number(self, number): :param number: The number of this FormatTest. :type: float """ - if not number: raise ValueError("Invalid value for `number`, must not be `None`") if number > 543.2: @@ -221,9 +214,6 @@ def float(self, float): :param float: The float of this FormatTest. :type: float """ - - if not float: - raise ValueError("Invalid value for `float`, must not be `None`") if float > 987.6: raise ValueError("Invalid value for `float`, must be a value less than or equal to `987.6`") if float < 54.3: @@ -251,9 +241,6 @@ def double(self, double): :param double: The double of this FormatTest. :type: float """ - - if not double: - raise ValueError("Invalid value for `double`, must not be `None`") if double > 123.4: raise ValueError("Invalid value for `double`, must be a value less than or equal to `123.4`") if double < 67.8: @@ -281,9 +268,6 @@ def string(self, string): :param string: The string of this FormatTest. :type: str """ - - if not string: - raise ValueError("Invalid value for `string`, must not be `None`") if not re.search('[a-z]', string, flags=re.IGNORECASE): raise ValueError("Invalid value for `string`, must be a follow pattern or equal to `/[a-z]/i`") @@ -424,7 +408,6 @@ def password(self, password): :param password: The password of this FormatTest. :type: str """ - if not password: raise ValueError("Invalid value for `password`, must not be `None`") if len(password) > 64: diff --git a/samples/client/petstore/python/petstore_api/models/map_test.py b/samples/client/petstore/python/petstore_api/models/map_test.py index 8201a5b4682..9c4f9f5a931 100644 --- a/samples/client/petstore/python/petstore_api/models/map_test.py +++ b/samples/client/petstore/python/petstore_api/models/map_test.py @@ -102,7 +102,7 @@ def map_of_enum_string(self, map_of_enum_string): if not set(map_of_enum_string.keys()).issubset(set(allowed_values)): raise ValueError( "Invalid keys in `map_of_enum_string` [{0}], must be a subset of [{1}]" - .format(", ".join(map(str, set(map_of_enum_string.keys())-set(allowed_values))), + .format(", ".join(map(str, set(map_of_enum_string.keys())-set(allowed_values))), ", ".join(map(str, allowed_values))) ) diff --git a/samples/client/petstore/python/petstore_api/rest.py b/samples/client/petstore/python/petstore_api/rest.py index 2a9e97d5490..f8a4457ebae 100644 --- a/samples/client/petstore/python/petstore_api/rest.py +++ b/samples/client/petstore/python/petstore_api/rest.py @@ -158,7 +158,7 @@ def request(self, method, url, query_params=None, headers=None, # Pass a `string` parameter directly in the body to support # other content types than Json when `body` argument is provided # in serialized form - elif isinstance(body, basestring): + elif isinstance(body, str): request_body = body r = self.pool_manager.request(method, url, body=request_body, diff --git a/samples/client/petstore/ruby/docs/FakeApi.md b/samples/client/petstore/ruby/docs/FakeApi.md index 08207555c66..1524d9c915f 100644 --- a/samples/client/petstore/ruby/docs/FakeApi.md +++ b/samples/client/petstore/ruby/docs/FakeApi.md @@ -91,7 +91,8 @@ opts = { binary: "B", # String | None date: Date.parse("2013-10-20"), # Date | None date_time: DateTime.parse("2013-10-20T19:20:30+01:00"), # DateTime | None - password: "password_example" # String | None + password: "password_example", # String | None + callback: "callback_example" # String | None } begin @@ -119,6 +120,7 @@ Name | Type | Description | Notes **date** | **Date**| None | [optional] **date_time** | **DateTime**| None | [optional] **password** | **String**| None | [optional] + **callback** | **String**| None | [optional] ### Return type diff --git a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb index 5a0398b6bc9..0eaba370798 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb @@ -104,6 +104,7 @@ def test_client_model_with_http_info(body, opts = {}) # @option opts [Date] :date None # @option opts [DateTime] :date_time None # @option opts [String] :password None + # @option opts [String] :callback None # @return [nil] def test_endpoint_parameters(number, double, pattern_without_delimiter, byte, opts = {}) test_endpoint_parameters_with_http_info(number, double, pattern_without_delimiter, byte, opts) @@ -126,6 +127,7 @@ def test_endpoint_parameters(number, double, pattern_without_delimiter, byte, op # @option opts [Date] :date None # @option opts [DateTime] :date_time None # @option opts [String] :password None + # @option opts [String] :callback None # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers def test_endpoint_parameters_with_http_info(number, double, pattern_without_delimiter, byte, opts = {}) if @api_client.config.debugging @@ -223,6 +225,7 @@ def test_endpoint_parameters_with_http_info(number, double, pattern_without_deli form_params["date"] = opts[:'date'] if !opts[:'date'].nil? form_params["dateTime"] = opts[:'date_time'] if !opts[:'date_time'].nil? form_params["password"] = opts[:'password'] if !opts[:'password'].nil? + form_params["callback"] = opts[:'callback'] if !opts[:'callback'].nil? # http body (model) post_body = nil From 65f925f45c9a07e99f9b32363b3fd548a11dae88 Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 7 Oct 2016 15:50:57 +0800 Subject: [PATCH 423/470] fix python required property check and validation for optional properties --- .../src/main/resources/python/model.mustache | 16 ++++----- .../python/petstore_api/models/animal.py | 2 ++ .../python/petstore_api/models/cat.py | 2 ++ .../python/petstore_api/models/dog.py | 2 ++ .../python/petstore_api/models/format_test.py | 34 +++++++++++-------- .../python/petstore_api/models/name.py | 2 ++ .../python/petstore_api/models/pet.py | 4 +++ 7 files changed, 39 insertions(+), 23 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index 78fd187b2da..68e064bd190 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -88,37 +88,37 @@ class {{classname}}(object): {{/isContainer}} {{/isEnum}} {{^isEnum}} -{{#hasValidation}} {{#required}} if {{name}} is None: raise ValueError("Invalid value for `{{name}}`, must not be `None`") {{/required}} +{{#hasValidation}} {{#maxLength}} - if len({{name}}) > {{maxLength}}: + if {{name}} is not None and len({{name}}) > {{maxLength}}: raise ValueError("Invalid value for `{{name}}`, length must be less than or equal to `{{maxLength}}`") {{/maxLength}} {{#minLength}} - if len({{name}}) < {{minLength}}: + if {{name}} is not None and len({{name}}) < {{minLength}}: raise ValueError("Invalid value for `{{name}}`, length must be greater than or equal to `{{minLength}}`") {{/minLength}} {{#maximum}} - if {{name}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}}: + if {{name}} is not None and {{name}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}}: raise ValueError("Invalid value for `{{name}}`, must be a value less than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}`{{maximum}}`") {{/maximum}} {{#minimum}} - if {{name}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}}: + if {{name}} is not None and {{name}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}}: raise ValueError("Invalid value for `{{name}}`, must be a value greater than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}`{{minimum}}`") {{/minimum}} {{#pattern}} - if not re.search('{{{vendorExtensions.x-regex}}}', {{name}}{{#vendorExtensions.x-modifiers}}{{#-first}}, flags={{/-first}}re.{{.}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}): + if {{name}} is not None and not re.search('{{{vendorExtensions.x-regex}}}', {{name}}{{#vendorExtensions.x-modifiers}}{{#-first}}, flags={{/-first}}re.{{.}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}): raise ValueError("Invalid value for `{{name}}`, must be a follow pattern or equal to `{{{pattern}}}`") {{/pattern}} {{#maxItems}} - if len({{name}}) > {{maxItems}}: + if {{name}} is not None and len({{name}}) > {{maxItems}}: raise ValueError("Invalid value for `{{name}}`, number of items must be less than or equal to `{{maxItems}}`") {{/maxItems}} {{#minItems}} - if len({{name}}) < {{minItems}}: + if {{name}} is not None and len({{name}}) < {{minItems}}: raise ValueError("Invalid value for `{{name}}`, number of items must be greater than or equal to `{{minItems}}`") {{/minItems}} {{/hasValidation}} diff --git a/samples/client/petstore/python/petstore_api/models/animal.py b/samples/client/petstore/python/petstore_api/models/animal.py index fb902912fbe..23bcbe07457 100644 --- a/samples/client/petstore/python/petstore_api/models/animal.py +++ b/samples/client/petstore/python/petstore_api/models/animal.py @@ -75,6 +75,8 @@ def class_name(self, class_name): :param class_name: The class_name of this Animal. :type: str """ + if class_name is None: + raise ValueError("Invalid value for `class_name`, must not be `None`") self._class_name = class_name diff --git a/samples/client/petstore/python/petstore_api/models/cat.py b/samples/client/petstore/python/petstore_api/models/cat.py index 7bd40711c59..361d5d091ae 100644 --- a/samples/client/petstore/python/petstore_api/models/cat.py +++ b/samples/client/petstore/python/petstore_api/models/cat.py @@ -78,6 +78,8 @@ def class_name(self, class_name): :param class_name: The class_name of this Cat. :type: str """ + if class_name is None: + raise ValueError("Invalid value for `class_name`, must not be `None`") self._class_name = class_name diff --git a/samples/client/petstore/python/petstore_api/models/dog.py b/samples/client/petstore/python/petstore_api/models/dog.py index 5e84656c958..36a1f1a3cb4 100644 --- a/samples/client/petstore/python/petstore_api/models/dog.py +++ b/samples/client/petstore/python/petstore_api/models/dog.py @@ -78,6 +78,8 @@ def class_name(self, class_name): :param class_name: The class_name of this Dog. :type: str """ + if class_name is None: + raise ValueError("Invalid value for `class_name`, must not be `None`") self._class_name = class_name diff --git a/samples/client/petstore/python/petstore_api/models/format_test.py b/samples/client/petstore/python/petstore_api/models/format_test.py index b6dcf81f37f..3c8682fdeca 100644 --- a/samples/client/petstore/python/petstore_api/models/format_test.py +++ b/samples/client/petstore/python/petstore_api/models/format_test.py @@ -108,9 +108,9 @@ def integer(self, integer): :param integer: The integer of this FormatTest. :type: int """ - if integer > 100.0: + if integer is not None and integer > 100.0: raise ValueError("Invalid value for `integer`, must be a value less than or equal to `100.0`") - if integer < 10.0: + if integer is not None and integer < 10.0: raise ValueError("Invalid value for `integer`, must be a value greater than or equal to `10.0`") self._integer = integer @@ -135,9 +135,9 @@ def int32(self, int32): :param int32: The int32 of this FormatTest. :type: int """ - if int32 > 200.0: + if int32 is not None and int32 > 200.0: raise ValueError("Invalid value for `int32`, must be a value less than or equal to `200.0`") - if int32 < 20.0: + if int32 is not None and int32 < 20.0: raise ValueError("Invalid value for `int32`, must be a value greater than or equal to `20.0`") self._int32 = int32 @@ -185,11 +185,11 @@ def number(self, number): :param number: The number of this FormatTest. :type: float """ - if not number: + if number is None: raise ValueError("Invalid value for `number`, must not be `None`") - if number > 543.2: + if number is not None and number > 543.2: raise ValueError("Invalid value for `number`, must be a value less than or equal to `543.2`") - if number < 32.1: + if number is not None and number < 32.1: raise ValueError("Invalid value for `number`, must be a value greater than or equal to `32.1`") self._number = number @@ -214,9 +214,9 @@ def float(self, float): :param float: The float of this FormatTest. :type: float """ - if float > 987.6: + if float is not None and float > 987.6: raise ValueError("Invalid value for `float`, must be a value less than or equal to `987.6`") - if float < 54.3: + if float is not None and float < 54.3: raise ValueError("Invalid value for `float`, must be a value greater than or equal to `54.3`") self._float = float @@ -241,9 +241,9 @@ def double(self, double): :param double: The double of this FormatTest. :type: float """ - if double > 123.4: + if double is not None and double > 123.4: raise ValueError("Invalid value for `double`, must be a value less than or equal to `123.4`") - if double < 67.8: + if double is not None and double < 67.8: raise ValueError("Invalid value for `double`, must be a value greater than or equal to `67.8`") self._double = double @@ -268,7 +268,7 @@ def string(self, string): :param string: The string of this FormatTest. :type: str """ - if not re.search('[a-z]', string, flags=re.IGNORECASE): + if string is not None and not re.search('[a-z]', string, flags=re.IGNORECASE): raise ValueError("Invalid value for `string`, must be a follow pattern or equal to `/[a-z]/i`") self._string = string @@ -293,6 +293,8 @@ def byte(self, byte): :param byte: The byte of this FormatTest. :type: str """ + if byte is None: + raise ValueError("Invalid value for `byte`, must not be `None`") self._byte = byte @@ -339,6 +341,8 @@ def date(self, date): :param date: The date of this FormatTest. :type: date """ + if date is None: + raise ValueError("Invalid value for `date`, must not be `None`") self._date = date @@ -408,11 +412,11 @@ def password(self, password): :param password: The password of this FormatTest. :type: str """ - if not password: + if password is None: raise ValueError("Invalid value for `password`, must not be `None`") - if len(password) > 64: + if password is not None and len(password) > 64: raise ValueError("Invalid value for `password`, length must be less than or equal to `64`") - if len(password) < 10: + if password is not None and len(password) < 10: raise ValueError("Invalid value for `password`, length must be greater than or equal to `10`") self._password = password diff --git a/samples/client/petstore/python/petstore_api/models/name.py b/samples/client/petstore/python/petstore_api/models/name.py index cb5c08f3736..a613643c624 100644 --- a/samples/client/petstore/python/petstore_api/models/name.py +++ b/samples/client/petstore/python/petstore_api/models/name.py @@ -81,6 +81,8 @@ def name(self, name): :param name: The name of this Name. :type: int """ + if name is None: + raise ValueError("Invalid value for `name`, must not be `None`") self._name = name diff --git a/samples/client/petstore/python/petstore_api/models/pet.py b/samples/client/petstore/python/petstore_api/models/pet.py index be58ba7af95..93d3699cd0d 100644 --- a/samples/client/petstore/python/petstore_api/models/pet.py +++ b/samples/client/petstore/python/petstore_api/models/pet.py @@ -133,6 +133,8 @@ def name(self, name): :param name: The name of this Pet. :type: str """ + if name is None: + raise ValueError("Invalid value for `name`, must not be `None`") self._name = name @@ -156,6 +158,8 @@ def photo_urls(self, photo_urls): :param photo_urls: The photo_urls of this Pet. :type: list[str] """ + if photo_urls is None: + raise ValueError("Invalid value for `photo_urls`, must not be `None`") self._photo_urls = photo_urls From d21613c6ab61b23eaeef09c9bd1eb6906cbdc58b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20Franz=C3=A9n?= Date: Sat, 8 Oct 2016 06:36:56 +0200 Subject: [PATCH 424/470] Bugfix/3929 do not set multipart (#3932) * Do not set Content-Type to multipart/form-data It causes superagent to not add the boundary in the Content-Type * Run shell-scripts --- .../resources/Javascript/ApiClient.mustache | 5 ++- .../javascript/README.md | 33 +++++++++--------- .../javascript/docs/FakeApi.md | 28 +++++++-------- .../javascript/docs/ModelReturn.md | 4 +-- .../javascript/package.json | 6 ++-- .../javascript/src/ApiClient.js | 31 +++++++++-------- .../javascript/src/api/FakeApi.js | 34 +++++++++---------- .../javascript/src/index.js | 22 ++++++------ .../javascript/src/model/ModelReturn.js | 24 ++++++------- .../petstore/javascript/docs/FakeApi.md | 4 ++- .../petstore/javascript/src/ApiClient.js | 5 ++- .../petstore/javascript/src/api/FakeApi.js | 4 ++- 12 files changed, 106 insertions(+), 94 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache index a85ebf9fbdd..d277079892c 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache @@ -363,7 +363,10 @@ var contentType = this.jsonPreferredMime(contentTypes); if (contentType) { - request.type(contentType); + // Issue with superagent and multipart/form-data (https://github.com/visionmedia/superagent/issues/746) + if(contentType != 'multipart/form-data') { + request.type(contentType); + } } else if (!request.header['Content-Type']) { request.type('application/json'); } diff --git a/samples/client/petstore-security-test/javascript/README.md b/samples/client/petstore-security-test/javascript/README.md index b77d3ebd6a0..f49c8f9d42e 100644 --- a/samples/client/petstore-security-test/javascript/README.md +++ b/samples/client/petstore-security-test/javascript/README.md @@ -1,12 +1,11 @@ -# swagger_petstore____end +# swagger_petstore____end____rn_n_r -SwaggerPetstoreEnd - JavaScript client for swagger_petstore____end -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ ' \" =end +SwaggerPetstoreEndRnNR - JavaScript client for swagger_petstore____end____rn_n_r +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- This SDK is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: -- API version: 1.0.0 ' \" =end -- Package version: 1.0.0 =end -- Build date: 2016-06-29T21:40:05.384+08:00 +- API version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r +- Package version: 1.0.0 *_/ =end -- \r\n \n \r - Build package: class io.swagger.codegen.languages.JavascriptClientCodegen ## Installation @@ -21,7 +20,7 @@ please follow the procedure in ["Publishing npm packages"](https://docs.npmjs.co Then install it via: ```shell -npm install swagger_petstore____end --save +npm install swagger_petstore____end____rn_n_r --save ``` #### git @@ -51,12 +50,12 @@ Then include *bundle.js* in the HTML pages. Please follow the [installation](#installation) instruction and execute the following JS code: ```javascript -var SwaggerPetstoreEnd = require('swagger_petstore____end'); +var SwaggerPetstoreEndRnNR = require('swagger_petstore____end____rn_n_r'); -var api = new SwaggerPetstoreEnd.FakeApi() +var api = new SwaggerPetstoreEndRnNR.FakeApi() var opts = { - 'testCodeInjectEnd': "testCodeInjectEnd_example" // {String} To test code injection ' \" =end + 'testCodeInjectEndRnNR': "testCodeInjectEndRnNR_example" // {String} To test code injection *_/ ' \" =end -- \\r\\n \\n \\r }; var callback = function(error, data, response) { @@ -66,22 +65,22 @@ var callback = function(error, data, response) { console.log('API called successfully.'); } }; -api.testCodeInjectEnd(opts, callback); +api.testCodeInjectEndRnNR(opts, callback); ``` ## Documentation for API Endpoints -All URIs are relative to *https://petstore.swagger.io ' \" =end/v2 ' \" =end* +All URIs are relative to *https://petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*SwaggerPetstoreEnd.FakeApi* | [**testCodeInjectEnd**](docs/FakeApi.md#testCodeInjectEnd) | **PUT** /fake | To test code injection ' \" =end +*SwaggerPetstoreEndRnNR.FakeApi* | [**testCodeInjectEndRnNR**](docs/FakeApi.md#testCodeInjectEndRnNR) | **PUT** /fake | To test code injection *_/ ' \" =end -- \\r\\n \\n \\r ## Documentation for Models - - [SwaggerPetstoreEnd.ModelReturn](docs/ModelReturn.md) + - [SwaggerPetstoreEndRnNR.ModelReturn](docs/ModelReturn.md) ## Documentation for Authorization @@ -90,7 +89,7 @@ Class | Method | HTTP request | Description ### api_key - **Type**: API key -- **API key parameter name**: api_key */ ' " =end +- **API key parameter name**: api_key */ ' " =end -- \r\n \n \r - **Location**: HTTP header ### petstore_auth @@ -99,6 +98,6 @@ Class | Method | HTTP request | Description - **Flow**: implicit - **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog - **Scopes**: - - write:pets: modify pets in your account */ ' " =end - - read:pets: read your pets */ ' " =end + - write:pets: modify pets in your account *_/ ' \" =end -- \\r\\n \\n \\r + - read:pets: read your pets *_/ ' \" =end -- \\r\\n \\n \\r diff --git a/samples/client/petstore-security-test/javascript/docs/FakeApi.md b/samples/client/petstore-security-test/javascript/docs/FakeApi.md index adbbd32fdb0..61b58cf72a9 100644 --- a/samples/client/petstore-security-test/javascript/docs/FakeApi.md +++ b/samples/client/petstore-security-test/javascript/docs/FakeApi.md @@ -1,26 +1,26 @@ -# SwaggerPetstoreEnd.FakeApi +# SwaggerPetstoreEndRnNR.FakeApi -All URIs are relative to *https://petstore.swagger.io ' \" =end/v2 ' \" =end* +All URIs are relative to *https://petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r* Method | HTTP request | Description ------------- | ------------- | ------------- -[**testCodeInjectEnd**](FakeApi.md#testCodeInjectEnd) | **PUT** /fake | To test code injection ' \" =end +[**testCodeInjectEndRnNR**](FakeApi.md#testCodeInjectEndRnNR) | **PUT** /fake | To test code injection *_/ ' \" =end -- \\r\\n \\n \\r - -# **testCodeInjectEnd** -> testCodeInjectEnd(opts) + +# **testCodeInjectEndRnNR** +> testCodeInjectEndRnNR(opts) -To test code injection ' \" =end +To test code injection *_/ ' \" =end -- \\r\\n \\n \\r ### Example ```javascript -var SwaggerPetstoreEnd = require('swagger_petstore____end'); +var SwaggerPetstoreEndRnNR = require('swagger_petstore____end____rn_n_r'); -var apiInstance = new SwaggerPetstoreEnd.FakeApi(); +var apiInstance = new SwaggerPetstoreEndRnNR.FakeApi(); var opts = { - 'testCodeInjectEnd': "testCodeInjectEnd_example" // String | To test code injection ' \" =end + 'testCodeInjectEndRnNR': "testCodeInjectEndRnNR_example" // String | To test code injection *_/ ' \" =end -- \\r\\n \\n \\r }; var callback = function(error, data, response) { @@ -30,14 +30,14 @@ var callback = function(error, data, response) { console.log('API called successfully.'); } }; -apiInstance.testCodeInjectEnd(opts, callback); +apiInstance.testCodeInjectEndRnNR(opts, callback); ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **testCodeInjectEnd** | **String**| To test code injection ' \" =end | [optional] + **testCodeInjectEndRnNR** | **String**| To test code injection *_/ ' \" =end -- \\r\\n \\n \\r | [optional] ### Return type @@ -49,6 +49,6 @@ No authorization required ### HTTP request headers - - **Content-Type**: application/json, */ =end - - **Accept**: application/json, */ =end + - **Content-Type**: application/json, *_/ =end -- + - **Accept**: application/json, *_/ =end -- diff --git a/samples/client/petstore-security-test/javascript/docs/ModelReturn.md b/samples/client/petstore-security-test/javascript/docs/ModelReturn.md index 2341e97142f..e542020a95c 100644 --- a/samples/client/petstore-security-test/javascript/docs/ModelReturn.md +++ b/samples/client/petstore-security-test/javascript/docs/ModelReturn.md @@ -1,8 +1,8 @@ -# SwaggerPetstoreEnd.ModelReturn +# SwaggerPetstoreEndRnNR.ModelReturn ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**_return** | **Integer** | property description ' \" =end | [optional] +**_return** | **Number** | property description *_/ ' \" =end -- \\r\\n \\n \\r | [optional] diff --git a/samples/client/petstore-security-test/javascript/package.json b/samples/client/petstore-security-test/javascript/package.json index 13a19a00ad3..89f2c51c2c2 100644 --- a/samples/client/petstore-security-test/javascript/package.json +++ b/samples/client/petstore-security-test/javascript/package.json @@ -1,7 +1,7 @@ { - "name": "swagger_petstore____end", - "version": "1.0.0 =end", - "description": "This_spec_is_mainly_for_testing_Petstore_server_and_contains_fake_endpoints_models__Please_do_not_use_this_for_any_other_purpose__Special_characters_______end", + "name": "swagger_petstore____end____rn_n_r", + "version": "1.0.0 *_/ =end -- \r\n \n \r", + "description": "This_spec_is_mainly_for_testing_Petstore_server_and_contains_fake_endpoints_models__Please_do_not_use_this_for_any_other_purpose__Special_characters_______end______", "license": "Apache-2.0", "main": "src/index.js", "scripts": { diff --git a/samples/client/petstore-security-test/javascript/src/ApiClient.js b/samples/client/petstore-security-test/javascript/src/ApiClient.js index b22ed5202a5..20e0bc173fe 100644 --- a/samples/client/petstore-security-test/javascript/src/ApiClient.js +++ b/samples/client/petstore-security-test/javascript/src/ApiClient.js @@ -1,9 +1,9 @@ /** - * Swagger Petstore ' \" =end - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ ' \" =end + * Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- * - * OpenAPI spec version: 1.0.0 ' \" =end - * Contact: apiteam@swagger.io ' \" =end + * OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -31,17 +31,17 @@ module.exports = factory(require('superagent')); } else { // Browser globals (root is window) - if (!root.SwaggerPetstoreEnd) { - root.SwaggerPetstoreEnd = {}; + if (!root.SwaggerPetstoreEndRnNR) { + root.SwaggerPetstoreEndRnNR = {}; } - root.SwaggerPetstoreEnd.ApiClient = factory(root.superagent); + root.SwaggerPetstoreEndRnNR.ApiClient = factory(root.superagent); } }(this, function(superagent) { 'use strict'; /** * @module ApiClient - * @version 1.0.0 =end + * @version 1.0.0 *_/ =end -- \r\n \n \r */ /** @@ -55,16 +55,16 @@ /** * The base URL against which to resolve every API call's (relative) path. * @type {String} - * @default https://petstore.swagger.io ' \" =end/v2 ' \" =end + * @default https://petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r */ - this.basePath = 'https://petstore.swagger.io ' \" =end/v2 ' \" =end'.replace(/\/+$/, ''); + this.basePath = 'https://petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r'.replace(/\/+$/, ''); /** * The authentication methods to be included for all API calls. * @type {Array.} */ this.authentications = { - 'api_key': {type: 'apiKey', 'in': 'header', name: 'api_key */ ' " =end'}, + 'api_key': {type: 'apiKey', 'in': 'header', name: 'api_key */ ' " =end -- \r\n \n \r'}, 'petstore_auth': {type: 'oauth2'} }; /** @@ -154,7 +154,7 @@ /** * Checks whether the given parameter value represents file-like content. * @param param The parameter to check. - * @returns {Boolean} true if param represents a file. + * @returns {Boolean} true if param represents a file. */ exports.prototype.isFileParam = function(param) { // fs.ReadStream in Node.js (but not in runtime like browserify) @@ -206,7 +206,7 @@ /** * Enumeration of collection format separator strategies. - * @enum {String} + * @enum {String} * @readonly */ exports.CollectionFormatEnum = { @@ -376,7 +376,10 @@ var contentType = this.jsonPreferredMime(contentTypes); if (contentType) { - request.type(contentType); + // Issue with superagent and multipart/form-data (https://github.com/visionmedia/superagent/issues/746) + if(contentType != 'multipart/form-data') { + request.type(contentType); + } } else if (!request.header['Content-Type']) { request.type('application/json'); } diff --git a/samples/client/petstore-security-test/javascript/src/api/FakeApi.js b/samples/client/petstore-security-test/javascript/src/api/FakeApi.js index f2ccf169d90..f7585314e66 100644 --- a/samples/client/petstore-security-test/javascript/src/api/FakeApi.js +++ b/samples/client/petstore-security-test/javascript/src/api/FakeApi.js @@ -1,9 +1,9 @@ /** - * Swagger Petstore ' \" =end - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ ' \" =end + * Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- * - * OpenAPI spec version: 1.0.0 ' \" =end - * Contact: apiteam@swagger.io ' \" =end + * OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -31,10 +31,10 @@ module.exports = factory(require('../ApiClient')); } else { // Browser globals (root is window) - if (!root.SwaggerPetstoreEnd) { - root.SwaggerPetstoreEnd = {}; + if (!root.SwaggerPetstoreEndRnNR) { + root.SwaggerPetstoreEndRnNR = {}; } - root.SwaggerPetstoreEnd.FakeApi = factory(root.SwaggerPetstoreEnd.ApiClient); + root.SwaggerPetstoreEndRnNR.FakeApi = factory(root.SwaggerPetstoreEndRnNR.ApiClient); } }(this, function(ApiClient) { 'use strict'; @@ -42,7 +42,7 @@ /** * Fake service. * @module api/FakeApi - * @version 1.0.0 =end + * @version 1.0.0 *_/ =end -- \r\n \n \r */ /** @@ -57,20 +57,20 @@ /** - * Callback function to receive the result of the testCodeInjectEnd operation. - * @callback module:api/FakeApi~testCodeInjectEndCallback + * Callback function to receive the result of the testCodeInjectEndRnNR operation. + * @callback module:api/FakeApi~testCodeInjectEndRnNRCallback * @param {String} error Error message, if any. * @param data This operation does not return a value. * @param {String} response The complete HTTP response. */ /** - * To test code injection ' \" =end + * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r * @param {Object} opts Optional parameters - * @param {String} opts.testCodeInjectEnd To test code injection ' \" =end - * @param {module:api/FakeApi~testCodeInjectEndCallback} callback The callback function, accepting three arguments: error, data, response + * @param {String} opts.testCodeInjectEndRnNR To test code injection *_/ ' \" =end -- \\r\\n \\n \\r + * @param {module:api/FakeApi~testCodeInjectEndRnNRCallback} callback The callback function, accepting three arguments: error, data, response */ - this.testCodeInjectEnd = function(opts, callback) { + this.testCodeInjectEndRnNR = function(opts, callback) { opts = opts || {}; var postBody = null; @@ -82,12 +82,12 @@ var headerParams = { }; var formParams = { - 'test code inject */ ' " =end': opts['testCodeInjectEnd'] + 'test code inject */ ' " =end -- \r\n \n \r': opts['testCodeInjectEndRnNR'] }; var authNames = []; - var contentTypes = ['application/json', '*/ =end']; - var accepts = ['application/json', '*/ =end']; + var contentTypes = ['application/json', '*_/ =end -- ']; + var accepts = ['application/json', '*_/ =end -- ']; var returnType = null; return this.apiClient.callApi( diff --git a/samples/client/petstore-security-test/javascript/src/index.js b/samples/client/petstore-security-test/javascript/src/index.js index 6c5081c188c..3a2295732ee 100644 --- a/samples/client/petstore-security-test/javascript/src/index.js +++ b/samples/client/petstore-security-test/javascript/src/index.js @@ -1,9 +1,9 @@ /** - * Swagger Petstore ' \" =end - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ ' \" =end + * Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- * - * OpenAPI spec version: 1.0.0 ' \" =end - * Contact: apiteam@swagger.io ' \" =end + * OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -34,14 +34,14 @@ 'use strict'; /** - * This_spec_is_mainly_for_testing_Petstore_server_and_contains_fake_endpoints_models__Please_do_not_use_this_for_any_other_purpose__Special_characters_______end.
+ * This_spec_is_mainly_for_testing_Petstore_server_and_contains_fake_endpoints_models__Please_do_not_use_this_for_any_other_purpose__Special_characters_______end______.
* The index module provides access to constructors for all the classes which comprise the public API. *

* An AMD (recommended!) or CommonJS application will generally do something equivalent to the following: *

-   * var SwaggerPetstoreEnd = require('index'); // See note below*.
-   * var xxxSvc = new SwaggerPetstoreEnd.XxxApi(); // Allocate the API class we're going to use.
-   * var yyyModel = new SwaggerPetstoreEnd.Yyy(); // Construct a model instance.
+   * var SwaggerPetstoreEndRnNR = require('index'); // See note below*.
+   * var xxxSvc = new SwaggerPetstoreEndRnNR.XxxApi(); // Allocate the API class we're going to use.
+   * var yyyModel = new SwaggerPetstoreEndRnNR.Yyy(); // Construct a model instance.
    * yyyModel.someProperty = 'someValue';
    * ...
    * var zzz = xxxSvc.doSomething(yyyModel); // Invoke the service.
@@ -53,8 +53,8 @@
    * 

* A non-AMD browser application (discouraged) might do something like this: *

-   * var xxxSvc = new SwaggerPetstoreEnd.XxxApi(); // Allocate the API class we're going to use.
-   * var yyy = new SwaggerPetstoreEnd.Yyy(); // Construct a model instance.
+   * var xxxSvc = new SwaggerPetstoreEndRnNR.XxxApi(); // Allocate the API class we're going to use.
+   * var yyy = new SwaggerPetstoreEndRnNR.Yyy(); // Construct a model instance.
    * yyyModel.someProperty = 'someValue';
    * ...
    * var zzz = xxxSvc.doSomething(yyyModel); // Invoke the service.
@@ -62,7 +62,7 @@
    * 
*

* @module index - * @version 1.0.0 =end + * @version 1.0.0 *_/ =end -- \r\n \n \r */ var exports = { /** diff --git a/samples/client/petstore-security-test/javascript/src/model/ModelReturn.js b/samples/client/petstore-security-test/javascript/src/model/ModelReturn.js index 8c5d596cdca..7803d3622ca 100644 --- a/samples/client/petstore-security-test/javascript/src/model/ModelReturn.js +++ b/samples/client/petstore-security-test/javascript/src/model/ModelReturn.js @@ -1,9 +1,9 @@ /** - * Swagger Petstore ' \" =end - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ ' \" =end + * Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- * - * OpenAPI spec version: 1.0.0 ' \" =end - * Contact: apiteam@swagger.io ' \" =end + * OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -31,10 +31,10 @@ module.exports = factory(require('../ApiClient')); } else { // Browser globals (root is window) - if (!root.SwaggerPetstoreEnd) { - root.SwaggerPetstoreEnd = {}; + if (!root.SwaggerPetstoreEndRnNR) { + root.SwaggerPetstoreEndRnNR = {}; } - root.SwaggerPetstoreEnd.ModelReturn = factory(root.SwaggerPetstoreEnd.ApiClient); + root.SwaggerPetstoreEndRnNR.ModelReturn = factory(root.SwaggerPetstoreEndRnNR.ApiClient); } }(this, function(ApiClient) { 'use strict'; @@ -45,12 +45,12 @@ /** * The ModelReturn model module. * @module model/ModelReturn - * @version 1.0.0 =end + * @version 1.0.0 *_/ =end -- \r\n \n \r */ /** * Constructs a new ModelReturn. - * Model for testing reserved words ' \" =end + * Model for testing reserved words *_/ ' \" =end -- \\r\\n \\n \\r * @alias module:model/ModelReturn * @class */ @@ -72,15 +72,15 @@ obj = obj || new exports(); if (data.hasOwnProperty('return')) { - obj['return'] = ApiClient.convertToType(data['return'], 'Integer'); + obj['return'] = ApiClient.convertToType(data['return'], 'Number'); } } return obj; } /** - * property description ' \" =end - * @member {Integer} return + * property description *_/ ' \" =end -- \\r\\n \\n \\r + * @member {Number} return */ exports.prototype['return'] = undefined; diff --git a/samples/client/petstore/javascript/docs/FakeApi.md b/samples/client/petstore/javascript/docs/FakeApi.md index b754b8815cf..4be1079607b 100644 --- a/samples/client/petstore/javascript/docs/FakeApi.md +++ b/samples/client/petstore/javascript/docs/FakeApi.md @@ -90,7 +90,8 @@ var opts = { 'binary': "B", // String | None '_date': new Date("2013-10-20"), // Date | None 'dateTime': new Date("2013-10-20T19:20:30+01:00"), // Date | None - 'password': "password_example" // String | None + 'password': "password_example", // String | None + 'callback': "callback_example" // String | None }; var callback = function(error, data, response) { @@ -120,6 +121,7 @@ Name | Type | Description | Notes **_date** | **Date**| None | [optional] **dateTime** | **Date**| None | [optional] **password** | **String**| None | [optional] + **callback** | **String**| None | [optional] ### Return type diff --git a/samples/client/petstore/javascript/src/ApiClient.js b/samples/client/petstore/javascript/src/ApiClient.js index 1ca3143bc09..720b9417343 100644 --- a/samples/client/petstore/javascript/src/ApiClient.js +++ b/samples/client/petstore/javascript/src/ApiClient.js @@ -377,7 +377,10 @@ var contentType = this.jsonPreferredMime(contentTypes); if (contentType) { - request.type(contentType); + // Issue with superagent and multipart/form-data (https://github.com/visionmedia/superagent/issues/746) + if(contentType != 'multipart/form-data') { + request.type(contentType); + } } else if (!request.header['Content-Type']) { request.type('application/json'); } diff --git a/samples/client/petstore/javascript/src/api/FakeApi.js b/samples/client/petstore/javascript/src/api/FakeApi.js index 0d4ccca70ef..edda32926dc 100644 --- a/samples/client/petstore/javascript/src/api/FakeApi.js +++ b/samples/client/petstore/javascript/src/api/FakeApi.js @@ -125,6 +125,7 @@ * @param {Date} opts._date None * @param {Date} opts.dateTime None * @param {String} opts.password None + * @param {String} opts.callback None * @param {module:api/FakeApi~testEndpointParametersCallback} callback The callback function, accepting three arguments: error, data, response */ this.testEndpointParameters = function(_number, _double, patternWithoutDelimiter, _byte, opts, callback) { @@ -171,7 +172,8 @@ 'binary': opts['binary'], 'date': opts['_date'], 'dateTime': opts['dateTime'], - 'password': opts['password'] + 'password': opts['password'], + 'callback': opts['callback'] }; var authNames = ['http_basic_test']; From c1a6bbb86a2466c32d4a874797b755d91458433c Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 9 Oct 2016 14:06:55 +0800 Subject: [PATCH 425/470] [Python][Flask] fix python2 support in Flask (#3952) * flask python2 petstore sample * fix python2 support in flask --- bin/flaskConnexion-python2.sh | 32 + bin/supportPython2.json | 3 + .../resources/flaskConnexion/README.mustache | 6 + .../resources/flaskConnexion/app.mustache | 5 + .../.swagger-codegen-ignore | 23 + .../petstore/flaskConnexion-python2/LICENSE | 201 +++++ .../petstore/flaskConnexion-python2/README.md | 28 + .../flaskConnexion-python2/__init__.py | 0 .../petstore/flaskConnexion-python2/app.py | 8 + .../controllers/__init__.py | 0 .../controllers/pet_controller.py | 24 + .../controllers/store_controller.py | 12 + .../controllers/user_controller.py | 24 + .../swagger/swagger.yaml | 754 ++++++++++++++++++ 14 files changed, 1120 insertions(+) create mode 100755 bin/flaskConnexion-python2.sh create mode 100644 bin/supportPython2.json create mode 100644 samples/server/petstore/flaskConnexion-python2/.swagger-codegen-ignore create mode 100644 samples/server/petstore/flaskConnexion-python2/LICENSE create mode 100644 samples/server/petstore/flaskConnexion-python2/README.md create mode 100644 samples/server/petstore/flaskConnexion-python2/__init__.py create mode 100644 samples/server/petstore/flaskConnexion-python2/app.py create mode 100644 samples/server/petstore/flaskConnexion-python2/controllers/__init__.py create mode 100644 samples/server/petstore/flaskConnexion-python2/controllers/pet_controller.py create mode 100644 samples/server/petstore/flaskConnexion-python2/controllers/store_controller.py create mode 100644 samples/server/petstore/flaskConnexion-python2/controllers/user_controller.py create mode 100644 samples/server/petstore/flaskConnexion-python2/swagger/swagger.yaml diff --git a/bin/flaskConnexion-python2.sh b/bin/flaskConnexion-python2.sh new file mode 100755 index 00000000000..313ef297bf8 --- /dev/null +++ b/bin/flaskConnexion-python2.sh @@ -0,0 +1,32 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +#ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l python-flask -o samples/server/petstore/flaskConnexion-python2 -DsupportPython2=true" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l python-flask -o samples/server/petstore/flaskConnexion-python2 -c bin/supportPython2.json" + +java $JAVA_OPTS -Dservice -jar $executable $ags diff --git a/bin/supportPython2.json b/bin/supportPython2.json new file mode 100644 index 00000000000..8fc7eca95ec --- /dev/null +++ b/bin/supportPython2.json @@ -0,0 +1,3 @@ +{ + "supportPython2": true +} diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/README.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/README.mustache index cc7805c9b97..d53139b49b2 100644 --- a/modules/swagger-codegen/src/main/resources/flaskConnexion/README.mustache +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/README.mustache @@ -10,8 +10,14 @@ This example uses the [Connexion](https://github.com/zalando/connexion) library To run the server, please execute the following: ``` +{{#supportPython2}} +sudo pip install -U connexion # install Connexion from PyPI +python app.py +{{/supportPython2}} +{{^supportPython2}} sudo pip3 install -U connexion # install Connexion from PyPI python3 app.py +{{/supportPython2}} ``` and open your browser to here: diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/app.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/app.mustache index ded223fb36d..85fd9a354f1 100644 --- a/modules/swagger-codegen/src/main/resources/flaskConnexion/app.mustache +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/app.mustache @@ -1,4 +1,9 @@ +{{#supportPython2}} +#!/usr/bin/env python +{{/supportPython2}} +{{^supportPython2}} #!/usr/bin/env python3 +{{/supportPython2}} import connexion diff --git a/samples/server/petstore/flaskConnexion-python2/.swagger-codegen-ignore b/samples/server/petstore/flaskConnexion-python2/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/flaskConnexion-python2/LICENSE b/samples/server/petstore/flaskConnexion-python2/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/server/petstore/flaskConnexion-python2/README.md b/samples/server/petstore/flaskConnexion-python2/README.md new file mode 100644 index 00000000000..cfc25505bd7 --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/README.md @@ -0,0 +1,28 @@ +# Swagger generated server + +## Overview +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the +[OpenAPI-Spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This +is an example of building a swagger-enabled Flask server. + +This example uses the [Connexion](https://github.com/zalando/connexion) library on top of Flask. + +To run the server, please execute the following: + +``` +sudo pip install -U connexion # install Connexion from PyPI +python app.py +``` + +and open your browser to here: + +``` +http://localhost:8080/v2/ui/ +``` + +Your Swagger definition lives here: + +``` +http://localhost:8080/v2/swagger.json +``` + diff --git a/samples/server/petstore/flaskConnexion-python2/__init__.py b/samples/server/petstore/flaskConnexion-python2/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/flaskConnexion-python2/app.py b/samples/server/petstore/flaskConnexion-python2/app.py new file mode 100644 index 00000000000..47814427205 --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/app.py @@ -0,0 +1,8 @@ +#!/usr/bin/env python + +import connexion + +if __name__ == '__main__': + app = connexion.App(__name__, specification_dir='./swagger/') + app.add_api('swagger.yaml', arguments={'title': 'This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.'}) + app.run(port=8080) diff --git a/samples/server/petstore/flaskConnexion-python2/controllers/__init__.py b/samples/server/petstore/flaskConnexion-python2/controllers/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/flaskConnexion-python2/controllers/pet_controller.py b/samples/server/petstore/flaskConnexion-python2/controllers/pet_controller.py new file mode 100644 index 00000000000..d58d3973ca2 --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/controllers/pet_controller.py @@ -0,0 +1,24 @@ + +def add_pet(body): + return 'do some magic!' + +def delete_pet(petId, apiKey = None): + return 'do some magic!' + +def find_pets_by_status(status): + return 'do some magic!' + +def find_pets_by_tags(tags): + return 'do some magic!' + +def get_pet_by_id(petId): + return 'do some magic!' + +def update_pet(body): + return 'do some magic!' + +def update_pet_with_form(petId, name = None, status = None): + return 'do some magic!' + +def upload_file(petId, additionalMetadata = None, file = None): + return 'do some magic!' diff --git a/samples/server/petstore/flaskConnexion-python2/controllers/store_controller.py b/samples/server/petstore/flaskConnexion-python2/controllers/store_controller.py new file mode 100644 index 00000000000..a25eb40febb --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/controllers/store_controller.py @@ -0,0 +1,12 @@ + +def delete_order(orderId): + return 'do some magic!' + +def get_inventory(): + return 'do some magic!' + +def get_order_by_id(orderId): + return 'do some magic!' + +def place_order(body): + return 'do some magic!' diff --git a/samples/server/petstore/flaskConnexion-python2/controllers/user_controller.py b/samples/server/petstore/flaskConnexion-python2/controllers/user_controller.py new file mode 100644 index 00000000000..ec4efef29eb --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/controllers/user_controller.py @@ -0,0 +1,24 @@ + +def create_user(body): + return 'do some magic!' + +def create_users_with_array_input(body): + return 'do some magic!' + +def create_users_with_list_input(body): + return 'do some magic!' + +def delete_user(username): + return 'do some magic!' + +def get_user_by_name(username): + return 'do some magic!' + +def login_user(username, password): + return 'do some magic!' + +def logout_user(): + return 'do some magic!' + +def update_user(username, body): + return 'do some magic!' diff --git a/samples/server/petstore/flaskConnexion-python2/swagger/swagger.yaml b/samples/server/petstore/flaskConnexion-python2/swagger/swagger.yaml new file mode 100644 index 00000000000..7b412611171 --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/swagger/swagger.yaml @@ -0,0 +1,754 @@ +--- +swagger: "2.0" +info: + description: "This is a sample server Petstore server. You can find out more about\ + \ Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).\ + \ For this sample, you can use the api key `special-key` to test the authorization\ + \ filters." + 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" +tags: +- name: "pet" + description: "Everything about your Pets" + externalDocs: + description: "Find out more" + url: "http://swagger.io" +- name: "store" + description: "Access to Petstore orders" +- name: "user" + description: "Operations about user" + externalDocs: + description: "Find out more about our store" + url: "http://swagger.io" +schemes: +- "http" +paths: + /pet: + post: + tags: + - "pet" + summary: "Add a new pet to the store" + description: "" + operationId: "controllers.pet_controller.add_pet" + consumes: + - "application/json" + - "application/xml" + produces: + - "application/xml" + - "application/json" + parameters: + - in: "body" + name: "body" + description: "Pet object that needs to be added to the store" + required: true + schema: + $ref: "#/definitions/Pet" + responses: + 405: + description: "Invalid input" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + x-tags: + - tag: "pet" + put: + tags: + - "pet" + summary: "Update an existing pet" + description: "" + operationId: "controllers.pet_controller.update_pet" + consumes: + - "application/json" + - "application/xml" + produces: + - "application/xml" + - "application/json" + parameters: + - in: "body" + name: "body" + description: "Pet object that needs to be added to the store" + required: true + 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" + x-tags: + - tag: "pet" + /pet/findByStatus: + get: + tags: + - "pet" + summary: "Finds Pets by status" + description: "Multiple status values can be provided with comma separated strings" + operationId: "controllers.pet_controller.find_pets_by_status" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "status" + in: "query" + description: "Status values that need to be considered for filter" + required: true + type: "array" + items: + type: "string" + default: "available" + enum: + - "available" + - "pending" + - "sold" + collectionFormat: "csv" + responses: + 200: + description: "successful operation" + schema: + type: "array" + items: + $ref: "#/definitions/Pet" + 400: + description: "Invalid status value" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + x-tags: + - tag: "pet" + /pet/findByTags: + get: + tags: + - "pet" + summary: "Finds Pets by tags" + description: "Multiple tags can be provided with comma separated strings. Use\ + \ tag1, tag2, tag3 for testing." + operationId: "controllers.pet_controller.find_pets_by_tags" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "tags" + in: "query" + description: "Tags to filter by" + required: true + type: "array" + items: + type: "string" + collectionFormat: "csv" + responses: + 200: + description: "successful operation" + schema: + type: "array" + items: + $ref: "#/definitions/Pet" + 400: + description: "Invalid tag value" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + x-tags: + - tag: "pet" + /pet/{petId}: + get: + tags: + - "pet" + summary: "Find pet by ID" + description: "Returns a single pet" + operationId: "controllers.pet_controller.get_pet_by_id" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "petId" + in: "path" + description: "ID of pet to return" + 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: [] + x-tags: + - tag: "pet" + post: + tags: + - "pet" + summary: "Updates a pet in the store with form data" + description: "" + operationId: "controllers.pet_controller.update_pet_with_form" + consumes: + - "application/x-www-form-urlencoded" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "petId" + in: "path" + description: "ID of pet that needs to be updated" + required: true + type: "integer" + format: "int64" + - 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" + x-tags: + - tag: "pet" + delete: + tags: + - "pet" + summary: "Deletes a pet" + description: "" + operationId: "controllers.pet_controller.delete_pet" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "api_key" + in: "header" + 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" + x-tags: + - tag: "pet" + /pet/{petId}/uploadImage: + post: + tags: + - "pet" + summary: "uploads an image" + description: "" + operationId: "controllers.pet_controller.upload_file" + consumes: + - "multipart/form-data" + produces: + - "application/json" + 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: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/ApiResponse" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + x-tags: + - tag: "pet" + /store/inventory: + get: + tags: + - "store" + summary: "Returns pet inventories by status" + description: "Returns a map of status codes to quantities" + operationId: "controllers.store_controller.get_inventory" + produces: + - "application/json" + parameters: [] + responses: + 200: + description: "successful operation" + schema: + type: "object" + additionalProperties: + type: "integer" + format: "int32" + security: + - api_key: [] + x-tags: + - tag: "store" + /store/order: + post: + tags: + - "store" + summary: "Place an order for a pet" + description: "" + operationId: "controllers.store_controller.place_order" + produces: + - "application/xml" + - "application/json" + parameters: + - in: "body" + name: "body" + description: "order placed for purchasing the pet" + required: true + schema: + $ref: "#/definitions/Order" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Order" + 400: + description: "Invalid Order" + x-tags: + - tag: "store" + /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: "controllers.store_controller.get_order_by_id" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "orderId" + in: "path" + description: "ID of pet that needs to be fetched" + required: true + type: "integer" + maximum: 5.0 + minimum: 1.0 + format: "int64" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Order" + 400: + description: "Invalid ID supplied" + 404: + description: "Order not found" + x-tags: + - tag: "store" + 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: "controllers.store_controller.delete_order" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "orderId" + in: "path" + description: "ID of the order that needs to be deleted" + required: true + type: "string" + minimum: 1.0 + responses: + 400: + description: "Invalid ID supplied" + 404: + description: "Order not found" + x-tags: + - tag: "store" + /user: + post: + tags: + - "user" + summary: "Create user" + description: "This can only be done by the logged in user." + operationId: "controllers.user_controller.create_user" + produces: + - "application/xml" + - "application/json" + parameters: + - in: "body" + name: "body" + description: "Created user object" + required: true + schema: + $ref: "#/definitions/User" + responses: + default: + description: "successful operation" + x-tags: + - tag: "user" + /user/createWithArray: + post: + tags: + - "user" + summary: "Creates list of users with given input array" + description: "" + operationId: "controllers.user_controller.create_users_with_array_input" + produces: + - "application/xml" + - "application/json" + parameters: + - in: "body" + name: "body" + description: "List of user object" + required: true + schema: + type: "array" + items: + $ref: "#/definitions/User" + responses: + default: + description: "successful operation" + x-tags: + - tag: "user" + /user/createWithList: + post: + tags: + - "user" + summary: "Creates list of users with given input array" + description: "" + operationId: "controllers.user_controller.create_users_with_list_input" + produces: + - "application/xml" + - "application/json" + parameters: + - in: "body" + name: "body" + description: "List of user object" + required: true + schema: + type: "array" + items: + $ref: "#/definitions/User" + responses: + default: + description: "successful operation" + x-tags: + - tag: "user" + /user/login: + get: + tags: + - "user" + summary: "Logs user into the system" + description: "" + operationId: "controllers.user_controller.login_user" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "username" + in: "query" + description: "The user name for login" + required: true + type: "string" + - name: "password" + in: "query" + description: "The password for login in clear text" + required: true + type: "string" + responses: + 200: + description: "successful operation" + schema: + type: "string" + headers: + X-Rate-Limit: + type: "integer" + format: "int32" + description: "calls per hour allowed by the user" + X-Expires-After: + type: "string" + format: "date-time" + description: "date in UTC when toekn expires" + 400: + description: "Invalid username/password supplied" + x-tags: + - tag: "user" + /user/logout: + get: + tags: + - "user" + summary: "Logs out current logged in user session" + description: "" + operationId: "controllers.user_controller.logout_user" + produces: + - "application/xml" + - "application/json" + parameters: [] + responses: + default: + description: "successful operation" + x-tags: + - tag: "user" + /user/{username}: + get: + tags: + - "user" + summary: "Get user by user name" + description: "" + operationId: "controllers.user_controller.get_user_by_name" + produces: + - "application/xml" + - "application/json" + 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" + 400: + description: "Invalid username supplied" + 404: + description: "User not found" + x-tags: + - tag: "user" + put: + tags: + - "user" + summary: "Updated user" + description: "This can only be done by the logged in user." + operationId: "controllers.user_controller.update_user" + produces: + - "application/xml" + - "application/json" + 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: true + schema: + $ref: "#/definitions/User" + responses: + 400: + description: "Invalid user supplied" + 404: + description: "User not found" + x-tags: + - tag: "user" + delete: + tags: + - "user" + summary: "Delete user" + description: "This can only be done by the logged in user." + operationId: "controllers.user_controller.delete_user" + produces: + - "application/xml" + - "application/json" + 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" + x-tags: + - tag: "user" +securityDefinitions: + api_key: + type: "apiKey" + name: "api_key" + in: "header" + petstore_auth: + type: "oauth2" + authorizationUrl: "http://petstore.swagger.io/api/oauth/dialog" + flow: "implicit" + scopes: + write:pets: "modify pets in your account" + read:pets: "read your pets" +definitions: + Order: + type: "object" + 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" + default: false + title: "Pet Order" + description: "An order for a pets from the pet store" + xml: + name: "Order" + Category: + type: "object" + properties: + id: + type: "integer" + format: "int64" + name: + type: "string" + title: "Pet catehgry" + description: "A category for a pet" + xml: + name: "Category" + User: + type: "object" + 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" + title: "a User" + description: "A User who is purchasing from the pet store" + xml: + name: "User" + Tag: + type: "object" + properties: + id: + type: "integer" + format: "int64" + name: + type: "string" + title: "Pet Tag" + description: "A tag for a pet" + xml: + name: "Tag" + Pet: + type: "object" + 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" + title: "a Pet" + description: "A pet for sale in the pet store" + xml: + name: "Pet" + ApiResponse: + type: "object" + properties: + code: + type: "integer" + format: "int32" + type: + type: "string" + message: + type: "string" + title: "An uploaded response" + description: "Describes the result of uploading an image resource" +externalDocs: + description: "Find out more about Swagger" + url: "http://swagger.io" From a94a27307d9a1f5abbebb8c0fb8dbdd7e228b3d6 Mon Sep 17 00:00:00 2001 From: Jim Schubert Date: Sun, 9 Oct 2016 08:31:35 -0400 Subject: [PATCH 426/470] [aspnet] Fix .sln/.xproj guids The AspNet5 generator was originally written to support project.json. The Project.xproj was implemented without a valid project guid or root namespace. During the transition period from project.json to Project.xproj, VS2015 would fallback to project.json. Newer versions of VS2015 don't seem to do this any longer. This commit defines the project's guid correctly, and sets the project's root namespace. See: #3680 --- .gitignore | 3 +++ .../languages/AspNet5ServerCodegen.java | 6 +++++ .../resources/aspnet5/Project.xproj.mustache | 6 ++--- .../main/resources/aspnet5/Solution.mustache | 16 ++++-------- .../server/petstore/aspnet5/IO.Swagger.sln | 18 +++++-------- samples/server/petstore/aspnet5/README.md | 26 ++++++++++++++++--- .../aspnet5/src/IO.Swagger/Dockerfile | 4 --- .../aspnet5/src/IO.Swagger/IO.Swagger.xproj | 6 ++--- 8 files changed, 48 insertions(+), 37 deletions(-) diff --git a/.gitignore b/.gitignore index adea0e97125..ad9f114fe29 100644 --- a/.gitignore +++ b/.gitignore @@ -140,3 +140,6 @@ samples/client/petstore/typescript-angular/**/typings samples/client/petstore/typescript-fetch/**/dist/ samples/client/petstore/typescript-fetch/**/typings +# aspnet5 +samples/server/petstore/aspnet5/.vs/ + diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AspNet5ServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AspNet5ServerCodegen.java index 8b73275984a..e98c1441254 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AspNet5ServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AspNet5ServerCodegen.java @@ -9,10 +9,14 @@ import java.io.File; import java.util.*; +import static java.util.UUID.randomUUID; + public class AspNet5ServerCodegen extends AbstractCSharpCodegen { protected String sourceFolder = "src" + File.separator + packageName; + private final String packageGuid = "{" + randomUUID().toString().toUpperCase() + "}"; + @SuppressWarnings("hiding") protected Logger LOGGER = LoggerFactory.getLogger(AspNet5ServerCodegen.class); @@ -81,6 +85,8 @@ public String getHelp() { public void processOpts() { super.processOpts(); + additionalProperties.put("packageGuid", packageGuid); + apiPackage = packageName + ".Controllers"; modelPackage = packageName + ".Models"; diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/Project.xproj.mustache b/modules/swagger-codegen/src/main/resources/aspnet5/Project.xproj.mustache index 22123b97009..16f3716730d 100644 --- a/modules/swagger-codegen/src/main/resources/aspnet5/Project.xproj.mustache +++ b/modules/swagger-codegen/src/main/resources/aspnet5/Project.xproj.mustache @@ -1,4 +1,4 @@ - + 14.0 @@ -6,8 +6,8 @@ - {{projectGuid}} - Sample + {{packageGuid}} + {{packageName}} .\obj .\bin\ v4.6 diff --git a/modules/swagger-codegen/src/main/resources/aspnet5/Solution.mustache b/modules/swagger-codegen/src/main/resources/aspnet5/Solution.mustache index 4ea98f8e492..c86909a4c8b 100644 --- a/modules/swagger-codegen/src/main/resources/aspnet5/Solution.mustache +++ b/modules/swagger-codegen/src/main/resources/aspnet5/Solution.mustache @@ -1,10 +1,7 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 +Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 14 VisualStudioVersion = 14.0.25420.1 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{815BE834-0656-4C12-84A4-43F2BA4B8BDE}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{AFF6BF88-8A7D-4736-AF81-31BCE86B19BD}" ProjectSection(SolutionItems) = preProject global.json = global.json @@ -18,15 +15,12 @@ Global Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {3B5990B3-40F1-4148-89B5-84AC71432557}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {3B5990B3-40F1-4148-89B5-84AC71432557}.Debug|Any CPU.Build.0 = Debug|Any CPU - {3B5990B3-40F1-4148-89B5-84AC71432557}.Release|Any CPU.ActiveCfg = Release|Any CPU - {3B5990B3-40F1-4148-89B5-84AC71432557}.Release|Any CPU.Build.0 = Release|Any CPU + {{packageGuid}}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {{packageGuid}}.Debug|Any CPU.Build.0 = Debug|Any CPU + {{packageGuid}}.Release|Any CPU.ActiveCfg = Release|Any CPU + {{packageGuid}}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {{packageGuid}} = {815BE834-0656-4C12-84A4-43F2BA4B8BDE} - EndGlobalSection EndGlobal \ No newline at end of file diff --git a/samples/server/petstore/aspnet5/IO.Swagger.sln b/samples/server/petstore/aspnet5/IO.Swagger.sln index 5337cb4c2cb..f376ce4f0f4 100644 --- a/samples/server/petstore/aspnet5/IO.Swagger.sln +++ b/samples/server/petstore/aspnet5/IO.Swagger.sln @@ -1,16 +1,13 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 +Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 14 VisualStudioVersion = 14.0.25420.1 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{815BE834-0656-4C12-84A4-43F2BA4B8BDE}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{AFF6BF88-8A7D-4736-AF81-31BCE86B19BD}" ProjectSection(SolutionItems) = preProject global.json = global.json EndProjectSection EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.xproj", "" +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.xproj", "{CF700387-34B9-4172-B648-7535827D5EEB}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -18,15 +15,12 @@ Global Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {3B5990B3-40F1-4148-89B5-84AC71432557}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {3B5990B3-40F1-4148-89B5-84AC71432557}.Debug|Any CPU.Build.0 = Debug|Any CPU - {3B5990B3-40F1-4148-89B5-84AC71432557}.Release|Any CPU.ActiveCfg = Release|Any CPU - {3B5990B3-40F1-4148-89B5-84AC71432557}.Release|Any CPU.Build.0 = Release|Any CPU + {CF700387-34B9-4172-B648-7535827D5EEB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CF700387-34B9-4172-B648-7535827D5EEB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CF700387-34B9-4172-B648-7535827D5EEB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CF700387-34B9-4172-B648-7535827D5EEB}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection - GlobalSection(NestedProjects) = preSolution - = {815BE834-0656-4C12-84A4-43F2BA4B8BDE} - EndGlobalSection EndGlobal \ No newline at end of file diff --git a/samples/server/petstore/aspnet5/README.md b/samples/server/petstore/aspnet5/README.md index 2bdca9e4d48..3ed276e77b1 100644 --- a/samples/server/petstore/aspnet5/README.md +++ b/samples/server/petstore/aspnet5/README.md @@ -1,7 +1,25 @@ -# {{packageName}} - ASP.NET Core 1.0 Server +# IO.Swagger - ASP.NET Core 1.0 Server -{{#appDescription}} -{{{appDescription}}} -{{/appDescription}} +This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. +## Run +Linux/OS X: + +``` +sh build.sh +``` + +Windows: + +``` +build.bat +``` + +## Run in Docker + +``` +cd src/IO.Swagger +docker build -t IO.Swagger . +docker run -p 5000:5000 IO.Swagger +``` diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/Dockerfile b/samples/server/petstore/aspnet5/src/IO.Swagger/Dockerfile index 5a44639a7b0..f4abe48a5cb 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/Dockerfile +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/Dockerfile @@ -1,7 +1,5 @@ FROM microsoft/dotnet:latest -RUN groupadd -r app && useradd -r -g app app - ENV DOTNET_CLI_TELEMETRY_OPTOUT 1 RUN mkdir -p /app/IO.Swagger @@ -10,7 +8,5 @@ WORKDIR /app/IO.Swagger EXPOSE 5000/tcp -USER app - RUN ["dotnet", "restore"] ENTRYPOINT ["dotnet", "run", "-p", "project.json", "web"] diff --git a/samples/server/petstore/aspnet5/src/IO.Swagger/IO.Swagger.xproj b/samples/server/petstore/aspnet5/src/IO.Swagger/IO.Swagger.xproj index 4002eaeb995..d8c2ce2535b 100644 --- a/samples/server/petstore/aspnet5/src/IO.Swagger/IO.Swagger.xproj +++ b/samples/server/petstore/aspnet5/src/IO.Swagger/IO.Swagger.xproj @@ -1,4 +1,4 @@ - + 14.0 @@ -6,8 +6,8 @@ - - Sample + {CF700387-34B9-4172-B648-7535827D5EEB} + IO.Swagger .\obj .\bin\ v4.6 From 1006b0ca0af69f59d1b79162b38644986e7a7f8a Mon Sep 17 00:00:00 2001 From: Stas Shakirov Date: Mon, 10 Oct 2016 09:57:28 +0300 Subject: [PATCH 427/470] added package paths for retrofit class names --- .../src/main/resources/Java/libraries/retrofit/api.mustache | 4 ++-- .../resources/Java/libraries/retrofit/bodyParams.mustache | 2 +- .../resources/Java/libraries/retrofit/formParams.mustache | 2 +- .../resources/Java/libraries/retrofit/headerParams.mustache | 2 +- .../resources/Java/libraries/retrofit/pathParams.mustache | 2 +- .../resources/Java/libraries/retrofit/queryParams.mustache | 2 +- .../src/main/resources/Java/libraries/retrofit2/api.mustache | 2 +- .../resources/Java/libraries/retrofit2/bodyParams.mustache | 2 +- .../resources/Java/libraries/retrofit2/formParams.mustache | 2 +- .../resources/Java/libraries/retrofit2/headerParams.mustache | 2 +- .../resources/Java/libraries/retrofit2/pathParams.mustache | 2 +- .../resources/Java/libraries/retrofit2/queryParams.mustache | 2 +- 12 files changed, 13 insertions(+), 13 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache index aa84768b47a..e03801db6c2 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache @@ -27,7 +27,7 @@ public interface {{classname}} { {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} */ {{#formParams}}{{#-first}} - {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} + {{#isMultipart}}@retrofit.http.Multipart{{/isMultipart}}{{^isMultipart}}@retrofit.http.FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} @{{httpMethod}}("{{path}}") {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}} {{operationId}}({{^allParams}});{{/allParams}} {{#allParams}}{{>libraries/retrofit/queryParams}}{{>libraries/retrofit/pathParams}}{{>libraries/retrofit/headerParams}}{{>libraries/retrofit/bodyParams}}{{>libraries/retrofit/formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}} @@ -41,7 +41,7 @@ public interface {{classname}} { * @return void */ {{#formParams}}{{#-first}} - {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} + {{#isMultipart}}@retrofit.http.Multipart{{/isMultipart}}{{^isMultipart}}@retrofit.http.FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} @{{httpMethod}}("{{path}}") void {{operationId}}( {{#allParams}}{{>libraries/retrofit/queryParams}}{{>libraries/retrofit/pathParams}}{{>libraries/retrofit/headerParams}}{{>libraries/retrofit/bodyParams}}{{>libraries/retrofit/formParams}}, {{/allParams}}Callback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> cb diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/bodyParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/bodyParams.mustache index f8788583db5..ed55732b053 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/bodyParams.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/bodyParams.mustache @@ -1 +1 @@ -{{#isBodyParam}}@Body {{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file +{{#isBodyParam}}@retrofit.http.Body {{{dataType}}} {{paramName}}{{/isBodyParam}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/formParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/formParams.mustache index be9a3ca9b26..aa92e88e720 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/formParams.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/formParams.mustache @@ -1 +1 @@ -{{#isFormParam}}{{#notFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{baseName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{baseName}}") TypedFile {{paramName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{#notFile}}{{#isMultipart}}@retrofit.http.Part{{/isMultipart}}{{^isMultipart}}@retrofit.http.Field{{/isMultipart}}("{{baseName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}{{#isMultipart}}@retrofit.http.Part{{/isMultipart}}{{^isMultipart}}@retrofit.http.Field{{/isMultipart}}("{{baseName}}") TypedFile {{paramName}}{{/isFile}}{{/isFormParam}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/headerParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/headerParams.mustache index 29206e1546b..336841150bb 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/headerParams.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/headerParams.mustache @@ -1 +1 @@ -{{#isHeaderParam}}@Header("{{baseName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file +{{#isHeaderParam}}@retrofit.http.Header("{{baseName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pathParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pathParams.mustache index 8a8bdc74c88..f779cf2fba5 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pathParams.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pathParams.mustache @@ -1 +1 @@ -{{#isPathParam}}@Path("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file +{{#isPathParam}}@retrofit.http.Path("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/queryParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/queryParams.mustache index 3c5b1bb7e69..913efbd82b8 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/queryParams.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/queryParams.mustache @@ -1 +1 @@ -{{#isQueryParam}}@Query("{{baseName}}") {{#collectionFormat}}{{#isCollectionFormatMulti}}{{{dataType}}}{{/isCollectionFormatMulti}}{{^isCollectionFormatMulti}}{{{collectionFormat.toUpperCase}}}Params{{/isCollectionFormatMulti}}{{/collectionFormat}}{{^collectionFormat}}{{{dataType}}}{{/collectionFormat}} {{paramName}}{{/isQueryParam}} \ No newline at end of file +{{#isQueryParam}}@retrofit.http.Query("{{baseName}}") {{#collectionFormat}}{{#isCollectionFormatMulti}}{{{dataType}}}{{/isCollectionFormatMulti}}{{^isCollectionFormatMulti}}{{{collectionFormat.toUpperCase}}}Params{{/isCollectionFormatMulti}}{{/collectionFormat}}{{^collectionFormat}}{{{dataType}}}{{/collectionFormat}} {{paramName}}{{/isQueryParam}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache index 7fa42fe732c..7682d27c9c8 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache @@ -28,7 +28,7 @@ public interface {{classname}} { {{/allParams}} * @return Call<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> */ {{#formParams}}{{#-first}} - {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} + {{#isMultipart}}@retrofit2.http.Multipart{{/isMultipart}}{{^isMultipart}}@retrofit2.http.FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} @{{httpMethod}}("{{path}}") {{#useRxJava}}Observable{{/useRxJava}}{{^useRxJava}}Call{{/useRxJava}}<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}({{^allParams}});{{/allParams}} {{#allParams}}{{>libraries/retrofit2/queryParams}}{{>libraries/retrofit2/pathParams}}{{>libraries/retrofit2/headerParams}}{{>libraries/retrofit2/bodyParams}}{{>libraries/retrofit2/formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/bodyParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/bodyParams.mustache index f8788583db5..7a0471dfbd2 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/bodyParams.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/bodyParams.mustache @@ -1 +1 @@ -{{#isBodyParam}}@Body {{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file +{{#isBodyParam}}@retrofit2.http.Body {{{dataType}}} {{paramName}}{{/isBodyParam}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/formParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/formParams.mustache index 0620c3a21ba..b29d30d6152 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/formParams.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/formParams.mustache @@ -1 +1 @@ -{{#isFormParam}}{{#notFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{baseName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{baseName}}\"; filename=\"{{baseName}}") RequestBody {{paramName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{#notFile}}{{#isMultipart}}@retrofit2.http.Part{{/isMultipart}}{{^isMultipart}}@retrofit2.http.Field{{/isMultipart}}("{{baseName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}{{#isMultipart}}@retrofit2.http.Part{{/isMultipart}}{{^isMultipart}}@retrofit2.http.Field{{/isMultipart}}("{{baseName}}\"; filename=\"{{baseName}}") RequestBody {{paramName}}{{/isFile}}{{/isFormParam}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/headerParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/headerParams.mustache index 29206e1546b..9d1ac8e0631 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/headerParams.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/headerParams.mustache @@ -1 +1 @@ -{{#isHeaderParam}}@Header("{{baseName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file +{{#isHeaderParam}}@retrofit2.http.Header("{{baseName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pathParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pathParams.mustache index 8a8bdc74c88..ea0e85de5d8 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pathParams.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pathParams.mustache @@ -1 +1 @@ -{{#isPathParam}}@Path("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file +{{#isPathParam}}@retrofit2.http.Path("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/queryParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/queryParams.mustache index 3c5b1bb7e69..f8d3d48ebd9 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/queryParams.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/queryParams.mustache @@ -1 +1 @@ -{{#isQueryParam}}@Query("{{baseName}}") {{#collectionFormat}}{{#isCollectionFormatMulti}}{{{dataType}}}{{/isCollectionFormatMulti}}{{^isCollectionFormatMulti}}{{{collectionFormat.toUpperCase}}}Params{{/isCollectionFormatMulti}}{{/collectionFormat}}{{^collectionFormat}}{{{dataType}}}{{/collectionFormat}} {{paramName}}{{/isQueryParam}} \ No newline at end of file +{{#isQueryParam}}@retrofit2.http.Query("{{baseName}}") {{#collectionFormat}}{{#isCollectionFormatMulti}}{{{dataType}}}{{/isCollectionFormatMulti}}{{^isCollectionFormatMulti}}{{{collectionFormat.toUpperCase}}}Params{{/isCollectionFormatMulti}}{{/collectionFormat}}{{^collectionFormat}}{{{dataType}}}{{/collectionFormat}} {{paramName}}{{/isQueryParam}} From dc2b8c29e258d4f09d8645189da977dffc034ed3 Mon Sep 17 00:00:00 2001 From: Nick Maynard Date: Mon, 10 Oct 2016 10:18:27 +0100 Subject: [PATCH 428/470] Add a new JAX-RS server generator - jaxrs-cxf-cdi (#3940) * Generate a JAX-RS server that assumes an Apache CXF framework on a Java EE server supporting CDI * Samples for jaxrs-cxf-cdi * Don't refer to missing class NotFoundException * Update samples without missing NotFoundException reference --- bin/jaxrs-cxf-cdi-petstore-server.sh | 31 + .../JavaJAXRSCXFCDIServerCodegen.java | 53 ++ .../cxf-cdi/allowableValues.mustache | 1 + .../resources/JavaJaxRS/cxf-cdi/api.mustache | 55 ++ .../JavaJaxRS/cxf-cdi/apiService.mustache | 25 + .../JavaJaxRS/cxf-cdi/apiServiceImpl.mustache | 31 + .../JavaJaxRS/cxf-cdi/bodyParams.mustache | 1 + .../JavaJaxRS/cxf-cdi/enumClass.mustache | 16 + .../JavaJaxRS/cxf-cdi/formParams.mustache | 1 + .../cxf-cdi/generatedAnnotation.mustache | 1 + .../JavaJaxRS/cxf-cdi/headerParams.mustache | 1 + .../JavaJaxRS/cxf-cdi/model.mustache | 14 + .../JavaJaxRS/cxf-cdi/pathParams.mustache | 1 + .../resources/JavaJaxRS/cxf-cdi/pojo.mustache | 75 ++ .../JavaJaxRS/cxf-cdi/queryParams.mustache | 1 + .../cxf-cdi/serviceBodyParams.mustache | 1 + .../cxf-cdi/serviceFormParams.mustache | 1 + .../cxf-cdi/serviceHeaderParams.mustache | 1 + .../cxf-cdi/servicePathParams.mustache | 1 + .../cxf-cdi/serviceQueryParams.mustache | 1 + .../services/io.swagger.codegen.CodegenConfig | 2 +- .../jaxrs-cxf-cdi/.swagger-codegen-ignore | 23 + samples/server/petstore/jaxrs-cxf-cdi/LICENSE | 201 +++++ .../src/gen/java/io/swagger/api/PetApi.java | 60 ++ .../java/io/swagger/api/PetApiService.java | 29 + .../src/gen/java/io/swagger/api/StoreApi.java | 38 + .../java/io/swagger/api/StoreApiService.java | 24 + .../src/gen/java/io/swagger/api/UserApi.java | 58 ++ .../java/io/swagger/api/UserApiService.java | 28 + .../gen/java/io/swagger/model/Category.java | 70 ++ .../io/swagger/model/ModelApiResponse.java | 83 ++ .../src/gen/java/io/swagger/model/Order.java | 146 +++ .../src/gen/java/io/swagger/model/Pet.java | 150 ++++ .../src/gen/java/io/swagger/model/Tag.java | 70 ++ .../src/gen/java/io/swagger/model/User.java | 149 ++++ .../swagger/api/impl/PetApiServiceImpl.java | 64 ++ .../swagger/api/impl/StoreApiServiceImpl.java | 43 + .../swagger/api/impl/UserApiServiceImpl.java | 63 ++ .../petstore/jaxrs-cxf-cdi/swagger.json | 831 ++++++++++++++++++ 39 files changed, 2443 insertions(+), 1 deletion(-) create mode 100755 bin/jaxrs-cxf-cdi-petstore-server.sh create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSCXFCDIServerCodegen.java create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/allowableValues.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/api.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/apiService.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/apiServiceImpl.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/bodyParams.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/enumClass.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/formParams.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/generatedAnnotation.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/headerParams.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/model.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pathParams.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pojo.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/queryParams.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/serviceBodyParams.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/serviceFormParams.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/serviceHeaderParams.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/servicePathParams.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/serviceQueryParams.mustache create mode 100644 samples/server/petstore/jaxrs-cxf-cdi/.swagger-codegen-ignore create mode 100644 samples/server/petstore/jaxrs-cxf-cdi/LICENSE create mode 100644 samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApi.java create mode 100644 samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApiService.java create mode 100644 samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApi.java create mode 100644 samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApiService.java create mode 100644 samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApi.java create mode 100644 samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApiService.java create mode 100644 samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Category.java create mode 100644 samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/ModelApiResponse.java create mode 100644 samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Order.java create mode 100644 samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Pet.java create mode 100644 samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Tag.java create mode 100644 samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/User.java create mode 100644 samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java create mode 100644 samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java create mode 100644 samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java create mode 100644 samples/server/petstore/jaxrs-cxf-cdi/swagger.json diff --git a/bin/jaxrs-cxf-cdi-petstore-server.sh b/bin/jaxrs-cxf-cdi-petstore-server.sh new file mode 100755 index 00000000000..ca9874a3d3f --- /dev/null +++ b/bin/jaxrs-cxf-cdi-petstore-server.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l jaxrs-cxf-cdi -o samples/server/petstore/jaxrs-cxf-cdi -DhideGenerationTimestamp=true" + +java $JAVA_OPTS -jar $executable $ags diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSCXFCDIServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSCXFCDIServerCodegen.java new file mode 100644 index 00000000000..ba6737388dc --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSCXFCDIServerCodegen.java @@ -0,0 +1,53 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.CodegenProperty; + +import java.io.File; + +public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen +{ + public JavaJAXRSCXFCDIServerCodegen() + { + sourceFolder = "src" + File.separator + "gen" + File.separator + "java"; + + // Three API templates to support CDI injection + apiTemplateFiles.put("apiService.mustache", ".java"); + apiTemplateFiles.put("apiServiceImpl.mustache", ".java"); + + // Use standard types + typeMapping.put("DateTime", "java.util.Date"); + + // Updated template directory + embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "cxf-cdi"; + } + + @Override + public String getName() + { + return "jaxrs-cxf-cdi"; + } + + @Override + public void processOpts() + { + super.processOpts(); + + supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen + } + + @Override + public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { + super.postProcessModelProperty(model, property); + + // Reinstate JsonProperty + model.imports.add("JsonProperty"); + } + + @Override + public String getHelp() + { + return "Generates a Java JAXRS Server according to JAXRS 2.0 specification, assuming an Apache CXF runtime and a Java EE runtime with CDI enabled."; + } + +} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/allowableValues.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/allowableValues.mustache new file mode 100644 index 00000000000..a48256d027a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/allowableValues.mustache @@ -0,0 +1 @@ +{{#allowableValues}}allowableValues="{{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}{{^values}}range=[{{#min}}{{.}}{{/min}}{{^min}}-infinity{{/min}}, {{#max}}{{.}}{{/max}}{{^max}}infinity{{/max}}]{{/values}}"{{/allowableValues}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/api.mustache new file mode 100644 index 00000000000..5fabe593164 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/api.mustache @@ -0,0 +1,55 @@ +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} +import {{package}}.{{classname}}Service; + +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.enterprise.context.RequestScoped; +import javax.inject.Inject; + +import io.swagger.annotations.*; + +import org.apache.cxf.jaxrs.ext.multipart.Attachment; + +import java.util.List; + +@Path("/{{baseName}}") +@RequestScoped + +@Api(description = "the {{baseName}} API") +{{#hasConsumes}}@Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} +{{#hasProduces}}@Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} +{{>generatedAnnotation}} + +public class {{classname}} { + + @Context SecurityContext securityContext; + + @Inject {{classname}}Service delegate; + +{{#operations}} +{{#operation}} + + @{{httpMethod}} + {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} + {{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} + {{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} + @ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}{{#hasAuthMethods}}, authorizations = { + {{#authMethods}}@Authorization(value = "{{name}}"{{#isOAuth}}, scopes = { + {{#scopes}}@AuthorizationScope(scope = "{{scope}}", description = "{{description}}"){{#hasMore}}, + {{/hasMore}}{{/scopes}} + }{{/isOAuth}}){{#hasMore}}, + {{/hasMore}}{{/authMethods}} + }{{/hasAuthMethods}}, tags={ {{#vendorExtensions.x-tags}}"{{tag}}"{{#hasMore}}, {{/hasMore}}{{/vendorExtensions.x-tags}} }) + @ApiResponses(value = { {{#responses}} + @ApiResponse(code = {{{code}}}, message = "{{{message}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}){{#hasMore}},{{/hasMore}}{{/responses}} }) + public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { + return delegate.{{nickname}}({{#allParams}}{{#isFile}}inputStream, fileDetail{{/isFile}}{{^isFile}}{{paramName}}{{/isFile}}, {{/allParams}}securityContext); + } +{{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/apiService.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/apiService.mustache new file mode 100644 index 00000000000..64eb6e38adb --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/apiService.mustache @@ -0,0 +1,25 @@ +package {{package}}; + +import {{package}}.*; +import {{modelPackage}}.*; + +import org.apache.cxf.jaxrs.ext.multipart.Attachment; + +{{#imports}}import {{import}}; +{{/imports}} + +import java.util.List; + +import java.io.InputStream; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + +{{>generatedAnnotation}} +{{#operations}} +public interface {{classname}}Service { + {{#operation}} + public Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}, {{/allParams}}SecurityContext securityContext); + {{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/apiServiceImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/apiServiceImpl.mustache new file mode 100644 index 00000000000..86c0d872291 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/apiServiceImpl.mustache @@ -0,0 +1,31 @@ +package {{package}}.impl; + +import {{package}}.*; +import {{modelPackage}}.*; + +import org.apache.cxf.jaxrs.ext.multipart.Attachment; + +{{#imports}}import {{import}}; +{{/imports}} + +import java.util.List; + +import java.io.InputStream; + +import javax.enterprise.context.RequestScoped; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + +@RequestScoped +{{>generatedAnnotation}} +{{#operations}} +public class {{classname}}ServiceImpl implements {{classname}}Service { + {{#operation}} + @Override + public Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}, {{/allParams}}SecurityContext securityContext) { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + {{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/bodyParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/bodyParams.mustache new file mode 100644 index 00000000000..2b28441d3d0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/bodyParams.mustache @@ -0,0 +1 @@ +{{#isBodyParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/enumClass.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/enumClass.mustache new file mode 100644 index 00000000000..1ef4a61efbe --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/enumClass.mustache @@ -0,0 +1,16 @@ +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlType; + +@XmlType(name="{{classname}}") +@XmlEnum +public enum {{classname}} { + {{#allowableValues}}{{.}}{{^-last}}, {{/-last}}{{#-last}};{{/-last}}{{/allowableValues}} + + public String value() { + return name(); + } + + public static {{classname}} fromValue(String v) { + return valueOf(v); + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/formParams.mustache new file mode 100644 index 00000000000..3bc0dfe132b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/formParams.mustache @@ -0,0 +1 @@ +{{#isFormParam}}{{#notFile}}@Multipart(value = "{{paramName}}"{{^required}}, required = false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}} @Multipart(value = "{{paramName}}"{{^required}}, required = false{{/required}}) InputStream {{paramName}}InputStream, @Multipart(value = "{{paramName}}" {{^required}}, required = false{{/required}}) Attachment {{paramName}}Detail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/generatedAnnotation.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/generatedAnnotation.mustache new file mode 100644 index 00000000000..49110fc1ad9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/generatedAnnotation.mustache @@ -0,0 +1 @@ +@javax.annotation.Generated(value = "{{generatorClass}}", date = "{{generatedDate}}") \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/headerParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/headerParams.mustache new file mode 100644 index 00000000000..1360d796826 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/headerParams.mustache @@ -0,0 +1 @@ +{{#isHeaderParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@HeaderParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/model.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/model.mustache new file mode 100644 index 00000000000..2c383a41a28 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/model.mustache @@ -0,0 +1,14 @@ +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} + +{{#models}} +{{#model}}{{#description}} +/** + * {{description}} + **/{{/description}} +{{#isEnum}}{{>enumClass}}{{/isEnum}} +{{^isEnum}}{{>pojo}}{{/isEnum}} +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pathParams.mustache new file mode 100644 index 00000000000..8d80210b4b4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pathParams.mustache @@ -0,0 +1 @@ +{{#isPathParam}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @PathParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pojo.mustache new file mode 100644 index 00000000000..f1d68d014e7 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pojo.mustache @@ -0,0 +1,75 @@ +import io.swagger.annotations.*; +import java.util.Objects; +{{#description}}@ApiModel(description = "{{{description}}}"){{/description}} + +public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { + {{#vars}}{{#isEnum}} + +{{>enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}} + +{{>enumClass}}{{/items}}{{/items.isEnum}} + private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}} + + {{#vars}} + /**{{#description}} + * {{{description}}}{{/description}}{{#minimum}} + * minimum: {{minimum}}{{/minimum}}{{#maximum}} + * maximum: {{maximum}}{{/maximum}} + **/ + public {{classname}} {{name}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + return this; + } + + {{#vendorExtensions.extraAnnotation}}{{vendorExtensions.extraAnnotation}}{{/vendorExtensions.extraAnnotation}} + @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") + @JsonProperty("{{baseName}}") + public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + } + public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + } + + {{/vars}} + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + {{classname}} {{classVarName}} = ({{classname}}) o;{{#hasVars}} + return {{#vars}}Objects.equals({{name}}, {{classVarName}}.{{name}}){{#hasMore}} && + {{/hasMore}}{{^hasMore}};{{/hasMore}}{{/vars}}{{/hasVars}}{{^hasVars}} + return true;{{/hasVars}} + } + + @Override + public int hashCode() { + return Objects.hash({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class {{classname}} {\n"); + {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} + {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{/vars}}sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/queryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/queryParams.mustache new file mode 100644 index 00000000000..6bff4a4b82d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/queryParams.mustache @@ -0,0 +1 @@ +{{#isQueryParam}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{#defaultValue}}@DefaultValue("{{{defaultValue}}}"){{/defaultValue}} @QueryParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/serviceBodyParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/serviceBodyParams.mustache new file mode 100644 index 00000000000..c7d1abfe527 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/serviceBodyParams.mustache @@ -0,0 +1 @@ +{{#isBodyParam}}{{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/serviceFormParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/serviceFormParams.mustache new file mode 100644 index 00000000000..a7a154a9822 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/serviceFormParams.mustache @@ -0,0 +1 @@ +{{#isFormParam}}{{#notFile}}{{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}InputStream {{paramName}}InputStream, Attachment {{paramName}}Detail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/serviceHeaderParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/serviceHeaderParams.mustache new file mode 100644 index 00000000000..bd03573d196 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/serviceHeaderParams.mustache @@ -0,0 +1 @@ +{{#isHeaderParam}}{{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/servicePathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/servicePathParams.mustache new file mode 100644 index 00000000000..6829cf8c7a6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/servicePathParams.mustache @@ -0,0 +1 @@ +{{#isPathParam}}{{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/serviceQueryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/serviceQueryParams.mustache new file mode 100644 index 00000000000..ff79730471d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/serviceQueryParams.mustache @@ -0,0 +1 @@ +{{#isQueryParam}}{{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file 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 3c3a092efe0..3c40b1d84e9 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 @@ -14,6 +14,7 @@ io.swagger.codegen.languages.JavaJerseyServerCodegen io.swagger.codegen.languages.JavaCXFServerCodegen io.swagger.codegen.languages.JavaResteasyServerCodegen io.swagger.codegen.languages.JavaJAXRSSpecServerCodegen +io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen io.swagger.codegen.languages.JavaInflectorServerCodegen io.swagger.codegen.languages.JavascriptClientCodegen io.swagger.codegen.languages.JavascriptClosureAngularClientCodegen @@ -53,4 +54,3 @@ io.swagger.codegen.languages.LumenServerCodegen io.swagger.codegen.languages.GoServerCodegen io.swagger.codegen.languages.ErlangServerCodegen io.swagger.codegen.languages.UndertowCodegen - diff --git a/samples/server/petstore/jaxrs-cxf-cdi/.swagger-codegen-ignore b/samples/server/petstore/jaxrs-cxf-cdi/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/jaxrs-cxf-cdi/LICENSE b/samples/server/petstore/jaxrs-cxf-cdi/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApi.java new file mode 100644 index 00000000000..5ef9496d397 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApi.java @@ -0,0 +1,60 @@ +package io.swagger.api; + +import io.swagger.model.Pet; +import io.swagger.model.ModelApiResponse; +import java.io.File; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; + +import org.apache.cxf.jaxrs.ext.multipart.*; + +@Path("/v2") +public interface PetApi { + @POST + + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) + Response addPet(Pet body); + @DELETE + @Path("/{petId}") + + @Produces({ "application/xml", "application/json" }) + Response deletePet(@PathParam("petId") Long petId,@HeaderParam("api_key") String apiKey); + @GET + @Path("/findByStatus") + + @Produces({ "application/xml", "application/json" }) + Response findPetsByStatus(@QueryParam("status") List status); + @GET + @Path("/findByTags") + + @Produces({ "application/xml", "application/json" }) + Response findPetsByTags(@QueryParam("tags") List tags); + @GET + @Path("/{petId}") + + @Produces({ "application/xml", "application/json" }) + Response getPetById(@PathParam("petId") Long petId); + @PUT + + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) + Response updatePet(Pet body); + @POST + @Path("/{petId}") + @Consumes({ "application/x-www-form-urlencoded" }) + @Produces({ "application/xml", "application/json" }) + Response updatePetWithForm(@PathParam("petId") Long petId,@Multipart(value = "name", required = false) String name,@Multipart(value = "status", required = false) String status); + @POST + @Path("/{petId}/uploadImage") + @Consumes({ "multipart/form-data" }) + @Produces({ "application/json" }) + Response uploadFile(@PathParam("petId") Long petId,@Multipart(value = "additionalMetadata", required = false) String additionalMetadata, @Multipart(value = "file", required = false) InputStream fileInputStream, + @Multipart(value = "file" , required = false) Attachment fileDetail); +} + diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApiService.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApiService.java new file mode 100644 index 00000000000..b982f07c1e0 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApiService.java @@ -0,0 +1,29 @@ +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import org.apache.cxf.jaxrs.ext.multipart.Attachment; + +import io.swagger.model.Pet; +import io.swagger.model.ModelApiResponse; +import java.io.File; + +import java.util.List; + +import java.io.InputStream; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-10-07T11:14:51.064+01:00") +public interface PetApiService { + public Response addPet(Pet body, SecurityContext securityContext); + public Response deletePet(Long petId, String apiKey, SecurityContext securityContext); + public Response findPetsByStatus(List status, SecurityContext securityContext); + public Response findPetsByTags(List tags, SecurityContext securityContext); + public Response getPetById(Long petId, SecurityContext securityContext); + public Response updatePet(Pet body, SecurityContext securityContext); + public Response updatePetWithForm(Long petId, String name, String status, SecurityContext securityContext); + public Response uploadFile(Long petId, String additionalMetadata, InputStream fileInputStream, Attachment fileDetail, SecurityContext securityContext); +} diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApi.java new file mode 100644 index 00000000000..0280c8b5d9f --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApi.java @@ -0,0 +1,38 @@ +package io.swagger.api; + +import java.util.Map; +import io.swagger.model.Order; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; + +import org.apache.cxf.jaxrs.ext.multipart.*; + +@Path("/v2") +public interface StoreApi { + @DELETE + @Path("/order/{orderId}") + + @Produces({ "application/xml", "application/json" }) + Response deleteOrder(@PathParam("orderId") String orderId); + @GET + @Path("/inventory") + + @Produces({ "application/json" }) + Response getInventory(); + @GET + @Path("/order/{orderId}") + + @Produces({ "application/xml", "application/json" }) + Response getOrderById(@PathParam("orderId") Long orderId); + @POST + @Path("/order") + + @Produces({ "application/xml", "application/json" }) + Response placeOrder(Order body); +} + diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApiService.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApiService.java new file mode 100644 index 00000000000..5f3c38f2fbc --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApiService.java @@ -0,0 +1,24 @@ +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import org.apache.cxf.jaxrs.ext.multipart.Attachment; + +import java.util.Map; +import io.swagger.model.Order; + +import java.util.List; + +import java.io.InputStream; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-10-07T11:14:51.064+01:00") +public interface StoreApiService { + public Response deleteOrder(String orderId, SecurityContext securityContext); + public Response getInventory(SecurityContext securityContext); + public Response getOrderById(Long orderId, SecurityContext securityContext); + public Response placeOrder(Order body, SecurityContext securityContext); +} diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApi.java new file mode 100644 index 00000000000..03112276e5c --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApi.java @@ -0,0 +1,58 @@ +package io.swagger.api; + +import io.swagger.model.User; +import java.util.List; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; + +import org.apache.cxf.jaxrs.ext.multipart.*; + +@Path("/v2") +public interface UserApi { + @POST + + + @Produces({ "application/xml", "application/json" }) + Response createUser(User body); + @POST + @Path("/createWithArray") + + @Produces({ "application/xml", "application/json" }) + Response createUsersWithArrayInput(List body); + @POST + @Path("/createWithList") + + @Produces({ "application/xml", "application/json" }) + Response createUsersWithListInput(List body); + @DELETE + @Path("/{username}") + + @Produces({ "application/xml", "application/json" }) + Response deleteUser(@PathParam("username") String username); + @GET + @Path("/{username}") + + @Produces({ "application/xml", "application/json" }) + Response getUserByName(@PathParam("username") String username); + @GET + @Path("/login") + + @Produces({ "application/xml", "application/json" }) + Response loginUser(@QueryParam("username") String username,@QueryParam("password") String password); + @GET + @Path("/logout") + + @Produces({ "application/xml", "application/json" }) + Response logoutUser(); + @PUT + @Path("/{username}") + + @Produces({ "application/xml", "application/json" }) + Response updateUser(@PathParam("username") String username,User body); +} + diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApiService.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApiService.java new file mode 100644 index 00000000000..5a8b782cd6b --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApiService.java @@ -0,0 +1,28 @@ +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import org.apache.cxf.jaxrs.ext.multipart.Attachment; + +import io.swagger.model.User; +import java.util.List; + +import java.util.List; + +import java.io.InputStream; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-10-07T11:14:51.064+01:00") +public interface UserApiService { + public Response createUser(User body, SecurityContext securityContext); + public Response createUsersWithArrayInput(List body, SecurityContext securityContext); + public Response createUsersWithListInput(List body, SecurityContext securityContext); + public Response deleteUser(String username, SecurityContext securityContext); + public Response getUserByName(String username, SecurityContext securityContext); + public Response loginUser(String username, String password, SecurityContext securityContext); + public Response logoutUser(SecurityContext securityContext); + public Response updateUser(String username, User body, SecurityContext securityContext); +} diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Category.java new file mode 100644 index 00000000000..0ab2fc43537 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Category.java @@ -0,0 +1,70 @@ +package io.swagger.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; + +@XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "Category", propOrder = + { "id", "name" +}) + +@XmlRootElement(name="Category") +public class Category { + + + @XmlElement(name="id") + private Long id = null; + + @XmlElement(name="name") + private String name = null; + + /** + **/ + + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + /** + **/ + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/ModelApiResponse.java new file mode 100644 index 00000000000..741d70648f1 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -0,0 +1,83 @@ +package io.swagger.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; + +@XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "ModelApiResponse", propOrder = + { "code", "type", "message" +}) + +@XmlRootElement(name="ModelApiResponse") +public class ModelApiResponse { + + + @XmlElement(name="code") + private Integer code = null; + + @XmlElement(name="type") + private String type = null; + + @XmlElement(name="message") + private String message = null; + + /** + **/ + + public Integer getCode() { + return code; + } + public void setCode(Integer code) { + this.code = code; + } + /** + **/ + + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + /** + **/ + + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Order.java new file mode 100644 index 00000000000..31f84c907f8 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Order.java @@ -0,0 +1,146 @@ +package io.swagger.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; + +@XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "Order", propOrder = + { "id", "petId", "quantity", "shipDate", "status", "complete" +}) + +@XmlRootElement(name="Order") +public class Order { + + + @XmlElement(name="id") + private Long id = null; + + @XmlElement(name="petId") + private Long petId = null; + + @XmlElement(name="quantity") + private Integer quantity = null; + + @XmlElement(name="shipDate") + private java.util.Date shipDate = null; + +@XmlType(name="StatusEnum") +@XmlEnum +public enum StatusEnum { + + PLACED(String.valueOf("placed")), APPROVED(String.valueOf("approved")), DELIVERED(String.valueOf("delivered")); + + + private String value; + + StatusEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + public static StatusEnum fromValue(String v) { + return valueOf(v); + } +} + + + @XmlElement(name="status") + private StatusEnum status = null; + + @XmlElement(name="complete") + private Boolean complete = false; + + /** + **/ + + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + /** + **/ + + public Long getPetId() { + return petId; + } + public void setPetId(Long petId) { + this.petId = petId; + } + /** + **/ + + public Integer getQuantity() { + return quantity; + } + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + /** + **/ + + public java.util.Date getShipDate() { + return shipDate; + } + public void setShipDate(java.util.Date shipDate) { + this.shipDate = shipDate; + } + /** + * Order Status + **/ + + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + /** + **/ + + public Boolean getComplete() { + return complete; + } + public void setComplete(Boolean complete) { + this.complete = complete; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Pet.java new file mode 100644 index 00000000000..d889d2a19cc --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Pet.java @@ -0,0 +1,150 @@ +package io.swagger.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.model.Category; +import io.swagger.model.Tag; +import java.util.ArrayList; +import java.util.List; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; + +@XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "Pet", propOrder = + { "id", "category", "name", "photoUrls", "tags", "status" +}) + +@XmlRootElement(name="Pet") +public class Pet { + + + @XmlElement(name="id") + private Long id = null; + + @XmlElement(name="category") + private Category category = null; + + @XmlElement(name="name") + private String name = null; + + @XmlElement(name="photoUrls") + private List photoUrls = new ArrayList(); + + @XmlElement(name="tags") + private List tags = new ArrayList(); + +@XmlType(name="StatusEnum") +@XmlEnum +public enum StatusEnum { + + AVAILABLE(String.valueOf("available")), PENDING(String.valueOf("pending")), SOLD(String.valueOf("sold")); + + + private String value; + + StatusEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + public static StatusEnum fromValue(String v) { + return valueOf(v); + } +} + + + @XmlElement(name="status") + private StatusEnum status = null; + + /** + **/ + + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + /** + **/ + + public Category getCategory() { + return category; + } + public void setCategory(Category category) { + this.category = category; + } + /** + **/ + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + /** + **/ + + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + /** + **/ + + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + /** + * pet status in the store + **/ + + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Tag.java new file mode 100644 index 00000000000..d2cdaf602af --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Tag.java @@ -0,0 +1,70 @@ +package io.swagger.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; + +@XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "Tag", propOrder = + { "id", "name" +}) + +@XmlRootElement(name="Tag") +public class Tag { + + + @XmlElement(name="id") + private Long id = null; + + @XmlElement(name="name") + private String name = null; + + /** + **/ + + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + /** + **/ + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/User.java new file mode 100644 index 00000000000..803cf2b73eb --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/User.java @@ -0,0 +1,149 @@ +package io.swagger.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; + +@XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "User", propOrder = + { "id", "username", "firstName", "lastName", "email", "password", "phone", "userStatus" +}) + +@XmlRootElement(name="User") +public class User { + + + @XmlElement(name="id") + private Long id = null; + + @XmlElement(name="username") + private String username = null; + + @XmlElement(name="firstName") + private String firstName = null; + + @XmlElement(name="lastName") + private String lastName = null; + + @XmlElement(name="email") + private String email = null; + + @XmlElement(name="password") + private String password = null; + + @XmlElement(name="phone") + private String phone = null; + + @XmlElement(name="userStatus") + private Integer userStatus = null; + + /** + **/ + + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + /** + **/ + + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + /** + **/ + + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + /** + **/ + + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } + /** + **/ + + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + /** + **/ + + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + /** + **/ + + public String getPhone() { + return phone; + } + public void setPhone(String phone) { + this.phone = phone; + } + /** + * User Status + **/ + + public Integer getUserStatus() { + return userStatus; + } + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java new file mode 100644 index 00000000000..cac1469aca1 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -0,0 +1,64 @@ +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import org.apache.cxf.jaxrs.ext.multipart.Attachment; + +import io.swagger.model.Pet; +import io.swagger.model.ModelApiResponse; +import java.io.File; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import javax.enterprise.context.RequestScoped; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + +@RequestScoped +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-10-06T16:59:45.939+01:00") +public class PetApiServiceImpl implements PetApiService { + @Override + public Response addPet(Pet body, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response deletePet(Long petId, String apiKey, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response findPetsByStatus(List status, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response findPetsByTags(List tags, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response getPetById(Long petId, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response updatePet(Pet body, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response updatePetWithForm(Long petId, String name, String status, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response uploadFile(Long petId, String additionalMetadata, InputStream fileInputStream, Attachment fileDetail, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } +} diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java new file mode 100644 index 00000000000..75ac7c475df --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java @@ -0,0 +1,43 @@ +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import org.apache.cxf.jaxrs.ext.multipart.Attachment; + +import java.util.Map; +import io.swagger.model.Order; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import javax.enterprise.context.RequestScoped; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + +@RequestScoped +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-10-06T16:59:45.939+01:00") +public class StoreApiServiceImpl implements StoreApiService { + @Override + public Response deleteOrder(String orderId, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response getInventory(SecurityContext securityContext) { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response getOrderById(Long orderId, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response placeOrder(Order body, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } +} diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java new file mode 100644 index 00000000000..c05deea0ad2 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java @@ -0,0 +1,63 @@ +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import org.apache.cxf.jaxrs.ext.multipart.Attachment; + +import io.swagger.model.User; +import java.util.List; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import javax.enterprise.context.RequestScoped; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + +@RequestScoped +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-10-06T16:59:45.939+01:00") +public class UserApiServiceImpl implements UserApiService { + @Override + public Response createUser(User body, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response createUsersWithArrayInput(List body, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response createUsersWithListInput(List body, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response deleteUser(String username, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response getUserByName(String username, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response loginUser(String username, String password, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response logoutUser(SecurityContext securityContext) { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response updateUser(String username, User body, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } +} diff --git a/samples/server/petstore/jaxrs-cxf-cdi/swagger.json b/samples/server/petstore/jaxrs-cxf-cdi/swagger.json new file mode 100644 index 00000000000..f48e38d5cb2 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/swagger.json @@ -0,0 +1,831 @@ +{ + "swagger" : "2.0", + "info" : { + "description" : "This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.", + "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", + "tags" : [ { + "name" : "pet", + "description" : "Everything about your Pets", + "externalDocs" : { + "description" : "Find out more", + "url" : "http://swagger.io" + } + }, { + "name" : "store", + "description" : "Access to Petstore orders" + }, { + "name" : "user", + "description" : "Operations about user", + "externalDocs" : { + "description" : "Find out more about our store", + "url" : "http://swagger.io" + } + } ], + "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/xml", "application/json" ], + "parameters" : [ { + "in" : "body", + "name" : "body", + "description" : "Pet object that needs to be added to the store", + "required" : true, + "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/xml", "application/json" ], + "parameters" : [ { + "in" : "body", + "name" : "body", + "description" : "Pet object that needs to be added to the store", + "required" : true, + "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 separated strings", + "operationId" : "findPetsByStatus", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "status", + "in" : "query", + "description" : "Status values that need to be considered for filter", + "required" : true, + "type" : "array", + "items" : { + "type" : "string", + "default" : "available", + "enum" : [ "available", "pending", "sold" ] + }, + "collectionFormat" : "csv" + } ], + "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" : "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", + "operationId" : "findPetsByTags", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "tags", + "in" : "query", + "description" : "Tags to filter by", + "required" : true, + "type" : "array", + "items" : { + "type" : "string" + }, + "collectionFormat" : "csv" + } ], + "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 single pet", + "operationId" : "getPetById", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "petId", + "in" : "path", + "description" : "ID of pet to return", + "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" : [ ] + } ] + }, + "post" : { + "tags" : [ "pet" ], + "summary" : "Updates a pet in the store with form data", + "description" : "", + "operationId" : "updatePetWithForm", + "consumes" : [ "application/x-www-form-urlencoded" ], + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "petId", + "in" : "path", + "description" : "ID of pet that needs to be updated", + "required" : true, + "type" : "integer", + "format" : "int64" + }, { + "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/xml", "application/json" ], + "parameters" : [ { + "name" : "api_key", + "in" : "header", + "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" ], + "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" : { + "200" : { + "description" : "successful operation", + "schema" : { + "$ref" : "#/definitions/ApiResponse" + } + } + }, + "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" ], + "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/xml", "application/json" ], + "parameters" : [ { + "in" : "body", + "name" : "body", + "description" : "order placed for purchasing the pet", + "required" : true, + "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/xml", "application/json" ], + "parameters" : [ { + "name" : "orderId", + "in" : "path", + "description" : "ID of pet that needs to be fetched", + "required" : true, + "type" : "integer", + "maximum" : 5.0, + "minimum" : 1.0, + "format" : "int64" + } ], + "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/xml", "application/json" ], + "parameters" : [ { + "name" : "orderId", + "in" : "path", + "description" : "ID of the order that needs to be deleted", + "required" : true, + "type" : "string", + "minimum" : 1.0 + } ], + "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/xml", "application/json" ], + "parameters" : [ { + "in" : "body", + "name" : "body", + "description" : "Created user object", + "required" : true, + "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/xml", "application/json" ], + "parameters" : [ { + "in" : "body", + "name" : "body", + "description" : "List of user object", + "required" : true, + "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/xml", "application/json" ], + "parameters" : [ { + "in" : "body", + "name" : "body", + "description" : "List of user object", + "required" : true, + "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/xml", "application/json" ], + "parameters" : [ { + "name" : "username", + "in" : "query", + "description" : "The user name for login", + "required" : true, + "type" : "string" + }, { + "name" : "password", + "in" : "query", + "description" : "The password for login in clear text", + "required" : true, + "type" : "string" + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "schema" : { + "type" : "string" + }, + "headers" : { + "X-Rate-Limit" : { + "type" : "integer", + "format" : "int32", + "description" : "calls per hour allowed by the user" + }, + "X-Expires-After" : { + "type" : "string", + "format" : "date-time", + "description" : "date in UTC when toekn expires" + } + } + }, + "400" : { + "description" : "Invalid username/password supplied" + } + } + } + }, + "/user/logout" : { + "get" : { + "tags" : [ "user" ], + "summary" : "Logs out current logged in user session", + "description" : "", + "operationId" : "logoutUser", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ ], + "responses" : { + "default" : { + "description" : "successful operation" + } + } + } + }, + "/user/{username}" : { + "get" : { + "tags" : [ "user" ], + "summary" : "Get user by user name", + "description" : "", + "operationId" : "getUserByName", + "produces" : [ "application/xml", "application/json" ], + "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" + } + }, + "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/xml", "application/json" ], + "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" : true, + "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/xml", "application/json" ], + "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" : { + "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" + } + }, + "api_key" : { + "type" : "apiKey", + "name" : "api_key", + "in" : "header" + } + }, + "definitions" : { + "Order" : { + "type" : "object", + "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", + "default" : false + } + }, + "title" : "Pet Order", + "description" : "An order for a pets from the pet store", + "xml" : { + "name" : "Order" + } + }, + "Category" : { + "type" : "object", + "properties" : { + "id" : { + "type" : "integer", + "format" : "int64" + }, + "name" : { + "type" : "string" + } + }, + "title" : "Pet catehgry", + "description" : "A category for a pet", + "xml" : { + "name" : "Category" + } + }, + "User" : { + "type" : "object", + "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" + } + }, + "title" : "a User", + "description" : "A User who is purchasing from the pet store", + "xml" : { + "name" : "User" + } + }, + "Tag" : { + "type" : "object", + "properties" : { + "id" : { + "type" : "integer", + "format" : "int64" + }, + "name" : { + "type" : "string" + } + }, + "title" : "Pet Tag", + "description" : "A tag for a pet", + "xml" : { + "name" : "Tag" + } + }, + "Pet" : { + "type" : "object", + "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" ] + } + }, + "title" : "a Pet", + "description" : "A pet for sale in the pet store", + "xml" : { + "name" : "Pet" + } + }, + "ApiResponse" : { + "type" : "object", + "properties" : { + "code" : { + "type" : "integer", + "format" : "int32" + }, + "type" : { + "type" : "string" + }, + "message" : { + "type" : "string" + } + }, + "title" : "An uploaded response", + "description" : "Describes the result of uploading an image resource" + } + }, + "externalDocs" : { + "description" : "Find out more about Swagger", + "url" : "http://swagger.io" + } +} \ No newline at end of file From 26faf6cf4e336aabe917e1ed336155ce8f6da60d Mon Sep 17 00:00:00 2001 From: Stas Shakirov Date: Mon, 10 Oct 2016 14:42:08 +0300 Subject: [PATCH 429/470] remove newline char in *.mustache; added generated code --- .../libraries/retrofit/bodyParams.mustache | 2 +- .../libraries/retrofit/formParams.mustache | 2 +- .../libraries/retrofit/headerParams.mustache | 2 +- .../libraries/retrofit/pathParams.mustache | 2 +- .../libraries/retrofit/queryParams.mustache | 2 +- .../libraries/retrofit2/bodyParams.mustache | 2 +- .../libraries/retrofit2/formParams.mustache | 2 +- .../retrofit2/formParams.mustache.save | 1 + .../libraries/retrofit2/headerParams.mustache | 2 +- .../libraries/retrofit2/pathParams.mustache | 2 +- .../libraries/retrofit2/queryParams.mustache | 2 +- .../java/io/swagger/client/api/FakeApi.java | 252 +++++++++++++++++- .../java/io/swagger/client/api/PetApi.java | 170 ++++++++++-- .../java/io/swagger/client/api/StoreApi.java | 42 ++- .../java/io/swagger/client/api/UserApi.java | 118 +++++++- .../model/AdditionalPropertiesClass.java | 4 +- .../java/io/swagger/client/model/Animal.java | 4 +- .../io/swagger/client/model/AnimalFarm.java | 4 +- .../model/ArrayOfArrayOfNumberOnly.java | 4 +- .../client/model/ArrayOfNumberOnly.java | 4 +- .../io/swagger/client/model/ArrayTest.java | 4 +- .../java/io/swagger/client/model/Cat.java | 4 +- .../io/swagger/client/model/Category.java | 4 +- .../java/io/swagger/client/model/Client.java | 4 +- .../java/io/swagger/client/model/Dog.java | 4 +- .../io/swagger/client/model/EnumArrays.java | 4 +- .../io/swagger/client/model/EnumClass.java | 1 - .../io/swagger/client/model/EnumTest.java | 4 +- .../io/swagger/client/model/FormatTest.java | 4 +- .../swagger/client/model/HasOnlyReadOnly.java | 4 +- .../java/io/swagger/client/model/MapTest.java | 4 +- ...ropertiesAndAdditionalPropertiesClass.java | 4 +- .../client/model/Model200Response.java | 4 +- .../client/model/ModelApiResponse.java | 4 +- .../io/swagger/client/model/ModelReturn.java | 4 +- .../java/io/swagger/client/model/Name.java | 4 +- .../io/swagger/client/model/NumberOnly.java | 4 +- .../java/io/swagger/client/model/Order.java | 4 +- .../java/io/swagger/client/model/Pet.java | 4 +- .../swagger/client/model/ReadOnlyFirst.java | 4 +- .../client/model/SpecialModelName.java | 4 +- .../java/io/swagger/client/model/Tag.java | 4 +- .../java/io/swagger/client/model/User.java | 4 +- .../petstore/java/retrofit2/docs/FakeApi.md | 6 +- .../java/io/swagger/client/api/FakeApi.java | 126 ++++++++- .../java/io/swagger/client/api/PetApi.java | 85 +++++- .../java/io/swagger/client/api/StoreApi.java | 21 +- .../java/io/swagger/client/api/UserApi.java | 59 +++- .../model/AdditionalPropertiesClass.java | 4 +- .../java/io/swagger/client/model/Animal.java | 4 +- .../io/swagger/client/model/AnimalFarm.java | 4 +- .../model/ArrayOfArrayOfNumberOnly.java | 4 +- .../client/model/ArrayOfNumberOnly.java | 4 +- .../io/swagger/client/model/ArrayTest.java | 4 +- .../java/io/swagger/client/model/Cat.java | 4 +- .../io/swagger/client/model/Category.java | 4 +- .../java/io/swagger/client/model/Client.java | 4 +- .../java/io/swagger/client/model/Dog.java | 4 +- .../io/swagger/client/model/EnumArrays.java | 4 +- .../io/swagger/client/model/EnumClass.java | 1 - .../io/swagger/client/model/EnumTest.java | 4 +- .../io/swagger/client/model/FormatTest.java | 4 +- .../swagger/client/model/HasOnlyReadOnly.java | 4 +- .../java/io/swagger/client/model/MapTest.java | 4 +- ...ropertiesAndAdditionalPropertiesClass.java | 4 +- .../client/model/Model200Response.java | 4 +- .../client/model/ModelApiResponse.java | 4 +- .../io/swagger/client/model/ModelReturn.java | 4 +- .../java/io/swagger/client/model/Name.java | 4 +- .../io/swagger/client/model/NumberOnly.java | 4 +- .../java/io/swagger/client/model/Order.java | 4 +- .../java/io/swagger/client/model/Pet.java | 4 +- .../swagger/client/model/ReadOnlyFirst.java | 4 +- .../client/model/SpecialModelName.java | 4 +- .../java/io/swagger/client/model/Tag.java | 4 +- .../java/io/swagger/client/model/User.java | 4 +- .../java/io/swagger/client/api/FakeApi.java | 126 ++++++++- .../java/io/swagger/client/api/PetApi.java | 85 +++++- .../java/io/swagger/client/api/StoreApi.java | 21 +- .../java/io/swagger/client/api/UserApi.java | 59 +++- .../model/AdditionalPropertiesClass.java | 4 +- .../java/io/swagger/client/model/Animal.java | 4 +- .../io/swagger/client/model/AnimalFarm.java | 4 +- .../model/ArrayOfArrayOfNumberOnly.java | 4 +- .../client/model/ArrayOfNumberOnly.java | 4 +- .../io/swagger/client/model/ArrayTest.java | 4 +- .../java/io/swagger/client/model/Cat.java | 4 +- .../io/swagger/client/model/Category.java | 4 +- .../java/io/swagger/client/model/Client.java | 4 +- .../java/io/swagger/client/model/Dog.java | 4 +- .../io/swagger/client/model/EnumArrays.java | 4 +- .../io/swagger/client/model/EnumClass.java | 1 - .../io/swagger/client/model/EnumTest.java | 4 +- .../io/swagger/client/model/FormatTest.java | 4 +- .../swagger/client/model/HasOnlyReadOnly.java | 4 +- .../java/io/swagger/client/model/MapTest.java | 4 +- ...ropertiesAndAdditionalPropertiesClass.java | 4 +- .../client/model/Model200Response.java | 4 +- .../client/model/ModelApiResponse.java | 4 +- .../io/swagger/client/model/ModelReturn.java | 4 +- .../java/io/swagger/client/model/Name.java | 4 +- .../io/swagger/client/model/NumberOnly.java | 4 +- .../java/io/swagger/client/model/Order.java | 4 +- .../java/io/swagger/client/model/Pet.java | 4 +- .../swagger/client/model/ReadOnlyFirst.java | 4 +- .../client/model/SpecialModelName.java | 4 +- .../java/io/swagger/client/model/Tag.java | 4 +- .../java/io/swagger/client/model/User.java | 4 +- 108 files changed, 1241 insertions(+), 277 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/formParams.mustache.save diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/bodyParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/bodyParams.mustache index ed55732b053..81de324b691 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/bodyParams.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/bodyParams.mustache @@ -1 +1 @@ -{{#isBodyParam}}@retrofit.http.Body {{{dataType}}} {{paramName}}{{/isBodyParam}} +{{#isBodyParam}}@retrofit.http.Body {{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/formParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/formParams.mustache index aa92e88e720..f1f9027ae51 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/formParams.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/formParams.mustache @@ -1 +1 @@ -{{#isFormParam}}{{#notFile}}{{#isMultipart}}@retrofit.http.Part{{/isMultipart}}{{^isMultipart}}@retrofit.http.Field{{/isMultipart}}("{{baseName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}{{#isMultipart}}@retrofit.http.Part{{/isMultipart}}{{^isMultipart}}@retrofit.http.Field{{/isMultipart}}("{{baseName}}") TypedFile {{paramName}}{{/isFile}}{{/isFormParam}} +{{#isFormParam}}{{#notFile}}{{#isMultipart}}@retrofit.http.Part{{/isMultipart}}{{^isMultipart}}@retrofit.http.Field{{/isMultipart}}("{{baseName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}{{#isMultipart}}@retrofit.http.Part{{/isMultipart}}{{^isMultipart}}@retrofit.http.Field{{/isMultipart}}("{{baseName}}") TypedFile {{paramName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/headerParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/headerParams.mustache index 336841150bb..5d6da4a9437 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/headerParams.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/headerParams.mustache @@ -1 +1 @@ -{{#isHeaderParam}}@retrofit.http.Header("{{baseName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}} +{{#isHeaderParam}}@retrofit.http.Header("{{baseName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pathParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pathParams.mustache index f779cf2fba5..7b8be8442e0 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pathParams.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pathParams.mustache @@ -1 +1 @@ -{{#isPathParam}}@retrofit.http.Path("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} +{{#isPathParam}}@retrofit.http.Path("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/queryParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/queryParams.mustache index 913efbd82b8..2a580ab34ec 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/queryParams.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/queryParams.mustache @@ -1 +1 @@ -{{#isQueryParam}}@retrofit.http.Query("{{baseName}}") {{#collectionFormat}}{{#isCollectionFormatMulti}}{{{dataType}}}{{/isCollectionFormatMulti}}{{^isCollectionFormatMulti}}{{{collectionFormat.toUpperCase}}}Params{{/isCollectionFormatMulti}}{{/collectionFormat}}{{^collectionFormat}}{{{dataType}}}{{/collectionFormat}} {{paramName}}{{/isQueryParam}} +{{#isQueryParam}}@retrofit.http.Query("{{baseName}}") {{#collectionFormat}}{{#isCollectionFormatMulti}}{{{dataType}}}{{/isCollectionFormatMulti}}{{^isCollectionFormatMulti}}{{{collectionFormat.toUpperCase}}}Params{{/isCollectionFormatMulti}}{{/collectionFormat}}{{^collectionFormat}}{{{dataType}}}{{/collectionFormat}} {{paramName}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/bodyParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/bodyParams.mustache index 7a0471dfbd2..97b03fcb717 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/bodyParams.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/bodyParams.mustache @@ -1 +1 @@ -{{#isBodyParam}}@retrofit2.http.Body {{{dataType}}} {{paramName}}{{/isBodyParam}} +{{#isBodyParam}}@retrofit2.http.Body {{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/formParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/formParams.mustache index b29d30d6152..2e237383ee3 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/formParams.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/formParams.mustache @@ -1 +1 @@ -{{#isFormParam}}{{#notFile}}{{#isMultipart}}@retrofit2.http.Part{{/isMultipart}}{{^isMultipart}}@retrofit2.http.Field{{/isMultipart}}("{{baseName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}{{#isMultipart}}@retrofit2.http.Part{{/isMultipart}}{{^isMultipart}}@retrofit2.http.Field{{/isMultipart}}("{{baseName}}\"; filename=\"{{baseName}}") RequestBody {{paramName}}{{/isFile}}{{/isFormParam}} +{{#isFormParam}}{{#notFile}}{{#isMultipart}}@retrofit2.http.Part{{/isMultipart}}{{^isMultipart}}@retrofit2.http.Field{{/isMultipart}}("{{baseName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}{{#isMultipart}}@retrofit2.http.Part{{/isMultipart}}{{^isMultipart}}@retrofit2.http.Field{{/isMultipart}}("{{baseName}}\"; filename=\"{{baseName}}") RequestBody {{paramName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/formParams.mustache.save b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/formParams.mustache.save new file mode 100644 index 00000000000..a203e99a223 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/formParams.mustache.save @@ -0,0 +1 @@ +{{#isFormParam}}{{#notFile}}{{#isMultipart}}retrofit.http@retrofit2.http.Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{baseName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{baseName}}\"; filename=\"{{baseName}}") RequestBody {{paramName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/headerParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/headerParams.mustache index 9d1ac8e0631..c7748f3bf27 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/headerParams.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/headerParams.mustache @@ -1 +1 @@ -{{#isHeaderParam}}@retrofit2.http.Header("{{baseName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}} +{{#isHeaderParam}}@retrofit2.http.Header("{{baseName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pathParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pathParams.mustache index ea0e85de5d8..8fe7c380c41 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pathParams.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pathParams.mustache @@ -1 +1 @@ -{{#isPathParam}}@retrofit2.http.Path("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} +{{#isPathParam}}@retrofit2.http.Path("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/queryParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/queryParams.mustache index f8d3d48ebd9..abb87510ecf 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/queryParams.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/queryParams.mustache @@ -1 +1 @@ -{{#isQueryParam}}@retrofit2.http.Query("{{baseName}}") {{#collectionFormat}}{{#isCollectionFormatMulti}}{{{dataType}}}{{/isCollectionFormatMulti}}{{^isCollectionFormatMulti}}{{{collectionFormat.toUpperCase}}}Params{{/isCollectionFormatMulti}}{{/collectionFormat}}{{^collectionFormat}}{{{dataType}}}{{/collectionFormat}} {{paramName}}{{/isQueryParam}} +{{#isQueryParam}}@retrofit2.http.Query("{{baseName}}") {{#collectionFormat}}{{#isCollectionFormatMulti}}{{{dataType}}}{{/isCollectionFormatMulti}}{{^isCollectionFormatMulti}}{{{collectionFormat.toUpperCase}}}Params{{/isCollectionFormatMulti}}{{/collectionFormat}}{{^collectionFormat}}{{{dataType}}}{{/collectionFormat}} {{paramName}}{{/isQueryParam}} \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java index fb02bbde690..e1c4644feea 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java @@ -27,7 +27,12 @@ public interface FakeApi { @PATCH("/fake") Client testClientModel( - @Body Client body + + + +@retrofit.http.Body Client body + + ); /** @@ -40,7 +45,12 @@ Client testClientModel( @PATCH("/fake") void testClientModel( - @Body Client body, Callback cb + + + +@retrofit.http.Body Client body + +, Callback cb ); /** * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -59,13 +69,84 @@ void testClientModel( * @param date None (optional) * @param dateTime None (optional) * @param password None (optional) + * @param paramCallback None (optional) * @return Void */ - @FormUrlEncoded + @retrofit.http.FormUrlEncoded @POST("/fake") Void testEndpointParameters( - @Field("number") BigDecimal number, @Field("double") Double _double, @Field("pattern_without_delimiter") String patternWithoutDelimiter, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("string") String string, @Field("binary") byte[] binary, @Field("date") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password + + + + +@retrofit.http.Field("number") BigDecimal number +, + + + +@retrofit.http.Field("double") Double _double +, + + + +@retrofit.http.Field("pattern_without_delimiter") String patternWithoutDelimiter +, + + + +@retrofit.http.Field("byte") byte[] _byte +, + + + +@retrofit.http.Field("integer") Integer integer +, + + + +@retrofit.http.Field("int32") Integer int32 +, + + + +@retrofit.http.Field("int64") Long int64 +, + + + +@retrofit.http.Field("float") Float _float +, + + + +@retrofit.http.Field("string") String string +, + + + +@retrofit.http.Field("binary") byte[] binary +, + + + +@retrofit.http.Field("date") LocalDate date +, + + + +@retrofit.http.Field("dateTime") DateTime dateTime +, + + + +@retrofit.http.Field("password") String password +, + + + +@retrofit.http.Field("callback") String paramCallback + ); /** @@ -84,14 +165,85 @@ Void testEndpointParameters( * @param date None (optional) * @param dateTime None (optional) * @param password None (optional) + * @param paramCallback None (optional) * @param cb callback method * @return void */ - @FormUrlEncoded + @retrofit.http.FormUrlEncoded @POST("/fake") void testEndpointParameters( - @Field("number") BigDecimal number, @Field("double") Double _double, @Field("pattern_without_delimiter") String patternWithoutDelimiter, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("string") String string, @Field("binary") byte[] binary, @Field("date") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password, Callback cb + + + + +@retrofit.http.Field("number") BigDecimal number +, + + + +@retrofit.http.Field("double") Double _double +, + + + +@retrofit.http.Field("pattern_without_delimiter") String patternWithoutDelimiter +, + + + +@retrofit.http.Field("byte") byte[] _byte +, + + + +@retrofit.http.Field("integer") Integer integer +, + + + +@retrofit.http.Field("int32") Integer int32 +, + + + +@retrofit.http.Field("int64") Long int64 +, + + + +@retrofit.http.Field("float") Float _float +, + + + +@retrofit.http.Field("string") String string +, + + + +@retrofit.http.Field("binary") byte[] binary +, + + + +@retrofit.http.Field("date") LocalDate date +, + + + +@retrofit.http.Field("dateTime") DateTime dateTime +, + + + +@retrofit.http.Field("password") String password +, + + + +@retrofit.http.Field("callback") String paramCallback +, Callback cb ); /** * To test enum parameters @@ -108,10 +260,50 @@ void testEndpointParameters( * @return Void */ - @FormUrlEncoded + @retrofit.http.FormUrlEncoded @GET("/fake") Void testEnumParameters( - @Field("enum_form_string_array") List enumFormStringArray, @Field("enum_form_string") String enumFormString, @Header("enum_header_string_array") List enumHeaderStringArray, @Header("enum_header_string") String enumHeaderString, @Query("enum_query_string_array") CSVParams enumQueryStringArray, @Query("enum_query_string") String enumQueryString, @Query("enum_query_integer") BigDecimal enumQueryInteger, @Field("enum_query_double") Double enumQueryDouble + + + + +@retrofit.http.Field("enum_form_string_array") List enumFormStringArray +, + + + +@retrofit.http.Field("enum_form_string") String enumFormString +, + +@retrofit.http.Header("enum_header_string_array") List enumHeaderStringArray + + +, + +@retrofit.http.Header("enum_header_string") String enumHeaderString + + +, @retrofit.http.Query("enum_query_string_array") CSVParams enumQueryStringArray + + + + +, @retrofit.http.Query("enum_query_string") String enumQueryString + + + + +, @retrofit.http.Query("enum_query_integer") BigDecimal enumQueryInteger + + + + +, + + + +@retrofit.http.Field("enum_query_double") Double enumQueryDouble + ); /** @@ -129,9 +321,49 @@ Void testEnumParameters( * @return void */ - @FormUrlEncoded + @retrofit.http.FormUrlEncoded @GET("/fake") void testEnumParameters( - @Field("enum_form_string_array") List enumFormStringArray, @Field("enum_form_string") String enumFormString, @Header("enum_header_string_array") List enumHeaderStringArray, @Header("enum_header_string") String enumHeaderString, @Query("enum_query_string_array") CSVParams enumQueryStringArray, @Query("enum_query_string") String enumQueryString, @Query("enum_query_integer") BigDecimal enumQueryInteger, @Field("enum_query_double") Double enumQueryDouble, Callback cb + + + + +@retrofit.http.Field("enum_form_string_array") List enumFormStringArray +, + + + +@retrofit.http.Field("enum_form_string") String enumFormString +, + +@retrofit.http.Header("enum_header_string_array") List enumHeaderStringArray + + +, + +@retrofit.http.Header("enum_header_string") String enumHeaderString + + +, @retrofit.http.Query("enum_query_string_array") CSVParams enumQueryStringArray + + + + +, @retrofit.http.Query("enum_query_string") String enumQueryString + + + + +, @retrofit.http.Query("enum_query_integer") BigDecimal enumQueryInteger + + + + +, + + + +@retrofit.http.Field("enum_query_double") Double enumQueryDouble +, Callback cb ); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java index a019a4bf886..eaeb49ffba4 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java @@ -26,7 +26,12 @@ public interface PetApi { @POST("/pet") Void addPet( - @Body Pet body + + + +@retrofit.http.Body Pet body + + ); /** @@ -39,7 +44,12 @@ Void addPet( @POST("/pet") void addPet( - @Body Pet body, Callback cb + + + +@retrofit.http.Body Pet body + +, Callback cb ); /** * Deletes a pet @@ -52,7 +62,17 @@ void addPet( @DELETE("/pet/{petId}") Void deletePet( - @Path("petId") Long petId, @Header("api_key") String apiKey + +@retrofit.http.Path("petId") Long petId + + + +, + +@retrofit.http.Header("api_key") String apiKey + + + ); /** @@ -66,7 +86,17 @@ Void deletePet( @DELETE("/pet/{petId}") void deletePet( - @Path("petId") Long petId, @Header("api_key") String apiKey, Callback cb + +@retrofit.http.Path("petId") Long petId + + + +, + +@retrofit.http.Header("api_key") String apiKey + + +, Callback cb ); /** * Finds Pets by status @@ -78,7 +108,12 @@ void deletePet( @GET("/pet/findByStatus") List findPetsByStatus( - @Query("status") CSVParams status + @retrofit.http.Query("status") CSVParams status + + + + + ); /** @@ -91,7 +126,12 @@ List findPetsByStatus( @GET("/pet/findByStatus") void findPetsByStatus( - @Query("status") CSVParams status, Callback> cb + @retrofit.http.Query("status") CSVParams status + + + + +, Callback> cb ); /** * Finds Pets by tags @@ -103,7 +143,12 @@ void findPetsByStatus( @GET("/pet/findByTags") List findPetsByTags( - @Query("tags") CSVParams tags + @retrofit.http.Query("tags") CSVParams tags + + + + + ); /** @@ -116,7 +161,12 @@ List findPetsByTags( @GET("/pet/findByTags") void findPetsByTags( - @Query("tags") CSVParams tags, Callback> cb + @retrofit.http.Query("tags") CSVParams tags + + + + +, Callback> cb ); /** * Find pet by ID @@ -128,7 +178,12 @@ void findPetsByTags( @GET("/pet/{petId}") Pet getPetById( - @Path("petId") Long petId + +@retrofit.http.Path("petId") Long petId + + + + ); /** @@ -141,7 +196,12 @@ Pet getPetById( @GET("/pet/{petId}") void getPetById( - @Path("petId") Long petId, Callback cb + +@retrofit.http.Path("petId") Long petId + + + +, Callback cb ); /** * Update an existing pet @@ -153,7 +213,12 @@ void getPetById( @PUT("/pet") Void updatePet( - @Body Pet body + + + +@retrofit.http.Body Pet body + + ); /** @@ -166,7 +231,12 @@ Void updatePet( @PUT("/pet") void updatePet( - @Body Pet body, Callback cb + + + +@retrofit.http.Body Pet body + +, Callback cb ); /** * Updates a pet in the store with form data @@ -178,10 +248,25 @@ void updatePet( * @return Void */ - @FormUrlEncoded + @retrofit.http.FormUrlEncoded @POST("/pet/{petId}") Void updatePetWithForm( - @Path("petId") Long petId, @Field("name") String name, @Field("status") String status + +@retrofit.http.Path("petId") Long petId + + + +, + + + +@retrofit.http.Field("name") String name +, + + + +@retrofit.http.Field("status") String status + ); /** @@ -194,10 +279,25 @@ Void updatePetWithForm( * @return void */ - @FormUrlEncoded + @retrofit.http.FormUrlEncoded @POST("/pet/{petId}") void updatePetWithForm( - @Path("petId") Long petId, @Field("name") String name, @Field("status") String status, Callback cb + +@retrofit.http.Path("petId") Long petId + + + +, + + + +@retrofit.http.Field("name") String name +, + + + +@retrofit.http.Field("status") String status +, Callback cb ); /** * uploads an image @@ -209,10 +309,25 @@ void updatePetWithForm( * @return ModelApiResponse */ - @Multipart + @retrofit.http.Multipart @POST("/pet/{petId}/uploadImage") ModelApiResponse uploadFile( - @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file") TypedFile file + +@retrofit.http.Path("petId") Long petId + + + +, + + + +@retrofit.http.Part("additionalMetadata") String additionalMetadata +, + + + +@retrofit.http.Part("file") TypedFile file + ); /** @@ -225,9 +340,24 @@ ModelApiResponse uploadFile( * @return void */ - @Multipart + @retrofit.http.Multipart @POST("/pet/{petId}/uploadImage") void uploadFile( - @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file") TypedFile file, Callback cb + +@retrofit.http.Path("petId") Long petId + + + +, + + + +@retrofit.http.Part("additionalMetadata") String additionalMetadata +, + + + +@retrofit.http.Part("file") TypedFile file +, Callback cb ); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java index def4aa2efc7..f9fed4bd1ce 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java @@ -24,7 +24,12 @@ public interface StoreApi { @DELETE("/store/order/{orderId}") Void deleteOrder( - @Path("orderId") String orderId + +@retrofit.http.Path("orderId") String orderId + + + + ); /** @@ -37,7 +42,12 @@ Void deleteOrder( @DELETE("/store/order/{orderId}") void deleteOrder( - @Path("orderId") String orderId, Callback cb + +@retrofit.http.Path("orderId") String orderId + + + +, Callback cb ); /** * Returns pet inventories by status @@ -71,7 +81,12 @@ void getInventory( @GET("/store/order/{orderId}") Order getOrderById( - @Path("orderId") Long orderId + +@retrofit.http.Path("orderId") Long orderId + + + + ); /** @@ -84,7 +99,12 @@ Order getOrderById( @GET("/store/order/{orderId}") void getOrderById( - @Path("orderId") Long orderId, Callback cb + +@retrofit.http.Path("orderId") Long orderId + + + +, Callback cb ); /** * Place an order for a pet @@ -96,7 +116,12 @@ void getOrderById( @POST("/store/order") Order placeOrder( - @Body Order body + + + +@retrofit.http.Body Order body + + ); /** @@ -109,6 +134,11 @@ Order placeOrder( @POST("/store/order") void placeOrder( - @Body Order body, Callback cb + + + +@retrofit.http.Body Order body + +, Callback cb ); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java index 8c3380d07d4..7de0bc3fb1a 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java @@ -24,7 +24,12 @@ public interface UserApi { @POST("/user") Void createUser( - @Body User body + + + +@retrofit.http.Body User body + + ); /** @@ -37,7 +42,12 @@ Void createUser( @POST("/user") void createUser( - @Body User body, Callback cb + + + +@retrofit.http.Body User body + +, Callback cb ); /** * Creates list of users with given input array @@ -49,7 +59,12 @@ void createUser( @POST("/user/createWithArray") Void createUsersWithArrayInput( - @Body List body + + + +@retrofit.http.Body List body + + ); /** @@ -62,7 +77,12 @@ Void createUsersWithArrayInput( @POST("/user/createWithArray") void createUsersWithArrayInput( - @Body List body, Callback cb + + + +@retrofit.http.Body List body + +, Callback cb ); /** * Creates list of users with given input array @@ -74,7 +94,12 @@ void createUsersWithArrayInput( @POST("/user/createWithList") Void createUsersWithListInput( - @Body List body + + + +@retrofit.http.Body List body + + ); /** @@ -87,7 +112,12 @@ Void createUsersWithListInput( @POST("/user/createWithList") void createUsersWithListInput( - @Body List body, Callback cb + + + +@retrofit.http.Body List body + +, Callback cb ); /** * Delete user @@ -99,7 +129,12 @@ void createUsersWithListInput( @DELETE("/user/{username}") Void deleteUser( - @Path("username") String username + +@retrofit.http.Path("username") String username + + + + ); /** @@ -112,7 +147,12 @@ Void deleteUser( @DELETE("/user/{username}") void deleteUser( - @Path("username") String username, Callback cb + +@retrofit.http.Path("username") String username + + + +, Callback cb ); /** * Get user by user name @@ -124,7 +164,12 @@ void deleteUser( @GET("/user/{username}") User getUserByName( - @Path("username") String username + +@retrofit.http.Path("username") String username + + + + ); /** @@ -137,7 +182,12 @@ User getUserByName( @GET("/user/{username}") void getUserByName( - @Path("username") String username, Callback cb + +@retrofit.http.Path("username") String username + + + +, Callback cb ); /** * Logs user into the system @@ -150,7 +200,17 @@ void getUserByName( @GET("/user/login") String loginUser( - @Query("username") String username, @Query("password") String password + @retrofit.http.Query("username") String username + + + + +, @retrofit.http.Query("password") String password + + + + + ); /** @@ -164,7 +224,17 @@ String loginUser( @GET("/user/login") void loginUser( - @Query("username") String username, @Query("password") String password, Callback cb + @retrofit.http.Query("username") String username + + + + +, @retrofit.http.Query("password") String password + + + + +, Callback cb ); /** * Logs out current logged in user session @@ -199,7 +269,17 @@ void logoutUser( @PUT("/user/{username}") Void updateUser( - @Path("username") String username, @Body User body + +@retrofit.http.Path("username") String username + + + +, + + +@retrofit.http.Body User body + + ); /** @@ -213,6 +293,16 @@ Void updateUser( @PUT("/user/{username}") void updateUser( - @Path("username") String username, @Body User body, Callback cb + +@retrofit.http.Path("username") String username + + + +, + + +@retrofit.http.Body User body + +, Callback cb ); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index d20b1402ce2..81d139e630b 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -33,12 +33,11 @@ import java.util.List; import java.util.Map; - /** * AdditionalPropertiesClass */ -public class AdditionalPropertiesClass { +public class AdditionalPropertiesClass { @SerializedName("map_property") private Map mapProperty = new HashMap(); @@ -131,5 +130,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Animal.java index 9b1ff3df1c5..bc73c4f93cb 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Animal.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Animal */ -public class Animal { +public class Animal { @SerializedName("className") private String className = null; @@ -118,5 +117,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AnimalFarm.java index 563476ccb3d..8a50c9c6cb5 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -30,12 +30,11 @@ import java.util.ArrayList; import java.util.List; - /** * AnimalFarm */ -public class AnimalFarm extends ArrayList { +public class AnimalFarm extends ArrayList { @Override public boolean equals(java.lang.Object o) { @@ -72,5 +71,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 4c2fa22800f..e0dde620ab4 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -33,12 +33,11 @@ import java.util.ArrayList; import java.util.List; - /** * ArrayOfArrayOfNumberOnly */ -public class ArrayOfArrayOfNumberOnly { +public class ArrayOfArrayOfNumberOnly { @SerializedName("ArrayArrayNumber") private List> arrayArrayNumber = new ArrayList>(); @@ -103,5 +102,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index 3c7d74dc3b5..e529ebc4fa8 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -33,12 +33,11 @@ import java.util.ArrayList; import java.util.List; - /** * ArrayOfNumberOnly */ -public class ArrayOfNumberOnly { +public class ArrayOfNumberOnly { @SerializedName("ArrayNumber") private List arrayNumber = new ArrayList(); @@ -103,5 +102,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayTest.java index 7e08b24fa6e..80df1b341f5 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayTest.java @@ -33,12 +33,11 @@ import java.util.ArrayList; import java.util.List; - /** * ArrayTest */ -public class ArrayTest { +public class ArrayTest { @SerializedName("array_of_string") private List arrayOfString = new ArrayList(); @@ -159,5 +158,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Cat.java index 9c5cb39f648..10a2f2c5c8d 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Cat.java @@ -31,12 +31,11 @@ import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; - /** * Cat */ -public class Cat extends Animal { +public class Cat extends Animal { @SerializedName("declawed") private Boolean declawed = null; @@ -97,5 +96,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Category.java index 44e76030eff..153df9edbfa 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Category.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Category */ -public class Category { +public class Category { @SerializedName("id") private Long id = null; @@ -118,5 +117,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Client.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Client.java index 54a54647918..1eb9e755db3 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Client.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Client.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Client */ -public class Client { +public class Client { @SerializedName("client") private String client = null; @@ -95,5 +94,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Dog.java index 880c159616c..079def9ecc6 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Dog.java @@ -31,12 +31,11 @@ import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; - /** * Dog */ -public class Dog extends Animal { +public class Dog extends Animal { @SerializedName("breed") private String breed = null; @@ -97,5 +96,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumArrays.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumArrays.java index c5096738755..7eea2d2a911 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumArrays.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumArrays.java @@ -32,12 +32,11 @@ import java.util.ArrayList; import java.util.List; - /** * EnumArrays */ -public class EnumArrays { +public class EnumArrays { /** * Gets or Sets justSymbol */ @@ -169,5 +168,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumClass.java index 7862a8b8952..a6072c381c4 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumClass.java @@ -29,7 +29,6 @@ import com.google.gson.annotations.SerializedName; - /** * Gets or Sets EnumClass */ diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumTest.java index 83896fbd849..bdd3a40bb28 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumTest.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * EnumTest */ -public class EnumTest { +public class EnumTest { /** * Gets or Sets enumString */ @@ -207,5 +206,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/FormatTest.java index a05f1d5c811..023042b8d96 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/FormatTest.java @@ -33,12 +33,11 @@ import org.joda.time.DateTime; import org.joda.time.LocalDate; - /** * FormatTest */ -public class FormatTest { +public class FormatTest { @SerializedName("integer") private Integer integer = null; @@ -384,5 +383,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java index e53b1a0d8be..43a5b6a6c92 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * HasOnlyReadOnly */ -public class HasOnlyReadOnly { +public class HasOnlyReadOnly { @SerializedName("bar") private String bar = null; @@ -100,5 +99,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MapTest.java index e7d394ed035..75586c606c9 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MapTest.java @@ -33,12 +33,11 @@ import java.util.List; import java.util.Map; - /** * MapTest */ -public class MapTest { +public class MapTest { @SerializedName("map_map_of_string") private Map> mapMapOfString = new HashMap>(); @@ -153,5 +152,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 887ba516d72..e6b8987656a 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -35,12 +35,11 @@ import java.util.Map; import org.joda.time.DateTime; - /** * MixedPropertiesAndAdditionalPropertiesClass */ -public class MixedPropertiesAndAdditionalPropertiesClass { +public class MixedPropertiesAndAdditionalPropertiesClass { @SerializedName("uuid") private String uuid = null; @@ -151,5 +150,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Model200Response.java index 980bc83e869..eabc63cd389 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Model200Response.java @@ -30,13 +30,12 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Model for testing model name starting with number */ @ApiModel(description = "Model for testing model name starting with number") -public class Model200Response { +public class Model200Response { @SerializedName("name") private Integer name = null; @@ -119,5 +118,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ModelApiResponse.java index f9c162a7934..e410a24757f 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * ModelApiResponse */ -public class ModelApiResponse { +public class ModelApiResponse { @SerializedName("code") private Integer code = null; @@ -141,5 +140,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ModelReturn.java index bbe7780055c..01d69fecb68 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ModelReturn.java @@ -30,13 +30,12 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Model for testing reserved words */ @ApiModel(description = "Model for testing reserved words") -public class ModelReturn { +public class ModelReturn { @SerializedName("return") private Integer _return = null; @@ -96,5 +95,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Name.java index d51354ceffa..c50f477abc3 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Name.java @@ -30,13 +30,12 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Model for testing model name same as property name */ @ApiModel(description = "Model for testing model name same as property name") -public class Name { +public class Name { @SerializedName("name") private Integer name = null; @@ -147,5 +146,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/NumberOnly.java index 2b1817300a9..0653baec68b 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/NumberOnly.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/NumberOnly.java @@ -31,12 +31,11 @@ import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; - /** * NumberOnly */ -public class NumberOnly { +public class NumberOnly { @SerializedName("JustNumber") private BigDecimal justNumber = null; @@ -96,5 +95,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java index f52e7bd5db4..d15cca81e05 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java @@ -31,12 +31,11 @@ import io.swagger.annotations.ApiModelProperty; import org.joda.time.DateTime; - /** * Order */ -public class Order { +public class Order { @SerializedName("id") private Long id = null; @@ -236,5 +235,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Pet.java index 06443e56915..2363e9ed02e 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Pet.java @@ -34,12 +34,11 @@ import java.util.ArrayList; import java.util.List; - /** * Pet */ -public class Pet { +public class Pet { @SerializedName("id") private Long id = null; @@ -249,5 +248,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index 75dbc55f9f5..f9f1503366f 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * ReadOnlyFirst */ -public class ReadOnlyFirst { +public class ReadOnlyFirst { @SerializedName("bar") private String bar = null; @@ -109,5 +108,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/SpecialModelName.java index 9744ad08268..10d56096dea 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * SpecialModelName */ -public class SpecialModelName { +public class SpecialModelName { @SerializedName("$special[property.name]") private Long specialPropertyName = null; @@ -95,5 +94,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Tag.java index 9eef0141c71..11870f0f0a8 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Tag.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Tag */ -public class Tag { +public class Tag { @SerializedName("id") private Long id = null; @@ -118,5 +117,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/User.java index 73584bfdccb..b04dc861682 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/User.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * User */ -public class User { +public class User { @SerializedName("id") private Long id = null; @@ -256,5 +255,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/docs/FakeApi.md b/samples/client/petstore/java/retrofit2/docs/FakeApi.md index f4cfc7e19cc..2e2b792d8d3 100644 --- a/samples/client/petstore/java/retrofit2/docs/FakeApi.md +++ b/samples/client/petstore/java/retrofit2/docs/FakeApi.md @@ -54,7 +54,7 @@ No authorization required # **testEndpointParameters** -> Void testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password) +> Void testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -90,8 +90,9 @@ byte[] binary = B; // byte[] | None LocalDate date = new LocalDate(); // LocalDate | None DateTime dateTime = new DateTime(); // DateTime | None String password = "password_example"; // String | None +String paramCallback = "paramCallback_example"; // String | None try { - Void result = apiInstance.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password); + Void result = apiInstance.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling FakeApi#testEndpointParameters"); @@ -116,6 +117,7 @@ Name | Type | Description | Notes **date** | **LocalDate**| None | [optional] **dateTime** | **DateTime**| None | [optional] **password** | **String**| None | [optional] + **paramCallback** | **String**| None | [optional] ### Return type diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java index 25bde1256dc..7479e230574 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java @@ -28,7 +28,12 @@ public interface FakeApi { @PATCH("fake") Call testClientModel( - @Body Client body + + + +@retrofit2.http.Body Client body + + ); /** @@ -47,13 +52,84 @@ Call testClientModel( * @param date None (optional) * @param dateTime None (optional) * @param password None (optional) + * @param paramCallback None (optional) * @return Call<Void> */ - @FormUrlEncoded + @retrofit2.http.FormUrlEncoded @POST("fake") Call testEndpointParameters( - @Field("number") BigDecimal number, @Field("double") Double _double, @Field("pattern_without_delimiter") String patternWithoutDelimiter, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("string") String string, @Field("binary") byte[] binary, @Field("date") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password + + + + +@retrofit2.http.Field("number") BigDecimal number +, + + + +@retrofit2.http.Field("double") Double _double +, + + + +@retrofit2.http.Field("pattern_without_delimiter") String patternWithoutDelimiter +, + + + +@retrofit2.http.Field("byte") byte[] _byte +, + + + +@retrofit2.http.Field("integer") Integer integer +, + + + +@retrofit2.http.Field("int32") Integer int32 +, + + + +@retrofit2.http.Field("int64") Long int64 +, + + + +@retrofit2.http.Field("float") Float _float +, + + + +@retrofit2.http.Field("string") String string +, + + + +@retrofit2.http.Field("binary") byte[] binary +, + + + +@retrofit2.http.Field("date") LocalDate date +, + + + +@retrofit2.http.Field("dateTime") DateTime dateTime +, + + + +@retrofit2.http.Field("password") String password +, + + + +@retrofit2.http.Field("callback") String paramCallback + ); /** @@ -70,10 +146,50 @@ Call testEndpointParameters( * @return Call<Void> */ - @FormUrlEncoded + @retrofit2.http.FormUrlEncoded @GET("fake") Call testEnumParameters( - @Field("enum_form_string_array") List enumFormStringArray, @Field("enum_form_string") String enumFormString, @Header("enum_header_string_array") List enumHeaderStringArray, @Header("enum_header_string") String enumHeaderString, @Query("enum_query_string_array") CSVParams enumQueryStringArray, @Query("enum_query_string") String enumQueryString, @Query("enum_query_integer") BigDecimal enumQueryInteger, @Field("enum_query_double") Double enumQueryDouble + + + + +@retrofit2.http.Field("enum_form_string_array") List enumFormStringArray +, + + + +@retrofit2.http.Field("enum_form_string") String enumFormString +, + +@retrofit2.http.Header("enum_header_string_array") List enumHeaderStringArray + + +, + +@retrofit2.http.Header("enum_header_string") String enumHeaderString + + +, @retrofit2.http.Query("enum_query_string_array") CSVParams enumQueryStringArray + + + + +, @retrofit2.http.Query("enum_query_string") String enumQueryString + + + + +, @retrofit2.http.Query("enum_query_integer") BigDecimal enumQueryInteger + + + + +, + + + +@retrofit2.http.Field("enum_query_double") Double enumQueryDouble + ); } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java index d5c574fbd3e..bd13312f581 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java @@ -27,7 +27,12 @@ public interface PetApi { @POST("pet") Call addPet( - @Body Pet body + + + +@retrofit2.http.Body Pet body + + ); /** @@ -40,7 +45,17 @@ Call addPet( @DELETE("pet/{petId}") Call deletePet( - @Path("petId") Long petId, @Header("api_key") String apiKey + +@retrofit2.http.Path("petId") Long petId + + + +, + +@retrofit2.http.Header("api_key") String apiKey + + + ); /** @@ -52,7 +67,12 @@ Call deletePet( @GET("pet/findByStatus") Call> findPetsByStatus( - @Query("status") CSVParams status + @retrofit2.http.Query("status") CSVParams status + + + + + ); /** @@ -64,7 +84,12 @@ Call> findPetsByStatus( @GET("pet/findByTags") Call> findPetsByTags( - @Query("tags") CSVParams tags + @retrofit2.http.Query("tags") CSVParams tags + + + + + ); /** @@ -76,7 +101,12 @@ Call> findPetsByTags( @GET("pet/{petId}") Call getPetById( - @Path("petId") Long petId + +@retrofit2.http.Path("petId") Long petId + + + + ); /** @@ -88,7 +118,12 @@ Call getPetById( @PUT("pet") Call updatePet( - @Body Pet body + + + +@retrofit2.http.Body Pet body + + ); /** @@ -100,10 +135,25 @@ Call updatePet( * @return Call<Void> */ - @FormUrlEncoded + @retrofit2.http.FormUrlEncoded @POST("pet/{petId}") Call updatePetWithForm( - @Path("petId") Long petId, @Field("name") String name, @Field("status") String status + +@retrofit2.http.Path("petId") Long petId + + + +, + + + +@retrofit2.http.Field("name") String name +, + + + +@retrofit2.http.Field("status") String status + ); /** @@ -115,10 +165,25 @@ Call updatePetWithForm( * @return Call<ModelApiResponse> */ - @Multipart + @retrofit2.http.Multipart @POST("pet/{petId}/uploadImage") Call uploadFile( - @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file\"; filename=\"file") RequestBody file + +@retrofit2.http.Path("petId") Long petId + + + +, + + + +@retrofit2.http.Part("additionalMetadata") String additionalMetadata +, + + + +@retrofit2.http.Part("file\"; filename=\"file") RequestBody file + ); } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java index 3e19600bedb..ebed8da8f52 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java @@ -25,7 +25,12 @@ public interface StoreApi { @DELETE("store/order/{orderId}") Call deleteOrder( - @Path("orderId") String orderId + +@retrofit2.http.Path("orderId") String orderId + + + + ); /** @@ -47,7 +52,12 @@ Call deleteOrder( @GET("store/order/{orderId}") Call getOrderById( - @Path("orderId") Long orderId + +@retrofit2.http.Path("orderId") Long orderId + + + + ); /** @@ -59,7 +69,12 @@ Call getOrderById( @POST("store/order") Call placeOrder( - @Body Order body + + + +@retrofit2.http.Body Order body + + ); } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java index 3fc76b6a1b2..1bf7d34d73c 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java @@ -25,7 +25,12 @@ public interface UserApi { @POST("user") Call createUser( - @Body User body + + + +@retrofit2.http.Body User body + + ); /** @@ -37,7 +42,12 @@ Call createUser( @POST("user/createWithArray") Call createUsersWithArrayInput( - @Body List body + + + +@retrofit2.http.Body List body + + ); /** @@ -49,7 +59,12 @@ Call createUsersWithArrayInput( @POST("user/createWithList") Call createUsersWithListInput( - @Body List body + + + +@retrofit2.http.Body List body + + ); /** @@ -61,7 +76,12 @@ Call createUsersWithListInput( @DELETE("user/{username}") Call deleteUser( - @Path("username") String username + +@retrofit2.http.Path("username") String username + + + + ); /** @@ -73,7 +93,12 @@ Call deleteUser( @GET("user/{username}") Call getUserByName( - @Path("username") String username + +@retrofit2.http.Path("username") String username + + + + ); /** @@ -86,7 +111,17 @@ Call getUserByName( @GET("user/login") Call loginUser( - @Query("username") String username, @Query("password") String password + @retrofit2.http.Query("username") String username + + + + +, @retrofit2.http.Query("password") String password + + + + + ); /** @@ -109,7 +144,17 @@ Call loginUser( @PUT("user/{username}") Call updateUser( - @Path("username") String username, @Body User body + +@retrofit2.http.Path("username") String username + + + +, + + +@retrofit2.http.Body User body + + ); } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index d20b1402ce2..81d139e630b 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -33,12 +33,11 @@ import java.util.List; import java.util.Map; - /** * AdditionalPropertiesClass */ -public class AdditionalPropertiesClass { +public class AdditionalPropertiesClass { @SerializedName("map_property") private Map mapProperty = new HashMap(); @@ -131,5 +130,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Animal.java index 9b1ff3df1c5..bc73c4f93cb 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Animal.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Animal */ -public class Animal { +public class Animal { @SerializedName("className") private String className = null; @@ -118,5 +117,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AnimalFarm.java index 563476ccb3d..8a50c9c6cb5 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -30,12 +30,11 @@ import java.util.ArrayList; import java.util.List; - /** * AnimalFarm */ -public class AnimalFarm extends ArrayList { +public class AnimalFarm extends ArrayList { @Override public boolean equals(java.lang.Object o) { @@ -72,5 +71,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 4c2fa22800f..e0dde620ab4 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -33,12 +33,11 @@ import java.util.ArrayList; import java.util.List; - /** * ArrayOfArrayOfNumberOnly */ -public class ArrayOfArrayOfNumberOnly { +public class ArrayOfArrayOfNumberOnly { @SerializedName("ArrayArrayNumber") private List> arrayArrayNumber = new ArrayList>(); @@ -103,5 +102,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index 3c7d74dc3b5..e529ebc4fa8 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -33,12 +33,11 @@ import java.util.ArrayList; import java.util.List; - /** * ArrayOfNumberOnly */ -public class ArrayOfNumberOnly { +public class ArrayOfNumberOnly { @SerializedName("ArrayNumber") private List arrayNumber = new ArrayList(); @@ -103,5 +102,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayTest.java index 7e08b24fa6e..80df1b341f5 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayTest.java @@ -33,12 +33,11 @@ import java.util.ArrayList; import java.util.List; - /** * ArrayTest */ -public class ArrayTest { +public class ArrayTest { @SerializedName("array_of_string") private List arrayOfString = new ArrayList(); @@ -159,5 +158,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Cat.java index 9c5cb39f648..10a2f2c5c8d 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Cat.java @@ -31,12 +31,11 @@ import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; - /** * Cat */ -public class Cat extends Animal { +public class Cat extends Animal { @SerializedName("declawed") private Boolean declawed = null; @@ -97,5 +96,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Category.java index 44e76030eff..153df9edbfa 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Category.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Category */ -public class Category { +public class Category { @SerializedName("id") private Long id = null; @@ -118,5 +117,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Client.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Client.java index 54a54647918..1eb9e755db3 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Client.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Client.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Client */ -public class Client { +public class Client { @SerializedName("client") private String client = null; @@ -95,5 +94,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Dog.java index 880c159616c..079def9ecc6 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Dog.java @@ -31,12 +31,11 @@ import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; - /** * Dog */ -public class Dog extends Animal { +public class Dog extends Animal { @SerializedName("breed") private String breed = null; @@ -97,5 +96,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumArrays.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumArrays.java index c5096738755..7eea2d2a911 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumArrays.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumArrays.java @@ -32,12 +32,11 @@ import java.util.ArrayList; import java.util.List; - /** * EnumArrays */ -public class EnumArrays { +public class EnumArrays { /** * Gets or Sets justSymbol */ @@ -169,5 +168,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumClass.java index 7862a8b8952..a6072c381c4 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumClass.java @@ -29,7 +29,6 @@ import com.google.gson.annotations.SerializedName; - /** * Gets or Sets EnumClass */ diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumTest.java index 83896fbd849..bdd3a40bb28 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumTest.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * EnumTest */ -public class EnumTest { +public class EnumTest { /** * Gets or Sets enumString */ @@ -207,5 +206,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/FormatTest.java index a05f1d5c811..023042b8d96 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/FormatTest.java @@ -33,12 +33,11 @@ import org.joda.time.DateTime; import org.joda.time.LocalDate; - /** * FormatTest */ -public class FormatTest { +public class FormatTest { @SerializedName("integer") private Integer integer = null; @@ -384,5 +383,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java index e53b1a0d8be..43a5b6a6c92 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * HasOnlyReadOnly */ -public class HasOnlyReadOnly { +public class HasOnlyReadOnly { @SerializedName("bar") private String bar = null; @@ -100,5 +99,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MapTest.java index e7d394ed035..75586c606c9 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MapTest.java @@ -33,12 +33,11 @@ import java.util.List; import java.util.Map; - /** * MapTest */ -public class MapTest { +public class MapTest { @SerializedName("map_map_of_string") private Map> mapMapOfString = new HashMap>(); @@ -153,5 +152,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 887ba516d72..e6b8987656a 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -35,12 +35,11 @@ import java.util.Map; import org.joda.time.DateTime; - /** * MixedPropertiesAndAdditionalPropertiesClass */ -public class MixedPropertiesAndAdditionalPropertiesClass { +public class MixedPropertiesAndAdditionalPropertiesClass { @SerializedName("uuid") private String uuid = null; @@ -151,5 +150,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Model200Response.java index 980bc83e869..eabc63cd389 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Model200Response.java @@ -30,13 +30,12 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Model for testing model name starting with number */ @ApiModel(description = "Model for testing model name starting with number") -public class Model200Response { +public class Model200Response { @SerializedName("name") private Integer name = null; @@ -119,5 +118,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ModelApiResponse.java index f9c162a7934..e410a24757f 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * ModelApiResponse */ -public class ModelApiResponse { +public class ModelApiResponse { @SerializedName("code") private Integer code = null; @@ -141,5 +140,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ModelReturn.java index bbe7780055c..01d69fecb68 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ModelReturn.java @@ -30,13 +30,12 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Model for testing reserved words */ @ApiModel(description = "Model for testing reserved words") -public class ModelReturn { +public class ModelReturn { @SerializedName("return") private Integer _return = null; @@ -96,5 +95,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Name.java index d51354ceffa..c50f477abc3 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Name.java @@ -30,13 +30,12 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Model for testing model name same as property name */ @ApiModel(description = "Model for testing model name same as property name") -public class Name { +public class Name { @SerializedName("name") private Integer name = null; @@ -147,5 +146,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/NumberOnly.java index 2b1817300a9..0653baec68b 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/NumberOnly.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/NumberOnly.java @@ -31,12 +31,11 @@ import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; - /** * NumberOnly */ -public class NumberOnly { +public class NumberOnly { @SerializedName("JustNumber") private BigDecimal justNumber = null; @@ -96,5 +95,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Order.java index f52e7bd5db4..d15cca81e05 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Order.java @@ -31,12 +31,11 @@ import io.swagger.annotations.ApiModelProperty; import org.joda.time.DateTime; - /** * Order */ -public class Order { +public class Order { @SerializedName("id") private Long id = null; @@ -236,5 +235,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Pet.java index 06443e56915..2363e9ed02e 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Pet.java @@ -34,12 +34,11 @@ import java.util.ArrayList; import java.util.List; - /** * Pet */ -public class Pet { +public class Pet { @SerializedName("id") private Long id = null; @@ -249,5 +248,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index 75dbc55f9f5..f9f1503366f 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * ReadOnlyFirst */ -public class ReadOnlyFirst { +public class ReadOnlyFirst { @SerializedName("bar") private String bar = null; @@ -109,5 +108,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/SpecialModelName.java index 9744ad08268..10d56096dea 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * SpecialModelName */ -public class SpecialModelName { +public class SpecialModelName { @SerializedName("$special[property.name]") private Long specialPropertyName = null; @@ -95,5 +94,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Tag.java index 9eef0141c71..11870f0f0a8 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Tag.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Tag */ -public class Tag { +public class Tag { @SerializedName("id") private Long id = null; @@ -118,5 +117,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/User.java index 73584bfdccb..b04dc861682 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/User.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * User */ -public class User { +public class User { @SerializedName("id") private Long id = null; @@ -256,5 +255,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java index 2bf3ea9e839..924c81ff6dc 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java @@ -28,7 +28,12 @@ public interface FakeApi { @PATCH("fake") Observable testClientModel( - @Body Client body + + + +@retrofit2.http.Body Client body + + ); /** @@ -47,13 +52,84 @@ Observable testClientModel( * @param date None (optional) * @param dateTime None (optional) * @param password None (optional) + * @param paramCallback None (optional) * @return Call<Void> */ - @FormUrlEncoded + @retrofit2.http.FormUrlEncoded @POST("fake") Observable testEndpointParameters( - @Field("number") BigDecimal number, @Field("double") Double _double, @Field("pattern_without_delimiter") String patternWithoutDelimiter, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("string") String string, @Field("binary") byte[] binary, @Field("date") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password + + + + +@retrofit2.http.Field("number") BigDecimal number +, + + + +@retrofit2.http.Field("double") Double _double +, + + + +@retrofit2.http.Field("pattern_without_delimiter") String patternWithoutDelimiter +, + + + +@retrofit2.http.Field("byte") byte[] _byte +, + + + +@retrofit2.http.Field("integer") Integer integer +, + + + +@retrofit2.http.Field("int32") Integer int32 +, + + + +@retrofit2.http.Field("int64") Long int64 +, + + + +@retrofit2.http.Field("float") Float _float +, + + + +@retrofit2.http.Field("string") String string +, + + + +@retrofit2.http.Field("binary") byte[] binary +, + + + +@retrofit2.http.Field("date") LocalDate date +, + + + +@retrofit2.http.Field("dateTime") DateTime dateTime +, + + + +@retrofit2.http.Field("password") String password +, + + + +@retrofit2.http.Field("callback") String paramCallback + ); /** @@ -70,10 +146,50 @@ Observable testEndpointParameters( * @return Call<Void> */ - @FormUrlEncoded + @retrofit2.http.FormUrlEncoded @GET("fake") Observable testEnumParameters( - @Field("enum_form_string_array") List enumFormStringArray, @Field("enum_form_string") String enumFormString, @Header("enum_header_string_array") List enumHeaderStringArray, @Header("enum_header_string") String enumHeaderString, @Query("enum_query_string_array") CSVParams enumQueryStringArray, @Query("enum_query_string") String enumQueryString, @Query("enum_query_integer") BigDecimal enumQueryInteger, @Field("enum_query_double") Double enumQueryDouble + + + + +@retrofit2.http.Field("enum_form_string_array") List enumFormStringArray +, + + + +@retrofit2.http.Field("enum_form_string") String enumFormString +, + +@retrofit2.http.Header("enum_header_string_array") List enumHeaderStringArray + + +, + +@retrofit2.http.Header("enum_header_string") String enumHeaderString + + +, @retrofit2.http.Query("enum_query_string_array") CSVParams enumQueryStringArray + + + + +, @retrofit2.http.Query("enum_query_string") String enumQueryString + + + + +, @retrofit2.http.Query("enum_query_integer") BigDecimal enumQueryInteger + + + + +, + + + +@retrofit2.http.Field("enum_query_double") Double enumQueryDouble + ); } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java index 77cfd8ae3de..cc6a867c755 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java @@ -27,7 +27,12 @@ public interface PetApi { @POST("pet") Observable addPet( - @Body Pet body + + + +@retrofit2.http.Body Pet body + + ); /** @@ -40,7 +45,17 @@ Observable addPet( @DELETE("pet/{petId}") Observable deletePet( - @Path("petId") Long petId, @Header("api_key") String apiKey + +@retrofit2.http.Path("petId") Long petId + + + +, + +@retrofit2.http.Header("api_key") String apiKey + + + ); /** @@ -52,7 +67,12 @@ Observable deletePet( @GET("pet/findByStatus") Observable> findPetsByStatus( - @Query("status") CSVParams status + @retrofit2.http.Query("status") CSVParams status + + + + + ); /** @@ -64,7 +84,12 @@ Observable> findPetsByStatus( @GET("pet/findByTags") Observable> findPetsByTags( - @Query("tags") CSVParams tags + @retrofit2.http.Query("tags") CSVParams tags + + + + + ); /** @@ -76,7 +101,12 @@ Observable> findPetsByTags( @GET("pet/{petId}") Observable getPetById( - @Path("petId") Long petId + +@retrofit2.http.Path("petId") Long petId + + + + ); /** @@ -88,7 +118,12 @@ Observable getPetById( @PUT("pet") Observable updatePet( - @Body Pet body + + + +@retrofit2.http.Body Pet body + + ); /** @@ -100,10 +135,25 @@ Observable updatePet( * @return Call<Void> */ - @FormUrlEncoded + @retrofit2.http.FormUrlEncoded @POST("pet/{petId}") Observable updatePetWithForm( - @Path("petId") Long petId, @Field("name") String name, @Field("status") String status + +@retrofit2.http.Path("petId") Long petId + + + +, + + + +@retrofit2.http.Field("name") String name +, + + + +@retrofit2.http.Field("status") String status + ); /** @@ -115,10 +165,25 @@ Observable updatePetWithForm( * @return Call<ModelApiResponse> */ - @Multipart + @retrofit2.http.Multipart @POST("pet/{petId}/uploadImage") Observable uploadFile( - @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file\"; filename=\"file") RequestBody file + +@retrofit2.http.Path("petId") Long petId + + + +, + + + +@retrofit2.http.Part("additionalMetadata") String additionalMetadata +, + + + +@retrofit2.http.Part("file\"; filename=\"file") RequestBody file + ); } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java index 4e93813692d..f763e317070 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java @@ -25,7 +25,12 @@ public interface StoreApi { @DELETE("store/order/{orderId}") Observable deleteOrder( - @Path("orderId") String orderId + +@retrofit2.http.Path("orderId") String orderId + + + + ); /** @@ -47,7 +52,12 @@ Observable deleteOrder( @GET("store/order/{orderId}") Observable getOrderById( - @Path("orderId") Long orderId + +@retrofit2.http.Path("orderId") Long orderId + + + + ); /** @@ -59,7 +69,12 @@ Observable getOrderById( @POST("store/order") Observable placeOrder( - @Body Order body + + + +@retrofit2.http.Body Order body + + ); } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/UserApi.java index 24a05ec40b8..4f13893a8f8 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/UserApi.java @@ -25,7 +25,12 @@ public interface UserApi { @POST("user") Observable createUser( - @Body User body + + + +@retrofit2.http.Body User body + + ); /** @@ -37,7 +42,12 @@ Observable createUser( @POST("user/createWithArray") Observable createUsersWithArrayInput( - @Body List body + + + +@retrofit2.http.Body List body + + ); /** @@ -49,7 +59,12 @@ Observable createUsersWithArrayInput( @POST("user/createWithList") Observable createUsersWithListInput( - @Body List body + + + +@retrofit2.http.Body List body + + ); /** @@ -61,7 +76,12 @@ Observable createUsersWithListInput( @DELETE("user/{username}") Observable deleteUser( - @Path("username") String username + +@retrofit2.http.Path("username") String username + + + + ); /** @@ -73,7 +93,12 @@ Observable deleteUser( @GET("user/{username}") Observable getUserByName( - @Path("username") String username + +@retrofit2.http.Path("username") String username + + + + ); /** @@ -86,7 +111,17 @@ Observable getUserByName( @GET("user/login") Observable loginUser( - @Query("username") String username, @Query("password") String password + @retrofit2.http.Query("username") String username + + + + +, @retrofit2.http.Query("password") String password + + + + + ); /** @@ -109,7 +144,17 @@ Observable loginUser( @PUT("user/{username}") Observable updateUser( - @Path("username") String username, @Body User body + +@retrofit2.http.Path("username") String username + + + +, + + +@retrofit2.http.Body User body + + ); } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index d20b1402ce2..81d139e630b 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -33,12 +33,11 @@ import java.util.List; import java.util.Map; - /** * AdditionalPropertiesClass */ -public class AdditionalPropertiesClass { +public class AdditionalPropertiesClass { @SerializedName("map_property") private Map mapProperty = new HashMap(); @@ -131,5 +130,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Animal.java index 9b1ff3df1c5..bc73c4f93cb 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Animal.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Animal */ -public class Animal { +public class Animal { @SerializedName("className") private String className = null; @@ -118,5 +117,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AnimalFarm.java index 563476ccb3d..8a50c9c6cb5 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -30,12 +30,11 @@ import java.util.ArrayList; import java.util.List; - /** * AnimalFarm */ -public class AnimalFarm extends ArrayList { +public class AnimalFarm extends ArrayList { @Override public boolean equals(java.lang.Object o) { @@ -72,5 +71,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 4c2fa22800f..e0dde620ab4 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -33,12 +33,11 @@ import java.util.ArrayList; import java.util.List; - /** * ArrayOfArrayOfNumberOnly */ -public class ArrayOfArrayOfNumberOnly { +public class ArrayOfArrayOfNumberOnly { @SerializedName("ArrayArrayNumber") private List> arrayArrayNumber = new ArrayList>(); @@ -103,5 +102,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index 3c7d74dc3b5..e529ebc4fa8 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -33,12 +33,11 @@ import java.util.ArrayList; import java.util.List; - /** * ArrayOfNumberOnly */ -public class ArrayOfNumberOnly { +public class ArrayOfNumberOnly { @SerializedName("ArrayNumber") private List arrayNumber = new ArrayList(); @@ -103,5 +102,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayTest.java index 7e08b24fa6e..80df1b341f5 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayTest.java @@ -33,12 +33,11 @@ import java.util.ArrayList; import java.util.List; - /** * ArrayTest */ -public class ArrayTest { +public class ArrayTest { @SerializedName("array_of_string") private List arrayOfString = new ArrayList(); @@ -159,5 +158,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Cat.java index 9c5cb39f648..10a2f2c5c8d 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Cat.java @@ -31,12 +31,11 @@ import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; - /** * Cat */ -public class Cat extends Animal { +public class Cat extends Animal { @SerializedName("declawed") private Boolean declawed = null; @@ -97,5 +96,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Category.java index 44e76030eff..153df9edbfa 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Category.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Category */ -public class Category { +public class Category { @SerializedName("id") private Long id = null; @@ -118,5 +117,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Client.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Client.java index 54a54647918..1eb9e755db3 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Client.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Client.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Client */ -public class Client { +public class Client { @SerializedName("client") private String client = null; @@ -95,5 +94,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Dog.java index 880c159616c..079def9ecc6 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Dog.java @@ -31,12 +31,11 @@ import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; - /** * Dog */ -public class Dog extends Animal { +public class Dog extends Animal { @SerializedName("breed") private String breed = null; @@ -97,5 +96,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumArrays.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumArrays.java index c5096738755..7eea2d2a911 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumArrays.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumArrays.java @@ -32,12 +32,11 @@ import java.util.ArrayList; import java.util.List; - /** * EnumArrays */ -public class EnumArrays { +public class EnumArrays { /** * Gets or Sets justSymbol */ @@ -169,5 +168,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumClass.java index 7862a8b8952..a6072c381c4 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumClass.java @@ -29,7 +29,6 @@ import com.google.gson.annotations.SerializedName; - /** * Gets or Sets EnumClass */ diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumTest.java index 83896fbd849..bdd3a40bb28 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumTest.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * EnumTest */ -public class EnumTest { +public class EnumTest { /** * Gets or Sets enumString */ @@ -207,5 +206,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/FormatTest.java index a05f1d5c811..023042b8d96 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/FormatTest.java @@ -33,12 +33,11 @@ import org.joda.time.DateTime; import org.joda.time.LocalDate; - /** * FormatTest */ -public class FormatTest { +public class FormatTest { @SerializedName("integer") private Integer integer = null; @@ -384,5 +383,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java index e53b1a0d8be..43a5b6a6c92 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * HasOnlyReadOnly */ -public class HasOnlyReadOnly { +public class HasOnlyReadOnly { @SerializedName("bar") private String bar = null; @@ -100,5 +99,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MapTest.java index e7d394ed035..75586c606c9 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MapTest.java @@ -33,12 +33,11 @@ import java.util.List; import java.util.Map; - /** * MapTest */ -public class MapTest { +public class MapTest { @SerializedName("map_map_of_string") private Map> mapMapOfString = new HashMap>(); @@ -153,5 +152,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 887ba516d72..e6b8987656a 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -35,12 +35,11 @@ import java.util.Map; import org.joda.time.DateTime; - /** * MixedPropertiesAndAdditionalPropertiesClass */ -public class MixedPropertiesAndAdditionalPropertiesClass { +public class MixedPropertiesAndAdditionalPropertiesClass { @SerializedName("uuid") private String uuid = null; @@ -151,5 +150,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Model200Response.java index 980bc83e869..eabc63cd389 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Model200Response.java @@ -30,13 +30,12 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Model for testing model name starting with number */ @ApiModel(description = "Model for testing model name starting with number") -public class Model200Response { +public class Model200Response { @SerializedName("name") private Integer name = null; @@ -119,5 +118,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ModelApiResponse.java index f9c162a7934..e410a24757f 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * ModelApiResponse */ -public class ModelApiResponse { +public class ModelApiResponse { @SerializedName("code") private Integer code = null; @@ -141,5 +140,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ModelReturn.java index bbe7780055c..01d69fecb68 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ModelReturn.java @@ -30,13 +30,12 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Model for testing reserved words */ @ApiModel(description = "Model for testing reserved words") -public class ModelReturn { +public class ModelReturn { @SerializedName("return") private Integer _return = null; @@ -96,5 +95,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Name.java index d51354ceffa..c50f477abc3 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Name.java @@ -30,13 +30,12 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Model for testing model name same as property name */ @ApiModel(description = "Model for testing model name same as property name") -public class Name { +public class Name { @SerializedName("name") private Integer name = null; @@ -147,5 +146,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/NumberOnly.java index 2b1817300a9..0653baec68b 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/NumberOnly.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/NumberOnly.java @@ -31,12 +31,11 @@ import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; - /** * NumberOnly */ -public class NumberOnly { +public class NumberOnly { @SerializedName("JustNumber") private BigDecimal justNumber = null; @@ -96,5 +95,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Order.java index f52e7bd5db4..d15cca81e05 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Order.java @@ -31,12 +31,11 @@ import io.swagger.annotations.ApiModelProperty; import org.joda.time.DateTime; - /** * Order */ -public class Order { +public class Order { @SerializedName("id") private Long id = null; @@ -236,5 +235,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Pet.java index 06443e56915..2363e9ed02e 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Pet.java @@ -34,12 +34,11 @@ import java.util.ArrayList; import java.util.List; - /** * Pet */ -public class Pet { +public class Pet { @SerializedName("id") private Long id = null; @@ -249,5 +248,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index 75dbc55f9f5..f9f1503366f 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * ReadOnlyFirst */ -public class ReadOnlyFirst { +public class ReadOnlyFirst { @SerializedName("bar") private String bar = null; @@ -109,5 +108,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/SpecialModelName.java index 9744ad08268..10d56096dea 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * SpecialModelName */ -public class SpecialModelName { +public class SpecialModelName { @SerializedName("$special[property.name]") private Long specialPropertyName = null; @@ -95,5 +94,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Tag.java index 9eef0141c71..11870f0f0a8 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Tag.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Tag */ -public class Tag { +public class Tag { @SerializedName("id") private Long id = null; @@ -118,5 +117,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/User.java index 73584bfdccb..b04dc861682 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/User.java @@ -30,12 +30,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * User */ -public class User { +public class User { @SerializedName("id") private Long id = null; @@ -256,5 +255,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } From 522e27b752bc39059af7f13d5ec25c21a5959aca Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 10 Oct 2016 21:10:52 +0800 Subject: [PATCH 430/470] add template owner jax-rs cxf cdi --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 9c3bf295fdb..33706464129 100644 --- a/README.md +++ b/README.md @@ -885,7 +885,8 @@ Here is a list of template creators: * Java Undertow: @stevehu * Java Spring Boot: @diyfr * JAX-RS RestEasy: @chameleon82 - * JAX-RS CXF: @hiveship + * JAX-RS CXF: @hiveship + * JAX-RS CXF (CDI): @nickcmaynard * PHP Lumen: @abcsum * PHP Slim: @jfastnacht * Ruby on Rails 5: @zlx From 268099582580810f57ce617f1baf0da491cf883a Mon Sep 17 00:00:00 2001 From: Christophe Bornet Date: Mon, 10 Oct 2016 18:42:52 +0200 Subject: [PATCH 431/470] [Java/Jackson] use a jdk6 compatible DateFormat for java.util.Date (#3768) * [feign] use a jdk6 compatible serializer for java.util.Date See #3727 Fix #3753 * [jersey] use a jdk6 compatible DateFormat for java.util.Date --- .../codegen/languages/JavaClientCodegen.java | 4 ++ .../main/resources/Java/ApiClient.mustache | 8 +--- .../resources/Java/RFC3339DateFormat.mustache | 21 +++++++++ .../Java/libraries/feign/ApiClient.mustache | 1 + .../libraries/feign/FormAwareEncoder.mustache | 7 +-- .../Java/libraries/jersey2/ApiClient.mustache | 10 +---- .../Java/libraries/jersey2/JSON.mustache | 1 + .../java/io/swagger/client/ApiClient.java | 1 + .../io/swagger/client/FormAwareEncoder.java | 7 +-- .../io/swagger/client/RFC3339DateFormat.java | 44 +++++++++++++++++++ .../java/io/swagger/client/ApiClient.java | 8 +--- .../io/swagger/client/RFC3339DateFormat.java | 44 +++++++++++++++++++ .../java/io/swagger/client/api/FakeApi.java | 2 +- .../java/io/swagger/client/api/PetApi.java | 2 +- .../java/io/swagger/client/ApiClient.java | 10 +---- .../src/main/java/io/swagger/client/JSON.java | 1 + .../io/swagger/client/RFC3339DateFormat.java | 44 +++++++++++++++++++ .../test/java/io/swagger/client/JSONTest.java | 19 +++++++- 18 files changed, 187 insertions(+), 47 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/Java/RFC3339DateFormat.mustache create mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/RFC3339DateFormat.java create mode 100644 samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/RFC3339DateFormat.java create mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/RFC3339DateFormat.java 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 3fe56dcd203..ebd53d1a2a9 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 @@ -142,6 +142,10 @@ public void processOpts() { } else { LOGGER.error("Unknown library option (-l/--library): " + getLibrary()); } + + if (additionalProperties.containsKey("jackson") ) { + supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", invokerFolder, "RFC3339DateFormat.java")); + } } private boolean usesAnyRetrofitLibrary() { diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index 5d434c6980b..3209498e234 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -40,7 +40,6 @@ import java.io.File; import java.io.UnsupportedEncodingException; import java.text.DateFormat; -import java.text.SimpleDateFormat; import {{invokerPackage}}.auth.Authentication; import {{invokerPackage}}.auth.HttpBasicAuth; @@ -96,12 +95,7 @@ public class ApiClient { } public static DateFormat buildDefaultDateFormat() { - // Use RFC3339 format for date and datetime. - // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 - DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); - // Use UTC as the default time zone. - dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - return dateFormat; + return new RFC3339DateFormat(); } /** diff --git a/modules/swagger-codegen/src/main/resources/Java/RFC3339DateFormat.mustache b/modules/swagger-codegen/src/main/resources/Java/RFC3339DateFormat.mustache new file mode 100644 index 00000000000..16fd2a495a7 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/RFC3339DateFormat.mustache @@ -0,0 +1,21 @@ +{{>licenseInfo}} +package {{invokerPackage}}; + +import com.fasterxml.jackson.databind.util.ISO8601DateFormat; +import com.fasterxml.jackson.databind.util.ISO8601Utils; + +import java.text.FieldPosition; +import java.util.Date; + + +public class RFC3339DateFormat extends ISO8601DateFormat { + + // Same as ISO8601DateFormat but serializing milliseconds. + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + String value = ISO8601Utils.format(date, true); + toAppendTo.append(value); + return toAppendTo; + } + +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache index 15ce7431551..5641afe195f 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache @@ -136,6 +136,7 @@ public class ApiClient { objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + objectMapper.setDateFormat(new RFC3339DateFormat()); {{^java8}} objectMapper.registerModule(new JodaModule()); {{/java8}} 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 index 822aad582d4..baf29b5f4de 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/FormAwareEncoder.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/FormAwareEncoder.mustache @@ -8,7 +8,6 @@ import java.nio.charset.Charset; import java.util.*; import java.text.DateFormat; -import java.text.SimpleDateFormat; import feign.codec.EncodeException; import feign.codec.Encoder; @@ -32,12 +31,8 @@ public class FormAwareEncoder implements Encoder { 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"); + this.dateFormat = new RFC3339DateFormat();; - // 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); 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 24de11aedaa..db0daf0d3f4 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 @@ -39,7 +39,6 @@ import java.io.File; import java.io.UnsupportedEncodingException; import java.text.DateFormat; -import java.text.SimpleDateFormat; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -70,14 +69,7 @@ public class ApiClient { json = new JSON(); httpClient = buildHttpClient(debugging); - // Use RFC3339 format for date and datetime. - // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 - this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); - - // Use UTC as the default time zone. - this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - - this.json.setDateFormat((DateFormat) dateFormat.clone()); + this.dateFormat = new RFC3339DateFormat(); // Set default User-Agent. setUserAgent("{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{artifactVersion}}}/java{{/httpUserAgent}}"); 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 index 243e444cf01..ec15354a8a6 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/JSON.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/JSON.mustache @@ -24,6 +24,7 @@ public class JSON implements ContextResolver { mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + mapper.setDateFormat(new RFC3339DateFormat()); {{#java8}} mapper.registerModule(new JavaTimeModule()); {{/java8}} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java index 95d8ca9db48..d4844ec8d05 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java @@ -132,6 +132,7 @@ private ObjectMapper createObjectMapper() { objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + objectMapper.setDateFormat(new RFC3339DateFormat()); objectMapper.registerModule(new JodaModule()); return objectMapper; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java index 179a2834da9..85e7fad4d72 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java @@ -8,7 +8,6 @@ import java.util.*; import java.text.DateFormat; -import java.text.SimpleDateFormat; import feign.codec.EncodeException; import feign.codec.Encoder; @@ -32,12 +31,8 @@ public class FormAwareEncoder implements Encoder { 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"); + this.dateFormat = new RFC3339DateFormat();; - // 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); diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/RFC3339DateFormat.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/RFC3339DateFormat.java new file mode 100644 index 00000000000..3d287008be5 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/RFC3339DateFormat.java @@ -0,0 +1,44 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.swagger.client; + +import com.fasterxml.jackson.databind.util.ISO8601DateFormat; +import com.fasterxml.jackson.databind.util.ISO8601Utils; + +import java.text.FieldPosition; +import java.util.Date; + + +public class RFC3339DateFormat extends ISO8601DateFormat { + + // Same as ISO8601DateFormat but serializing milliseconds. + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + String value = ISO8601Utils.format(date, true); + toAppendTo.append(value); + return toAppendTo; + } + +} \ No newline at end of file diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java index 278a088c48c..f371fe400cf 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java @@ -58,7 +58,6 @@ import java.io.UnsupportedEncodingException; import java.text.DateFormat; -import java.text.SimpleDateFormat; import io.swagger.client.auth.Authentication; import io.swagger.client.auth.HttpBasicAuth; @@ -109,12 +108,7 @@ public ApiClient() { } public static DateFormat buildDefaultDateFormat() { - // Use RFC3339 format for date and datetime. - // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 - DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); - // Use UTC as the default time zone. - dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - return dateFormat; + return new RFC3339DateFormat(); } /** diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/RFC3339DateFormat.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/RFC3339DateFormat.java new file mode 100644 index 00000000000..3d287008be5 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/RFC3339DateFormat.java @@ -0,0 +1,44 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.swagger.client; + +import com.fasterxml.jackson.databind.util.ISO8601DateFormat; +import com.fasterxml.jackson.databind.util.ISO8601Utils; + +import java.text.FieldPosition; +import java.util.Date; + + +public class RFC3339DateFormat extends ISO8601DateFormat { + + // Same as ISO8601DateFormat but serializing milliseconds. + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + String value = ISO8601Utils.format(date, true); + toAppendTo.append(value); + return toAppendTo; + } + +} \ No newline at end of file diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java index c280869cccb..bbf7b711513 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java @@ -34,8 +34,8 @@ import io.swagger.client.model.Client; import org.joda.time.LocalDate; -import org.joda.time.DateTime; import java.math.BigDecimal; +import org.joda.time.DateTime; import java.util.ArrayList; diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java index 25185b214b1..90c256ee9ce 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java @@ -33,8 +33,8 @@ import io.swagger.client.Pair; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.ModelApiResponse; +import java.io.File; import java.util.ArrayList; 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 dc056fe3b7c..ec4fea20fad 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 @@ -39,7 +39,6 @@ import java.io.UnsupportedEncodingException; import java.text.DateFormat; -import java.text.SimpleDateFormat; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -70,14 +69,7 @@ public ApiClient() { json = new JSON(); httpClient = buildHttpClient(debugging); - // Use RFC3339 format for date and datetime. - // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 - this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); - - // Use UTC as the default time zone. - this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - - this.json.setDateFormat((DateFormat) dateFormat.clone()); + this.dateFormat = new RFC3339DateFormat(); // Set default User-Agent. setUserAgent("Swagger-Codegen/1.0.0/java"); 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 d6f725b2caa..126fa1c856a 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 @@ -19,6 +19,7 @@ public JSON() { mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + mapper.setDateFormat(new RFC3339DateFormat()); mapper.registerModule(new JodaModule()); } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/RFC3339DateFormat.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/RFC3339DateFormat.java new file mode 100644 index 00000000000..3d287008be5 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/RFC3339DateFormat.java @@ -0,0 +1,44 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.swagger.client; + +import com.fasterxml.jackson.databind.util.ISO8601DateFormat; +import com.fasterxml.jackson.databind.util.ISO8601Utils; + +import java.text.FieldPosition; +import java.util.Date; + + +public class RFC3339DateFormat extends ISO8601DateFormat { + + // Same as ISO8601DateFormat but serializing milliseconds. + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + String value = ISO8601Utils.format(date, true); + toAppendTo.append(value); + return toAppendTo; + } + +} \ No newline at end of file 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 9386b3d5236..78556e36639 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 @@ -1,8 +1,11 @@ package io.swagger.client; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ser.std.SqlDateSerializer; import io.swagger.client.model.Order; import java.lang.Exception; +import java.sql.Date; import org.joda.time.DateTimeZone; import org.joda.time.format.DateTimeFormatter; @@ -17,7 +20,7 @@ public class JSONTest { @Before public void setup() { - json = new JSON(); + json = new ApiClient().getJSON(); order = new Order(); } @@ -42,4 +45,18 @@ public void testCustomDate() throws Exception { Order o = json.getContext(null).readValue(str, Order.class); assertEquals(dateStr, dateFormat.print(o.getShipDate())); } + + @Test + public void testSqlDateSerialization() throws Exception { + String str = json.getContext(null).writeValueAsString(new java.sql.Date(10)); + assertEquals("\"1970-01-01\"", str); + } + + @Test + public void testSqlDateDeserialization() throws Exception { + final String str = "1970-01-01"; + java.sql.Date date = json.getContext(null).readValue("\"" + str + "\"", java.sql.Date.class); + assertEquals(date.toString(), str); + } + } \ No newline at end of file From 6f2c139ff8eabfad2634b4387be87974cce76f59 Mon Sep 17 00:00:00 2001 From: Christophe Bornet Date: Mon, 10 Oct 2016 18:43:28 +0200 Subject: [PATCH 432/470] [Spring] Format datetime in rfc3339 (#3777) * [spring-boot] format datetime in rfc3339 See #3727 * [spring-mvc] format datetime in rfc3339 --- .../codegen/languages/SpringCodegen.java | 4 ++++ .../resources/JavaSpring/application.mustache | 4 +++- .../spring-boot/RFC3339DateFormat.mustache | 20 +++++++++++++++++++ .../spring-mvc/RFC3339DateFormat.mustache | 20 +++++++++++++++++++ .../swaggerUiConfiguration.mustache | 17 ++++++++++++++++ .../src/main/java/io/swagger/api/FakeApi.java | 2 +- .../src/main/java/io/swagger/api/PetApi.java | 2 +- .../configuration/RFC3339DateFormat.java | 20 +++++++++++++++++++ .../configuration/SwaggerUiConfiguration.java | 17 ++++++++++++++++ .../src/main/java/io/swagger/api/FakeApi.java | 2 +- .../io/swagger/api/FakeApiController.java | 2 +- .../src/main/java/io/swagger/api/PetApi.java | 2 +- .../java/io/swagger/api/PetApiController.java | 2 +- .../configuration/RFC3339DateFormat.java | 20 +++++++++++++++++++ .../configuration/SwaggerUiConfiguration.java | 17 ++++++++++++++++ .../java/io/swagger/RFC3339DateFormat.java | 20 +++++++++++++++++++ .../src/main/java/io/swagger/api/FakeApi.java | 2 +- .../io/swagger/api/FakeApiController.java | 2 +- .../src/main/java/io/swagger/api/PetApi.java | 2 +- .../java/io/swagger/api/PetApiController.java | 2 +- .../src/main/resources/application.properties | 4 +++- 21 files changed, 171 insertions(+), 12 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-boot/RFC3339DateFormat.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-mvc/RFC3339DateFormat.mustache create mode 100644 samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/RFC3339DateFormat.java create mode 100644 samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/RFC3339DateFormat.java create mode 100644 samples/server/petstore/springboot/src/main/java/io/swagger/RFC3339DateFormat.java diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java index 348f6cec727..d0bfe2f253e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java @@ -126,6 +126,8 @@ public void processOpts() { (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "HomeController.java")); supportingFiles.add(new SupportingFile("swagger2SpringBoot.mustache", (sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator), "Swagger2SpringBoot.java")); + supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", + (sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator), "RFC3339DateFormat.java")); supportingFiles.add(new SupportingFile("application.mustache", ("src.main.resources").replace(".", java.io.File.separator), "application.properties")); } @@ -136,6 +138,8 @@ public void processOpts() { (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "WebMvcConfiguration.java")); supportingFiles.add(new SupportingFile("swaggerUiConfiguration.mustache", (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerUiConfiguration.java")); + supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", + (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "RFC3339DateFormat.java")); supportingFiles.add(new SupportingFile("application.properties", ("src.main.resources").replace(".", java.io.File.separator), "swagger.properties")); } diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/application.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/application.mustache index b6923a2f77c..e686a5a0c33 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/application.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/application.mustache @@ -1,3 +1,5 @@ springfox.documentation.swagger.v2.path=/api-docs server.contextPath={{^contextPath}}/{{/contextPath}}{{#contextPath}}{{contextPath}}{{/contextPath}} -server.port={{serverPort}} \ No newline at end of file +server.port={{serverPort}} +spring.jackson.date-format={{basePackage}}.RFC3339DateFormat +spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-boot/RFC3339DateFormat.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-boot/RFC3339DateFormat.mustache new file mode 100644 index 00000000000..afe24ed9aba --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-boot/RFC3339DateFormat.mustache @@ -0,0 +1,20 @@ +package {{basePackage}}; + +import com.fasterxml.jackson.databind.util.ISO8601DateFormat; +import com.fasterxml.jackson.databind.util.ISO8601Utils; + +import java.text.FieldPosition; +import java.util.Date; + + +public class RFC3339DateFormat extends ISO8601DateFormat { + + // Same as ISO8601DateFormat but serializing milliseconds. + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + String value = ISO8601Utils.format(date, true); + toAppendTo.append(value); + return toAppendTo; + } + +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-mvc/RFC3339DateFormat.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-mvc/RFC3339DateFormat.mustache new file mode 100644 index 00000000000..2e60a5c4b97 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-mvc/RFC3339DateFormat.mustache @@ -0,0 +1,20 @@ +package {{configPackage}}; + +import com.fasterxml.jackson.databind.util.ISO8601DateFormat; +import com.fasterxml.jackson.databind.util.ISO8601Utils; + +import java.text.FieldPosition; +import java.util.Date; + + +public class RFC3339DateFormat extends ISO8601DateFormat { + + // Same as ISO8601DateFormat but serializing milliseconds. + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + String value = ISO8601Utils.format(date, true); + toAppendTo.append(value); + return toAppendTo; + } + +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-mvc/swaggerUiConfiguration.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-mvc/swaggerUiConfiguration.mustache index d4b4b62c770..f47156b68bc 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-mvc/swaggerUiConfiguration.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-mvc/swaggerUiConfiguration.mustache @@ -1,14 +1,21 @@ package {{configPackage}}; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.Import; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import springfox.documentation.swagger2.annotations.EnableSwagger2; +import java.util.List; + {{>generatedAnnotation}} @Configuration @ComponentScan(basePackages = "{{apiPackage}}") @@ -51,4 +58,14 @@ public class SwaggerUiConfiguration extends WebMvcConfigurerAdapter { } } + @Override + public void configureMessageConverters(List> converters) { + ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json() + .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + .dateFormat( new RFC3339DateFormat()) + .build(); + converters.add(new MappingJackson2HttpMessageConverter(objectMapper)); + super.configureMessageConverters(converters); + } + } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApi.java index 39bd2a95cb9..2f2140bc068 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApi.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Client; -import java.time.LocalDate; import java.time.OffsetDateTime; +import java.time.LocalDate; import java.math.BigDecimal; import io.swagger.annotations.*; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java index dca1545a5ef..8b23618a5a3 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import java.io.File; import io.swagger.model.ModelApiResponse; +import java.io.File; import io.swagger.annotations.*; import org.springframework.http.HttpStatus; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/RFC3339DateFormat.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/RFC3339DateFormat.java new file mode 100644 index 00000000000..4aaf6cd1c0c --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/RFC3339DateFormat.java @@ -0,0 +1,20 @@ +package io.swagger.configuration; + +import com.fasterxml.jackson.databind.util.ISO8601DateFormat; +import com.fasterxml.jackson.databind.util.ISO8601Utils; + +import java.text.FieldPosition; +import java.util.Date; + + +public class RFC3339DateFormat extends ISO8601DateFormat { + + // Same as ISO8601DateFormat but serializing milliseconds. + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + String value = ISO8601Utils.format(date, true); + toAppendTo.append(value); + return toAppendTo; + } + +} \ No newline at end of file diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java index c7614b0015b..e05672181db 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java @@ -1,14 +1,21 @@ package io.swagger.configuration; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.Import; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import springfox.documentation.swagger2.annotations.EnableSwagger2; +import java.util.List; + @Configuration @ComponentScan(basePackages = "io.swagger.api") @@ -51,4 +58,14 @@ public void addResourceHandlers(ResourceHandlerRegistry registry) { } } + @Override + public void configureMessageConverters(List> converters) { + ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json() + .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + .dateFormat( new RFC3339DateFormat()) + .build(); + converters.add(new MappingJackson2HttpMessageConverter(objectMapper)); + super.configureMessageConverters(converters); + } + } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApi.java index a9ed1dede00..262a5fe9a16 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApi.java @@ -2,8 +2,8 @@ import io.swagger.model.Client; import org.joda.time.LocalDate; -import org.joda.time.DateTime; import java.math.BigDecimal; +import org.joda.time.DateTime; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApiController.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApiController.java index 722544de7d3..2115ca4cf68 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApiController.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApiController.java @@ -2,8 +2,8 @@ import io.swagger.model.Client; import org.joda.time.LocalDate; -import org.joda.time.DateTime; import java.math.BigDecimal; +import org.joda.time.DateTime; import io.swagger.annotations.*; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java index 9b937019b32..ea0122441c1 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import java.io.File; import io.swagger.model.ModelApiResponse; +import java.io.File; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApiController.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApiController.java index af909d49ab8..8b95d74de51 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApiController.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApiController.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import java.io.File; import io.swagger.model.ModelApiResponse; +import java.io.File; import io.swagger.annotations.*; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/RFC3339DateFormat.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/RFC3339DateFormat.java new file mode 100644 index 00000000000..4aaf6cd1c0c --- /dev/null +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/RFC3339DateFormat.java @@ -0,0 +1,20 @@ +package io.swagger.configuration; + +import com.fasterxml.jackson.databind.util.ISO8601DateFormat; +import com.fasterxml.jackson.databind.util.ISO8601Utils; + +import java.text.FieldPosition; +import java.util.Date; + + +public class RFC3339DateFormat extends ISO8601DateFormat { + + // Same as ISO8601DateFormat but serializing milliseconds. + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + String value = ISO8601Utils.format(date, true); + toAppendTo.append(value); + return toAppendTo; + } + +} \ No newline at end of file diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java index c7614b0015b..e05672181db 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java @@ -1,14 +1,21 @@ package io.swagger.configuration; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.Import; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import springfox.documentation.swagger2.annotations.EnableSwagger2; +import java.util.List; + @Configuration @ComponentScan(basePackages = "io.swagger.api") @@ -51,4 +58,14 @@ public void addResourceHandlers(ResourceHandlerRegistry registry) { } } + @Override + public void configureMessageConverters(List> converters) { + ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json() + .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + .dateFormat( new RFC3339DateFormat()) + .build(); + converters.add(new MappingJackson2HttpMessageConverter(objectMapper)); + super.configureMessageConverters(converters); + } + } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/RFC3339DateFormat.java b/samples/server/petstore/springboot/src/main/java/io/swagger/RFC3339DateFormat.java new file mode 100644 index 00000000000..0c3d276d2d4 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/RFC3339DateFormat.java @@ -0,0 +1,20 @@ +package io.swagger; + +import com.fasterxml.jackson.databind.util.ISO8601DateFormat; +import com.fasterxml.jackson.databind.util.ISO8601Utils; + +import java.text.FieldPosition; +import java.util.Date; + + +public class RFC3339DateFormat extends ISO8601DateFormat { + + // Same as ISO8601DateFormat but serializing milliseconds. + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + String value = ISO8601Utils.format(date, true); + toAppendTo.append(value); + return toAppendTo; + } + +} \ No newline at end of file diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApi.java index a9ed1dede00..262a5fe9a16 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApi.java @@ -2,8 +2,8 @@ import io.swagger.model.Client; import org.joda.time.LocalDate; -import org.joda.time.DateTime; import java.math.BigDecimal; +import org.joda.time.DateTime; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApiController.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApiController.java index 722544de7d3..2115ca4cf68 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApiController.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApiController.java @@ -2,8 +2,8 @@ import io.swagger.model.Client; import org.joda.time.LocalDate; -import org.joda.time.DateTime; import java.math.BigDecimal; +import org.joda.time.DateTime; import io.swagger.annotations.*; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java index 9b937019b32..ea0122441c1 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import java.io.File; import io.swagger.model.ModelApiResponse; +import java.io.File; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java index af909d49ab8..8b95d74de51 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import java.io.File; import io.swagger.model.ModelApiResponse; +import java.io.File; import io.swagger.annotations.*; diff --git a/samples/server/petstore/springboot/src/main/resources/application.properties b/samples/server/petstore/springboot/src/main/resources/application.properties index eb4cac4bec6..a2ef8627027 100644 --- a/samples/server/petstore/springboot/src/main/resources/application.properties +++ b/samples/server/petstore/springboot/src/main/resources/application.properties @@ -1,3 +1,5 @@ springfox.documentation.swagger.v2.path=/api-docs server.contextPath=/v2 -server.port=8080 \ No newline at end of file +server.port=8080 +spring.jackson.date-format=io.swagger.RFC3339DateFormat +spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false \ No newline at end of file From 2d8b8a941f99c239be94a27dc12940d58ebd9688 Mon Sep 17 00:00:00 2001 From: jfiala Date: Mon, 10 Oct 2016 19:30:30 +0200 Subject: [PATCH 433/470] fix AbstractOptionsTest, add default false for USE_BEANVALIDATION --- .../java/io/swagger/codegen/java/JavaClientOptionsTest.java | 2 ++ .../io/swagger/codegen/options/JavaClientOptionsProvider.java | 1 + .../java/io/swagger/codegen/options/JavaOptionsProvider.java | 1 + 3 files changed, 4 insertions(+) diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java index aea42d72401..73dabd98cf2 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java @@ -56,6 +56,8 @@ protected void setExpectations() { times = 1; clientCodegen.setFullJavaUtil(Boolean.valueOf(JavaOptionsProvider.FULL_JAVA_UTIL_VALUE)); times = 1; + clientCodegen.setUseBeanValidation(Boolean.valueOf(JavaOptionsProvider.USE_BEANVALIDATION)); + times = 1; }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaClientOptionsProvider.java index 53cfe826d36..93f83d8eb1b 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaClientOptionsProvider.java @@ -16,6 +16,7 @@ public Map createOptions() { Map options = new HashMap(super.createOptions()); options.put(CodegenConstants.LIBRARY, DEFAULT_LIBRARY_VALUE); options.put(JavaClientCodegen.USE_RX_JAVA, "false"); + options.put(JavaClientCodegen.USE_BEANVALIDATION, "false"); return options; } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java index 468eb5c972f..b8412e79e92 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java @@ -19,6 +19,7 @@ public class JavaOptionsProvider implements OptionsProvider { public static final String SERIALIZABLE_MODEL_VALUE = "false"; public static final String FULL_JAVA_UTIL_VALUE = "true"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final String USE_BEANVALIDATION = "false"; private ImmutableMap options; From 504f8f1f21c41fa5ab29049131891edceada9e4b Mon Sep 17 00:00:00 2001 From: ClayAtWork Date: Mon, 10 Oct 2016 20:45:59 -0700 Subject: [PATCH 434/470] 2208 fix Objc Mapping Generation (#3894) * Change test to test valid compileable code. This is not a Objective-C Generic, but a protocol. This is what the JSONModel mapping library expects * Update implementation to properly render NSDictionaries that will work with JSONModel --- .../java/io/swagger/codegen/languages/ObjcClientCodegen.java | 2 +- .../src/test/java/io/swagger/codegen/objc/ObjcModelTest.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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 c80cc129b62..cb4b76c32bb 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 @@ -359,7 +359,7 @@ public String getTypeDeclaration(Property p) { return getSwaggerType(p) + "*"; } } - return getSwaggerType(p) + "*"; + return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*"; } } else { String swaggerType = getSwaggerType(p); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java index 76e5ced012f..c2d0fd0f7af 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java @@ -224,7 +224,7 @@ public void complexMapPropertyTest() { final CodegenProperty property1 = cm.vars.get(0); Assert.assertEquals(property1.baseName, "children"); Assert.assertEquals(property1.complexType, "SWGChildren"); - Assert.assertEquals(property1.datatype, "NSDictionary*"); + Assert.assertEquals(property1.datatype, "NSDictionary*"); Assert.assertEquals(property1.name, "children"); Assert.assertEquals(property1.baseType, "NSDictionary"); Assert.assertEquals(property1.containerType, "map"); From da6e829c8e1bbcdd48a3bc69370ef04595252821 Mon Sep 17 00:00:00 2001 From: Oliver Vidovic Date: Tue, 11 Oct 2016 11:43:54 -0400 Subject: [PATCH 435/470] issue-890 correct fix for deprecated Jersey method additionally - fixed EnumValueTest to the directory structure based on the declared package - regenerated samples/client/java/jersey1 --- .../src/main/resources/Java/ApiClient.mustache | 2 +- samples/client/petstore/java/jersey1/docs/FakeApi.md | 6 ++++-- .../jersey1/src/main/java/io/swagger/client/ApiClient.java | 2 +- .../src/main/java/io/swagger/client/RFC3339DateFormat.java | 2 +- .../src/main/java/io/swagger/client/api/FakeApi.java | 5 ++++- .../io/swagger/client/model/AdditionalPropertiesClass.java | 4 ++-- .../src/main/java/io/swagger/client/model/Animal.java | 4 ++-- .../src/main/java/io/swagger/client/model/AnimalFarm.java | 4 ++-- .../io/swagger/client/model/ArrayOfArrayOfNumberOnly.java | 4 ++-- .../java/io/swagger/client/model/ArrayOfNumberOnly.java | 4 ++-- .../src/main/java/io/swagger/client/model/ArrayTest.java | 4 ++-- .../jersey1/src/main/java/io/swagger/client/model/Cat.java | 4 ++-- .../src/main/java/io/swagger/client/model/Category.java | 4 ++-- .../src/main/java/io/swagger/client/model/Client.java | 4 ++-- .../jersey1/src/main/java/io/swagger/client/model/Dog.java | 4 ++-- .../src/main/java/io/swagger/client/model/EnumArrays.java | 4 ++-- .../src/main/java/io/swagger/client/model/EnumClass.java | 1 - .../src/main/java/io/swagger/client/model/EnumTest.java | 4 ++-- .../src/main/java/io/swagger/client/model/FormatTest.java | 4 ++-- .../main/java/io/swagger/client/model/HasOnlyReadOnly.java | 4 ++-- .../src/main/java/io/swagger/client/model/MapTest.java | 4 ++-- .../model/MixedPropertiesAndAdditionalPropertiesClass.java | 4 ++-- .../main/java/io/swagger/client/model/Model200Response.java | 4 ++-- .../main/java/io/swagger/client/model/ModelApiResponse.java | 4 ++-- .../src/main/java/io/swagger/client/model/ModelReturn.java | 4 ++-- .../jersey1/src/main/java/io/swagger/client/model/Name.java | 4 ++-- .../src/main/java/io/swagger/client/model/NumberOnly.java | 4 ++-- .../src/main/java/io/swagger/client/model/Order.java | 4 ++-- .../jersey1/src/main/java/io/swagger/client/model/Pet.java | 4 ++-- .../main/java/io/swagger/client/model/ReadOnlyFirst.java | 4 ++-- .../main/java/io/swagger/client/model/SpecialModelName.java | 4 ++-- .../jersey1/src/main/java/io/swagger/client/model/Tag.java | 4 ++-- .../jersey1/src/main/java/io/swagger/client/model/User.java | 4 ++-- .../io/swagger/client/{api => }/model/EnumValueTest.java | 0 34 files changed, 65 insertions(+), 61 deletions(-) rename samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/{api => }/model/EnumValueTest.java (100%) diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index 3209498e234..c34dd51dcea 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -609,7 +609,7 @@ public class ApiClient { statusCode = response.getStatusInfo().getStatusCode(); responseHeaders = response.getHeaders(); - if(response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) { + if(response.getStatusInfo().getStatusCode() == ClientResponse.Status.NO_CONTENT.getStatusCode()) { return null; } else if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { if (returnType == null) diff --git a/samples/client/petstore/java/jersey1/docs/FakeApi.md b/samples/client/petstore/java/jersey1/docs/FakeApi.md index 9012aff618e..29813bd9349 100644 --- a/samples/client/petstore/java/jersey1/docs/FakeApi.md +++ b/samples/client/petstore/java/jersey1/docs/FakeApi.md @@ -54,7 +54,7 @@ No authorization required # **testEndpointParameters** -> testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password) +> testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -90,8 +90,9 @@ byte[] binary = B; // byte[] | None LocalDate date = new LocalDate(); // LocalDate | None DateTime dateTime = new DateTime(); // DateTime | None String password = "password_example"; // String | None +String paramCallback = "paramCallback_example"; // String | None try { - apiInstance.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password); + apiInstance.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); } catch (ApiException e) { System.err.println("Exception when calling FakeApi#testEndpointParameters"); e.printStackTrace(); @@ -115,6 +116,7 @@ Name | Type | Description | Notes **date** | **LocalDate**| None | [optional] **dateTime** | **DateTime**| None | [optional] **password** | **String**| None | [optional] + **paramCallback** | **String**| None | [optional] ### Return type diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java index f371fe400cf..040449d3e4b 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java @@ -622,7 +622,7 @@ public T invokeAPI(String path, String method, List queryParams, Objec statusCode = response.getStatusInfo().getStatusCode(); responseHeaders = response.getHeaders(); - if(response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) { + if(response.getStatusInfo().getStatusCode() == ClientResponse.Status.NO_CONTENT.getStatusCode()) { return null; } else if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { if (returnType == null) diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/RFC3339DateFormat.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/RFC3339DateFormat.java index 3d287008be5..d662f9457d7 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/RFC3339DateFormat.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/RFC3339DateFormat.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java index bbf7b711513..bfa6f66e56d 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java @@ -120,9 +120,10 @@ public Client testClientModel(Client body) throws ApiException { * @param date None (optional) * @param dateTime None (optional) * @param password None (optional) + * @param paramCallback None (optional) * @throws ApiException if fails to make API call */ - public void testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { + public void testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, DateTime dateTime, String password, String paramCallback) throws ApiException { Object localVarPostBody = null; // verify the required parameter 'number' is set @@ -181,6 +182,8 @@ public void testEndpointParameters(BigDecimal number, Double _double, String pat localVarFormParams.put("dateTime", dateTime); if (password != null) localVarFormParams.put("password", password); +if (paramCallback != null) + localVarFormParams.put("callback", paramCallback); final String[] localVarAccepts = { "application/xml; charset=utf-8", "application/json; charset=utf-8" diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 2da13804a0d..db74fca66a7 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -34,12 +34,11 @@ import java.util.List; import java.util.Map; - /** * AdditionalPropertiesClass */ -public class AdditionalPropertiesClass { +public class AdditionalPropertiesClass { @JsonProperty("map_property") private Map mapProperty = new HashMap(); @@ -132,5 +131,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Animal.java index 346da224ad1..6799afd7beb 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Animal.java @@ -31,12 +31,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Animal */ -public class Animal { +public class Animal { @JsonProperty("className") private String className = null; @@ -119,5 +118,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AnimalFarm.java index 563476ccb3d..8a50c9c6cb5 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -30,12 +30,11 @@ import java.util.ArrayList; import java.util.List; - /** * AnimalFarm */ -public class AnimalFarm extends ArrayList { +public class AnimalFarm extends ArrayList { @Override public boolean equals(java.lang.Object o) { @@ -72,5 +71,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index a99f2009385..e57ce230767 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -34,12 +34,11 @@ import java.util.ArrayList; import java.util.List; - /** * ArrayOfArrayOfNumberOnly */ -public class ArrayOfArrayOfNumberOnly { +public class ArrayOfArrayOfNumberOnly { @JsonProperty("ArrayArrayNumber") private List> arrayArrayNumber = new ArrayList>(); @@ -104,5 +103,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index 1aaf27b9921..6dafaf06c62 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -34,12 +34,11 @@ import java.util.ArrayList; import java.util.List; - /** * ArrayOfNumberOnly */ -public class ArrayOfNumberOnly { +public class ArrayOfNumberOnly { @JsonProperty("ArrayNumber") private List arrayNumber = new ArrayList(); @@ -104,5 +103,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayTest.java index 124d8bfa3a1..8bb3d0c57b7 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayTest.java @@ -34,12 +34,11 @@ import java.util.ArrayList; import java.util.List; - /** * ArrayTest */ -public class ArrayTest { +public class ArrayTest { @JsonProperty("array_of_string") private List arrayOfString = new ArrayList(); @@ -160,5 +159,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Cat.java index 41dc312a10f..949df449199 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Cat.java @@ -32,12 +32,11 @@ import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; - /** * Cat */ -public class Cat extends Animal { +public class Cat extends Animal { @JsonProperty("declawed") private Boolean declawed = null; @@ -98,5 +97,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Category.java index ba4ce89c297..b8e278b2a74 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Category.java @@ -31,12 +31,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Category */ -public class Category { +public class Category { @JsonProperty("id") private Long id = null; @@ -119,5 +118,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Client.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Client.java index 43ade4b6fcb..024f8cb3b72 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Client.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Client.java @@ -31,12 +31,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Client */ -public class Client { +public class Client { @JsonProperty("client") private String client = null; @@ -96,5 +95,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Dog.java index 788aee5c226..00e981ab434 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Dog.java @@ -32,12 +32,11 @@ import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; - /** * Dog */ -public class Dog extends Animal { +public class Dog extends Animal { @JsonProperty("breed") private String breed = null; @@ -98,5 +97,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumArrays.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumArrays.java index 45295c524f6..14047380180 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumArrays.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumArrays.java @@ -33,12 +33,11 @@ import java.util.ArrayList; import java.util.List; - /** * EnumArrays */ -public class EnumArrays { +public class EnumArrays { /** * Gets or Sets justSymbol */ @@ -186,5 +185,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumClass.java index f9887c69340..c2f4ae53735 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumClass.java @@ -27,7 +27,6 @@ import java.util.Objects; - import com.fasterxml.jackson.annotation.JsonCreator; /** diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumTest.java index a7268316c40..53665518adb 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumTest.java @@ -31,12 +31,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * EnumTest */ -public class EnumTest { +public class EnumTest { /** * Gets or Sets enumString */ @@ -232,5 +231,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/FormatTest.java index 2b5b4204281..b7f9513f03c 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/FormatTest.java @@ -34,12 +34,11 @@ import org.joda.time.DateTime; import org.joda.time.LocalDate; - /** * FormatTest */ -public class FormatTest { +public class FormatTest { @JsonProperty("integer") private Integer integer = null; @@ -385,5 +384,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java index d874a545244..1cd90edaae8 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -31,12 +31,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * HasOnlyReadOnly */ -public class HasOnlyReadOnly { +public class HasOnlyReadOnly { @JsonProperty("bar") private String bar = null; @@ -101,5 +100,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MapTest.java index f8cf1ad5d1a..60751c48d8c 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MapTest.java @@ -34,12 +34,11 @@ import java.util.List; import java.util.Map; - /** * MapTest */ -public class MapTest { +public class MapTest { @JsonProperty("map_map_of_string") private Map> mapMapOfString = new HashMap>(); @@ -162,5 +161,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 20958fd50d8..b738c397191 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -36,12 +36,11 @@ import java.util.Map; import org.joda.time.DateTime; - /** * MixedPropertiesAndAdditionalPropertiesClass */ -public class MixedPropertiesAndAdditionalPropertiesClass { +public class MixedPropertiesAndAdditionalPropertiesClass { @JsonProperty("uuid") private String uuid = null; @@ -152,5 +151,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Model200Response.java index 8f48dd8020e..849f208ff7a 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Model200Response.java @@ -31,13 +31,12 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Model for testing model name starting with number */ @ApiModel(description = "Model for testing model name starting with number") -public class Model200Response { +public class Model200Response { @JsonProperty("name") private Integer name = null; @@ -120,5 +119,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelApiResponse.java index 70ee2a834c0..79d704bc1bf 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -31,12 +31,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * ModelApiResponse */ -public class ModelApiResponse { +public class ModelApiResponse { @JsonProperty("code") private Integer code = null; @@ -142,5 +141,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelReturn.java index 28294a15090..0d85efb9884 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelReturn.java @@ -31,13 +31,12 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Model for testing reserved words */ @ApiModel(description = "Model for testing reserved words") -public class ModelReturn { +public class ModelReturn { @JsonProperty("return") private Integer _return = null; @@ -97,5 +96,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Name.java index 4b70e8df1a6..cc3e7252197 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Name.java @@ -31,13 +31,12 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Model for testing model name same as property name */ @ApiModel(description = "Model for testing model name same as property name") -public class Name { +public class Name { @JsonProperty("name") private Integer name = null; @@ -148,5 +147,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/NumberOnly.java index ad74058d2e5..c7eb42d616c 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/NumberOnly.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/NumberOnly.java @@ -32,12 +32,11 @@ import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; - /** * NumberOnly */ -public class NumberOnly { +public class NumberOnly { @JsonProperty("JustNumber") private BigDecimal justNumber = null; @@ -97,5 +96,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Order.java index 1616b030b9d..6dd1a55c543 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Order.java @@ -32,12 +32,11 @@ import io.swagger.annotations.ApiModelProperty; import org.joda.time.DateTime; - /** * Order */ -public class Order { +public class Order { @JsonProperty("id") private Long id = null; @@ -244,5 +243,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Pet.java index a89e0ea3e05..06e43f726f3 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Pet.java @@ -35,12 +35,11 @@ import java.util.ArrayList; import java.util.List; - /** * Pet */ -public class Pet { +public class Pet { @JsonProperty("id") private Long id = null; @@ -257,5 +256,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index 63e11bf14fd..5c7ed3ec0a6 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -31,12 +31,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * ReadOnlyFirst */ -public class ReadOnlyFirst { +public class ReadOnlyFirst { @JsonProperty("bar") private String bar = null; @@ -110,5 +109,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/SpecialModelName.java index f8c5c06ca40..74695119c3e 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -31,12 +31,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * SpecialModelName */ -public class SpecialModelName { +public class SpecialModelName { @JsonProperty("$special[property.name]") private Long specialPropertyName = null; @@ -96,5 +95,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Tag.java index 27be94678da..a886efeac4b 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Tag.java @@ -31,12 +31,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Tag */ -public class Tag { +public class Tag { @JsonProperty("id") private Long id = null; @@ -119,5 +118,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/User.java index 84e3b147049..f73fff70097 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/User.java @@ -31,12 +31,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * User */ -public class User { +public class User { @JsonProperty("id") private Long id = null; @@ -257,5 +256,6 @@ private String toIndentedString(java.lang.Object o) { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/model/EnumValueTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/model/EnumValueTest.java similarity index 100% rename from samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/model/EnumValueTest.java rename to samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/model/EnumValueTest.java From 0a2d62a8ba2ecfd479ee2a4449f3af40c036a931 Mon Sep 17 00:00:00 2001 From: Jason Gavris Date: Tue, 11 Oct 2016 12:44:53 -0400 Subject: [PATCH 436/470] [Swift] Add / as enum separator --- .../main/java/io/swagger/codegen/languages/SwiftCodegen.java | 4 ++-- .../test/java/io/swagger/codegen/swift/SwiftCodegenTest.java | 5 +++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java index dc5969fc4b3..b9595c163a6 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java @@ -396,8 +396,8 @@ public String toSwiftyEnumName(String value) { return value; } - char[] separators = {'-', '_', ' ', ':'}; - return WordUtils.capitalizeFully(StringUtils.lowerCase(value), separators).replaceAll("[-_ :]", ""); + char[] separators = {'-', '_', ' ', ':', '/'}; + return WordUtils.capitalizeFully(StringUtils.lowerCase(value), separators).replaceAll("[-_ :/]", ""); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftCodegenTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftCodegenTest.java index 0fbfcf5efea..62a6fb58482 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftCodegenTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftCodegenTest.java @@ -49,6 +49,11 @@ public void testLowercaseWithUnderscore() throws Exception { Assert.assertEquals(swiftCodegen.toSwiftyEnumName("entry_name"), "EntryName"); } + @Test + public void testSlash() throws Exception { + Assert.assertEquals(swiftCodegen.toSwiftyEnumName("application/x-tar"), "ApplicationXTar"); + } + @Test(description = "returns NSData when response format is binary") public void binaryDataTest() { final Swagger model = new SwaggerParser().read("src/test/resources/2_0/binaryDataTest.json"); From 823ce72e2e0748172d9c7e7265f5f2c719a99fa8 Mon Sep 17 00:00:00 2001 From: Nick Maynard Date: Wed, 12 Oct 2016 08:43:44 +0100 Subject: [PATCH 437/470] jaxrs-cxf-cdi POM template (#3958) * Don't refer to missing class in Impl classes * Add POM for jaxrs-cxf-cdi * Correct jaxrs-cxf-cdi artifactId * Update samples for jaxrs-cxf-cdi * Regenerate jaxrs-cxf-cdi samples --- .../JavaJAXRSCXFCDIServerCodegen.java | 29 ++++--- .../JavaJaxRS/cxf-cdi/apiServiceImpl.mustache | 2 +- .../resources/JavaJaxRS/cxf-cdi/pom.mustache | 82 +++++++++++++++++++ samples/server/petstore/jaxrs-cxf-cdi/pom.xml | 82 +++++++++++++++++++ .../java/io/swagger/api/PetApiService.java | 2 +- .../java/io/swagger/api/StoreApiService.java | 2 +- .../java/io/swagger/api/UserApiService.java | 2 +- .../swagger/api/impl/PetApiServiceImpl.java | 19 ++--- .../swagger/api/impl/StoreApiServiceImpl.java | 11 ++- .../swagger/api/impl/UserApiServiceImpl.java | 19 ++--- 10 files changed, 208 insertions(+), 42 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pom.mustache create mode 100644 samples/server/petstore/jaxrs-cxf-cdi/pom.xml diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSCXFCDIServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSCXFCDIServerCodegen.java index ba6737388dc..6dcf3f58075 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSCXFCDIServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSCXFCDIServerCodegen.java @@ -1,5 +1,6 @@ package io.swagger.codegen.languages; +import io.swagger.codegen.*; import io.swagger.codegen.CodegenModel; import io.swagger.codegen.CodegenProperty; @@ -9,17 +10,19 @@ public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen { public JavaJAXRSCXFCDIServerCodegen() { - sourceFolder = "src" + File.separator + "gen" + File.separator + "java"; + artifactId = "swagger-jaxrs-cxf-cdi-server"; - // Three API templates to support CDI injection - apiTemplateFiles.put("apiService.mustache", ".java"); - apiTemplateFiles.put("apiServiceImpl.mustache", ".java"); + sourceFolder = "src" + File.separator + "gen" + File.separator + "java"; - // Use standard types - typeMapping.put("DateTime", "java.util.Date"); + // Three API templates to support CDI injection + apiTemplateFiles.put("apiService.mustache", ".java"); + apiTemplateFiles.put("apiServiceImpl.mustache", ".java"); - // Updated template directory - embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "cxf-cdi"; + // Use standard types + typeMapping.put("DateTime", "java.util.Date"); + + // Updated template directory + embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "cxf-cdi"; } @Override @@ -34,20 +37,22 @@ public void processOpts() super.processOpts(); supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen + + writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); } @Override public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { - super.postProcessModelProperty(model, property); + super.postProcessModelProperty(model, property); - // Reinstate JsonProperty - model.imports.add("JsonProperty"); + // Reinstate JsonProperty + model.imports.add("JsonProperty"); } @Override public String getHelp() { - return "Generates a Java JAXRS Server according to JAXRS 2.0 specification, assuming an Apache CXF runtime and a Java EE runtime with CDI enabled."; + return "Generates a Java JAXRS Server according to JAXRS 2.0 specification, assuming an Apache CXF runtime and a Java EE runtime with CDI enabled."; } } diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/apiServiceImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/apiServiceImpl.mustache index 86c0d872291..bce7fe5e930 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/apiServiceImpl.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/apiServiceImpl.mustache @@ -24,7 +24,7 @@ public class {{classname}}ServiceImpl implements {{classname}}Service { @Override public Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}, {{/allParams}}SecurityContext securityContext) { // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + return Response.ok().entity("magic!").build(); } {{/operation}} } diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pom.mustache new file mode 100644 index 00000000000..a5a683b9748 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pom.mustache @@ -0,0 +1,82 @@ + + 4.0.0 + {{groupId}} + {{artifactId}} + war + {{artifactId}} + {{artifactVersion}} + + + + src/main/java + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.9.1 + + + add-source + generate-sources + + add-source + + + + src/gen/java + + + + + + + + + maven-war-plugin + 3.0.0 + + false + + + + + + + + + + javax + javaee-api + 7.0 + provided + + + + + org.apache.cxf + cxf-rt-frontend-jaxrs + + + 3.0.2 + provided + + + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + [2.8.3,3) + + + + + io.swagger + swagger-annotations + [1.5.3,2) + + + + + \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-cxf-cdi/pom.xml b/samples/server/petstore/jaxrs-cxf-cdi/pom.xml new file mode 100644 index 00000000000..4534f2961ac --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/pom.xml @@ -0,0 +1,82 @@ + + 4.0.0 + io.swagger + swagger-jaxrs-cxf-cdi-server + war + swagger-jaxrs-cxf-cdi-server + 1.0.0 + + + + src/main/java + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.9.1 + + + add-source + generate-sources + + add-source + + + + src/gen/java + + + + + + + + + maven-war-plugin + 3.0.0 + + false + + + + + + + + + + javax + javaee-api + 7.0 + provided + + + + + org.apache.cxf + cxf-rt-frontend-jaxrs + + + 3.0.2 + provided + + + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + [2.8.3,3) + + + + + io.swagger + swagger-annotations + [1.5.3,2) + + + + + \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApiService.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApiService.java index b982f07c1e0..2505bbee827 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApiService.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApiService.java @@ -16,7 +16,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-10-07T11:14:51.064+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-10-11T07:40:42.070+01:00") public interface PetApiService { public Response addPet(Pet body, SecurityContext securityContext); public Response deletePet(Long petId, String apiKey, SecurityContext securityContext); diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApiService.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApiService.java index 5f3c38f2fbc..2dc8535c8e5 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApiService.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApiService.java @@ -15,7 +15,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-10-07T11:14:51.064+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-10-11T07:40:42.070+01:00") public interface StoreApiService { public Response deleteOrder(String orderId, SecurityContext securityContext); public Response getInventory(SecurityContext securityContext); diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApiService.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApiService.java index 5a8b782cd6b..f8c61f5f0a0 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApiService.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApiService.java @@ -15,7 +15,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-10-07T11:14:51.064+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-10-11T07:40:42.070+01:00") public interface UserApiService { public Response createUser(User body, SecurityContext securityContext); public Response createUsersWithArrayInput(List body, SecurityContext securityContext); diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java index cac1469aca1..7923a562ad6 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -10,7 +10,6 @@ import java.io.File; import java.util.List; -import io.swagger.api.NotFoundException; import java.io.InputStream; @@ -19,46 +18,46 @@ import javax.ws.rs.core.SecurityContext; @RequestScoped -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-10-06T16:59:45.939+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-10-11T07:40:42.070+01:00") public class PetApiServiceImpl implements PetApiService { @Override public Response addPet(Pet body, SecurityContext securityContext) { // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + return Response.ok().entity("magic!").build(); } @Override public Response deletePet(Long petId, String apiKey, SecurityContext securityContext) { // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + return Response.ok().entity("magic!").build(); } @Override public Response findPetsByStatus(List status, SecurityContext securityContext) { // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + return Response.ok().entity("magic!").build(); } @Override public Response findPetsByTags(List tags, SecurityContext securityContext) { // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + return Response.ok().entity("magic!").build(); } @Override public Response getPetById(Long petId, SecurityContext securityContext) { // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + return Response.ok().entity("magic!").build(); } @Override public Response updatePet(Pet body, SecurityContext securityContext) { // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + return Response.ok().entity("magic!").build(); } @Override public Response updatePetWithForm(Long petId, String name, String status, SecurityContext securityContext) { // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + return Response.ok().entity("magic!").build(); } @Override public Response uploadFile(Long petId, String additionalMetadata, InputStream fileInputStream, Attachment fileDetail, SecurityContext securityContext) { // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + return Response.ok().entity("magic!").build(); } } diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java index 75ac7c475df..9dfc758effd 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java @@ -9,7 +9,6 @@ import io.swagger.model.Order; import java.util.List; -import io.swagger.api.NotFoundException; import java.io.InputStream; @@ -18,26 +17,26 @@ import javax.ws.rs.core.SecurityContext; @RequestScoped -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-10-06T16:59:45.939+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-10-11T07:40:42.070+01:00") public class StoreApiServiceImpl implements StoreApiService { @Override public Response deleteOrder(String orderId, SecurityContext securityContext) { // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + return Response.ok().entity("magic!").build(); } @Override public Response getInventory(SecurityContext securityContext) { // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + return Response.ok().entity("magic!").build(); } @Override public Response getOrderById(Long orderId, SecurityContext securityContext) { // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + return Response.ok().entity("magic!").build(); } @Override public Response placeOrder(Order body, SecurityContext securityContext) { // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + return Response.ok().entity("magic!").build(); } } diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java index c05deea0ad2..cf89da4b47a 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java @@ -9,7 +9,6 @@ import java.util.List; import java.util.List; -import io.swagger.api.NotFoundException; import java.io.InputStream; @@ -18,46 +17,46 @@ import javax.ws.rs.core.SecurityContext; @RequestScoped -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-10-06T16:59:45.939+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-10-11T07:40:42.070+01:00") public class UserApiServiceImpl implements UserApiService { @Override public Response createUser(User body, SecurityContext securityContext) { // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + return Response.ok().entity("magic!").build(); } @Override public Response createUsersWithArrayInput(List body, SecurityContext securityContext) { // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + return Response.ok().entity("magic!").build(); } @Override public Response createUsersWithListInput(List body, SecurityContext securityContext) { // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + return Response.ok().entity("magic!").build(); } @Override public Response deleteUser(String username, SecurityContext securityContext) { // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + return Response.ok().entity("magic!").build(); } @Override public Response getUserByName(String username, SecurityContext securityContext) { // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + return Response.ok().entity("magic!").build(); } @Override public Response loginUser(String username, String password, SecurityContext securityContext) { // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + return Response.ok().entity("magic!").build(); } @Override public Response logoutUser(SecurityContext securityContext) { // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + return Response.ok().entity("magic!").build(); } @Override public Response updateUser(String username, User body, SecurityContext securityContext) { // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + return Response.ok().entity("magic!").build(); } } From 47d3c3a7678ccd92d829f09d2b8b95a49a38f263 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 12 Oct 2016 15:48:34 +0800 Subject: [PATCH 438/470] update retrofit1,2 samples --- .../client/petstore/java/retrofit/gradlew.bat | 180 ++++++------- .../java/io/swagger/client/api/FakeApi.java | 244 +----------------- .../java/io/swagger/client/api/PetApi.java | 160 ++---------- .../java/io/swagger/client/api/StoreApi.java | 42 +-- .../java/io/swagger/client/api/UserApi.java | 118 +-------- .../petstore/java/retrofit2/gradlew.bat | 180 ++++++------- .../java/io/swagger/client/api/FakeApi.java | 123 +-------- .../java/io/swagger/client/api/PetApi.java | 79 +----- .../java/io/swagger/client/api/StoreApi.java | 21 +- .../java/io/swagger/client/api/UserApi.java | 59 +---- .../petstore/java/retrofit2rx/docs/FakeApi.md | 6 +- .../petstore/java/retrofit2rx/gradlew.bat | 180 ++++++------- .../java/io/swagger/client/api/FakeApi.java | 123 +-------- .../java/io/swagger/client/api/PetApi.java | 79 +----- .../java/io/swagger/client/api/StoreApi.java | 21 +- .../java/io/swagger/client/api/UserApi.java | 59 +---- 16 files changed, 358 insertions(+), 1316 deletions(-) diff --git a/samples/client/petstore/java/retrofit/gradlew.bat b/samples/client/petstore/java/retrofit/gradlew.bat index 72d362dafd8..5f192121eb4 100644 --- a/samples/client/petstore/java/retrofit/gradlew.bat +++ b/samples/client/petstore/java/retrofit/gradlew.bat @@ -1,90 +1,90 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -set CMD_LINE_ARGS=%$ - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java index e1c4644feea..0f8f3975814 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java @@ -8,8 +8,8 @@ import io.swagger.client.model.Client; import org.joda.time.LocalDate; -import java.math.BigDecimal; import org.joda.time.DateTime; +import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; @@ -27,12 +27,7 @@ public interface FakeApi { @PATCH("/fake") Client testClientModel( - - - -@retrofit.http.Body Client body - - + @retrofit.http.Body Client body ); /** @@ -45,12 +40,7 @@ Client testClientModel( @PATCH("/fake") void testClientModel( - - - -@retrofit.http.Body Client body - -, Callback cb + @retrofit.http.Body Client body, Callback cb ); /** * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -76,77 +66,7 @@ void testClientModel( @retrofit.http.FormUrlEncoded @POST("/fake") Void testEndpointParameters( - - - - -@retrofit.http.Field("number") BigDecimal number -, - - - -@retrofit.http.Field("double") Double _double -, - - - -@retrofit.http.Field("pattern_without_delimiter") String patternWithoutDelimiter -, - - - -@retrofit.http.Field("byte") byte[] _byte -, - - - -@retrofit.http.Field("integer") Integer integer -, - - - -@retrofit.http.Field("int32") Integer int32 -, - - - -@retrofit.http.Field("int64") Long int64 -, - - - -@retrofit.http.Field("float") Float _float -, - - - -@retrofit.http.Field("string") String string -, - - - -@retrofit.http.Field("binary") byte[] binary -, - - - -@retrofit.http.Field("date") LocalDate date -, - - - -@retrofit.http.Field("dateTime") DateTime dateTime -, - - - -@retrofit.http.Field("password") String password -, - - - -@retrofit.http.Field("callback") String paramCallback - + @retrofit.http.Field("number") BigDecimal number, @retrofit.http.Field("double") Double _double, @retrofit.http.Field("pattern_without_delimiter") String patternWithoutDelimiter, @retrofit.http.Field("byte") byte[] _byte, @retrofit.http.Field("integer") Integer integer, @retrofit.http.Field("int32") Integer int32, @retrofit.http.Field("int64") Long int64, @retrofit.http.Field("float") Float _float, @retrofit.http.Field("string") String string, @retrofit.http.Field("binary") byte[] binary, @retrofit.http.Field("date") LocalDate date, @retrofit.http.Field("dateTime") DateTime dateTime, @retrofit.http.Field("password") String password, @retrofit.http.Field("callback") String paramCallback ); /** @@ -173,77 +93,7 @@ Void testEndpointParameters( @retrofit.http.FormUrlEncoded @POST("/fake") void testEndpointParameters( - - - - -@retrofit.http.Field("number") BigDecimal number -, - - - -@retrofit.http.Field("double") Double _double -, - - - -@retrofit.http.Field("pattern_without_delimiter") String patternWithoutDelimiter -, - - - -@retrofit.http.Field("byte") byte[] _byte -, - - - -@retrofit.http.Field("integer") Integer integer -, - - - -@retrofit.http.Field("int32") Integer int32 -, - - - -@retrofit.http.Field("int64") Long int64 -, - - - -@retrofit.http.Field("float") Float _float -, - - - -@retrofit.http.Field("string") String string -, - - - -@retrofit.http.Field("binary") byte[] binary -, - - - -@retrofit.http.Field("date") LocalDate date -, - - - -@retrofit.http.Field("dateTime") DateTime dateTime -, - - - -@retrofit.http.Field("password") String password -, - - - -@retrofit.http.Field("callback") String paramCallback -, Callback cb + @retrofit.http.Field("number") BigDecimal number, @retrofit.http.Field("double") Double _double, @retrofit.http.Field("pattern_without_delimiter") String patternWithoutDelimiter, @retrofit.http.Field("byte") byte[] _byte, @retrofit.http.Field("integer") Integer integer, @retrofit.http.Field("int32") Integer int32, @retrofit.http.Field("int64") Long int64, @retrofit.http.Field("float") Float _float, @retrofit.http.Field("string") String string, @retrofit.http.Field("binary") byte[] binary, @retrofit.http.Field("date") LocalDate date, @retrofit.http.Field("dateTime") DateTime dateTime, @retrofit.http.Field("password") String password, @retrofit.http.Field("callback") String paramCallback, Callback cb ); /** * To test enum parameters @@ -263,47 +113,7 @@ void testEndpointParameters( @retrofit.http.FormUrlEncoded @GET("/fake") Void testEnumParameters( - - - - -@retrofit.http.Field("enum_form_string_array") List enumFormStringArray -, - - - -@retrofit.http.Field("enum_form_string") String enumFormString -, - -@retrofit.http.Header("enum_header_string_array") List enumHeaderStringArray - - -, - -@retrofit.http.Header("enum_header_string") String enumHeaderString - - -, @retrofit.http.Query("enum_query_string_array") CSVParams enumQueryStringArray - - - - -, @retrofit.http.Query("enum_query_string") String enumQueryString - - - - -, @retrofit.http.Query("enum_query_integer") BigDecimal enumQueryInteger - - - - -, - - - -@retrofit.http.Field("enum_query_double") Double enumQueryDouble - + @retrofit.http.Field("enum_form_string_array") List enumFormStringArray, @retrofit.http.Field("enum_form_string") String enumFormString, @retrofit.http.Header("enum_header_string_array") List enumHeaderStringArray, @retrofit.http.Header("enum_header_string") String enumHeaderString, @retrofit.http.Query("enum_query_string_array") CSVParams enumQueryStringArray, @retrofit.http.Query("enum_query_string") String enumQueryString, @retrofit.http.Query("enum_query_integer") BigDecimal enumQueryInteger, @retrofit.http.Field("enum_query_double") Double enumQueryDouble ); /** @@ -324,46 +134,6 @@ Void testEnumParameters( @retrofit.http.FormUrlEncoded @GET("/fake") void testEnumParameters( - - - - -@retrofit.http.Field("enum_form_string_array") List enumFormStringArray -, - - - -@retrofit.http.Field("enum_form_string") String enumFormString -, - -@retrofit.http.Header("enum_header_string_array") List enumHeaderStringArray - - -, - -@retrofit.http.Header("enum_header_string") String enumHeaderString - - -, @retrofit.http.Query("enum_query_string_array") CSVParams enumQueryStringArray - - - - -, @retrofit.http.Query("enum_query_string") String enumQueryString - - - - -, @retrofit.http.Query("enum_query_integer") BigDecimal enumQueryInteger - - - - -, - - - -@retrofit.http.Field("enum_query_double") Double enumQueryDouble -, Callback cb + @retrofit.http.Field("enum_form_string_array") List enumFormStringArray, @retrofit.http.Field("enum_form_string") String enumFormString, @retrofit.http.Header("enum_header_string_array") List enumHeaderStringArray, @retrofit.http.Header("enum_header_string") String enumHeaderString, @retrofit.http.Query("enum_query_string_array") CSVParams enumQueryStringArray, @retrofit.http.Query("enum_query_string") String enumQueryString, @retrofit.http.Query("enum_query_integer") BigDecimal enumQueryInteger, @retrofit.http.Field("enum_query_double") Double enumQueryDouble, Callback cb ); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java index eaeb49ffba4..eaaac18845f 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java @@ -7,8 +7,8 @@ import retrofit.mime.*; import io.swagger.client.model.Pet; -import io.swagger.client.model.ModelApiResponse; import java.io.File; +import io.swagger.client.model.ModelApiResponse; import java.util.ArrayList; import java.util.HashMap; @@ -26,12 +26,7 @@ public interface PetApi { @POST("/pet") Void addPet( - - - -@retrofit.http.Body Pet body - - + @retrofit.http.Body Pet body ); /** @@ -44,12 +39,7 @@ Void addPet( @POST("/pet") void addPet( - - - -@retrofit.http.Body Pet body - -, Callback cb + @retrofit.http.Body Pet body, Callback cb ); /** * Deletes a pet @@ -62,17 +52,7 @@ void addPet( @DELETE("/pet/{petId}") Void deletePet( - -@retrofit.http.Path("petId") Long petId - - - -, - -@retrofit.http.Header("api_key") String apiKey - - - + @retrofit.http.Path("petId") Long petId, @retrofit.http.Header("api_key") String apiKey ); /** @@ -86,17 +66,7 @@ Void deletePet( @DELETE("/pet/{petId}") void deletePet( - -@retrofit.http.Path("petId") Long petId - - - -, - -@retrofit.http.Header("api_key") String apiKey - - -, Callback cb + @retrofit.http.Path("petId") Long petId, @retrofit.http.Header("api_key") String apiKey, Callback cb ); /** * Finds Pets by status @@ -109,11 +79,6 @@ void deletePet( @GET("/pet/findByStatus") List findPetsByStatus( @retrofit.http.Query("status") CSVParams status - - - - - ); /** @@ -126,12 +91,7 @@ List findPetsByStatus( @GET("/pet/findByStatus") void findPetsByStatus( - @retrofit.http.Query("status") CSVParams status - - - - -, Callback> cb + @retrofit.http.Query("status") CSVParams status, Callback> cb ); /** * Finds Pets by tags @@ -144,11 +104,6 @@ void findPetsByStatus( @GET("/pet/findByTags") List findPetsByTags( @retrofit.http.Query("tags") CSVParams tags - - - - - ); /** @@ -161,12 +116,7 @@ List findPetsByTags( @GET("/pet/findByTags") void findPetsByTags( - @retrofit.http.Query("tags") CSVParams tags - - - - -, Callback> cb + @retrofit.http.Query("tags") CSVParams tags, Callback> cb ); /** * Find pet by ID @@ -178,12 +128,7 @@ void findPetsByTags( @GET("/pet/{petId}") Pet getPetById( - -@retrofit.http.Path("petId") Long petId - - - - + @retrofit.http.Path("petId") Long petId ); /** @@ -196,12 +141,7 @@ Pet getPetById( @GET("/pet/{petId}") void getPetById( - -@retrofit.http.Path("petId") Long petId - - - -, Callback cb + @retrofit.http.Path("petId") Long petId, Callback cb ); /** * Update an existing pet @@ -213,12 +153,7 @@ void getPetById( @PUT("/pet") Void updatePet( - - - -@retrofit.http.Body Pet body - - + @retrofit.http.Body Pet body ); /** @@ -231,12 +166,7 @@ Void updatePet( @PUT("/pet") void updatePet( - - - -@retrofit.http.Body Pet body - -, Callback cb + @retrofit.http.Body Pet body, Callback cb ); /** * Updates a pet in the store with form data @@ -251,22 +181,7 @@ void updatePet( @retrofit.http.FormUrlEncoded @POST("/pet/{petId}") Void updatePetWithForm( - -@retrofit.http.Path("petId") Long petId - - - -, - - - -@retrofit.http.Field("name") String name -, - - - -@retrofit.http.Field("status") String status - + @retrofit.http.Path("petId") Long petId, @retrofit.http.Field("name") String name, @retrofit.http.Field("status") String status ); /** @@ -282,22 +197,7 @@ Void updatePetWithForm( @retrofit.http.FormUrlEncoded @POST("/pet/{petId}") void updatePetWithForm( - -@retrofit.http.Path("petId") Long petId - - - -, - - - -@retrofit.http.Field("name") String name -, - - - -@retrofit.http.Field("status") String status -, Callback cb + @retrofit.http.Path("petId") Long petId, @retrofit.http.Field("name") String name, @retrofit.http.Field("status") String status, Callback cb ); /** * uploads an image @@ -312,22 +212,7 @@ void updatePetWithForm( @retrofit.http.Multipart @POST("/pet/{petId}/uploadImage") ModelApiResponse uploadFile( - -@retrofit.http.Path("petId") Long petId - - - -, - - - -@retrofit.http.Part("additionalMetadata") String additionalMetadata -, - - - -@retrofit.http.Part("file") TypedFile file - + @retrofit.http.Path("petId") Long petId, @retrofit.http.Part("additionalMetadata") String additionalMetadata, @retrofit.http.Part("file") TypedFile file ); /** @@ -343,21 +228,6 @@ ModelApiResponse uploadFile( @retrofit.http.Multipart @POST("/pet/{petId}/uploadImage") void uploadFile( - -@retrofit.http.Path("petId") Long petId - - - -, - - - -@retrofit.http.Part("additionalMetadata") String additionalMetadata -, - - - -@retrofit.http.Part("file") TypedFile file -, Callback cb + @retrofit.http.Path("petId") Long petId, @retrofit.http.Part("additionalMetadata") String additionalMetadata, @retrofit.http.Part("file") TypedFile file, Callback cb ); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java index f9fed4bd1ce..c29f87ef9cc 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java @@ -24,12 +24,7 @@ public interface StoreApi { @DELETE("/store/order/{orderId}") Void deleteOrder( - -@retrofit.http.Path("orderId") String orderId - - - - + @retrofit.http.Path("orderId") String orderId ); /** @@ -42,12 +37,7 @@ Void deleteOrder( @DELETE("/store/order/{orderId}") void deleteOrder( - -@retrofit.http.Path("orderId") String orderId - - - -, Callback cb + @retrofit.http.Path("orderId") String orderId, Callback cb ); /** * Returns pet inventories by status @@ -81,12 +71,7 @@ void getInventory( @GET("/store/order/{orderId}") Order getOrderById( - -@retrofit.http.Path("orderId") Long orderId - - - - + @retrofit.http.Path("orderId") Long orderId ); /** @@ -99,12 +84,7 @@ Order getOrderById( @GET("/store/order/{orderId}") void getOrderById( - -@retrofit.http.Path("orderId") Long orderId - - - -, Callback cb + @retrofit.http.Path("orderId") Long orderId, Callback cb ); /** * Place an order for a pet @@ -116,12 +96,7 @@ void getOrderById( @POST("/store/order") Order placeOrder( - - - -@retrofit.http.Body Order body - - + @retrofit.http.Body Order body ); /** @@ -134,11 +109,6 @@ Order placeOrder( @POST("/store/order") void placeOrder( - - - -@retrofit.http.Body Order body - -, Callback cb + @retrofit.http.Body Order body, Callback cb ); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java index 7de0bc3fb1a..43876970c3f 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java @@ -24,12 +24,7 @@ public interface UserApi { @POST("/user") Void createUser( - - - -@retrofit.http.Body User body - - + @retrofit.http.Body User body ); /** @@ -42,12 +37,7 @@ Void createUser( @POST("/user") void createUser( - - - -@retrofit.http.Body User body - -, Callback cb + @retrofit.http.Body User body, Callback cb ); /** * Creates list of users with given input array @@ -59,12 +49,7 @@ void createUser( @POST("/user/createWithArray") Void createUsersWithArrayInput( - - - -@retrofit.http.Body List body - - + @retrofit.http.Body List body ); /** @@ -77,12 +62,7 @@ Void createUsersWithArrayInput( @POST("/user/createWithArray") void createUsersWithArrayInput( - - - -@retrofit.http.Body List body - -, Callback cb + @retrofit.http.Body List body, Callback cb ); /** * Creates list of users with given input array @@ -94,12 +74,7 @@ void createUsersWithArrayInput( @POST("/user/createWithList") Void createUsersWithListInput( - - - -@retrofit.http.Body List body - - + @retrofit.http.Body List body ); /** @@ -112,12 +87,7 @@ Void createUsersWithListInput( @POST("/user/createWithList") void createUsersWithListInput( - - - -@retrofit.http.Body List body - -, Callback cb + @retrofit.http.Body List body, Callback cb ); /** * Delete user @@ -129,12 +99,7 @@ void createUsersWithListInput( @DELETE("/user/{username}") Void deleteUser( - -@retrofit.http.Path("username") String username - - - - + @retrofit.http.Path("username") String username ); /** @@ -147,12 +112,7 @@ Void deleteUser( @DELETE("/user/{username}") void deleteUser( - -@retrofit.http.Path("username") String username - - - -, Callback cb + @retrofit.http.Path("username") String username, Callback cb ); /** * Get user by user name @@ -164,12 +124,7 @@ void deleteUser( @GET("/user/{username}") User getUserByName( - -@retrofit.http.Path("username") String username - - - - + @retrofit.http.Path("username") String username ); /** @@ -182,12 +137,7 @@ User getUserByName( @GET("/user/{username}") void getUserByName( - -@retrofit.http.Path("username") String username - - - -, Callback cb + @retrofit.http.Path("username") String username, Callback cb ); /** * Logs user into the system @@ -200,17 +150,7 @@ void getUserByName( @GET("/user/login") String loginUser( - @retrofit.http.Query("username") String username - - - - -, @retrofit.http.Query("password") String password - - - - - + @retrofit.http.Query("username") String username, @retrofit.http.Query("password") String password ); /** @@ -224,17 +164,7 @@ String loginUser( @GET("/user/login") void loginUser( - @retrofit.http.Query("username") String username - - - - -, @retrofit.http.Query("password") String password - - - - -, Callback cb + @retrofit.http.Query("username") String username, @retrofit.http.Query("password") String password, Callback cb ); /** * Logs out current logged in user session @@ -269,17 +199,7 @@ void logoutUser( @PUT("/user/{username}") Void updateUser( - -@retrofit.http.Path("username") String username - - - -, - - -@retrofit.http.Body User body - - + @retrofit.http.Path("username") String username, @retrofit.http.Body User body ); /** @@ -293,16 +213,6 @@ Void updateUser( @PUT("/user/{username}") void updateUser( - -@retrofit.http.Path("username") String username - - - -, - - -@retrofit.http.Body User body - -, Callback cb + @retrofit.http.Path("username") String username, @retrofit.http.Body User body, Callback cb ); } diff --git a/samples/client/petstore/java/retrofit2/gradlew.bat b/samples/client/petstore/java/retrofit2/gradlew.bat index 72d362dafd8..5f192121eb4 100644 --- a/samples/client/petstore/java/retrofit2/gradlew.bat +++ b/samples/client/petstore/java/retrofit2/gradlew.bat @@ -1,90 +1,90 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -set CMD_LINE_ARGS=%$ - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java index 7479e230574..d1068513f0e 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java @@ -10,8 +10,8 @@ import io.swagger.client.model.Client; import org.joda.time.LocalDate; -import java.math.BigDecimal; import org.joda.time.DateTime; +import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; @@ -28,12 +28,7 @@ public interface FakeApi { @PATCH("fake") Call testClientModel( - - - -@retrofit2.http.Body Client body - - + @retrofit2.http.Body Client body ); /** @@ -59,77 +54,7 @@ Call testClientModel( @retrofit2.http.FormUrlEncoded @POST("fake") Call testEndpointParameters( - - - - -@retrofit2.http.Field("number") BigDecimal number -, - - - -@retrofit2.http.Field("double") Double _double -, - - - -@retrofit2.http.Field("pattern_without_delimiter") String patternWithoutDelimiter -, - - - -@retrofit2.http.Field("byte") byte[] _byte -, - - - -@retrofit2.http.Field("integer") Integer integer -, - - - -@retrofit2.http.Field("int32") Integer int32 -, - - - -@retrofit2.http.Field("int64") Long int64 -, - - - -@retrofit2.http.Field("float") Float _float -, - - - -@retrofit2.http.Field("string") String string -, - - - -@retrofit2.http.Field("binary") byte[] binary -, - - - -@retrofit2.http.Field("date") LocalDate date -, - - - -@retrofit2.http.Field("dateTime") DateTime dateTime -, - - - -@retrofit2.http.Field("password") String password -, - - - -@retrofit2.http.Field("callback") String paramCallback - + @retrofit2.http.Field("number") BigDecimal number, @retrofit2.http.Field("double") Double _double, @retrofit2.http.Field("pattern_without_delimiter") String patternWithoutDelimiter, @retrofit2.http.Field("byte") byte[] _byte, @retrofit2.http.Field("integer") Integer integer, @retrofit2.http.Field("int32") Integer int32, @retrofit2.http.Field("int64") Long int64, @retrofit2.http.Field("float") Float _float, @retrofit2.http.Field("string") String string, @retrofit2.http.Field("binary") byte[] binary, @retrofit2.http.Field("date") LocalDate date, @retrofit2.http.Field("dateTime") DateTime dateTime, @retrofit2.http.Field("password") String password, @retrofit2.http.Field("callback") String paramCallback ); /** @@ -149,47 +74,7 @@ Call testEndpointParameters( @retrofit2.http.FormUrlEncoded @GET("fake") Call testEnumParameters( - - - - -@retrofit2.http.Field("enum_form_string_array") List enumFormStringArray -, - - - -@retrofit2.http.Field("enum_form_string") String enumFormString -, - -@retrofit2.http.Header("enum_header_string_array") List enumHeaderStringArray - - -, - -@retrofit2.http.Header("enum_header_string") String enumHeaderString - - -, @retrofit2.http.Query("enum_query_string_array") CSVParams enumQueryStringArray - - - - -, @retrofit2.http.Query("enum_query_string") String enumQueryString - - - - -, @retrofit2.http.Query("enum_query_integer") BigDecimal enumQueryInteger - - - - -, - - - -@retrofit2.http.Field("enum_query_double") Double enumQueryDouble - + @retrofit2.http.Field("enum_form_string_array") List enumFormStringArray, @retrofit2.http.Field("enum_form_string") String enumFormString, @retrofit2.http.Header("enum_header_string_array") List enumHeaderStringArray, @retrofit2.http.Header("enum_header_string") String enumHeaderString, @retrofit2.http.Query("enum_query_string_array") CSVParams enumQueryStringArray, @retrofit2.http.Query("enum_query_string") String enumQueryString, @retrofit2.http.Query("enum_query_integer") BigDecimal enumQueryInteger, @retrofit2.http.Field("enum_query_double") Double enumQueryDouble ); } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java index bd13312f581..3f61279a66b 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java @@ -9,8 +9,8 @@ import okhttp3.RequestBody; import io.swagger.client.model.Pet; -import io.swagger.client.model.ModelApiResponse; import java.io.File; +import io.swagger.client.model.ModelApiResponse; import java.util.ArrayList; import java.util.HashMap; @@ -27,12 +27,7 @@ public interface PetApi { @POST("pet") Call addPet( - - - -@retrofit2.http.Body Pet body - - + @retrofit2.http.Body Pet body ); /** @@ -45,17 +40,7 @@ Call addPet( @DELETE("pet/{petId}") Call deletePet( - -@retrofit2.http.Path("petId") Long petId - - - -, - -@retrofit2.http.Header("api_key") String apiKey - - - + @retrofit2.http.Path("petId") Long petId, @retrofit2.http.Header("api_key") String apiKey ); /** @@ -68,11 +53,6 @@ Call deletePet( @GET("pet/findByStatus") Call> findPetsByStatus( @retrofit2.http.Query("status") CSVParams status - - - - - ); /** @@ -85,11 +65,6 @@ Call> findPetsByStatus( @GET("pet/findByTags") Call> findPetsByTags( @retrofit2.http.Query("tags") CSVParams tags - - - - - ); /** @@ -101,12 +76,7 @@ Call> findPetsByTags( @GET("pet/{petId}") Call getPetById( - -@retrofit2.http.Path("petId") Long petId - - - - + @retrofit2.http.Path("petId") Long petId ); /** @@ -118,12 +88,7 @@ Call getPetById( @PUT("pet") Call updatePet( - - - -@retrofit2.http.Body Pet body - - + @retrofit2.http.Body Pet body ); /** @@ -138,22 +103,7 @@ Call updatePet( @retrofit2.http.FormUrlEncoded @POST("pet/{petId}") Call updatePetWithForm( - -@retrofit2.http.Path("petId") Long petId - - - -, - - - -@retrofit2.http.Field("name") String name -, - - - -@retrofit2.http.Field("status") String status - + @retrofit2.http.Path("petId") Long petId, @retrofit2.http.Field("name") String name, @retrofit2.http.Field("status") String status ); /** @@ -168,22 +118,7 @@ Call updatePetWithForm( @retrofit2.http.Multipart @POST("pet/{petId}/uploadImage") Call uploadFile( - -@retrofit2.http.Path("petId") Long petId - - - -, - - - -@retrofit2.http.Part("additionalMetadata") String additionalMetadata -, - - - -@retrofit2.http.Part("file\"; filename=\"file") RequestBody file - + @retrofit2.http.Path("petId") Long petId, @retrofit2.http.Part("additionalMetadata") String additionalMetadata, @retrofit2.http.Part("file\"; filename=\"file") RequestBody file ); } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java index ebed8da8f52..f9df7d8e8d6 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java @@ -25,12 +25,7 @@ public interface StoreApi { @DELETE("store/order/{orderId}") Call deleteOrder( - -@retrofit2.http.Path("orderId") String orderId - - - - + @retrofit2.http.Path("orderId") String orderId ); /** @@ -52,12 +47,7 @@ Call deleteOrder( @GET("store/order/{orderId}") Call getOrderById( - -@retrofit2.http.Path("orderId") Long orderId - - - - + @retrofit2.http.Path("orderId") Long orderId ); /** @@ -69,12 +59,7 @@ Call getOrderById( @POST("store/order") Call placeOrder( - - - -@retrofit2.http.Body Order body - - + @retrofit2.http.Body Order body ); } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java index 1bf7d34d73c..ee1114dc2dc 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java @@ -25,12 +25,7 @@ public interface UserApi { @POST("user") Call createUser( - - - -@retrofit2.http.Body User body - - + @retrofit2.http.Body User body ); /** @@ -42,12 +37,7 @@ Call createUser( @POST("user/createWithArray") Call createUsersWithArrayInput( - - - -@retrofit2.http.Body List body - - + @retrofit2.http.Body List body ); /** @@ -59,12 +49,7 @@ Call createUsersWithArrayInput( @POST("user/createWithList") Call createUsersWithListInput( - - - -@retrofit2.http.Body List body - - + @retrofit2.http.Body List body ); /** @@ -76,12 +61,7 @@ Call createUsersWithListInput( @DELETE("user/{username}") Call deleteUser( - -@retrofit2.http.Path("username") String username - - - - + @retrofit2.http.Path("username") String username ); /** @@ -93,12 +73,7 @@ Call deleteUser( @GET("user/{username}") Call getUserByName( - -@retrofit2.http.Path("username") String username - - - - + @retrofit2.http.Path("username") String username ); /** @@ -111,17 +86,7 @@ Call getUserByName( @GET("user/login") Call loginUser( - @retrofit2.http.Query("username") String username - - - - -, @retrofit2.http.Query("password") String password - - - - - + @retrofit2.http.Query("username") String username, @retrofit2.http.Query("password") String password ); /** @@ -144,17 +109,7 @@ Call loginUser( @PUT("user/{username}") Call updateUser( - -@retrofit2.http.Path("username") String username - - - -, - - -@retrofit2.http.Body User body - - + @retrofit2.http.Path("username") String username, @retrofit2.http.Body User body ); } diff --git a/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md b/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md index f4cfc7e19cc..2e2b792d8d3 100644 --- a/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md +++ b/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md @@ -54,7 +54,7 @@ No authorization required # **testEndpointParameters** -> Void testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password) +> Void testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -90,8 +90,9 @@ byte[] binary = B; // byte[] | None LocalDate date = new LocalDate(); // LocalDate | None DateTime dateTime = new DateTime(); // DateTime | None String password = "password_example"; // String | None +String paramCallback = "paramCallback_example"; // String | None try { - Void result = apiInstance.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password); + Void result = apiInstance.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling FakeApi#testEndpointParameters"); @@ -116,6 +117,7 @@ Name | Type | Description | Notes **date** | **LocalDate**| None | [optional] **dateTime** | **DateTime**| None | [optional] **password** | **String**| None | [optional] + **paramCallback** | **String**| None | [optional] ### Return type diff --git a/samples/client/petstore/java/retrofit2rx/gradlew.bat b/samples/client/petstore/java/retrofit2rx/gradlew.bat index 72d362dafd8..5f192121eb4 100644 --- a/samples/client/petstore/java/retrofit2rx/gradlew.bat +++ b/samples/client/petstore/java/retrofit2rx/gradlew.bat @@ -1,90 +1,90 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -set CMD_LINE_ARGS=%$ - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java index 924c81ff6dc..2b832afd1ef 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java @@ -10,8 +10,8 @@ import io.swagger.client.model.Client; import org.joda.time.LocalDate; -import java.math.BigDecimal; import org.joda.time.DateTime; +import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; @@ -28,12 +28,7 @@ public interface FakeApi { @PATCH("fake") Observable testClientModel( - - - -@retrofit2.http.Body Client body - - + @retrofit2.http.Body Client body ); /** @@ -59,77 +54,7 @@ Observable testClientModel( @retrofit2.http.FormUrlEncoded @POST("fake") Observable testEndpointParameters( - - - - -@retrofit2.http.Field("number") BigDecimal number -, - - - -@retrofit2.http.Field("double") Double _double -, - - - -@retrofit2.http.Field("pattern_without_delimiter") String patternWithoutDelimiter -, - - - -@retrofit2.http.Field("byte") byte[] _byte -, - - - -@retrofit2.http.Field("integer") Integer integer -, - - - -@retrofit2.http.Field("int32") Integer int32 -, - - - -@retrofit2.http.Field("int64") Long int64 -, - - - -@retrofit2.http.Field("float") Float _float -, - - - -@retrofit2.http.Field("string") String string -, - - - -@retrofit2.http.Field("binary") byte[] binary -, - - - -@retrofit2.http.Field("date") LocalDate date -, - - - -@retrofit2.http.Field("dateTime") DateTime dateTime -, - - - -@retrofit2.http.Field("password") String password -, - - - -@retrofit2.http.Field("callback") String paramCallback - + @retrofit2.http.Field("number") BigDecimal number, @retrofit2.http.Field("double") Double _double, @retrofit2.http.Field("pattern_without_delimiter") String patternWithoutDelimiter, @retrofit2.http.Field("byte") byte[] _byte, @retrofit2.http.Field("integer") Integer integer, @retrofit2.http.Field("int32") Integer int32, @retrofit2.http.Field("int64") Long int64, @retrofit2.http.Field("float") Float _float, @retrofit2.http.Field("string") String string, @retrofit2.http.Field("binary") byte[] binary, @retrofit2.http.Field("date") LocalDate date, @retrofit2.http.Field("dateTime") DateTime dateTime, @retrofit2.http.Field("password") String password, @retrofit2.http.Field("callback") String paramCallback ); /** @@ -149,47 +74,7 @@ Observable testEndpointParameters( @retrofit2.http.FormUrlEncoded @GET("fake") Observable testEnumParameters( - - - - -@retrofit2.http.Field("enum_form_string_array") List enumFormStringArray -, - - - -@retrofit2.http.Field("enum_form_string") String enumFormString -, - -@retrofit2.http.Header("enum_header_string_array") List enumHeaderStringArray - - -, - -@retrofit2.http.Header("enum_header_string") String enumHeaderString - - -, @retrofit2.http.Query("enum_query_string_array") CSVParams enumQueryStringArray - - - - -, @retrofit2.http.Query("enum_query_string") String enumQueryString - - - - -, @retrofit2.http.Query("enum_query_integer") BigDecimal enumQueryInteger - - - - -, - - - -@retrofit2.http.Field("enum_query_double") Double enumQueryDouble - + @retrofit2.http.Field("enum_form_string_array") List enumFormStringArray, @retrofit2.http.Field("enum_form_string") String enumFormString, @retrofit2.http.Header("enum_header_string_array") List enumHeaderStringArray, @retrofit2.http.Header("enum_header_string") String enumHeaderString, @retrofit2.http.Query("enum_query_string_array") CSVParams enumQueryStringArray, @retrofit2.http.Query("enum_query_string") String enumQueryString, @retrofit2.http.Query("enum_query_integer") BigDecimal enumQueryInteger, @retrofit2.http.Field("enum_query_double") Double enumQueryDouble ); } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java index cc6a867c755..3c183bb08f9 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java @@ -9,8 +9,8 @@ import okhttp3.RequestBody; import io.swagger.client.model.Pet; -import io.swagger.client.model.ModelApiResponse; import java.io.File; +import io.swagger.client.model.ModelApiResponse; import java.util.ArrayList; import java.util.HashMap; @@ -27,12 +27,7 @@ public interface PetApi { @POST("pet") Observable addPet( - - - -@retrofit2.http.Body Pet body - - + @retrofit2.http.Body Pet body ); /** @@ -45,17 +40,7 @@ Observable addPet( @DELETE("pet/{petId}") Observable deletePet( - -@retrofit2.http.Path("petId") Long petId - - - -, - -@retrofit2.http.Header("api_key") String apiKey - - - + @retrofit2.http.Path("petId") Long petId, @retrofit2.http.Header("api_key") String apiKey ); /** @@ -68,11 +53,6 @@ Observable deletePet( @GET("pet/findByStatus") Observable> findPetsByStatus( @retrofit2.http.Query("status") CSVParams status - - - - - ); /** @@ -85,11 +65,6 @@ Observable> findPetsByStatus( @GET("pet/findByTags") Observable> findPetsByTags( @retrofit2.http.Query("tags") CSVParams tags - - - - - ); /** @@ -101,12 +76,7 @@ Observable> findPetsByTags( @GET("pet/{petId}") Observable getPetById( - -@retrofit2.http.Path("petId") Long petId - - - - + @retrofit2.http.Path("petId") Long petId ); /** @@ -118,12 +88,7 @@ Observable getPetById( @PUT("pet") Observable updatePet( - - - -@retrofit2.http.Body Pet body - - + @retrofit2.http.Body Pet body ); /** @@ -138,22 +103,7 @@ Observable updatePet( @retrofit2.http.FormUrlEncoded @POST("pet/{petId}") Observable updatePetWithForm( - -@retrofit2.http.Path("petId") Long petId - - - -, - - - -@retrofit2.http.Field("name") String name -, - - - -@retrofit2.http.Field("status") String status - + @retrofit2.http.Path("petId") Long petId, @retrofit2.http.Field("name") String name, @retrofit2.http.Field("status") String status ); /** @@ -168,22 +118,7 @@ Observable updatePetWithForm( @retrofit2.http.Multipart @POST("pet/{petId}/uploadImage") Observable uploadFile( - -@retrofit2.http.Path("petId") Long petId - - - -, - - - -@retrofit2.http.Part("additionalMetadata") String additionalMetadata -, - - - -@retrofit2.http.Part("file\"; filename=\"file") RequestBody file - + @retrofit2.http.Path("petId") Long petId, @retrofit2.http.Part("additionalMetadata") String additionalMetadata, @retrofit2.http.Part("file\"; filename=\"file") RequestBody file ); } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java index f763e317070..e8eac3c525b 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java @@ -25,12 +25,7 @@ public interface StoreApi { @DELETE("store/order/{orderId}") Observable deleteOrder( - -@retrofit2.http.Path("orderId") String orderId - - - - + @retrofit2.http.Path("orderId") String orderId ); /** @@ -52,12 +47,7 @@ Observable deleteOrder( @GET("store/order/{orderId}") Observable getOrderById( - -@retrofit2.http.Path("orderId") Long orderId - - - - + @retrofit2.http.Path("orderId") Long orderId ); /** @@ -69,12 +59,7 @@ Observable getOrderById( @POST("store/order") Observable placeOrder( - - - -@retrofit2.http.Body Order body - - + @retrofit2.http.Body Order body ); } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/UserApi.java index 4f13893a8f8..579134971f8 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/UserApi.java @@ -25,12 +25,7 @@ public interface UserApi { @POST("user") Observable createUser( - - - -@retrofit2.http.Body User body - - + @retrofit2.http.Body User body ); /** @@ -42,12 +37,7 @@ Observable createUser( @POST("user/createWithArray") Observable createUsersWithArrayInput( - - - -@retrofit2.http.Body List body - - + @retrofit2.http.Body List body ); /** @@ -59,12 +49,7 @@ Observable createUsersWithArrayInput( @POST("user/createWithList") Observable createUsersWithListInput( - - - -@retrofit2.http.Body List body - - + @retrofit2.http.Body List body ); /** @@ -76,12 +61,7 @@ Observable createUsersWithListInput( @DELETE("user/{username}") Observable deleteUser( - -@retrofit2.http.Path("username") String username - - - - + @retrofit2.http.Path("username") String username ); /** @@ -93,12 +73,7 @@ Observable deleteUser( @GET("user/{username}") Observable getUserByName( - -@retrofit2.http.Path("username") String username - - - - + @retrofit2.http.Path("username") String username ); /** @@ -111,17 +86,7 @@ Observable getUserByName( @GET("user/login") Observable loginUser( - @retrofit2.http.Query("username") String username - - - - -, @retrofit2.http.Query("password") String password - - - - - + @retrofit2.http.Query("username") String username, @retrofit2.http.Query("password") String password ); /** @@ -144,17 +109,7 @@ Observable loginUser( @PUT("user/{username}") Observable updateUser( - -@retrofit2.http.Path("username") String username - - - -, - - -@retrofit2.http.Body User body - - + @retrofit2.http.Path("username") String username, @retrofit2.http.Body User body ); } From 0efa5cab353c4c7ac83f5313a8046180c2acdb24 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 12 Oct 2016 16:07:37 +0800 Subject: [PATCH 439/470] Revert "[WIP] Improve PHP client emitted code quality" --- .../src/main/resources/php/ApiClient.mustache | 154 ++++++++---------- .../main/resources/php/ApiException.mustache | 6 +- .../resources/php/ObjectSerializer.mustache | 6 +- .../src/main/resources/php/api.mustache | 29 ++-- .../src/main/resources/php/api_test.mustache | 7 + .../main/resources/php/configuration.mustache | 35 +--- .../src/main/resources/php/model.mustache | 1 - .../main/resources/php/model_generic.mustache | 6 +- 8 files changed, 106 insertions(+), 138 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index bbe7d20ad92..effdbedb7f8 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -31,13 +31,13 @@ namespace {{invokerPackage}}; */ class ApiClient { - public static $PATCH = 'PATCH'; - public static $POST = 'POST'; - public static $GET = 'GET'; - public static $HEAD = 'HEAD'; - public static $OPTIONS = 'OPTIONS'; - public static $PUT = 'PUT'; - public static $DELETE = 'DELETE'; + public static $PATCH = "PATCH"; + public static $POST = "POST"; + public static $GET = "GET"; + public static $HEAD = "HEAD"; + public static $OPTIONS = "OPTIONS"; + public static $PUT = "PUT"; + public static $DELETE = "DELETE"; /** * Configuration @@ -58,7 +58,7 @@ class ApiClient * * @param Configuration $config config for this ApiClient */ - public function __construct(Configuration $config = null) + public function __construct(\{{invokerPackage}}\Configuration $config = null) { if ($config === null) { $config = Configuration::getDefaultConfiguration(); @@ -91,7 +91,7 @@ class ApiClient /** * Get API key (with prefix if set) * - * @param string $apiKeyIdentifier name of API key + * @param string $apiKeyIdentifier name of apikey * * @return string API key with the prefix */ @@ -100,13 +100,14 @@ class ApiClient $prefix = $this->config->getApiKeyPrefix($apiKeyIdentifier); $apiKey = $this->config->getApiKey($apiKeyIdentifier); - if ($apiKey === null) { + if (!isset($apiKey)) { return null; } - $keyWithPrefix = $apiKey; - if ($prefix !== null) { - $keyWithPrefix = $prefix.' '.$apiKey; + if (isset($prefix)) { + $keyWithPrefix = $prefix." ".$apiKey; + } else { + $keyWithPrefix = $apiKey; } return $keyWithPrefix; @@ -115,24 +116,19 @@ class ApiClient /** * Make the HTTP call (Sync) * - * @param string $resourcePath path to method endpoint - * @param string $method method to call - * @param array $queryParams parameters to be place in query URL - * @param array|string $postData parameters to be placed in POST body - * @param array $headerParams parameters to be place in request header - * @param string $responseType expected response type of the endpoint + * @param string $resourcePath path to method endpoint + * @param string $method method to call + * @param array $queryParams parameters to be place in query URL + * @param array $postData parameters to be placed in POST body + * @param array $headerParams parameters to be place in request header + * @param string $responseType expected response type of the endpoint + * @param string $endpointPath path to method endpoint before expanding parameters * - * @throws ApiException on a non 2xx response + * @throws \{{invokerPackage}}\ApiException on a non 2xx response * @return mixed */ - public function callApi( - $resourcePath, - $method, - array $queryParams, - $postData, - array $headerParams, - $responseType = null - ) { + public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType = null, $endpointPath = null) + { $headers = []; // construct the http header @@ -146,10 +142,10 @@ class ApiClient } // form data - if (is_array($postData) && in_array('Content-Type: application/x-www-form-urlencoded', $headers, true)) { + if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers, true)) { $postData = http_build_query($postData); - } elseif ((is_object($postData) || is_array($postData)) && !in_array('Content-Type: multipart/form-data', $headers, true)) { // json model - $postData = json_encode(ObjectSerializer::sanitizeForSerialization($postData)); + } elseif ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers, true)) { // json model + $postData = json_encode(\{{invokerPackage}}\ObjectSerializer::sanitizeForSerialization($postData)); } $url = $this->config->getHost() . $resourcePath; @@ -165,12 +161,12 @@ class ApiClient curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); // disable SSL verification, if needed - if ($this->config->isSSLVerification() === false) { + if ($this->config->getSSLVerification() === false) { curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); } - if ($queryParams !== null) { + if (!empty($queryParams)) { $url = ($url . '?' . http_build_query($queryParams)); } @@ -180,16 +176,16 @@ class ApiClient } elseif ($method === self::$HEAD) { curl_setopt($curl, CURLOPT_NOBODY, true); } elseif ($method === self::$OPTIONS) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'OPTIONS'); + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "OPTIONS"); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); } elseif ($method === self::$PATCH) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PATCH'); + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH"); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); } elseif ($method === self::$PUT) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT'); + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); } elseif ($method === self::$DELETE) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE'); + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); } elseif ($method !== self::$GET) { throw new ApiException('Method ' . $method . ' is not recognized.'); @@ -200,12 +196,8 @@ class ApiClient curl_setopt($curl, CURLOPT_USERAGENT, $this->config->getUserAgent()); // debugging for curl - if ($this->config->isDebug()) { - error_log( - '[DEBUG] HTTP Request body ~BEGIN~'.PHP_EOL.print_r($postData, true).PHP_EOL.'~END~'.PHP_EOL, - 3, - $this->config->getDebugFile() - ); + if ($this->config->getDebug()) { + error_log("[DEBUG] HTTP Request body ~BEGIN~".PHP_EOL.print_r($postData, true).PHP_EOL."~END~".PHP_EOL, 3, $this->config->getDebugFile()); curl_setopt($curl, CURLOPT_VERBOSE, 1); curl_setopt($curl, CURLOPT_STDERR, fopen($this->config->getDebugFile(), 'a')); @@ -218,59 +210,55 @@ class ApiClient // Make the request $response = curl_exec($curl); - $httpHeaderSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE); - $httpHeader = $this->httpParseHeaders(substr($response, 0, $httpHeaderSize)); - $httpBody = substr($response, $httpHeaderSize); - $responseInfo = curl_getinfo($curl); + $http_header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); + $http_header = $this->httpParseHeaders(substr($response, 0, $http_header_size)); + $http_body = substr($response, $http_header_size); + $response_info = curl_getinfo($curl); // debug HTTP response body - if ($this->config->isDebug()) { - error_log( - '[DEBUG] HTTP Response body ~BEGIN~'.PHP_EOL.print_r($httpBody, true).PHP_EOL.'~END~'.PHP_EOL, - 3, - $this->config->getDebugFile() - ); + if ($this->config->getDebug()) { + error_log("[DEBUG] HTTP Response body ~BEGIN~".PHP_EOL.print_r($http_body, true).PHP_EOL."~END~".PHP_EOL, 3, $this->config->getDebugFile()); } // Handle the response - if ($responseInfo['http_code'] === 0) { - $curlErrorMessage = curl_error($curl); + if ($response_info['http_code'] === 0) { + $curl_error_message = curl_error($curl); // curl_exec can sometimes fail but still return a blank message from curl_error(). - if ($curlErrorMessage !== '') { - $errorMessage = 'API call to '.$url.' failed: '.$curlErrorMessage; + if (!empty($curl_error_message)) { + $error_message = "API call to $url failed: $curl_error_message"; } else { - $errorMessage = 'API call to '.$url.' failed, but for an unknown reason. ' . - 'This could happen if you are disconnected from the network.'; + $error_message = "API call to $url failed, but for an unknown reason. " . + "This could happen if you are disconnected from the network."; } - $exception = new ApiException($errorMessage, 0, null, null); - $exception->setResponseObject($responseInfo); + $exception = new ApiException($error_message, 0, null, null); + $exception->setResponseObject($response_info); throw $exception; - } elseif ($responseInfo['http_code'] >= 200 && $responseInfo['http_code'] <= 299) { + } elseif ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299) { // return raw body if response is a file if ($responseType === '\SplFileObject' || $responseType === 'string') { - return [$httpBody, $responseInfo['http_code'], $httpHeader]; + return [$http_body, $response_info['http_code'], $http_header]; } - $data = json_decode($httpBody); + $data = json_decode($http_body); if (json_last_error() > 0) { // if response is a string - $data = $httpBody; + $data = $http_body; } } else { - $data = json_decode($httpBody); + $data = json_decode($http_body); if (json_last_error() > 0) { // if response is a string - $data = $httpBody; + $data = $http_body; } throw new ApiException( - '['.$responseInfo['http_code'].'] Error connecting to the API ('.$url.')', - $responseInfo['http_code'], - $httpHeader, + "[".$response_info['http_code']."] Error connecting to the API ($url)", + $response_info['http_code'], + $http_header, $data ); } - return [$data, $responseInfo['http_code'], $httpHeader]; + return [$data, $response_info['http_code'], $http_header]; } /** @@ -282,9 +270,9 @@ class ApiClient */ public function selectHeaderAccept($accept) { - if (count($accept) === 0 || (count($accept) === 1 && $accept[0] === '')) { + if (count($accept) === 0 or (count($accept) === 1 and $accept[0] === '')) { return null; - } elseif (preg_grep('/application\\/json/i', $accept)) { + } elseif (preg_grep("/application\/json/i", $accept)) { return 'application/json'; } else { return implode(',', $accept); @@ -294,35 +282,35 @@ class ApiClient /** * Return the content type based on an array of content-type provided * - * @param string[] $contentType Array for Content-type + * @param string[] $content_type Array fo content-type * * @return string Content-Type (e.g. application/json) */ - public function selectHeaderContentType($contentType) + public function selectHeaderContentType($content_type) { - if (count($contentType) === 0 || (count($contentType) === 1 && $contentType[0] === '')) { + if (count($content_type) === 0 or (count($content_type) === 1 and $content_type[0] === '')) { return 'application/json'; - } elseif (preg_grep('/application\\/json/i', $contentType)) { + } elseif (preg_grep("/application\/json/i", $content_type)) { return 'application/json'; } else { - return implode(',', $contentType); + return implode(',', $content_type); } } /** * Return an array of HTTP response headers * - * @param string $rawHeaders A string of raw HTTP response headers + * @param string $raw_headers A string of raw HTTP response headers * - * @return string[] Array of HTTP response headers + * @return string[] Array of HTTP response heaers */ - protected function httpParseHeaders($rawHeaders) + protected function httpParseHeaders($raw_headers) { // ref/credit: http://php.net/manual/en/function.http-parse-headers.php#112986 $headers = []; $key = ''; - foreach (explode("\n", $rawHeaders) as $h) { + foreach (explode("\n", $raw_headers) as $h) { $h = explode(':', $h, 2); if (isset($h[1])) { @@ -336,7 +324,7 @@ class ApiClient $key = $h[0]; } else { - if (strpos($h[0], "\t") === 0) { + if (substr($h[0], 0, 1) === "\t") { $headers[$key] .= "\r\n\t".trim($h[0]); } elseif (!$key) { $headers[0] = trim($h[0]); diff --git a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache index 2ec9079d555..f99a793fbc6 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache @@ -62,7 +62,7 @@ class ApiException extends Exception * @param string $responseHeaders HTTP response header * @param mixed $responseBody HTTP body of the server response either as Json or string */ - public function __construct($message = '', $code = 0, $responseHeaders = null, $responseBody = null) + public function __construct($message = "", $code = 0, $responseHeaders = null, $responseBody = null) { parent::__construct($message, $code); $this->responseHeaders = $responseHeaders; @@ -90,7 +90,7 @@ class ApiException extends Exception } /** - * Sets the deserialized response object (during deserialization) + * Sets the deseralized response object (during deserialization) * * @param mixed $obj Deserialized response object * @@ -102,7 +102,7 @@ class ApiException extends Exception } /** - * Gets the deserialized response object (during deserialization) + * Gets the deseralized response object (during deserialization) * * @return mixed the deserialized response object */ diff --git a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache index 5495b4f4611..7208e4c7784 100644 --- a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache @@ -213,7 +213,7 @@ class ObjectSerializer } elseif (substr($class, 0, 4) === 'map[') { // for associative array e.g. map[string,int] $inner = substr($class, 4, -1); $deserialized = []; - if (strrpos($inner, ',') !== false) { + if (strrpos($inner, ",") !== false) { $subClass_array = explode(',', $inner, 2); $subClass = $subClass_array[1]; foreach ($data as $key => $value) { @@ -254,9 +254,9 @@ class ObjectSerializer } else { $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); } - $deserialized = new \SplFileObject($filename, 'w'); + $deserialized = new \SplFileObject($filename, "w"); $byte_written = $deserialized->fwrite($data); - if (Configuration::getDefaultConfiguration()->isDebug()) { + if (Configuration::getDefaultConfiguration()->getDebug()) { error_log("[DEBUG] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file after processing.".PHP_EOL, 3, Configuration::getDefaultConfiguration()->getDebugFile()); } diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index ef0139e23fe..26583a6f3d1 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -21,6 +21,8 @@ namespace {{apiPackage}}; use \{{invokerPackage}}\ApiClient; use \{{invokerPackage}}\ApiException; +use \{{invokerPackage}}\Configuration; +use \{{invokerPackage}}\ObjectSerializer; /** * {{classname}} Class Doc Comment @@ -36,28 +38,29 @@ use \{{invokerPackage}}\ApiException; /** * API Client * - * @var ApiClient instance of the ApiClient + * @var \{{invokerPackage}}\ApiClient instance of the ApiClient */ protected $apiClient; /** * Constructor * - * @param ApiClient|null $apiClient The API client to use + * @param \{{invokerPackage}}\ApiClient|null $apiClient The api client to use */ - public function __construct(ApiClient $apiClient = null) + public function __construct(\{{invokerPackage}}\ApiClient $apiClient = null) { if ($apiClient === null) { $apiClient = new ApiClient(); $apiClient->getConfig()->setHost('{{basePath}}'); } - $this->setApiClient($apiClient); + + $this->apiClient = $apiClient; } /** * Get API client * - * @return ApiClient get the API client + * @return \{{invokerPackage}}\ApiClient get the API client */ public function getApiClient() { @@ -67,11 +70,11 @@ use \{{invokerPackage}}\ApiException; /** * Set the API client * - * @param ApiClient $apiClient set the API client + * @param \{{invokerPackage}}\ApiClient $apiClient set the API client * * @return {{classname}} */ - public function setApiClient(ApiClient $apiClient) + public function setApiClient(\{{invokerPackage}}\ApiClient $apiClient) { $this->apiClient = $apiClient; return $this; @@ -112,7 +115,6 @@ use \{{invokerPackage}}\ApiException; * @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} {{/allParams}} * @throws \{{invokerPackage}}\ApiException on non-2xx response - * @throws \InvalidArgumentException * @return array of {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}null{{/returnType}}, HTTP status code, HTTP response headers (array of strings) */ public function {{operationId}}WithHttpInfo({{#allParams}}${{paramName}}{{^required}} = null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) @@ -164,7 +166,7 @@ use \{{invokerPackage}}\ApiException; {{/hasValidation}} {{/allParams}} // parse inputs - $resourcePath = '{{path}}'; + $resourcePath = "{{path}}"; $httpBody = ''; $queryParams = []; $headerParams = []; @@ -206,14 +208,14 @@ use \{{invokerPackage}}\ApiException; {{/collectionFormat}} if (${{paramName}} !== null) { $resourcePath = str_replace( - '{'.'{{baseName}}'.'}', + "{" . "{{baseName}}" . "}", $this->apiClient->getSerializer()->toPathValue(${{paramName}}), $resourcePath ); } {{/pathParams}} // default format to json - $resourcePath = str_replace('{format}', 'json', $resourcePath); + $resourcePath = str_replace("{format}", "json", $resourcePath); {{#formParams}} // form params @@ -275,11 +277,12 @@ use \{{invokerPackage}}\ApiException; $httpBody, $headerParams, {{#returnType}} - '{{returnType}}' + '{{returnType}}', {{/returnType}} {{^returnType}} - null + null, {{/returnType}} + '{{path}}' ); {{#returnType}} diff --git a/modules/swagger-codegen/src/main/resources/php/api_test.mustache b/modules/swagger-codegen/src/main/resources/php/api_test.mustache index c4a549caace..99ad7065c9b 100644 --- a/modules/swagger-codegen/src/main/resources/php/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api_test.mustache @@ -19,6 +19,11 @@ namespace {{invokerPackage}}; +use \{{invokerPackage}}\Configuration; +use \{{invokerPackage}}\ApiClient; +use \{{invokerPackage}}\ApiException; +use \{{invokerPackage}}\ObjectSerializer; + /** * {{classname}}Test Class Doc Comment * @@ -30,6 +35,7 @@ namespace {{invokerPackage}}; */ {{#operations}}class {{classname}}Test extends \PHPUnit_Framework_TestCase { + /** * Setup before running any test cases */ @@ -67,6 +73,7 @@ namespace {{invokerPackage}}; * Test case for {{{operationId}}} * * {{{summary}}}. + * */ public function test{{vendorExtensions.x-testOperationId}}() { diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/configuration.mustache index 94104b781b8..bae256b3bd3 100644 --- a/modules/swagger-codegen/src/main/resources/php/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/configuration.mustache @@ -31,10 +31,7 @@ namespace {{invokerPackage}}; */ class Configuration { - /** - * @var Configuration - */ - private static $defaultConfiguration; + private static $defaultConfiguration = null; /** * Associate array to store API key(s) @@ -97,7 +94,7 @@ class Configuration * * @var string */ - protected $userAgent = '{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{#artifactVersion}}{{{.}}}{{/artifactVersion}}{{^artifactVersion}}1.0.0{{/artifactVersion}}/php{{/httpUserAgent}}'; + protected $userAgent = "{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{#artifactVersion}}{{{.}}}{{/artifactVersion}}{{^artifactVersion}}1.0.0{{/artifactVersion}}/php{{/httpUserAgent}}"; /** * Debug switch (default set to false) @@ -264,7 +261,6 @@ class Configuration * @param string $headerName header name (e.g. Token) * @param string $headerValue header value (e.g. 1z8wp3) * - * @throws \InvalidArgumentException * @return Configuration */ public function addDefaultHeader($headerName, $headerValue) @@ -297,7 +293,6 @@ class Configuration public function deleteDefaultHeader($headerName) { unset($this->defaultHeaders[$headerName]); - return $this; } /** @@ -328,7 +323,6 @@ class Configuration * * @param string $userAgent the user agent of the api client * - * @throws \InvalidArgumentException * @return Configuration */ public function setUserAgent($userAgent) @@ -356,7 +350,6 @@ class Configuration * * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] * - * @throws \InvalidArgumentException * @return Configuration */ public function setCurlTimeout($seconds) @@ -397,17 +390,6 @@ class Configuration * * @return bool */ - public function isDebug() - { - return $this->debug; - } - - /** - * Gets the debug flag - * - * @return bool - * @deprecated - */ public function getDebug() { return $this->debug; @@ -477,17 +459,6 @@ class Configuration * * @return boolean True if the certificate should be validated, false otherwise */ - public function isSSLVerification() - { - return $this->sslVerification; - } - - /** - * Gets if SSL verification should be enabled or disabled - * - * @return boolean True if the certificate should be validated, false otherwise - * @deprecated - */ public function getSSLVerification() { return $this->sslVerification; @@ -508,7 +479,7 @@ class Configuration } /** - * Sets the default configuration instance + * Sets the detault configuration instance * * @param Configuration $config An instance of the Configuration Object * diff --git a/modules/swagger-codegen/src/main/resources/php/model.mustache b/modules/swagger-codegen/src/main/resources/php/model.mustache index 04f178091e5..efecdf2e596 100644 --- a/modules/swagger-codegen/src/main/resources/php/model.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model.mustache @@ -23,7 +23,6 @@ namespace {{modelPackage}}; use \ArrayAccess; -use \{{invokerPackage}}\ObjectSerializer; /** * {{classname}} Class Doc Comment diff --git a/modules/swagger-codegen/src/main/resources/php/model_generic.mustache b/modules/swagger-codegen/src/main/resources/php/model_generic.mustache index 3937e8d9838..1e221b78377 100644 --- a/modules/swagger-codegen/src/main/resources/php/model_generic.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model_generic.mustache @@ -183,7 +183,7 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple * validate all the properties in the model * return true if all passed * - * @return bool True if all properties are valid + * @return bool True if all properteis are valid */ public function valid() { @@ -365,9 +365,9 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple public function __toString() { if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print - return json_encode(ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); + return json_encode(\{{invokerPackage}}\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); } - return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + return json_encode(\{{invokerPackage}}\ObjectSerializer::sanitizeForSerialization($this)); } } \ No newline at end of file From a76d69513c03baf5675d3ae8826315fcafa07ccc Mon Sep 17 00:00:00 2001 From: weiyang Date: Wed, 12 Oct 2016 17:14:36 +0800 Subject: [PATCH 440/470] [html]Group api index by operations.baseName (#3953) * [html]Group api index by operations.baseName Signed-off-by: weiyang * [html][samples]Group api index by operations.baseName Signed-off-by: weiyang --- .../main/resources/htmlDocs/index.mustache | 10 +++++---- .../resources/htmlDocs/style.css.mustache | 5 ++--- samples/html/index.html | 22 ++++++++++++++----- 3 files changed, 24 insertions(+), 13 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache index 3c49831c8e8..466df75c41f 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache @@ -28,23 +28,25 @@ [ Jump to Models ] {{! for the tables of content, I cheat and don't use CSS styles.... }} -

Table of Contents

+

Table of Contents

{{access}}
{{#apiInfo}} -
    {{#apis}} {{#operations}} +

    {{baseName}}

    + {{/operations}} {{/apis}} -
{{/apiInfo}} {{#apiInfo}} {{#apis}} {{#operations}} +

{{baseName}}

{{#operation}}
@@ -150,7 +152,7 @@

Models

[ Jump to Methods ] -

Table of Contents

+

Table of Contents

    {{#models}} {{#model}} diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/style.css.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/style.css.mustache index 8d9a5755d7b..04eccf69491 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/style.css.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/style.css.mustache @@ -1,4 +1,4 @@ -body { +body { font-family: Trebuchet MS, sans-serif; font-size: 15px; color: #444; @@ -20,7 +20,6 @@ hr { border: 0; color: #ddd; background-color: #ddd; - display: none; } .app-desc { @@ -170,4 +169,4 @@ font-style: italic; color: #FFF; display: inline-block; text-decoration: none; -} \ No newline at end of file +} diff --git a/samples/html/index.html b/samples/html/index.html index 18b6a2fa44c..d83d25c03a5 100644 --- a/samples/html/index.html +++ b/samples/html/index.html @@ -3,7 +3,7 @@ Swagger Petstore @@ -196,9 +196,10 @@

    Access

    Methods

    [ Jump to Models ] -

    Table of Contents

    +

    Table of Contents

    -
      +

      Pet

      + +

      Store

      + +

      User

      +
    + +

    Pet

    Up @@ -683,6 +691,7 @@

    200

    ApiResponse

    +

    Store

    Up @@ -896,6 +905,7 @@

    400


    +

    User

    Up @@ -1254,7 +1264,7 @@

    404

    Models

    [ Jump to Methods ] -

    Table of Contents

    +

    Table of Contents

    1. ApiResponse
    2. Category
    3. From 34f1e3614660f0771d3798eb34f464c04de0f057 Mon Sep 17 00:00:00 2001 From: Hamed Ramezanian Date: Thu, 13 Oct 2016 07:41:40 +0100 Subject: [PATCH 441/470] Sanitize tuples properly (#3949) * Sanitize tuples properly In Python, Tuples are fixed size in nature whereas lists are dynamic. So they should be sanitize as same as lists. Failure case here is when you have a query or post parameter as Datetime. * Update the Petstore sample * Skip file sanitization * Return tuple instead of list * Sanitize all tuples, no exceptions --- .../src/main/resources/python/api_client.mustache | 5 ++++- samples/client/petstore/python/petstore_api/api_client.py | 5 ++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index 3879b3cd706..0a5864a81af 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -176,7 +176,7 @@ class ApiClient(object): :param obj: The data to serialize. :return: The serialized form of data. """ - types = (str, float, bool, tuple) + tuple(integer_types) + (text_type,) + types = (str, float, bool, bytes) + tuple(integer_types) + (text_type,) if isinstance(obj, type(None)): return None elif isinstance(obj, types): @@ -184,6 +184,9 @@ class ApiClient(object): elif isinstance(obj, list): return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj] + elif isinstance(obj, tuple): + return tuple(self.sanitize_for_serialization(sub_obj) + for sub_obj in obj) elif isinstance(obj, (datetime, date)): return obj.isoformat() else: diff --git a/samples/client/petstore/python/petstore_api/api_client.py b/samples/client/petstore/python/petstore_api/api_client.py index 2c8dc409135..adf66173dbc 100644 --- a/samples/client/petstore/python/petstore_api/api_client.py +++ b/samples/client/petstore/python/petstore_api/api_client.py @@ -176,7 +176,7 @@ def sanitize_for_serialization(self, obj): :param obj: The data to serialize. :return: The serialized form of data. """ - types = (str, float, bool, tuple) + tuple(integer_types) + (text_type,) + types = (str, float, bool, bytes) + tuple(integer_types) + (text_type,) if isinstance(obj, type(None)): return None elif isinstance(obj, types): @@ -184,6 +184,9 @@ def sanitize_for_serialization(self, obj): elif isinstance(obj, list): return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj] + elif isinstance(obj, tuple): + return tuple(self.sanitize_for_serialization(sub_obj) + for sub_obj in obj) elif isinstance(obj, (datetime, date)): return obj.isoformat() else: From d0f3cd642d01de18017c2a3d0b999c2337230219 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 13 Oct 2016 15:28:11 +0800 Subject: [PATCH 442/470] fix missing () in python doc --- .../swagger-codegen/src/main/resources/python/README.mustache | 2 +- samples/client/petstore/python/README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/README.mustache b/modules/swagger-codegen/src/main/resources/python/README.mustache index 9f592946b06..9f432447443 100644 --- a/modules/swagger-codegen/src/main/resources/python/README.mustache +++ b/modules/swagger-codegen/src/main/resources/python/README.mustache @@ -70,7 +70,7 @@ from pprint import pprint {{{packageName}}}.configuration.access_token = 'YOUR_ACCESS_TOKEN'{{/isOAuth}}{{/authMethods}} {{/hasAuthMethods}} # create an instance of the API class -api_instance = {{{packageName}}}.{{{classname}}} +api_instance = {{{packageName}}}.{{{classname}}}() {{#allParams}}{{paramName}} = {{{example}}} # {{{dataType}}} | {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} {{/allParams}} diff --git a/samples/client/petstore/python/README.md b/samples/client/petstore/python/README.md index ec654c5190e..7b29cebd534 100644 --- a/samples/client/petstore/python/README.md +++ b/samples/client/petstore/python/README.md @@ -51,7 +51,7 @@ import petstore_api from petstore_api.rest import ApiException from pprint import pprint # create an instance of the API class -api_instance = petstore_api.FakeApi +api_instance = petstore_api.FakeApi() body = petstore_api.Client() # Client | client model try: From 47c387470c12f6e3f69225e1ff95409dd117074e Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 13 Oct 2016 16:38:39 +0800 Subject: [PATCH 443/470] fix required prop check for ruby client --- .../resources/ruby/partial_model_generic.mustache | 4 ++-- .../petstore/ruby/lib/petstore/models/animal.rb | 4 ++++ .../client/petstore/ruby/lib/petstore/models/cat.rb | 4 ++++ .../client/petstore/ruby/lib/petstore/models/dog.rb | 4 ++++ .../ruby/lib/petstore/models/format_test.rb | 13 ++++++++----- .../petstore/ruby/lib/petstore/models/name.rb | 4 ++++ .../client/petstore/ruby/lib/petstore/models/pet.rb | 8 ++++++++ 7 files changed, 34 insertions(+), 7 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/ruby/partial_model_generic.mustache b/modules/swagger-codegen/src/main/resources/ruby/partial_model_generic.mustache index 20662ae9771..00a75b25396 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/partial_model_generic.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/partial_model_generic.mustache @@ -78,13 +78,13 @@ def list_invalid_properties invalid_properties = Array.new {{#vars}} - {{#hasValidation}} {{#required}} if @{{{name}}}.nil? invalid_properties.push("invalid value for '{{{name}}}', {{{name}}} cannot be nil.") end - {{/required}} + {{/required}} + {{#hasValidation}} {{#maxLength}} if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.to_s.length > {{{maxLength}}} invalid_properties.push("invalid value for '{{{name}}}', the character length must be smaller than or equal to {{{maxLength}}}.") diff --git a/samples/client/petstore/ruby/lib/petstore/models/animal.rb b/samples/client/petstore/ruby/lib/petstore/models/animal.rb index 7dad66580fa..0e941aa2657 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/animal.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/animal.rb @@ -71,6 +71,10 @@ def initialize(attributes = {}) # @return Array for valid properies with the reasons def list_invalid_properties invalid_properties = Array.new + if @class_name.nil? + invalid_properties.push("invalid value for 'class_name', class_name cannot be nil.") + end + return invalid_properties end diff --git a/samples/client/petstore/ruby/lib/petstore/models/cat.rb b/samples/client/petstore/ruby/lib/petstore/models/cat.rb index 7ed6e12ddd0..3d42282a5f4 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/cat.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/cat.rb @@ -79,6 +79,10 @@ def initialize(attributes = {}) # @return Array for valid properies with the reasons def list_invalid_properties invalid_properties = Array.new + if @class_name.nil? + invalid_properties.push("invalid value for 'class_name', class_name cannot be nil.") + end + return invalid_properties end diff --git a/samples/client/petstore/ruby/lib/petstore/models/dog.rb b/samples/client/petstore/ruby/lib/petstore/models/dog.rb index 0e8a993caea..addfdcfec84 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/dog.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/dog.rb @@ -79,6 +79,10 @@ def initialize(attributes = {}) # @return Array for valid properies with the reasons def list_invalid_properties invalid_properties = Array.new + if @class_name.nil? + invalid_properties.push("invalid value for 'class_name', class_name cannot be nil.") + end + return invalid_properties end diff --git a/samples/client/petstore/ruby/lib/petstore/models/format_test.rb b/samples/client/petstore/ruby/lib/petstore/models/format_test.rb index f734b42b993..75b105e8678 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/format_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/format_test.rb @@ -157,7 +157,6 @@ def initialize(attributes = {}) # @return Array for valid properies with the reasons def list_invalid_properties invalid_properties = Array.new - if !@integer.nil? && @integer > 100.0 invalid_properties.push("invalid value for 'integer', must be smaller than or equal to 100.0.") end @@ -166,7 +165,6 @@ def list_invalid_properties invalid_properties.push("invalid value for 'integer', must be greater than or equal to 10.0.") end - if !@int32.nil? && @int32 > 200.0 invalid_properties.push("invalid value for 'int32', must be smaller than or equal to 200.0.") end @@ -187,7 +185,6 @@ def list_invalid_properties invalid_properties.push("invalid value for 'number', must be greater than or equal to 32.1.") end - if !@float.nil? && @float > 987.6 invalid_properties.push("invalid value for 'float', must be smaller than or equal to 987.6.") end @@ -196,7 +193,6 @@ def list_invalid_properties invalid_properties.push("invalid value for 'float', must be greater than or equal to 54.3.") end - if !@double.nil? && @double > 123.4 invalid_properties.push("invalid value for 'double', must be smaller than or equal to 123.4.") end @@ -205,11 +201,18 @@ def list_invalid_properties invalid_properties.push("invalid value for 'double', must be greater than or equal to 67.8.") end - if !@string.nil? && @string !~ Regexp.new(/[a-z]/i) invalid_properties.push("invalid value for 'string', must conform to the pattern /[a-z]/i.") end + if @byte.nil? + invalid_properties.push("invalid value for 'byte', byte cannot be nil.") + end + + if @date.nil? + invalid_properties.push("invalid value for 'date', date cannot be nil.") + end + if @password.nil? invalid_properties.push("invalid value for 'password', password cannot be nil.") end diff --git a/samples/client/petstore/ruby/lib/petstore/models/name.rb b/samples/client/petstore/ruby/lib/petstore/models/name.rb index 27a37cdc19c..47b1319b638 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/name.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/name.rb @@ -85,6 +85,10 @@ def initialize(attributes = {}) # @return Array for valid properies with the reasons def list_invalid_properties invalid_properties = Array.new + if @name.nil? + invalid_properties.push("invalid value for 'name', name cannot be nil.") + end + return invalid_properties end diff --git a/samples/client/petstore/ruby/lib/petstore/models/pet.rb b/samples/client/petstore/ruby/lib/petstore/models/pet.rb index 52191258d7a..18ad44b0830 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/pet.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/pet.rb @@ -127,6 +127,14 @@ def initialize(attributes = {}) # @return Array for valid properies with the reasons def list_invalid_properties invalid_properties = Array.new + if @name.nil? + invalid_properties.push("invalid value for 'name', name cannot be nil.") + end + + if @photo_urls.nil? + invalid_properties.push("invalid value for 'photo_urls', photo_urls cannot be nil.") + end + return invalid_properties end From 4b0d58abfd4a93d4f526055132478694ad602184 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 13 Oct 2016 18:15:04 +0800 Subject: [PATCH 444/470] fix hasHeaderParams tag --- .../codegen/languages/ConfluenceWikiGenerator.java | 12 ++++++++++++ .../main/resources/confluenceWikiDocs/index.mustache | 6 +++--- .../src/main/resources/htmlDocs/index.mustache | 4 ++-- samples/documentation/cwiki/confluence-markup.txt | 4 +++- samples/html/index.html | 4 ++++ 5 files changed, 24 insertions(+), 6 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ConfluenceWikiGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ConfluenceWikiGenerator.java index 747dcdfd769..972721bcfa1 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ConfluenceWikiGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ConfluenceWikiGenerator.java @@ -92,4 +92,16 @@ public Map postProcessOperations(Map objs) { } return objs; } + + @Override + public String escapeQuotationMark(String input) { + // just return the original string + return input; + } + + @Override + public String escapeUnsafeCharacters(String input) { + // just return the original string + return input; + } } diff --git a/modules/swagger-codegen/src/main/resources/confluenceWikiDocs/index.mustache b/modules/swagger-codegen/src/main/resources/confluenceWikiDocs/index.mustache index 0a90ab4c549..28312bb4b74 100644 --- a/modules/swagger-codegen/src/main/resources/confluenceWikiDocs/index.mustache +++ b/modules/swagger-codegen/src/main/resources/confluenceWikiDocs/index.mustache @@ -32,12 +32,12 @@ h2. Endpoints {{/bodyParams}} {{/hasBodyParam}} - {{#hasHeaderParam}} + {{#hasHeaderParams}} h5. Header Parameters ||Name||Description||Required||Default||Pattern|| {{#headerParam}}{{>param}} {{/headerParam}} - {{/hasHeaderParam}} + {{/hasHeaderParams}} {{#hasQueryParams}} h5. Query Parameters @@ -91,4 +91,4 @@ h2. Models {{#vars}} |{{name}} |{{#isNotRequired}}(x){{/isNotRequired}} |{{datatype}} |{{description}} | {{/vars}} {{/model}} -{{/models}} \ No newline at end of file +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache index 466df75c41f..d3c2681bced 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache @@ -80,12 +80,12 @@
    {{/hasBodyParam}} - {{#hasHeaderParam}} + {{#hasHeaderParams}}

    Request headers

    {{#headerParam}}{{>headerParam}}{{/headerParam}}
    - {{/hasHeaderParam}} + {{/hasHeaderParams}} {{#hasQueryParams}}

    Query parameters

    diff --git a/samples/documentation/cwiki/confluence-markup.txt b/samples/documentation/cwiki/confluence-markup.txt index dcbba6877a7..83996a97de8 100644 --- a/samples/documentation/cwiki/confluence-markup.txt +++ b/samples/documentation/cwiki/confluence-markup.txt @@ -60,7 +60,9 @@ h2. Endpoints |petId |Pet id to delete |(/) | | | - + h5. Header Parameters + ||Name||Description||Required||Default||Pattern|| + diff --git a/samples/html/index.html b/samples/html/index.html index d83d25c03a5..425b46386d2 100644 --- a/samples/html/index.html +++ b/samples/html/index.html @@ -288,6 +288,10 @@

    Path parameters

    +

    Request headers

    +
    + +
    From e101d22bc3d35d4622bcf7b295a28befba0e23fc Mon Sep 17 00:00:00 2001 From: Radim Date: Thu, 13 Oct 2016 13:46:37 +0200 Subject: [PATCH 445/470] typo relesae -> release --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 33706464129..6546e9d8926 100644 --- a/README.md +++ b/README.md @@ -151,7 +151,7 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ ``` (if you're on Windows, replace the last command with `java -jar modules\swagger-codegen-cli\target\swagger-codegen-cli.jar generate -i http://petstore.swagger.io/v2/swagger.json -l php -o c:\temp\php_api_client`) -You can also download the JAR (latest relesae) directly from [maven.org](http://central.maven.org/maven2/io/swagger/swagger-codegen-cli/2.2.1/swagger-codegen-cli-2.2.1.jar ) +You can also download the JAR (latest release) directly from [maven.org](http://central.maven.org/maven2/io/swagger/swagger-codegen-cli/2.2.1/swagger-codegen-cli-2.2.1.jar ) To get a list of **general** options available, please run `java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar help generate` From 7df89e6ff49412555d4efb987c5efdf07c3145aa Mon Sep 17 00:00:00 2001 From: feda12 Date: Thu, 13 Oct 2016 09:43:53 -0500 Subject: [PATCH 446/470] Added OrderCloud.io to list of companies using swagger-codegen (#3971) * Added OrderCloud.io to list of companies using swagger-codegen * Fixed alphabetical order for OrderCloud.io --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 6546e9d8926..5ecc466d4c5 100644 --- a/README.md +++ b/README.md @@ -783,6 +783,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [nViso](http://www.nviso.ch/) - [Okiok](https://www.okiok.com) - [Onedata](http://onedata.org) +- [OrderCloud.io](http://ordercloud.io) - [OSDN](https://osdn.jp) - [PagerDuty](https://www.pagerduty.com) - [Pepipost](https://www.pepipost.com) From 6199c5d1c36dc61fe9646ea65fcaf7aaafa35637 Mon Sep 17 00:00:00 2001 From: Brian Shamblen Date: Thu, 13 Oct 2016 18:22:08 -0700 Subject: [PATCH 447/470] Updates to html2 templates to use security headers in curl examples (#3987) * Fixes #3974 * Update petstore example for html2 --- .../src/main/resources/htmlDocs2/index.mustache | 2 +- samples/html2/index.html | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/index.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/index.mustache index 4c3989dc1c2..c07ed7ca1e1 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs2/index.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/index.mustache @@ -266,7 +266,7 @@ function loadGoogleFontCss() {
    
    -curl -X {{httpMethod}}{{#isApiKey}} -H "apiKey: [[apiKey]]" -H "apiSecret: [[apiSecret]]"{{/isApiKey}} "{{basePath}}{{path}}{{#hasQueryParams}}?{{#queryParams}}{{^-first}}&{{/-first}}{{paramName}}={{vendorExtensions.x-eg}}{{/queryParams}}{{/hasQueryParams}}"
    +curl -X {{httpMethod}}{{#authMethods}}{{#isApiKey}}{{#isKeyInHeader}} -H "{{keyParamName}}: [[apiKey]]" {{/isKeyInHeader}}{{/isApiKey}}{{#isBasic}} -H "Authorization: Basic [[basicHash]]" {{/isBasic}}{{/authMethods}} "{{basePath}}{{path}}{{#hasQueryParams}}?{{#queryParams}}{{^-first}}&{{/-first}}{{paramName}}={{vendorExtensions.x-eg}}{{/queryParams}}{{/hasQueryParams}}"
     
     
     
    diff --git a/samples/html2/index.html b/samples/html2/index.html index 86b9fa7313e..38c4970ed5e 100644 --- a/samples/html2/index.html +++ b/samples/html2/index.html @@ -2834,7 +2834,7 @@

    Usage and SDK Samples

    
    -curl -X get "http://petstore.swagger.io/v2/pet/{petId}"
    +curl -X get -H "api_key: [[apiKey]]"  "http://petstore.swagger.io/v2/pet/{petId}"
     
     
     
    @@ -5195,7 +5195,7 @@

    Usage and SDK Samples

    
    -curl -X get "http://petstore.swagger.io/v2/store/inventory"
    +curl -X get -H "api_key: [[apiKey]]"  "http://petstore.swagger.io/v2/store/inventory"
     
     
     
    @@ -9921,7 +9921,7 @@

    Status: 404 - User not found

    - Generated 2016-09-29T11:08:44.942+08:00 + Generated 2016-10-13T09:03:51.792-07:00
    From 03ed192b98534e8fcfb85a4f6613cc746d1d1295 Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 14 Oct 2016 11:12:37 +0800 Subject: [PATCH 448/470] [Android] fix URL encoding for Android API client (#3992) * fix url encoding for android * add exception handling for url encoding in android --- .../src/main/resources/android/apiInvoker.mustache | 10 +++++++--- .../android/libraries/volley/apiInvoker.mustache | 7 ++++++- .../src/main/java/io/swagger/client/ApiInvoker.java | 10 +++++++--- .../src/main/java/io/swagger/client/ApiInvoker.java | 7 ++++++- 4 files changed, 26 insertions(+), 8 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/android/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/android/apiInvoker.mustache index 0b3f24c9f0b..0dac1bb8f59 100644 --- a/modules/swagger-codegen/src/main/resources/android/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/android/apiInvoker.mustache @@ -16,6 +16,8 @@ import org.apache.http.params.*; import org.apache.http.util.EntityUtils; import java.io.File; +import java.io.IOException; +import java.io.UnsupportedEncodingException; import java.net.Socket; import java.net.UnknownHostException; import java.net.URLEncoder; @@ -25,8 +27,6 @@ import java.util.Map; import java.util.HashMap; import java.util.List; import java.util.ArrayList; -import java.io.IOException; -import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import java.security.KeyManagementException; @@ -207,7 +207,11 @@ public class ApiInvoker { } public String escapeString(String str) { - return str; + try { + return URLEncoder.encode(str, "UTF-8"); + } catch (UnsupportedEncodingException e) { + return str; + } } public static Object deserialize(String json, String containerType, Class cls) throws ApiException { diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiInvoker.mustache index e40f4c04124..d57d8bb058f 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiInvoker.mustache @@ -20,6 +20,7 @@ import org.apache.http.HttpEntity; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; +import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.ArrayList; @@ -232,7 +233,11 @@ public class ApiInvoker { } public String escapeString(String str) { - return str; + try { + return URLEncoder.encode(str, "UTF-8"); + } catch (UnsupportedEncodingException e) { + return str; + } } public static Object deserialize(String json, String containerType, Class cls) throws ApiException { diff --git a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/ApiInvoker.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/ApiInvoker.java index 24f5a129780..7118a48d50e 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/ApiInvoker.java +++ b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/ApiInvoker.java @@ -39,6 +39,8 @@ import org.apache.http.util.EntityUtils; import java.io.File; +import java.io.IOException; +import java.io.UnsupportedEncodingException; import java.net.Socket; import java.net.UnknownHostException; import java.net.URLEncoder; @@ -48,8 +50,6 @@ import java.util.HashMap; import java.util.List; import java.util.ArrayList; -import java.io.IOException; -import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import java.security.KeyManagementException; @@ -230,7 +230,11 @@ public void addDefaultHeader(String key, String value) { } public String escapeString(String str) { - return str; + try { + return URLEncoder.encode(str, "UTF-8"); + } catch (UnsupportedEncodingException e) { + return str; + } } public static Object deserialize(String json, String containerType, Class cls) throws ApiException { diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiInvoker.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiInvoker.java index 158209c4be2..e1e32e370a3 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiInvoker.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiInvoker.java @@ -43,6 +43,7 @@ import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; +import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.ArrayList; @@ -246,7 +247,11 @@ public void addDefaultHeader(String key, String value) { } public String escapeString(String str) { - return str; + try { + return URLEncoder.encode(str, "UTF-8"); + } catch (UnsupportedEncodingException e) { + return str; + } } public static Object deserialize(String json, String containerType, Class cls) throws ApiException { From cc0e9427a43a240b71e2f361da3151fa6209c551 Mon Sep 17 00:00:00 2001 From: jfiala Date: Sat, 2 Jul 2016 18:01:45 +0200 Subject: [PATCH 449/470] add pom-file to cxf including cxf-client #2017 --- .../languages/JavaCXFServerCodegen.java | 12 ++ .../main/resources/JavaJaxRS/cxf/pom.mustache | 139 ++++++++++++++++++ 2 files changed, 151 insertions(+) create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java index 35fae461666..90285601aef 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java @@ -8,6 +8,7 @@ import io.swagger.codegen.CodegenModel; import io.swagger.codegen.CodegenOperation; import io.swagger.codegen.CodegenProperty; +import io.swagger.codegen.SupportingFile; import io.swagger.models.Operation; public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen @@ -39,6 +40,17 @@ public JavaCXFServerCodegen() } + @Override + public void processOpts() + { + super.processOpts(); + + supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen + writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); + + + } + @Override public String getName() { diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache new file mode 100644 index 00000000000..ca0d370b98a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache @@ -0,0 +1,139 @@ + + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + + src/main/java + + + org.apache.maven.plugins + maven-war-plugin + 2.1.1 + + + maven-failsafe-plugin + 2.6 + + + + integration-test + verify + + + + + + org.eclipse.jetty + jetty-maven-plugin + ${jetty-version} + + + / + + target/${project.artifactId}-${project.version} + 8079 + stopit + + {{serverPort}} + 60000 + + + + + start-jetty + pre-integration-test + + start + + + 0 + true + + + + stop-jetty + post-integration-test + + stop + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.9.1 + + + add-source + generate-sources + + add-source + + + + src/gen/java + + + + + + + + + + io.swagger + swagger-jersey2-jaxrs + compile + ${swagger-core-version} + + + ch.qos.logback + logback-classic + ${logback-version} + compile + + + ch.qos.logback + logback-core + ${logback-version} + compile + + + junit + junit + ${junit-version} + test + + + org.apache.cxf + cxf-rt-rs-client + 3.1.6 + test + + + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + true + + + + + {{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}} + ${java.version} + ${java.version} + 1.5.9 + 9.2.9.v20150224 + 2.22.2 + 4.12 + 1.1.7 + 2.5 + UTF-8 + + From 008c55852a0cfb34d664fdcbc4c8379b18eca593 Mon Sep 17 00:00:00 2001 From: jfiala Date: Sat, 2 Jul 2016 18:12:47 +0200 Subject: [PATCH 450/470] adapt pom sourceFolder in pom.mustache to gen/java #2017 --- .../src/main/resources/JavaJaxRS/cxf/pom.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache index ca0d370b98a..43d02dec937 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache @@ -75,7 +75,7 @@ - src/gen/java + gen/java From 8dab093bd8f2605cd2eb6ebb9b9fe2adf78cafa6 Mon Sep 17 00:00:00 2001 From: jfiala Date: Sat, 2 Jul 2016 18:53:00 +0200 Subject: [PATCH 451/470] add test templates for CXF #2017 --- .../languages/JavaCXFServerCodegen.java | 3 +- .../src/main/resources/Java/model.mustache | 1 + .../resources/JavaJaxRS/cxf/api_test.mustache | 59 +++++++++++++++++++ .../JavaJaxRS/cxf/licenseInfo.mustache | 23 ++++++++ .../resources/JavaJaxRS/cxf/model.mustache | 1 + .../resources/JavaJaxRS/cxf/pojo.mustache | 9 +++ .../main/resources/JavaJaxRS/cxf/pom.mustache | 8 +++ 7 files changed, 102 insertions(+), 2 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/licenseInfo.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java index 90285601aef..8b0fca153e0 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java @@ -44,11 +44,10 @@ public JavaCXFServerCodegen() public void processOpts() { super.processOpts(); - + supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); - } @Override diff --git a/modules/swagger-codegen/src/main/resources/Java/model.mustache b/modules/swagger-codegen/src/main/resources/Java/model.mustache index 31148bafcec..8d13853a107 100644 --- a/modules/swagger-codegen/src/main/resources/Java/model.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/model.mustache @@ -13,6 +13,7 @@ import java.io.Serializable; import android.os.Parcelable; import android.os.Parcel; {{/parcelableModel}} +import javax.validation.constraints.*; {{#models}} {{#model}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache new file mode 100644 index 00000000000..524f20dfb39 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache @@ -0,0 +1,59 @@ +{{>licenseInfo}} + +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} +import org.junit.Test; +import org.junit.Before; + +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.client.JAXRSClientFactory; +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; + + +{{^fullJavaUtil}} +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +{{/fullJavaUtil}} + +/** + * API tests for {{classname}} + */ +public class {{classname}}Test { + + private {{classname}} api; + + @Before + public void setup() { + JacksonJsonProvider provider = new JacksonJsonProvider(); + List providers = new ArrayList(); + providers.add(provider); + + api = JAXRSClientFactory.create("{{basePath}}", {{classname}}.class, providers); + } + + {{#operations}}{{#operation}} + /** + * {{summary}} + * + * {{notes}} + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void {{operationId}}Test() { + {{#allParams}} + {{{dataType}}} {{paramName}} = new {{{dataType}}}(); + {{/allParams}} + Response response = api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + + {{#returnType}}{{{returnType}}} responseModel = response.readEntity({{{returnType}}}.class);{{/returnType}} + + // TODO: test validations + } + {{/operation}}{{/operations}} +} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/licenseInfo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/licenseInfo.mustache new file mode 100644 index 00000000000..861d97234cf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/licenseInfo.mustache @@ -0,0 +1,23 @@ +/** + * {{{appName}}} + * {{{appDescription}}} + * + * {{#version}}OpenAPI spec version: {{{version}}}{{/version}} + * {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/model.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/model.mustache index 25e0c244ed9..69b4aa7656f 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/model.mustache @@ -2,6 +2,7 @@ package {{package}}; {{#imports}}import {{import}}; {{/imports}} +import javax.validation.constraints.*; {{#models}} {{#model}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache index c214ae2ae84..26ff946af81 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache @@ -27,6 +27,15 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { * minimum: {{minimum}}{{/minimum}}{{#maximum}} * maximum: {{maximum}}{{/maximum}} **/ + {{#required}} + @NotNull{{/required}}{{! +}}{{#pattern}} + @Pattern(regexp="{{pattern}}"){{/pattern}}{{#minLength}}{{#maxLength}} + @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} + @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} + @Size(max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minimum}} + //@Min({{minimum}}){{/minimum}}{{#maximum}} + //@Max({{maximum}}){{/maximum}} {{#vendorExtensions.extraAnnotation}}{{vendorExtensions.extraAnnotation}}{{/vendorExtensions.extraAnnotation}} public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache index 43d02dec937..c161b605836 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache @@ -108,12 +108,20 @@ ${junit-version} test + org.apache.cxf cxf-rt-rs-client 3.1.6 test + + + javax.validation + validation-api + 1.1.0.Final + provided + From b34db722d5e8486372dfc93487e7c6df48e8729a Mon Sep 17 00:00:00 2001 From: jfiala Date: Sat, 2 Jul 2016 19:11:24 +0200 Subject: [PATCH 452/470] optimize mustache template structure, remove tabs #3280 #2549 --- .../src/main/resources/Java/pojo.mustache | 15 ++++++++++++++ .../src/main/resources/Java/pom.mustache | 8 ++++++++ .../resources/JavaJaxRS/cxf/pojo.mustache | 20 ++++++++++++------- .../main/resources/JavaJaxRS/cxf/pom.mustache | 12 +++++------ 4 files changed, 42 insertions(+), 13 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache index adb200bc449..73e4f1697fc 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache @@ -66,6 +66,21 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#parcela {{#vendorExtensions.extraAnnotation}} {{{vendorExtensions.extraAnnotation}}} {{/vendorExtensions.extraAnnotation}} +{{#required}} + @NotNull{{/required}}{{! +}} +{{#pattern}} + @Pattern(regexp="{{pattern}}") +{{/pattern}} +{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} + @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} + @Size(max={{maxLength}}){{/maxLength}}{{/minLength}} +{{#minimum}} + //@Min({{minimum}}) +{{/minimum}} +{{#maximum}} + //@Max({{maximum}}) +{{/maximum}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; diff --git a/modules/swagger-codegen/src/main/resources/Java/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/pom.mustache index 99a12b6391d..be82fcd96e4 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pom.mustache @@ -180,6 +180,14 @@ migbase64 2.2 + + + + javax.validation + validation-api + 1.1.0.Final + provided + diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache index 26ff946af81..ad5ef14b9d6 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache @@ -27,15 +27,21 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { * minimum: {{minimum}}{{/minimum}}{{#maximum}} * maximum: {{maximum}}{{/maximum}} **/ - {{#required}} +{{#required}} @NotNull{{/required}}{{! -}}{{#pattern}} - @Pattern(regexp="{{pattern}}"){{/pattern}}{{#minLength}}{{#maxLength}} - @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} +}} +{{#pattern}} + @Pattern(regexp="{{pattern}}") +{{/pattern}} +{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} - @Size(max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minimum}} - //@Min({{minimum}}){{/minimum}}{{#maximum}} - //@Max({{maximum}}){{/maximum}} + @Size(max={{maxLength}}){{/maxLength}}{{/minLength}} +{{#minimum}} + //@Min({{minimum}}) +{{/minimum}} +{{#maximum}} + //@Max({{maximum}}) +{{/maximum}} {{#vendorExtensions.extraAnnotation}}{{vendorExtensions.extraAnnotation}}{{/vendorExtensions.extraAnnotation}} public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache index c161b605836..f20c1f8bef6 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache @@ -115,13 +115,13 @@ 3.1.6 test - + - javax.validation - validation-api - 1.1.0.Final - provided - + javax.validation + validation-api + 1.1.0.Final + provided + From fa02f47abf9e688e8d206d8a124a1f0ecfa58e3a Mon Sep 17 00:00:00 2001 From: jfiala Date: Sat, 2 Jul 2016 19:21:05 +0200 Subject: [PATCH 453/470] refined dependency to swagger-jaxrs #2017 --- .../src/main/resources/JavaJaxRS/cxf/pom.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache index f20c1f8bef6..f8a33fd7fe1 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache @@ -86,7 +86,7 @@ io.swagger - swagger-jersey2-jaxrs + swagger-jaxrs compile ${swagger-core-version} From 4786f258e960f31297701b5fb587995a01436334 Mon Sep 17 00:00:00 2001 From: jfiala Date: Sat, 2 Jul 2016 19:51:44 +0200 Subject: [PATCH 454/470] refined annotations and line breaks #2549 --- .../src/main/resources/Java/pojo.mustache | 25 +++++++-- .../resources/JavaJaxRS/cxf/pojo.mustache | 51 +++++++++++++++---- 2 files changed, 60 insertions(+), 16 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache index 73e4f1697fc..1db11a21b7a 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache @@ -67,14 +67,26 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#parcela {{{vendorExtensions.extraAnnotation}}} {{/vendorExtensions.extraAnnotation}} {{#required}} - @NotNull{{/required}}{{! -}} + @NotNull +{{/required}} {{#pattern}} @Pattern(regexp="{{pattern}}") {{/pattern}} -{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} - @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} - @Size(max={{maxLength}}){{/maxLength}}{{/minLength}} +{{#minLength}} +{{#maxLength}} + @Size(min={{minLength}},max={{maxLength}}) +{{/maxLength}} +{{/minLength}} +{{#minLength}} +{{^maxLength}} + @Size(min={{minLength}}) +{{/maxLength}} +{{/minLength}} +{{^minLength}} +{{#maxLength}} + @Size(max={{maxLength}}) + {{/maxLength}} + {{/minLength}} {{#minimum}} //@Min({{minimum}}) {{/minimum}} @@ -82,6 +94,9 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#parcela //@Max({{maximum}}) {{/maximum}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") +{{#vendorExtensions.extraAnnotation}} + {{vendorExtensions.extraAnnotation}} +{{/vendorExtensions.extraAnnotation}} public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; } diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache index ad5ef14b9d6..357fe96dcc4 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache @@ -1,3 +1,4 @@ +import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlAccessType; @@ -11,6 +12,9 @@ import javax.xml.bind.annotation.XmlEnum; }){{/hasVars}} {{^hasVars}}@XmlType(name = "{{classname}}"){{/hasVars}} {{^parent}}@XmlRootElement(name="{{classname}}"){{/parent}} +{{#description}} +@ApiModel(description="{{{description}}}") +{{/description}} public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{#vars}}{{#isEnum}} @@ -22,27 +26,52 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}} {{#vars}} - /**{{#description}} - * {{{description}}}{{/description}}{{#minimum}} - * minimum: {{minimum}}{{/minimum}}{{#maximum}} - * maximum: {{maximum}}{{/maximum}} - **/ + /** + {{#description}} + * {{{description}}} + {{/description}} + {{^description}} + * Get {{name}} + {{/description}} + {{#minimum}} + * minimum: {{minimum}} + {{/minimum}} + {{#maximum}} + * maximum: {{maximum}} + {{/maximum}} + * @return {{name}} + **/ {{#required}} - @NotNull{{/required}}{{! -}} + @NotNull +{{/required}} {{#pattern}} @Pattern(regexp="{{pattern}}") {{/pattern}} -{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} - @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} - @Size(max={{maxLength}}){{/maxLength}}{{/minLength}} +{{#minLength}} +{{#maxLength}} + @Size(min={{minLength}},max={{maxLength}}) +{{/maxLength}} +{{/minLength}} +{{#minLength}} +{{^maxLength}} + @Size(min={{minLength}}) +{{/maxLength}} +{{/minLength}} +{{^minLength}} +{{#maxLength}} + @Size(max={{maxLength}}) + {{/maxLength}} + {{/minLength}} {{#minimum}} //@Min({{minimum}}) {{/minimum}} {{#maximum}} //@Max({{maximum}}) {{/maximum}} - {{#vendorExtensions.extraAnnotation}}{{vendorExtensions.extraAnnotation}}{{/vendorExtensions.extraAnnotation}} + @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") +{{#vendorExtensions.extraAnnotation}} + {{vendorExtensions.extraAnnotation}} +{{/vendorExtensions.extraAnnotation}} public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; } From b26aaa8a31d44e3b9dc5d5b68aa847a4f5d7b45c Mon Sep 17 00:00:00 2001 From: jfiala Date: Sun, 3 Jul 2016 18:11:21 +0200 Subject: [PATCH 455/470] fix tabs instead of spaces... --- .../languages/JavaCXFServerCodegen.java | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java index 8b0fca153e0..3dcf3a4e38b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java @@ -12,9 +12,9 @@ import io.swagger.models.Operation; public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen -{ - public JavaCXFServerCodegen() - { +{ + public JavaCXFServerCodegen() + { super(); sourceFolder = "gen" + File.separator + "java"; outputFolder = "generated-code/JavaJaxRS-CXF"; @@ -37,24 +37,24 @@ public JavaCXFServerCodegen() embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "cxf"; - } + } - @Override - public void processOpts() - { - super.processOpts(); - - supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen + @Override + public void processOpts() + { + super.processOpts(); + + supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); - } - - @Override - public String getName() - { - return "jaxrs-cxf"; - } + } + + @Override + public String getName() + { + return "jaxrs-cxf"; + } @Override public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { From 52ca86fbf04a462e213fcd90b02e4b716b90bec2 Mon Sep 17 00:00:00 2001 From: jfiala Date: Sun, 3 Jul 2016 18:24:41 +0200 Subject: [PATCH 456/470] move annotations from getter to field for server model --- .../resources/JavaJaxRS/cxf/pojo.mustache | 38 +++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache index 357fe96dcc4..e916ea92c9c 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache @@ -23,24 +23,6 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{>enumClass}}{{/items}}{{/items.isEnum}} @XmlElement(name="{{baseName}}") - private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}} - - {{#vars}} - /** - {{#description}} - * {{{description}}} - {{/description}} - {{^description}} - * Get {{name}} - {{/description}} - {{#minimum}} - * minimum: {{minimum}} - {{/minimum}} - {{#maximum}} - * maximum: {{maximum}} - {{/maximum}} - * @return {{name}} - **/ {{#required}} @NotNull {{/required}} @@ -67,8 +49,26 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{/minimum}} {{#maximum}} //@Max({{maximum}}) -{{/maximum}} +{{/maximum}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") + private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}} + + {{#vars}} + /** + {{#description}} + * {{{description}}} + {{/description}} + {{^description}} + * Get {{name}} + {{/description}} + {{#minimum}} + * minimum: {{minimum}} + {{/minimum}} + {{#maximum}} + * maximum: {{maximum}} + {{/maximum}} + * @return {{name}} + **/ {{#vendorExtensions.extraAnnotation}} {{vendorExtensions.extraAnnotation}} {{/vendorExtensions.extraAnnotation}} From 681ac8d8f804908cec6dbc6a520466586da6224f Mon Sep 17 00:00:00 2001 From: jfiala Date: Sun, 3 Jul 2016 18:24:41 +0200 Subject: [PATCH 457/470] cleanup tabs --- .../src/main/resources/JavaJaxRS/cxf/pojo.mustache | 2 +- .../src/main/resources/JavaJaxRS/cxf/pom.mustache | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache index e916ea92c9c..af565cdbf35 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache @@ -8,7 +8,7 @@ import javax.xml.bind.annotation.XmlEnum; @XmlAccessorType(XmlAccessType.FIELD) {{#hasVars}} @XmlType(name = "{{classname}}", propOrder = - { {{#vars}}"{{name}}"{{^-last}}, {{/-last}}{{/vars}} + { {{#vars}}"{{name}}"{{^-last}}, {{/-last}}{{/vars}} }){{/hasVars}} {{^hasVars}}@XmlType(name = "{{classname}}"){{/hasVars}} {{^parent}}@XmlRootElement(name="{{classname}}"){{/parent}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache index f8a33fd7fe1..9019f5e7332 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache @@ -110,11 +110,11 @@ - org.apache.cxf - cxf-rt-rs-client - 3.1.6 - test - + org.apache.cxf + cxf-rt-rs-client + 3.1.6 + test + javax.validation From 320f7b617aa4e1f9ffe0816e1a648317ee951f00 Mon Sep 17 00:00:00 2001 From: jfiala Date: Sun, 3 Jul 2016 18:40:45 +0200 Subject: [PATCH 458/470] add example for gzipping #2017 --- .../resources/JavaJaxRS/cxf/api_test.mustache | 30 ++++++++++++++----- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache index 524f20dfb39..a7f92f667ea 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache @@ -9,9 +9,12 @@ import org.junit.Before; import javax.ws.rs.core.Response; import org.apache.cxf.jaxrs.client.JAXRSClientFactory; +import org.apache.cxf.jaxrs.client.ClientConfiguration; +import org.apache.cxf.jaxrs.client.WebClient; +import org.apache.cxf.transport.common.gzip.GZIPInInterceptor; +import org.apache.cxf.transport.common.gzip.GZIPOutInterceptor; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; - {{^fullJavaUtil}} import java.util.ArrayList; import java.util.HashMap; @@ -28,11 +31,24 @@ public class {{classname}}Test { @Before public void setup() { - JacksonJsonProvider provider = new JacksonJsonProvider(); - List providers = new ArrayList(); - providers.add(provider); - - api = JAXRSClientFactory.create("{{basePath}}", {{classname}}.class, providers); + JacksonJsonProvider provider = new JacksonJsonProvider(); + List providers = new ArrayList(); + providers.add(provider); + + api = JAXRSClientFactory.create("{{basePath}}", {{classname}}.class, providers); + + org.apache.cxf.jaxrs.client.Client client = WebClient.client(api); + + ClientConfiguration config = WebClient.getConfig(client); + + // Example for using Gzipping + GZIPOutInterceptor gzipOutInterceptor = new GZIPOutInterceptor(); + // use Gzipping for first request sent to server + //gzipOutInterceptor.setForce(true); + config.getOutInterceptors().add(gzipOutInterceptor); + + config.getInInterceptors().add(new GZIPInInterceptor()); + } {{#operations}}{{#operation}} @@ -51,7 +67,7 @@ public class {{classname}}Test { {{/allParams}} Response response = api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); - {{#returnType}}{{{returnType}}} responseModel = response.readEntity({{{returnType}}}.class);{{/returnType}} + {{#returnType}}{{{returnType}}} responseModel = response.readEntity({{{returnType}}}.class);{{/returnType}} // TODO: test validations } From a8811c362662cdc1c0941b20d7449df755545dae Mon Sep 17 00:00:00 2001 From: jfiala Date: Sun, 3 Jul 2016 20:53:54 +0200 Subject: [PATCH 459/470] add complete WAR to cxf-server #2017 --- .../languages/JavaCXFServerCodegen.java | 30 ++++++-- .../main/resources/JavaJaxRS/cxf/api.mustache | 9 +++ .../JavaJaxRS/cxf/apiServiceImpl.mustache | 44 ++++++++++++ .../resources/JavaJaxRS/cxf/api_test.mustache | 4 +- .../JavaJaxRS/cxf/context.xml.mustache | 71 +++++++++++++++++++ .../JavaJaxRS/cxf/jboss-web.xml.mustache | 7 ++ .../main/resources/JavaJaxRS/cxf/pom.mustache | 61 +++++++++++++--- .../main/resources/JavaJaxRS/cxf/web.mustache | 23 ++++++ 8 files changed, 233 insertions(+), 16 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/context.xml.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/jboss-web.xml.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/web.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java index 3dcf3a4e38b..94362b6236c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java @@ -11,18 +11,31 @@ import io.swagger.codegen.SupportingFile; import io.swagger.models.Operation; +/** + * TODO #2017: + * - reuse bean-validation-annotations in Java? + * - pom.xml: maybe add cxf-version property + * - api_test.mustache: add switch for using gzip in test cases? + * + * + * + */ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen { public JavaCXFServerCodegen() { super(); - sourceFolder = "gen" + File.separator + "java"; - outputFolder = "generated-code/JavaJaxRS-CXF"; apiTestTemplateFiles.clear(); // TODO: add test template - //TODO add auto-generated pom.xml for maven - //apiTemplateFiles.put("pom.mustache", "pom.xml"); - + supportsInheritance = true; + + artifactId = "swagger-cxf-server"; + + sourceFolder = "gen" + File.separator + "java"; + outputFolder = "generated-code/JavaJaxRS-CXF"; + + apiTemplateFiles.put("apiServiceImpl.mustache", ".java"); + // clear model and api doc template as this codegen // does not support auto-generated markdown doc at the moment //TODO: add doc templates @@ -48,6 +61,13 @@ public void processOpts() supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); + writeOptional(outputFolder, new SupportingFile("web.mustache", + ("src/main/webapp/WEB-INF"), "web.xml")); + writeOptional(outputFolder, new SupportingFile("context.xml.mustache", + ("src/main/webapp/WEB-INF"), "context.xml")); + writeOptional(outputFolder, new SupportingFile("jboss-web.xml.mustache", + ("src/main/webapp/WEB-INF"), "jboss-web.xml")); + } @Override diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache index 7454d0141c3..566d7581f66 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache @@ -12,7 +12,11 @@ import javax.ws.rs.core.Response; import org.apache.cxf.jaxrs.ext.multipart.*; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + @Path("{{contextPath}}") +@Api(value = "/", description = "{{description}}") public interface {{classname}} { {{#operations}} {{#operation}} @@ -20,7 +24,12 @@ public interface {{classname}} { {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} {{#hasConsumes}}@Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} {{#hasProduces}}@Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} +{{#summary}} +@ApiOperation(value = "{{summary}}") +{{/summary}} + public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}); Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}); + {{/operation}} } {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache new file mode 100644 index 00000000000..dde547f91c6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache @@ -0,0 +1,44 @@ +package {{package}}.impl; + +import {{package}}.*; +{{#imports}}import {{import}}; +{{/imports}} + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.model.wadl.Description; +import org.apache.cxf.jaxrs.model.wadl.DocTarget; + +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; + +@Path("/") +{{#description}} +@Api(value = "/", description = "{{description}}") +{{/description}} +public class {{classname}}ServiceImpl implements {{classname}} { +{{#operations}} +{{#operation}} + @{{httpMethod}} + {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} + {{#hasConsumes}}@Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} + {{#hasProduces}}@Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} + {{! add description for CXF WADL (must be added to implementation class }} +{{#summary}} + @Description(value = "{{summary}}", target = DocTarget.METHOD) +{{/summary}} + public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}) { + // TODO: Implement... + + {{#returnType}}return null;{{/returnType}} + } + +{{/operation}} +} +{{/operations}} + diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache index a7f92f667ea..7d275deb8c2 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache @@ -65,9 +65,7 @@ public class {{classname}}Test { {{#allParams}} {{{dataType}}} {{paramName}} = new {{{dataType}}}(); {{/allParams}} - Response response = api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); - - {{#returnType}}{{{returnType}}} responseModel = response.readEntity({{{returnType}}}.class);{{/returnType}} + {{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); // TODO: test validations } diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/context.xml.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/context.xml.mustache new file mode 100644 index 00000000000..1c7aeb4d64d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/context.xml.mustache @@ -0,0 +1,71 @@ + + + + + + + + + + + + +{{#apiInfo}} +{{#apis}} + +{{/apis}} +{{/apiInfo}} + + + + + + + + + + + + + + + + + + + + +{{#apiInfo}} +{{#apis}} + +{{/apis}} +{{/apiInfo}} + + + + + + + + + + + + diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/jboss-web.xml.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/jboss-web.xml.mustache new file mode 100644 index 00000000000..ef688c10e91 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/jboss-web.xml.mustache @@ -0,0 +1,7 @@ + + + + + swagger-cxf-server + + diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache index 9019f5e7332..5144bd95c9f 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache @@ -2,7 +2,7 @@ 4.0.0 {{groupId}} {{artifactId}} - jar + war {{artifactId}} {{artifactVersion}} @@ -25,7 +25,7 @@ - + org.codehaus.mojo build-helper-maven-plugin @@ -81,6 +81,14 @@ + + + + maven-war-plugin + + true + + @@ -108,6 +116,13 @@ ${junit-version} test + + + javax.validation + validation-api + 1.1.0.Final + provided + org.apache.cxf @@ -115,13 +130,43 @@ 3.1.6 test - + + - javax.validation - validation-api - 1.1.0.Final - provided + org.apache.cxf + cxf-rt-frontend-jaxrs + 3.1.6 + compile + + org.apache.cxf + cxf-rt-rs-service-description + 3.1.6 + compile + + + org.apache.cxf + cxf-rt-ws-policy + 3.1.6 + compile + + + org.apache.cxf + cxf-rt-wsdl + 3.1.6 + compile + + + + org.springframework + spring-context + 4.2.5.RELEASE + + + org.springframework + spring-web + 4.2.5.RELEASE + diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/web.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/web.mustache new file mode 100644 index 00000000000..9d905ae076b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/web.mustache @@ -0,0 +1,23 @@ + + + + + contextConfigLocation + WEB-INF/context.xml + + + org.springframework.web.context.ContextLoaderListener + + + CXF Service Servlet + CXFServiceServlet + org.apache.cxf.transport.servlet.CXFServlet + 1 + + + CXFServiceServlet + /rest/* + + + From 4da6712eccf6728130892fccb71b9378048bb145 Mon Sep 17 00:00:00 2001 From: jfiala Date: Sun, 3 Jul 2016 21:11:04 +0200 Subject: [PATCH 460/470] add readme + rework pom #2017 --- .../languages/JavaCXFServerCodegen.java | 3 +++ .../main/resources/JavaJaxRS/cxf/pom.mustache | 21 +++++++++-------- .../main/resources/JavaJaxRS/cxf/readme.md | 23 +++++++++++++++++++ 3 files changed, 38 insertions(+), 9 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/readme.md diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java index 94362b6236c..d219d4f51f1 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java @@ -59,8 +59,11 @@ public void processOpts() super.processOpts(); supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen + writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); + writeOptional(outputFolder, new SupportingFile("readme.md", "", "readme.md")); + writeOptional(outputFolder, new SupportingFile("web.mustache", ("src/main/webapp/WEB-INF"), "web.xml")); writeOptional(outputFolder, new SupportingFile("context.xml.mustache", diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache index 5144bd95c9f..40a6135e636 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache @@ -120,14 +120,14 @@ javax.validation validation-api - 1.1.0.Final + ${beanvalidation-version} provided org.apache.cxf cxf-rt-rs-client - 3.1.6 + ${cxf-version} test @@ -135,37 +135,37 @@ org.apache.cxf cxf-rt-frontend-jaxrs - 3.1.6 + ${cxf-version} compile org.apache.cxf cxf-rt-rs-service-description - 3.1.6 + ${cxf-version} compile org.apache.cxf cxf-rt-ws-policy - 3.1.6 + ${cxf-version} compile org.apache.cxf cxf-rt-wsdl - 3.1.6 + ${cxf-version} compile - + org.springframework spring-context - 4.2.5.RELEASE + ${spring-version} org.springframework spring-web - 4.2.5.RELEASE + ${spring-version} @@ -187,6 +187,9 @@ 4.12 1.1.7 2.5 + 1.1.0.Final + 4.2.5.RELEASE + 3.1.6 UTF-8 diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/readme.md b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/readme.md new file mode 100644 index 00000000000..27925cedf44 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/readme.md @@ -0,0 +1,23 @@ + +# JAX-RS CXF 3 server application + +## Supported features +* Bean-Validation-API support +* Spring-configuration of Swagger, WADL and Endpoints +* Swagger-API is accessible (CXF3 Swagger2Feature) +* WADL is accessible (CXF WADL-Generator) +* Unit-tests include Gzip-Interceptors for demonstration + + +## Urls to access the REST API + +* Available services listing +http://localhost:8080/swagger-cxf-server/rest/services/ + +* Swagger API + http://localhost:8080/swagger-cxf-server/rest/services/swagger.json + +* CXF WADL + http://localhost:8080/swagger-cxf-server/rest/services?_wadl + + From 4df86dc856888faa0e75622edd68567f8f08007f Mon Sep 17 00:00:00 2001 From: jfiala Date: Sat, 10 Sep 2016 20:23:47 +0200 Subject: [PATCH 461/470] add cli switch for beanvalidation #2549 --- .../languages/JavaCXFServerCodegen.java | 29 ++++++++++++- .../codegen/languages/JavaClientCodegen.java | 17 +++++++- .../src/main/resources/Java/model.mustache | 2 + .../src/main/resources/Java/pojo.mustache | 2 + .../src/main/resources/Java/pom.mustache | 4 +- .../main/resources/JavaJaxRS/cxf/api.mustache | 5 +-- .../JavaJaxRS/cxf/apiServiceImpl.mustache | 12 +----- .../resources/JavaJaxRS/cxf/pojo.mustache | 42 ++++++++++--------- .../main/resources/JavaJaxRS/cxf/pom.mustache | 2 + 9 files changed, 77 insertions(+), 38 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java index d219d4f51f1..5e1a24c331f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java @@ -4,7 +4,12 @@ import java.io.File; import java.util.List; import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenModel; import io.swagger.codegen.CodegenOperation; import io.swagger.codegen.CodegenProperty; @@ -21,7 +26,14 @@ * */ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen -{ +{ + private static final Logger LOGGER = LoggerFactory.getLogger(JavaCXFServerCodegen.class); + + public static final String USE_BEANVALIDATION = "useBeanValidation"; + + protected boolean useBeanValidation = false; + + public JavaCXFServerCodegen() { super(); @@ -50,6 +62,8 @@ public JavaCXFServerCodegen() embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "cxf"; + cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations")); + } @@ -58,6 +72,15 @@ public void processOpts() { super.processOpts(); + if (additionalProperties.containsKey(USE_BEANVALIDATION)) { + boolean useBeanValidationProp = Boolean.valueOf(additionalProperties.get(USE_BEANVALIDATION).toString()); + this.setUseBeanValidation(useBeanValidationProp); + + // write back as boolean + additionalProperties.put(USE_BEANVALIDATION, useBeanValidationProp); + } + + supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); @@ -99,4 +122,8 @@ public String getHelp() { return "Generates a Java JAXRS Server application based on Apache CXF framework."; } + + public void setUseBeanValidation(boolean useBeanValidation) { + this.useBeanValidation = useBeanValidation; + } } 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 ebd53d1a2a9..80e766bab17 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 @@ -15,6 +15,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen { public static final String USE_RX_JAVA = "useRxJava"; public static final String PARCELABLE_MODEL = "parcelableModel"; + public static final String USE_BEANVALIDATION = "useBeanValidation"; public static final String RETROFIT_1 = "retrofit"; public static final String RETROFIT_2 = "retrofit2"; @@ -22,6 +23,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen { protected String gradleWrapperPackage = "gradle.wrapper"; protected boolean useRxJava = false; protected boolean parcelableModel = false; + protected boolean useBeanValidation = false; public JavaClientCodegen() { super(); @@ -34,6 +36,7 @@ public JavaClientCodegen() { cliOptions.add(CliOption.newBoolean(USE_RX_JAVA, "Whether to use the RxJava adapter with the retrofit2 library.")); cliOptions.add(CliOption.newBoolean(PARCELABLE_MODEL, "Whether to generate models for Android that implement Parcelable with the okhttp-gson library.")); + cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations")); supportedLibraries.put("jersey1", "HTTP client: Jersey client 1.19.1. JSON processing: Jackson 2.7.0"); supportedLibraries.put("feign", "HTTP client: Netflix Feign 8.16.0. JSON processing: Jackson 2.7.0"); @@ -78,6 +81,14 @@ public void processOpts() { } // put the boolean value back to PARCELABLE_MODEL in additionalProperties additionalProperties.put(PARCELABLE_MODEL, parcelableModel); + + if (additionalProperties.containsKey(USE_BEANVALIDATION)) { + boolean useBeanValidationProp = Boolean.valueOf(additionalProperties.get(USE_BEANVALIDATION).toString()); + this.setUseBeanValidation(useBeanValidationProp); + + // write back as boolean + additionalProperties.put(USE_BEANVALIDATION, useBeanValidationProp); + } final String invokerFolder = (sourceFolder + '/' + invokerPackage).replace(".", "/"); final String authFolder = (sourceFolder + '/' + invokerPackage + ".auth").replace(".", "/"); @@ -176,7 +187,7 @@ public Map postProcessOperations(Map objs) { operation.returnType = "Void"; } if (usesRetrofit2Library() && StringUtils.isNotEmpty(operation.path) && operation.path.startsWith("/")) - operation.path = operation.path.substring(1); + operation.path = operation.path.substring(1); } } } @@ -232,4 +243,8 @@ public void setUseRxJava(boolean useRxJava) { public void setParcelableModel(boolean parcelableModel) { this.parcelableModel = parcelableModel; } + public void setUseBeanValidation(boolean useBeanValidation) { + this.useBeanValidation = useBeanValidation; + } + } diff --git a/modules/swagger-codegen/src/main/resources/Java/model.mustache b/modules/swagger-codegen/src/main/resources/Java/model.mustache index 8d13853a107..c697b32ff7a 100644 --- a/modules/swagger-codegen/src/main/resources/Java/model.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/model.mustache @@ -13,7 +13,9 @@ import java.io.Serializable; import android.os.Parcelable; import android.os.Parcel; {{/parcelableModel}} +{{#useBeanValidation}} import javax.validation.constraints.*; +{{/useBeanValidation}} {{#models}} {{#model}} diff --git a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache index 1db11a21b7a..959338ba86f 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache @@ -66,6 +66,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#parcela {{#vendorExtensions.extraAnnotation}} {{{vendorExtensions.extraAnnotation}}} {{/vendorExtensions.extraAnnotation}} +{{#useBeanValidation}} {{#required}} @NotNull {{/required}} @@ -93,6 +94,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#parcela {{#maximum}} //@Max({{maximum}}) {{/maximum}} +{{/useBeanValidation}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") {{#vendorExtensions.extraAnnotation}} {{vendorExtensions.extraAnnotation}} diff --git a/modules/swagger-codegen/src/main/resources/Java/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/pom.mustache index be82fcd96e4..a5392522568 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pom.mustache @@ -180,7 +180,7 @@ migbase64 2.2 - +{{#useBeanValidation}} javax.validation @@ -188,7 +188,7 @@ 1.1.0.Final provided - +{{/useBeanValidation}} junit diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache index 566d7581f66..b591d86f011 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache @@ -25,11 +25,10 @@ public interface {{classname}} { {{#hasConsumes}}@Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} {{#hasProduces}}@Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} {{#summary}} -@ApiOperation(value = "{{summary}}") + @ApiOperation(value = "{{summary}}") {{/summary}} - public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}); + public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}); - {{/operation}} } {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache index dde547f91c6..3a9fe5480ca 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache @@ -17,22 +17,12 @@ import org.apache.cxf.jaxrs.ext.multipart.*; import io.swagger.annotations.Api; -@Path("/") {{#description}} -@Api(value = "/", description = "{{description}}") {{/description}} public class {{classname}}ServiceImpl implements {{classname}} { {{#operations}} {{#operation}} - @{{httpMethod}} - {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} - {{#hasConsumes}}@Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} - {{#hasProduces}}@Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} - {{! add description for CXF WADL (must be added to implementation class }} -{{#summary}} - @Description(value = "{{summary}}", target = DocTarget.METHOD) -{{/summary}} - public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}) { + public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { // TODO: Implement... {{#returnType}}return null;{{/returnType}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache index af565cdbf35..d8be3155f56 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache @@ -23,6 +23,26 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{>enumClass}}{{/items}}{{/items.isEnum}} @XmlElement(name="{{baseName}}") + @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") + private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}} + + {{#vars}} + /** + {{#description}} + * {{{description}}} + {{/description}} + {{^description}} + * Get {{name}} + {{/description}} + {{#minimum}} + * minimum: {{minimum}} + {{/minimum}} + {{#maximum}} + * maximum: {{maximum}} + {{/maximum}} + * @return {{name}} + **/ +{{#useBeanValidation}} {{#required}} @NotNull {{/required}} @@ -49,26 +69,8 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{/minimum}} {{#maximum}} //@Max({{maximum}}) -{{/maximum}} - @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") - private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}} - - {{#vars}} - /** - {{#description}} - * {{{description}}} - {{/description}} - {{^description}} - * Get {{name}} - {{/description}} - {{#minimum}} - * minimum: {{minimum}} - {{/minimum}} - {{#maximum}} - * maximum: {{maximum}} - {{/maximum}} - * @return {{name}} - **/ +{{/maximum}} +{{/useBeanValidation}} {{#vendorExtensions.extraAnnotation}} {{vendorExtensions.extraAnnotation}} {{/vendorExtensions.extraAnnotation}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache index 40a6135e636..f600dfee8e4 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pom.mustache @@ -116,6 +116,7 @@ ${junit-version} test +{{#useBeanValidation}} javax.validation @@ -123,6 +124,7 @@ ${beanvalidation-version} provided +{{/useBeanValidation}} org.apache.cxf From fb6fed9d68e5404849dc605ca5cbdc7e8383663f Mon Sep 17 00:00:00 2001 From: Johannes Fiala Date: Sun, 11 Sep 2016 12:09:00 +0200 Subject: [PATCH 462/470] move beanvalidation into separate subtemplate and reuse for cxf --- .../src/main/resources/Java/pojo.mustache | 31 +------------------ .../resources/JavaJaxRS/cxf/pojo.mustache | 31 +------------------ 2 files changed, 2 insertions(+), 60 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache index 959338ba86f..67ef6032609 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache @@ -66,36 +66,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#parcela {{#vendorExtensions.extraAnnotation}} {{{vendorExtensions.extraAnnotation}}} {{/vendorExtensions.extraAnnotation}} -{{#useBeanValidation}} -{{#required}} - @NotNull -{{/required}} -{{#pattern}} - @Pattern(regexp="{{pattern}}") -{{/pattern}} -{{#minLength}} -{{#maxLength}} - @Size(min={{minLength}},max={{maxLength}}) -{{/maxLength}} -{{/minLength}} -{{#minLength}} -{{^maxLength}} - @Size(min={{minLength}}) -{{/maxLength}} -{{/minLength}} -{{^minLength}} -{{#maxLength}} - @Size(max={{maxLength}}) - {{/maxLength}} - {{/minLength}} -{{#minimum}} - //@Min({{minimum}}) -{{/minimum}} -{{#maximum}} - //@Max({{maximum}}) -{{/maximum}} -{{/useBeanValidation}} - @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") +{{#useBeanValidation}}{{>beanValidation}}{{/useBeanValidation}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") {{#vendorExtensions.extraAnnotation}} {{vendorExtensions.extraAnnotation}} {{/vendorExtensions.extraAnnotation}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache index d8be3155f56..dbf7ab6b87f 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache @@ -42,39 +42,10 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{/maximum}} * @return {{name}} **/ -{{#useBeanValidation}} -{{#required}} - @NotNull -{{/required}} -{{#pattern}} - @Pattern(regexp="{{pattern}}") -{{/pattern}} -{{#minLength}} -{{#maxLength}} - @Size(min={{minLength}},max={{maxLength}}) -{{/maxLength}} -{{/minLength}} -{{#minLength}} -{{^maxLength}} - @Size(min={{minLength}}) -{{/maxLength}} -{{/minLength}} -{{^minLength}} -{{#maxLength}} - @Size(max={{maxLength}}) - {{/maxLength}} - {{/minLength}} -{{#minimum}} - //@Min({{minimum}}) -{{/minimum}} -{{#maximum}} - //@Max({{maximum}}) -{{/maximum}} -{{/useBeanValidation}} {{#vendorExtensions.extraAnnotation}} {{vendorExtensions.extraAnnotation}} {{/vendorExtensions.extraAnnotation}} - public {{{datatypeWithEnum}}} {{getter}}() { +{{#useBeanValidation}}{{>..\..\java\beanValidation}}{{/useBeanValidation}} public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; } public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { From 6aa5cd622ca2b4810f90804cedea63594edc67bd Mon Sep 17 00:00:00 2001 From: Johannes Fiala Date: Sun, 11 Sep 2016 12:17:24 +0200 Subject: [PATCH 463/470] add beanValidation java template --- .../resources/Java/beanValidation.mustache | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 modules/swagger-codegen/src/main/resources/Java/beanValidation.mustache diff --git a/modules/swagger-codegen/src/main/resources/Java/beanValidation.mustache b/modules/swagger-codegen/src/main/resources/Java/beanValidation.mustache new file mode 100644 index 00000000000..f9a3265fbb2 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/beanValidation.mustache @@ -0,0 +1,27 @@ +{{#required}} + @NotNull +{{/required}} +{{#pattern}} + @Pattern(regexp="{{pattern}}") +{{/pattern}} +{{#minLength}} +{{#maxLength}} + @Size(min={{minLength}},max={{maxLength}}) +{{/maxLength}} +{{/minLength}} +{{#minLength}} +{{^maxLength}} + @Size(min={{minLength}}) +{{/maxLength}} +{{/minLength}} +{{^minLength}} +{{#maxLength}} + @Size(max={{maxLength}}) + {{/maxLength}} + {{/minLength}} +{{#minimum}} + //@Min({{minimum}}) +{{/minimum}} +{{#maximum}} + //@Max({{maximum}}) +{{/maximum}} \ No newline at end of file From 94cacdcde7da06d83794fff9fd6d4e1fada8a30d Mon Sep 17 00:00:00 2001 From: jfiala Date: Sun, 11 Sep 2016 20:47:55 +0200 Subject: [PATCH 464/470] corrected path to mustache file --- .../src/main/resources/JavaJaxRS/cxf/pojo.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache index dbf7ab6b87f..3078ef74ece 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache @@ -45,7 +45,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{#vendorExtensions.extraAnnotation}} {{vendorExtensions.extraAnnotation}} {{/vendorExtensions.extraAnnotation}} -{{#useBeanValidation}}{{>..\..\java\beanValidation}}{{/useBeanValidation}} public {{{datatypeWithEnum}}} {{getter}}() { +{{#useBeanValidation}}{{>../../java/beanValidation}}{{/useBeanValidation}} public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; } public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { From d99929c26028d98426716cbd338b3551849b53fa Mon Sep 17 00:00:00 2001 From: jfiala Date: Mon, 10 Oct 2016 19:30:30 +0200 Subject: [PATCH 465/470] fix AbstractOptionsTest, add default false for USE_BEANVALIDATION --- .../java/io/swagger/codegen/java/JavaClientOptionsTest.java | 2 ++ .../io/swagger/codegen/options/JavaClientOptionsProvider.java | 1 + .../java/io/swagger/codegen/options/JavaOptionsProvider.java | 1 + 3 files changed, 4 insertions(+) diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java index aea42d72401..73dabd98cf2 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java @@ -56,6 +56,8 @@ protected void setExpectations() { times = 1; clientCodegen.setFullJavaUtil(Boolean.valueOf(JavaOptionsProvider.FULL_JAVA_UTIL_VALUE)); times = 1; + clientCodegen.setUseBeanValidation(Boolean.valueOf(JavaOptionsProvider.USE_BEANVALIDATION)); + times = 1; }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaClientOptionsProvider.java index a1da4cfd808..88255633518 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaClientOptionsProvider.java @@ -17,6 +17,7 @@ public Map createOptions() { options.put(CodegenConstants.LIBRARY, DEFAULT_LIBRARY_VALUE); options.put(JavaClientCodegen.USE_RX_JAVA, "false"); options.put(JavaClientCodegen.PARCELABLE_MODEL, "false"); + options.put(JavaClientCodegen.USE_BEANVALIDATION, "false"); return options; } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java index 468eb5c972f..b8412e79e92 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java @@ -19,6 +19,7 @@ public class JavaOptionsProvider implements OptionsProvider { public static final String SERIALIZABLE_MODEL_VALUE = "false"; public static final String FULL_JAVA_UTIL_VALUE = "true"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final String USE_BEANVALIDATION = "false"; private ImmutableMap options; From fc2b3ee29f23385b25ec2a475a3f39e0bad614ce Mon Sep 17 00:00:00 2001 From: jfiala Date: Fri, 14 Oct 2016 13:20:42 +0200 Subject: [PATCH 466/470] add beanvalidation to okhttp-gson library #2549 --- .../resources/Java/libraries/okhttp-gson/pom.mustache | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache index f6a64180085..698c1a97f94 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache @@ -131,6 +131,15 @@ ${jodatime-version} {{/java8}} + {{#useBeanValidation}} + + + javax.validation + validation-api + 1.1.0.Final + provided + + {{/useBeanValidation}} @@ -152,4 +161,4 @@ 4.12 UTF-8 - + \ No newline at end of file From e62a357dca5718a5ed26d11496e07822971714f5 Mon Sep 17 00:00:00 2001 From: jfiala Date: Fri, 14 Oct 2016 13:21:52 +0200 Subject: [PATCH 467/470] cleanup api.mustache for cxf #3281 --- .../src/main/resources/JavaJaxRS/cxf/api.mustache | 1 - 1 file changed, 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache index 377a981ab70..78cb04420d3 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache @@ -29,7 +29,6 @@ public interface {{classname}} { @ApiOperation(value = "{{summary}}") {{/summary}} public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); - Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}); {{/operation}} } {{/operations}} From a57947f8bd4fd757c2b5dc34e850a8e67e75d4b5 Mon Sep 17 00:00:00 2001 From: jfiala Date: Fri, 14 Oct 2016 13:23:44 +0200 Subject: [PATCH 468/470] temporary fix for invalid BeanValidation-pattern with / #2549 --- .../java/io/swagger/codegen/languages/JavaClientCodegen.java | 5 +++++ 1 file changed, 5 insertions(+) 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 80e766bab17..b3c286f93da 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 @@ -235,6 +235,11 @@ public Map postProcessModelsEnum(Map objs) { } return objs; } + + // TODO: Override DefaultCodeGen - Temporary solution to fix invalid BeanValidation-Regexp-patterns surrounded with "/" + public String toRegularExpression(String pattern) { + return escapeText(pattern); + } public void setUseRxJava(boolean useRxJava) { this.useRxJava = useRxJava; From 65e87f23a6804a0d5c0926c916a9cd6866e7fee0 Mon Sep 17 00:00:00 2001 From: jfiala Date: Fri, 14 Oct 2016 13:23:44 +0200 Subject: [PATCH 469/470] temporary fix for invalid BeanValidation-pattern with / #2549 --- .../io/swagger/codegen/languages/AbstractJavaCodegen.java | 6 ++++++ .../io/swagger/codegen/languages/JavaClientCodegen.java | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java index 9d4d16df9d4..ef87b3e1373 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java @@ -930,5 +930,11 @@ private String deriveInvokerPackageName(String input) { } return sb.toString(); } + + + // TODO: Override DefaultCodeGen - Temporary solution to fix invalid BeanValidation-Regexp-patterns surrounded with "/" + public String toRegularExpression(String pattern) { + return escapeText(pattern); + } } 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 80e766bab17..419eb2c6973 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 @@ -235,7 +235,7 @@ public Map postProcessModelsEnum(Map objs) { } return objs; } - + public void setUseRxJava(boolean useRxJava) { this.useRxJava = useRxJava; } From c0e56fe93c6e312d4f01e0afd6fd97ac0bcb7770 Mon Sep 17 00:00:00 2001 From: jfiala Date: Fri, 14 Oct 2016 16:59:41 +0200 Subject: [PATCH 470/470] remove jaxrs-annotations from implementation classes #3281 --- .../src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache | 2 +- .../src/main/resources/JavaJaxRS/cxf/queryParamsImpl.mustache | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/queryParamsImpl.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache index 3a9fe5480ca..9b55d4c7551 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache @@ -22,7 +22,7 @@ import io.swagger.annotations.Api; public class {{classname}}ServiceImpl implements {{classname}} { {{#operations}} {{#operation}} - public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { + public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}}({{#allParams}}{{>queryParamsImpl}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { // TODO: Implement... {{#returnType}}return null;{{/returnType}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/queryParamsImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/queryParamsImpl.mustache new file mode 100644 index 00000000000..ff79730471d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/queryParamsImpl.mustache @@ -0,0 +1 @@ +{{#isQueryParam}}{{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file